@siiway/ui-core 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +14 -1
  3. package/dist/boot.d.ts +24 -0
  4. package/dist/boot.d.ts.map +1 -0
  5. package/dist/boot.js +38 -0
  6. package/dist/boot.js.map +1 -0
  7. package/dist/duration.d.ts +27 -0
  8. package/dist/duration.d.ts.map +1 -0
  9. package/dist/duration.js +87 -0
  10. package/dist/duration.js.map +1 -0
  11. package/dist/i18n/en.d.ts +3 -0
  12. package/dist/i18n/en.d.ts.map +1 -0
  13. package/dist/i18n/en.js +56 -0
  14. package/dist/i18n/en.js.map +1 -0
  15. package/dist/i18n/index.d.ts +11 -0
  16. package/dist/i18n/index.d.ts.map +1 -0
  17. package/dist/i18n/index.js +16 -0
  18. package/dist/i18n/index.js.map +1 -0
  19. package/dist/i18n/types.d.ts +72 -0
  20. package/dist/i18n/types.d.ts.map +1 -0
  21. package/dist/i18n/types.js +2 -0
  22. package/dist/i18n/types.js.map +1 -0
  23. package/dist/i18n/zh.d.ts +3 -0
  24. package/dist/i18n/zh.d.ts.map +1 -0
  25. package/dist/i18n/zh.js +56 -0
  26. package/dist/i18n/zh.js.map +1 -0
  27. package/dist/index.d.ts +12 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +12 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/scheme.d.ts +36 -0
  32. package/dist/scheme.d.ts.map +1 -0
  33. package/dist/scheme.js +49 -0
  34. package/dist/scheme.js.map +1 -0
  35. package/dist/theme/brand.d.ts +17 -0
  36. package/dist/theme/brand.d.ts.map +1 -0
  37. package/dist/theme/brand.js +25 -0
  38. package/dist/theme/brand.js.map +1 -0
  39. package/dist/theme/color.d.ts +26 -0
  40. package/dist/theme/color.d.ts.map +1 -0
  41. package/dist/theme/color.js +148 -0
  42. package/dist/theme/color.js.map +1 -0
  43. package/dist/theme/overrides.d.ts +12 -0
  44. package/dist/theme/overrides.d.ts.map +1 -0
  45. package/dist/theme/overrides.js +12 -0
  46. package/dist/theme/overrides.js.map +1 -0
  47. package/dist/tokens/canvas.d.ts +8 -0
  48. package/dist/tokens/canvas.d.ts.map +1 -0
  49. package/dist/tokens/canvas.js +7 -0
  50. package/dist/tokens/canvas.js.map +1 -0
  51. package/dist/tokens/neutral.d.ts +55 -0
  52. package/dist/tokens/neutral.d.ts.map +1 -0
  53. package/dist/tokens/neutral.js +110 -0
  54. package/dist/tokens/neutral.js.map +1 -0
  55. package/dist/tokens/radii.d.ts +8 -0
  56. package/dist/tokens/radii.d.ts.map +1 -0
  57. package/dist/tokens/radii.js +8 -0
  58. package/dist/tokens/radii.js.map +1 -0
  59. package/dist/tokens/shadows.d.ts +14 -0
  60. package/dist/tokens/shadows.d.ts.map +1 -0
  61. package/dist/tokens/shadows.js +21 -0
  62. package/dist/tokens/shadows.js.map +1 -0
  63. package/package.json +25 -2
  64. package/src/boot.ts +55 -0
  65. package/src/duration.ts +119 -0
  66. package/src/i18n/en.ts +66 -0
  67. package/src/i18n/index.ts +24 -0
  68. package/src/i18n/types.ts +82 -0
  69. package/src/i18n/zh.ts +65 -0
  70. package/src/index.ts +46 -0
  71. package/src/scheme.ts +71 -0
  72. package/src/theme/brand.ts +32 -0
  73. package/src/theme/color.ts +147 -0
  74. package/src/theme/overrides.ts +15 -0
  75. package/src/tokens/canvas.ts +8 -0
  76. package/src/tokens/neutral.ts +116 -0
  77. package/src/tokens/radii.ts +7 -0
  78. package/src/tokens/shadows.ts +27 -0
