Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add useUserAgent #449

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/start/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ A set of primitives for Solid Start

- [`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.
- [`useUserAgent`](#useuseragent) - Creates a Server Cookie providing a type safe way to store a theme and access it on the server or client.

## Installation

Expand Down Expand Up @@ -66,6 +67,14 @@ const [theme, setTheme] = createUserTheme("cookieName", {
theme(); // => "light" | "dark"
```

## `useUserAgent`

Provides the value of the `userAgent` string isomorphically on the client or server

```ts
const userAgent: string | null = useUserAgent();
```

## Demo

You can view a demo of this primitive here: <https://codesandbox.io/p/sandbox/amazing-easley-wqk38i?file=%2Fsrc%2Fstart_primitive%2Findex.ts%3A36%2C20>
Expand Down
10 changes: 5 additions & 5 deletions packages/start/dev/index.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { Component, createSignal } from "solid-js";

import { Component } from "solid-js";
import { createUserTheme } from "../";
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
3 changes: 2 additions & 1 deletion packages/start/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
"stage": 0,
"list": [
"createServerCookie",
"createUserTheme"
"createUserTheme",
"useUserAgent"
],
"category": "Solid Start"
},
Expand Down
104 changes: 3 additions & 101 deletions packages/start/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,101 +1,3 @@
import { createSignal, createEffect, Signal } from "solid-js";
import { isServer } from "solid-js/web";
import { parseCookie } from "solid-start";
import { useRequest } from "solid-start/server";

export type MaxAgeOptions = {
/**
* 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
*/
deserialize?: (str: string | undefined) => T;
/**
* 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
*
* @param name The name of the cookie to be set
* @param options Options for the cookie {@see ServerCookieOptions}
* @return Returns an accessor and setter to manage the user's current theme
*/
export function createServerCookie<T>(
name: string,
options: ServerCookieOptions<T> & {
deserialize: (str: string | undefined) => T;
serialize: (value: T) => string;
},
): Signal<T>;
export function createServerCookie(
name: string,
options?: ServerCookieOptions,
): Signal<string | undefined>;
export function createServerCookie<T>(
name: string,
options?: ServerCookieOptions<T | undefined>,
): Signal<T | undefined> {
const {
deserialize = (v: any) => v as T,
serialize = String,
cookieMaxAge = YEAR,
} = options ?? {};

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

createEffect(p => {
const string = serialize(cookie());
if (p !== string) document.cookie = `${name}=${string};max-age=${cookieMaxAge}`;
return string;
});

return [cookie, setCookie];
}

export type Theme = "light" | "dark";

export type UserThemeOptions = MaxAgeOptions & {
/**
* The default theme to be used if the cookie is not set
*/
defaultValue?: Theme;
};

/**
* Composes {@link createServerCookie} to provide a type safe way to store a theme and access it on the server or client.
*
* @param name The name of the cookie to be set
* @param options Options for the cookie {@link UserThemeOptions}
*/
export function createUserTheme(
name: string | undefined,
options: UserThemeOptions & { defaultValue: Theme },
): Signal<Theme>;
export function createUserTheme(
name?: string,
options?: UserThemeOptions,
): Signal<Theme | undefined>;
export function createUserTheme(name = "theme", options?: UserThemeOptions): Signal<any> {
const defaultValue = options?.defaultValue;
return createServerCookie(name, {
...options,
deserialize: str => (str === "light" || str === "dark" ? str : defaultValue),
serialize: String,
});
}
export * from "./serverCookie";
export * from "./userTheme";
export * from "./userAgent";
69 changes: 69 additions & 0 deletions packages/start/src/serverCookie.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { createSignal, createEffect, Signal } from "solid-js";
import { isServer } from "solid-js/web";
import { parseCookie } from "solid-start";
import { useRequest } from "solid-start/server";

export type MaxAgeOptions = {
/**
* 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
*/
deserialize?: (str: string | undefined) => T;
/**
* 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
*
* @param name The name of the cookie to be set
* @param options Options for the cookie {@see ServerCookieOptions}
* @return Returns an accessor and setter to manage the user's current theme
*/
export function createServerCookie<T>(
name: string,
options: ServerCookieOptions<T> & {
deserialize: (str: string | undefined) => T;
serialize: (value: T) => string;
},
): Signal<T>;
export function createServerCookie(
name: string,
options?: ServerCookieOptions,
): Signal<string | undefined>;
export function createServerCookie<T>(
name: string,
options?: ServerCookieOptions<T | undefined>,
): Signal<T | undefined> {
const {
deserialize = (v: any) => v as T,
serialize = String,
cookieMaxAge = YEAR,
} = options ?? {};

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

createEffect(p => {
const string = serialize(cookie());
if (p !== string) document.cookie = `${name}=${string};max-age=${cookieMaxAge}`;
return string;
});

return [cookie, setCookie];
}
13 changes: 13 additions & 0 deletions packages/start/src/userAgent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useRequest } from "solid-start/server";
import { isServer } from "solid-js/web";
/** A primitive that allows for the user agent string to be accessed isomorphically on the client, or on the server
* @return Returns the user agent string, or null
*/
export function useUserAgent() {
const event = useRequest();
atk marked this conversation as resolved.
Show resolved Hide resolved
if (isServer) {
const userAgent = event.request.headers.get("user-agent") ?? null;
return userAgent;
}
return navigator.userAgent;
}
34 changes: 34 additions & 0 deletions packages/start/src/userTheme.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Signal } from "solid-js";
import { MaxAgeOptions, createServerCookie } from "./serverCookie";

export type Theme = "light" | "dark";

export type UserThemeOptions = MaxAgeOptions & {
/**
* The default theme to be used if the cookie is not set
*/
defaultValue?: Theme;
};

/**
* Composes {@link createServerCookie} to provide a type safe way to store a theme and access it on the server or client.
*
* @param name The name of the cookie to be set
* @param options Options for the cookie {@link UserThemeOptions}
*/
export function createUserTheme(
name: string | undefined,
options: UserThemeOptions & { defaultValue: Theme },
): Signal<Theme>;
export function createUserTheme(
name?: string,
options?: UserThemeOptions,
): Signal<Theme | undefined>;
export function createUserTheme(name = "theme", options?: UserThemeOptions): Signal<any> {
const defaultValue = options?.defaultValue;
return createServerCookie(name, {
...options,
deserialize: str => (str === "light" || str === "dark" ? str : defaultValue),
serialize: String,
});
}