Skip to content

Commit

Permalink
[FIX] Update start package (#660)
Browse files Browse the repository at this point in the history
  • Loading branch information
thetarnav authored Sep 30, 2024
2 parents debb49f + a04bb61 commit 4338fa9
Show file tree
Hide file tree
Showing 9 changed files with 218 additions and 1,884 deletions.
File renamed without changes.
99 changes: 99 additions & 0 deletions packages/cookies/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<p>
<img width="100%" src="https://assets.solidjs.com/banner?type=Primitives&background=tiles&project=cookies" alt="Solid Primitives cookies">
</p>

# @solid-primitives/cookies

[![turborepo](https://img.shields.io/badge/built%20with-turborepo-cc00ff.svg?style=for-the-badge&logo=turborepo)](https://turborepo.org/)
[![size](https://img.shields.io/bundlephobia/minzip/@solid-primitives/cookies?style=for-the-badge&label=size)](https://bundlephobia.com/package/@solid-primitives/cookies)
[![version](https://img.shields.io/npm/v/@solid-primitives/cookies?style=for-the-badge)](https://www.npmjs.com/package/@solid-primitives/cookies)
[![stage](https://img.shields.io/endpoint?style=for-the-badge&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-0.json)](https://github.com/solidjs-community/solid-primitives#contribution-process)

A set of primitives for handling cookies in solid

- [`createServerCookie`](#createservercookie) - Provides a getter and setter for a reactive cookie, which works isomorphically.
- [`createUserTheme`](#createusertheme) - Creates a Server Cookie providing a type safe way to store a theme and access it on the server or client.
- [`getCookiesString`](#getCookiesString) - A primitive that allows for the cookie string to be accessed isomorphically on the client, or on the server

## Installation

```bash
npm install @solid-primitives/cookies
# or
yarn add @solid-primitives/cookies
# or
pnpm add @solid-primitives/cookies
```

## How to use it

## `createServerCookie`

A primitive for creating a cookie that can be accessed isomorphically on the client, or the server.

```ts
import { createServerCookie } from "@solid-primitives/cookies"

const [cookie, setCookie] = createServerCookie("cookieName");

cookie(); // => string | undefined
```

### Custom serialization

Custom cookie serializers and deserializers can also be implemented

```ts
import { createServerCookie } from "@solid-primitives/cookies"

const [serverCookie, setServerCookie] = createServerCookie("coolCookie", {
deserialize: str => (str ? str.split(" ") : []), // Deserializes cookie into a string[]
serialize: val => (val ? val.join(" ") : ""), // serializes the value back into a string
});

serverCookie(); // => string[]
```

## `createUserTheme`

Composes `createServerCookie` to provide a type safe way to store a theme and access it on the server or client.

```ts
import { createUserTheme } from "@solid-primitives/cookies"

const [theme, setTheme] = createUserTheme("cookieName");

theme(); // => "light" | "dark" | undefined

// with default value
const [theme, setTheme] = createUserTheme("cookieName", {
defaultValue: "light",
});

theme(); // => "light" | "dark"
```

## `getCookiesString`

A primitive that allows for the cookie string to be accessed isomorphically on the client, or on the server.
Uses `getRequestEvent` on the server and `document.cookie` on the client.

```ts
import { getCookiesString, parseCookie } from "@solid-primitives/cookies"

const string = getCookiesString()
const cookie = parseCookie(string, "cookie_name")
```


## Examples

PRs welcome :)

## Demo

You can view a demo of this primitive here: <https://codesandbox.io/p/sandbox/amazing-easley-wqk38i?file=%2Fsrc%2Fcookies_primitive%2Findex.ts%3A36%2C20>

## Changelog

See [CHANGELOG.md](./CHANGELOG.md)
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import { Component, createSignal } from "solid-js";
import { Component } from "solid-js";
import { createUserTheme } from "../src/index.js";

const App: Component = () => {
const [count, setCount] = createSignal(0);
const increment = () => setCount(count() + 1);
const [theme, setTheme] = createUserTheme();
const increment = () => setTheme(theme() === "light" ? "dark" : "light");
return (
<div class={`min-h-screen ${"dark" == "dark" ? "dark" : ""}`}>
<div class="box-border flex min-h-screen w-full flex-col items-center justify-center space-y-4 bg-gray-800 p-24 text-white">
<div class="wrapper-v">
<h4>Counter component</h4>
<p class="caption">it's very important...</p>
<button class="btn" onClick={increment}>
{count()}
{theme()}
</button>
</div>
</div>
Expand Down
25 changes: 12 additions & 13 deletions packages/start/package.json → packages/cookies/package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
{
"name": "@solid-primitives/start",
"version": "0.0.4",
"description": "A set of primitives for Solid Start",
"author": "Thomas",
"name": "@solid-primitives/cookies",
"version": "0.0.1",
"description": "A set of primitives for handling cookies in solid",
"author": "Thomas Beer (https://github.com/Tommypop2)",
"contributors": [
"Damian Tarnawski <[email protected]>"
"Damian Tarnawski <[email protected]>",
"Seth Murphy (https://github.com/eagerestwolf)"
],
"license": "MIT",
"homepage": "https://primitives.solidjs.community/package/start",
"homepage": "https://primitives.solidjs.community/package/cookies",
"repository": {
"type": "git",
"url": "git+https://github.com/solidjs-community/solid-primitives.git"
Expand All @@ -16,18 +17,18 @@
"url": "https://github.com/solidjs-community/solid-primitives/issues"
},
"primitive": {
"name": "start",
"name": "cookies",
"stage": 0,
"list": [
"createServerCookie",
"createUserTheme"
"createUserTheme",
"getCookiesString"
],
"category": "Solid Start"
},
"keywords": [
"solid",
"primitives",
"solid-start",
"ssr"
],
"private": false,
Expand Down Expand Up @@ -59,11 +60,9 @@
"test:ssr": "pnpm run vitest --mode ssr"
},
"peerDependencies": {
"solid-js": "^1.6.12",
"solid-start": ">=0.2.26"
"solid-js": "^1.8.18"
},
"devDependencies": {
"solid-js": "^1.8.7",
"solid-start": "^0.3.10"
"solid-js": "^1.8.18"
}
}
57 changes: 33 additions & 24 deletions packages/start/src/index.ts → packages/cookies/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,43 @@
import { createSignal, createEffect, Signal } from "solid-js";
import { isServer } from "solid-js/web";
import { parseCookie } from "solid-start";
import { useRequest } from "solid-start/server/ServerContext.jsx";
import { getRequestEvent, isServer } from "solid-js/web";

const YEAR = 365 * 24 * 60 * 60;

/*
Original code by Chakra UI
MIT Licensed, Copyright (c) 2019 Segun Adebayo.
Credits to the Chakra UI team:
https://github.com/chakra-ui/chakra-ui/blob/%40chakra-ui/toast%401.2.0/packages/color-mode/src/storage-manager.ts
*/

export function parseCookie(cookie: string, key: string): string | undefined {
return cookie.match(new RegExp(`(^| )${key}=([^;]+)`))?.[2];
}

/**
* A primitive that allows for the cookie string to be accessed isomorphically on the client, or on the server
* @return Returns the cookie string
*/
export function getCookiesString(): string {
if (isServer) {
return getRequestEvent()?.request.headers.get("cookie") ?? ""
}
return document.cookie
}

export type MaxAgeOptions = {
/**
* The maximum age of the cookie in seconds. Defaults to 1 year.
*/
/** The maximum age of the cookie in seconds. Defaults to 1 year. */
cookieMaxAge?: number;
};

export type ServerCookieOptions<T = string> = MaxAgeOptions & {
/**
* A function to deserialize the cookie value to be used as signal value
*/
/** A function to deserialize the cookie value to be used as signal value */
deserialize?: (str: string | undefined) => T;
/**
* A function to serialize the signal value to be used as cookie value
*/
/** A function to serialize the signal value to be used as cookie value */
serialize?: (value: T) => string;
};

const YEAR = 365 * 24 * 60 * 60;

/**
* A primitive for creating a cookie that can be accessed isomorphically on the client, or the server
*
Expand Down Expand Up @@ -51,13 +66,7 @@ export function createServerCookie<T>(
cookieMaxAge = YEAR,
} = options ?? {};

const [cookie, setCookie] = createSignal(
deserialize(
parseCookie(isServer ? (useRequest().request.headers.get("cookie") ?? "") : document.cookie)[
name
],
),
);
const [cookie, setCookie] = createSignal(deserialize(parseCookie(getCookiesString(), name)));

createEffect(p => {
const string = serialize(cookie());
Expand Down Expand Up @@ -91,10 +100,10 @@ export function createUserTheme(
name?: string,
options?: UserThemeOptions,
): Signal<Theme | undefined>;
export function createUserTheme(name = "theme", options?: UserThemeOptions): Signal<any> {
const defaultValue = options?.defaultValue;
export function createUserTheme(name = "theme", options: UserThemeOptions = {}): Signal<any> {
const {defaultValue, cookieMaxAge} = options;
return createServerCookie(name, {
...options,
cookieMaxAge,
deserialize: str => (str === "light" || str === "dark" ? str : defaultValue),
serialize: String,
});
Expand Down
File renamed without changes.
19 changes: 0 additions & 19 deletions packages/start/CHANGELOG.md

This file was deleted.

Loading

0 comments on commit 4338fa9

Please sign in to comment.