package/package.json CHANGED
@@ -1,11 +1,34 @@
1
1
  {
2
2
  "name": "@siiway/ui-core",
3
- "version": "0.0.0",
4
- "description": "Placeholder so npm trusted publishing can be set up. Use 0.1.0 or later.",
3
+ "version": "0.2.0",
4
+ "description": "SiiWay design tokens, theme maths and UI strings, for any framework.",
5
5
  "license": "MIT",
6
+ "homepage": "https://ui.siiway.org",
7
+ "type": "module",
8
+ "sideEffects": false,
6
9
  "repository": {
7
10
  "type": "git",
8
11
  "url": "git+https://github.com/siiway/ui.git",
9
12
  "directory": "packages/core"
13
+ },
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "./package.json": "./package.json"
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "!dist/.tsbuildinfo",
24
+ "src",
25
+ "LICENSE",
26
+ "README.md"
27
+ ],
28
+ "scripts": {
29
+ "build": "tsc -b"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
10
33
  }
11
34
  }
package/src/boot.ts ADDED
@@ -0,0 +1,55 @@
1
+ import { SCHEME_COOKIE_ATTRIBUTES, THEME_STORAGE_KEY, type ThemeMode } from "./scheme.js";
2
+ import { CANVAS } from "./tokens/canvas.js";
3
+
4
+ export interface SchemeBootOptions {
5
+ /** The `localStorage` key the choice is kept under; the same as `useThemeMode`'s. */
6
+ storageKey?: string;
7
+ /** When nothing valid is stored. Defaults to `system`. */
8
+ defaultMode?: ThemeMode;
9
+ /**
10
+ * A cookie to write the scheme to, for the server to render in
11
+ * (`schemeFromRequest`), such as `SCHEME_COOKIE`. Give `useThemeMode` the same.
12
+ */
13
+ cookie?: string;
14
+ }
15
+
16
+ // A value as a JavaScript literal that is safe inside an inline <script>.
17
+ function literal(value: string): string {
18
+ return JSON.stringify(value).replace(/</g, "\\u003c");
19
+ }
20
+
21
+ /**
22
+ * JavaScript for an inline `<script>` in the page's `<head>`, after
23
+ * `<meta name="theme-color">` if there is one. Before anything renders, it
24
+ * reads the stored choice, resolves `system` with the OS setting, and draws
25
+ * `<html>` in that scheme: `data-scheme`, `color-scheme`, the canvas
26
+ * background and `--siiway-canvas`. Each `theme-color` takes the canvas.
27
+ * Without it, a dark page is white until the app's JavaScript runs.
28
+ * `<UiProvider page>` keeps `<html>` the same way afterwards. With `cookie`,
29
+ * it also writes the scheme there, for the server to render the next request in.
30
+ */
31
+ export function schemeBootScript({
32
+ storageKey = THEME_STORAGE_KEY,
33
+ defaultMode = "system",
34
+ cookie,
35
+ }: SchemeBootOptions = {}): string {
36
+ return [
37
+ "(function(){",
38
+ "var m;",
39
+ `try{m=localStorage.getItem(${literal(storageKey)})}catch(e){}`,
40
+ `if(m!=="system"&&m!=="light"&&m!=="dark")m=${literal(defaultMode)};`,
41
+ 'var s=m!=="system"?m:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";',
42
+ "var r=document.documentElement;",
43
+ `var c=s==="dark"?${literal(CANVAS.dark)}:${literal(CANVAS.light)};`,
44
+ 'r.setAttribute("data-scheme",s);',
45
+ "r.style.colorScheme=s;",
46
+ "r.style.backgroundColor=c;",
47
+ 'r.style.setProperty("--siiway-canvas",c);',
48
+ `for(var t=document.querySelectorAll(${literal('meta[name="theme-color"]')}),i=0;i<t.length;i++)t[i].setAttribute("content",c);`,
49
+ // As schemeCookie() writes it.
50
+ cookie
51
+ ? `try{document.cookie=${literal(`${cookie}=`)}+s+${literal(SCHEME_COOKIE_ATTRIBUTES)}+(self.isSecureContext?";secure":"")}catch(e){}`
52
+ : "",
53
+ "})();",
54
+ ].join("");
55
+ }
@@ -0,0 +1,119 @@
1
+ // Parse durations people type, like "60min", "1 hour", "30 days", into whole
2
+ // minutes or days, depending on the field's storage unit. A bare number is in
3
+ // the field's unit. The unit words come from the library's strings
4
+ // (`UiStrings.durationUnits`), so each language reads its own; English by
5
+ // default.
6
+
7
+ import { en } from "./i18n/en.js";
8
+
9
+ export type DurationUnit = "minutes" | "days";
10
+
11
+ /** The units a duration can be typed in. A month is 30 days, a year 365. */
12
+ export type DurationUnitKey = "s" | "m" | "h" | "d" | "w" | "mo" | "y";
13
+
14
+ /** One language's words for each unit, matched ignoring case. */
15
+ export type DurationUnitWords = Record<DurationUnitKey, readonly string[]>;
16
+
17
+ /**
18
+ * Parse a duration string. Returns the integer count in the field's
19
+ * `defaultUnit`, or `null` for an empty string ("use the site default"),
20
+ * or a `string` error code for an unparseable input.
21
+ */
22
+ export type ParseResult =
23
+ | { kind: "ok"; value: number }
24
+ | { kind: "blank" }
25
+ | { kind: "error"; reason: "format" | "non_positive" | "unknown_unit" };
26
+
27
+ function unitFor(
28
+ word: string,
29
+ units: DurationUnitWords | readonly DurationUnitWords[],
30
+ ): DurationUnitKey | null {
31
+ const tables =
32
+ "s" in units ? [units as DurationUnitWords] : (units as readonly DurationUnitWords[]);
33
+ for (const table of tables) {
34
+ for (const key of Object.keys(table) as DurationUnitKey[]) {
35
+ if (table[key].some((name) => name.toLowerCase() === word)) return key;
36
+ }
37
+ }
38
+ return null;
39
+ }
40
+
41
+ /** Reads `input` with the unit words of `units`, one language or several. */
42
+ export function parseDuration(
43
+ input: string,
44
+ defaultUnit: DurationUnit,
45
+ units: DurationUnitWords | readonly DurationUnitWords[] = en.durationUnits,
46
+ ): ParseResult {
47
+ const trimmed = input.trim();
48
+ if (!trimmed) return { kind: "blank" };
49
+
50
+ // Strict: a number, optional whitespace, optional unit word (letters, in
51
+ // any script). Reject anything else (commas, multiple numbers, units
52
+ // without a number, etc.).
53
+ const match = trimmed.match(/^(\d+(?:\.\d+)?)\s*(\p{L}*)$/u);
54
+ if (!match) return { kind: "error", reason: "format" };
55
+
56
+ const num = parseFloat(match[1]!);
57
+ if (!Number.isFinite(num) || num <= 0) {
58
+ return { kind: "error", reason: "non_positive" };
59
+ }
60
+
61
+ const unitRaw = (match[2] ?? "").toLowerCase();
62
+ const canonical = unitRaw === "" ? null : unitFor(unitRaw, units);
63
+ if (unitRaw !== "" && !canonical) {
64
+ return { kind: "error", reason: "unknown_unit" };
65
+ }
66
+
67
+ // Convert to minutes first, then down to the field's unit.
68
+ let totalMinutes: number;
69
+ switch (canonical) {
70
+ case "s":
71
+ totalMinutes = num / 60;
72
+ break;
73
+ case "m":
74
+ totalMinutes = num;
75
+ break;
76
+ case "h":
77
+ totalMinutes = num * 60;
78
+ break;
79
+ case "d":
80
+ totalMinutes = num * 60 * 24;
81
+ break;
82
+ case "w":
83
+ totalMinutes = num * 60 * 24 * 7;
84
+ break;
85
+ case "mo":
86
+ totalMinutes = num * 60 * 24 * 30;
87
+ break;
88
+ case "y":
89
+ totalMinutes = num * 60 * 24 * 365;
90
+ break;
91
+ case null:
92
+ // No unit — interpret in the field's default unit.
93
+ totalMinutes = defaultUnit === "minutes" ? num : num * 60 * 24;
94
+ break;
95
+ default: {
96
+ // Exhaustiveness check.
97
+ const _exhaustive: never = canonical;
98
+ void _exhaustive;
99
+ totalMinutes = num;
100
+ }
101
+ }
102
+
103
+ const value =
104
+ defaultUnit === "minutes" ? Math.round(totalMinutes) : Math.round(totalMinutes / (60 * 24));
105
+
106
+ // Round-down for very small inputs (e.g. "30s" in a days-unit field) but
107
+ // never let a positive duration round to 0 — that would mint zero-TTL
108
+ // tokens. Clamp to 1 of the field's unit.
109
+ if (value < 1) return { kind: "ok", value: 1 };
110
+ return { kind: "ok", value };
111
+ }
112
+
113
+ /**
114
+ * Format an integer count with its unit, in English. The duration field
115
+ * shows the app's language instead (`UiStrings.duration`).
116
+ */
117
+ export function formatDuration(value: number, defaultUnit: DurationUnit): string {
118
+ return en.duration(value, defaultUnit);
119
+ }
package/src/i18n/en.ts ADDED
@@ -0,0 +1,66 @@
1
+ import type { UiStrings } from "./types.js";
2
+
3
+ export const en: UiStrings = {
4
+ cancel: "Cancel",
5
+ clear: "Clear",
6
+ close: "Close",
7
+ required: "Required",
8
+
9
+ copy: "Copy",
10
+ copied: "Copied!",
11
+ copyFailed: "Copy failed",
12
+
13
+ saveChanges: "Save changes",
14
+ discardChanges: "Discard changes",
15
+
16
+ showPassword: "Show password",
17
+ hidePassword: "Hide password",
18
+
19
+ previous: "Previous",
20
+ next: "Next",
21
+ pageOf: (page, total) => `${page} / ${total}`,
22
+ totalItems: (count) => (count === 1 ? `${count} item` : `${count} items`),
23
+ pageNumber: "Page",
24
+ goToPage: "Go to page",
25
+ go: "Go",
26
+
27
+ pickColor: "Pick a color",
28
+ hexColor: "Hex color",
29
+ optionalHexColor: "Optional hex color",
30
+ invalidHexColor: "Enter a three- or six-digit hex color.",
31
+ colorArea: "Color saturation and brightness",
32
+ saturation: "Saturation",
33
+ brightness: "Brightness",
34
+ hue: "Hue",
35
+
36
+ theme: "Theme",
37
+ themeSystem: "System",
38
+ themeLight: "Light",
39
+ themeDark: "Dark",
40
+
41
+ search: "Search",
42
+ commandMove: "to move",
43
+ commandOpen: "to open",
44
+ commandClose: "to close",
45
+
46
+ onThisPage: "On this page",
47
+ loading: "Loading",
48
+ openNavigation: "Open navigation",
49
+ primaryNavigation: "Primary",
50
+ navigation: "Navigation",
51
+ closeNavigation: "Close navigation",
52
+ duration: (value, unit) =>
53
+ unit === "minutes" ? `${value} min` : value === 1 ? "1 day" : `${value} days`,
54
+ durationUnits: {
55
+ s: ["s", "sec", "secs", "second", "seconds"],
56
+ m: ["m", "min", "mins", "minute", "minutes"],
57
+ h: ["h", "hr", "hrs", "hour", "hours"],
58
+ d: ["d", "day", "days"],
59
+ w: ["w", "wk", "wks", "week", "weeks"],
60
+ mo: ["mo", "mon", "month", "months"],
61
+ y: ["y", "yr", "yrs", "year", "years"],
62
+ },
63
+ durationInvalid: "Invalid format: try “60” or “1 hour”",
64
+ durationNotPositive: "Must be a positive duration",
65
+ durationUnknownUnit: "Unknown time unit",
66
+ };
@@ -0,0 +1,24 @@
1
+ import { en } from "./en.js";
2
+ import type { UiLocale, UiStrings } from "./types.js";
3
+ import { zh } from "./zh.js";
4
+
5
+ export type { UiLocale, UiStrings } from "./types.js";
6
+
7
+ export const UI_STRINGS: Record<UiLocale, UiStrings> = { en, zh };
8
+
9
+ /**
10
+ * The library locale for a BCP-47 tag: any `zh` tag (`zh`, `zh-CN`,
11
+ * `zh-Hans-CN`) is `zh`, everything else is `en`.
12
+ */
13
+ export function uiLocale(locale: string | null | undefined): UiLocale {
14
+ return locale?.trim().toLowerCase().split(/[-_]/)[0] === "zh" ? "zh" : "en";
15
+ }
16
+
17
+ /** The strings for a BCP-47 tag, with any of them replaced by `overrides`. */
18
+ export function pickStrings(
19
+ locale: string | null | undefined,
20
+ overrides?: Partial<UiStrings>,
21
+ ): UiStrings {
22
+ const base = UI_STRINGS[uiLocale(locale)];
23
+ return overrides ? { ...base, ...overrides } : base;
24
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * The text the library's own components show: button labels, feedback,
3
+ * `aria-label`s and placeholders. Everything else comes in as props, already
4
+ * translated by the app. Each locale satisfies this type, so a key missing
5
+ * from one fails the typecheck.
6
+ */
7
+ import type { DurationUnit, DurationUnitWords } from "../duration.js";
8
+
9
+ export interface UiStrings {
10
+ cancel: string;
11
+ clear: string;
12
+ close: string;
13
+ required: string;
14
+
15
+ copy: string;
16
+ copied: string;
17
+ copyFailed: string;
18
+
19
+ saveChanges: string;
20
+ discardChanges: string;
21
+
22
+ showPassword: string;
23
+ hidePassword: string;
24
+
25
+ previous: string;
26
+ next: string;
27
+ /** Pagination position, e.g. "2 / 7". */
28
+ pageOf: (page: number, total: number) => string;
29
+ totalItems: (count: number) => string;
30
+ /** Placeholder of the go-to-page field. */
31
+ pageNumber: string;
32
+ goToPage: string;
33
+ go: string;
34
+
35
+ pickColor: string;
36
+ hexColor: string;
37
+ optionalHexColor: string;
38
+ invalidHexColor: string;
39
+ colorArea: string;
40
+ saturation: string;
41
+ brightness: string;
42
+ hue: string;
43
+
44
+ /** Label of the theme switch. */
45
+ theme: string;
46
+ themeSystem: string;
47
+ themeLight: string;
48
+ themeDark: string;
49
+
50
+ /** The search button's label and the command palette's field name. */
51
+ search: string;
52
+ /** The command palette's key hints, each after its key: "↑ ↓ to move". */
53
+ commandMove: string;
54
+ commandOpen: string;
55
+ commandClose: string;
56
+
57
+ /** The outline's heading. */
58
+ onThisPage: string;
59
+ /** Names a spinner that has no text of its own, such as a page still loading. */
60
+ loading: string;
61
+ /** The top bar's menu button, which opens the navigation on a narrow screen. */
62
+ openNavigation: string;
63
+ /** Names the top bar's links for screen readers. */
64
+ primaryNavigation: string;
65
+ /** Names the app shell's sidebar while it is a drawer. */
66
+ navigation: string;
67
+ /** The button in the drawer that closes it. */
68
+ closeNavigation: string;
69
+
70
+ /** A duration as the duration field shows it, e.g. "30 days". It must read
71
+ * back with `parseDuration`. */
72
+ duration: (value: number, unit: DurationUnit) => string;
73
+ /** This language's words for each unit, which the duration field reads. */
74
+ durationUnits: DurationUnitWords;
75
+ /** The duration field's errors. */
76
+ durationInvalid: string;
77
+ durationNotPositive: string;
78
+ durationUnknownUnit: string;
79
+ }
80
+
81
+ /** Locales the library ships strings for. */
82
+ export type UiLocale = "en" | "zh";
package/src/i18n/zh.ts ADDED
@@ -0,0 +1,65 @@
1
+ import type { UiStrings } from "./types.js";
2
+
3
+ export const zh: UiStrings = {
4
+ cancel: "取消",
5
+ clear: "清除",
6
+ close: "关闭",
7
+ required: "必填",
8
+
9
+ copy: "复制",
10
+ copied: "已复制!",
11
+ copyFailed: "复制失败",
12
+
13
+ saveChanges: "保存更改",
14
+ discardChanges: "放弃更改",
15
+
16
+ showPassword: "显示密码",
17
+ hidePassword: "隐藏密码",
18
+
19
+ previous: "上一页",
20
+ next: "下一页",
21
+ pageOf: (page, total) => `${page} / ${total}`,
22
+ totalItems: (count) => `共 ${count} 项`,
23
+ pageNumber: "页数",
24
+ goToPage: "跳转到页",
25
+ go: "跳转",
26
+
27
+ pickColor: "选择颜色",
28
+ hexColor: "十六进制颜色",
29
+ optionalHexColor: "可选的十六进制颜色",
30
+ invalidHexColor: "请输入三位或六位十六进制色值。",
31
+ colorArea: "颜色饱和度和亮度",
32
+ saturation: "饱和度",
33
+ brightness: "亮度",
34
+ hue: "色相",
35
+
36
+ theme: "主题",
37
+ themeSystem: "跟随系统",
38
+ themeLight: "浅色",
39
+ themeDark: "深色",
40
+
41
+ search: "搜索",
42
+ commandMove: "移动",
43
+ commandOpen: "打开",
44
+ commandClose: "关闭",
45
+
46
+ onThisPage: "目录",
47
+ loading: "加载中",
48
+ openNavigation: "打开导航",
49
+ primaryNavigation: "主导航",
50
+ navigation: "导航",
51
+ closeNavigation: "关闭导航",
52
+ duration: (value, unit) => (unit === "minutes" ? `${value} 分钟` : `${value} 天`),
53
+ durationUnits: {
54
+ s: ["秒", "秒钟"],
55
+ m: ["分", "分钟"],
56
+ h: ["时", "小时", "个小时"],
57
+ d: ["天", "日"],
58
+ w: ["周", "星期", "个星期"],
59
+ mo: ["月", "个月"],
60
+ y: ["年"],
61
+ },
62
+ durationInvalid: "格式无效,试试“60”或“1 小时”",
63
+ durationNotPositive: "时长必须大于零",
64
+ durationUnknownUnit: "无法识别的时间单位",
65
+ };
package/src/index.ts ADDED
@@ -0,0 +1,46 @@
1
+ export {
2
+ SCHEME_COOKIE,
3
+ THEME_STORAGE_KEY,
4
+ isThemeMode,
5
+ resolveScheme,
6
+ schemeCookie,
7
+ schemeFromRequest,
8
+ type Scheme,
9
+ type SchemeRequestOptions,
10
+ type ThemeMode,
11
+ } from "./scheme.js";
12
+ export { schemeBootScript, type SchemeBootOptions } from "./boot.js";
13
+
14
+ export { NEUTRAL, type NeutralTokens } from "./tokens/neutral.js";
15
+ export { RADII } from "./tokens/radii.js";
16
+ export { SHADOWS, type ShadowTokens } from "./tokens/shadows.js";
17
+ export { CANVAS } from "./tokens/canvas.js";
18
+
19
+ export {
20
+ normalizeHexColor,
21
+ normalizeAccent,
22
+ hexToHsl,
23
+ hslToHex,
24
+ hexToHsv,
25
+ hsvToHex,
26
+ type HsvColor,
27
+ } from "./theme/color.js";
28
+ export {
29
+ DEFAULT_ACCENT,
30
+ BRAND_SHADES,
31
+ brandRamp,
32
+ type BrandShade,
33
+ type BrandRamp,
34
+ } from "./theme/brand.js";
35
+ export { themeOverrides, type ThemeOverrides } from "./theme/overrides.js";
36
+
37
+ export { UI_STRINGS, uiLocale, pickStrings, type UiLocale, type UiStrings } from "./i18n/index.js";
38
+
39
+ export {
40
+ parseDuration,
41
+ formatDuration,
42
+ type DurationUnit,
43
+ type DurationUnitKey,
44
+ type DurationUnitWords,
45
+ type ParseResult,
46
+ } from "./duration.js";
package/src/scheme.ts ADDED
@@ -0,0 +1,71 @@
1
+ /** A resolved colour scheme: what the page is drawn in right now. */
2
+ export type Scheme = "light" | "dark";
3
+
4
+ /** A person's colour-scheme choice: a fixed scheme, or follow the OS. */
5
+ export type ThemeMode = "system" | Scheme;
6
+
7
+ /** Where the choice is kept by default (`localStorage`), by `useThemeMode` and `schemeBootScript`. */
8
+ export const THEME_STORAGE_KEY = "siiway-theme";
9
+
10
+ /** Whether a value, such as one read back from storage, is a ThemeMode. */
11
+ export function isThemeMode(value: unknown): value is ThemeMode {
12
+ return value === "system" || value === "light" || value === "dark";
13
+ }
14
+
15
+ /** The scheme a mode draws in: `system` follows the OS. */
16
+ export function resolveScheme(mode: ThemeMode, systemDark: boolean): Scheme {
17
+ if (mode !== "system") return mode;
18
+ return systemDark ? "dark" : "light";
19
+ }
20
+
21
+ /** A name for the cookie that carries the scheme to the server, as `schemeFromRequest` reads it by default. */
22
+ export const SCHEME_COOKIE = "siiway-scheme";
23
+
24
+ // A year, on every path, and sent when someone follows a link from another site.
25
+ export const SCHEME_COOKIE_ATTRIBUTES = ";path=/;max-age=31536000;samesite=lax";
26
+
27
+ /**
28
+ * The scheme cookie, as `document.cookie` takes it, the way `schemeBootScript`
29
+ * and `useThemeMode` write it. `secure` (in a secure context) lets the name
30
+ * start with `__Host-`.
31
+ */
32
+ export function schemeCookie(name: string, scheme: Scheme, secure: boolean): string {
33
+ return `${name}=${scheme}${SCHEME_COOKIE_ATTRIBUTES}${secure ? ";secure" : ""}`;
34
+ }
35
+
36
+ /** How the app keeps the scheme: `schemeBootScript`'s options fit. */
37
+ export interface SchemeRequestOptions {
38
+ /** The cookie's name, as given to `schemeBootScript` and `useThemeMode`. Defaults to `SCHEME_COOKIE`. */
39
+ cookie?: string;
40
+ /**
41
+ * The app's `defaultMode`. For `light` or `dark`, the hint is left out: a
42
+ * first visit draws that, whatever the OS. Defaults to `system`.
43
+ */
44
+ defaultMode?: ThemeMode;
45
+ }
46
+
47
+ /**
48
+ * The scheme to render a request in: the scheme cookie from the `Cookie`
49
+ * header, else (for `defaultMode` `system`) the browser's
50
+ * `Sec-CH-Prefers-Color-Scheme` hint, else null, for `defaultMode`'s scheme.
51
+ */
52
+ export function schemeFromRequest(
53
+ cookieHeader?: string | null,
54
+ prefersColorSchemeHint?: string | null,
55
+ { cookie = SCHEME_COOKIE, defaultMode = "system" }: SchemeRequestOptions = {},
56
+ ): Scheme | null {
57
+ // The last that matches: a browser sends cookies with longer paths first,
58
+ // and an old one set on a page's path would come before ours, on `/`.
59
+ // Commas too: the Fetch API joins repeated `Cookie` fields with ", ".
60
+ let found: Scheme | null = null;
61
+ for (const part of (cookieHeader ?? "").split(/[;,]/)) {
62
+ const at = part.indexOf("=");
63
+ if (at < 0 || part.slice(0, at).trim() !== cookie) continue;
64
+ const value = part.slice(at + 1).trim();
65
+ if (value === "light" || value === "dark") found = value;
66
+ }
67
+ if (found || defaultMode !== "system") return found;
68
+ // A structured header: the value comes quoted, as "dark".
69
+ const hint = prefersColorSchemeHint?.trim().replace(/^"(.*)"$/, "$1");
70
+ return hint === "light" || hint === "dark" ? hint : null;
71
+ }
@@ -0,0 +1,32 @@
1
+ import { hexToHsl, hslToHex, normalizeAccent } from "./color.js";
2
+
3
+ /** Fluent's default blue, used when no accent is configured. */
4
+ export const DEFAULT_ACCENT = "#0078d4";
5
+
6
+ export const BRAND_SHADES = [
7
+ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160,
8
+ ] as const;
9
+
10
+ export type BrandShade = (typeof BRAND_SHADES)[number];
11
+
12
+ /** Sixteen shades of one hue, darkest (10) to lightest (160). Fluent calls this BrandVariants. */
13
+ export type BrandRamp = Record<BrandShade, string>;
14
+
15
+ /**
16
+ * Builds the brand ramp around an accent colour.
17
+ *
18
+ * Fluent ramps run dark → light: light themes tint surfaces with the high
19
+ * shades and dark themes lift foregrounds with them. The accent is anchored
20
+ * at shade 80, which the light theme uses for primary buttons, links and
21
+ * focus, so those stay exactly the colour that was configured. Each step is
22
+ * 7 points of lightness, clamped to 5–96.
23
+ */
24
+ export function brandRamp(accent?: string | null): BrandRamp {
25
+ const [h, s, l] = hexToHsl(normalizeAccent(accent, DEFAULT_ACCENT));
26
+ const ramp = {} as BrandRamp;
27
+ BRAND_SHADES.forEach((shade, i) => {
28
+ const lightness = Math.max(5, Math.min(96, l + (i - 7) * 7));
29
+ ramp[shade] = hslToHex(h, s, lightness);
30
+ });
31
+ return ramp;
32
+ }