@nyxwire/astro 0.0.0-stage → 0.1.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.
@@ -0,0 +1,164 @@
1
+ ---
2
+ import { flavorMeta, flavorNames } from '@nyxwire/palette'
3
+
4
+ interface Props {
5
+ /** Accessible name of the group. */
6
+ label?: string
7
+ class?: string
8
+ }
9
+
10
+ const { label = 'Color flavor', class: className } = Astro.props
11
+ ---
12
+
13
+ <nw-flavor-select class={className}>
14
+ <div class="nw-flavor-select" role="group" aria-label={label}>
15
+ {
16
+ (['auto', ...flavorNames] as const).map((id, index) => (
17
+ <button
18
+ type="button"
19
+ class="nw-flavor-option"
20
+ data-nw-flavor-option={id}
21
+ aria-pressed="false"
22
+ tabindex={index === 0 ? 0 : -1}
23
+ title={id === 'auto' ? 'Follow system appearance' : flavorMeta[id].mood}
24
+ disabled
25
+ >
26
+ {id === 'auto' ? 'Auto' : flavorMeta[id].label}
27
+ </button>
28
+ ))
29
+ }
30
+ </div>
31
+ </nw-flavor-select>
32
+
33
+ <script>
34
+ import { FLAVOR_CHANGE_EVENT, isFlavorPreference } from '../../dist/index.js'
35
+
36
+ class NwFlavorSelect extends HTMLElement {
37
+ private get buttons(): HTMLButtonElement[] {
38
+ return [...this.querySelectorAll<HTMLButtonElement>('button[data-nw-flavor-option]')]
39
+ }
40
+
41
+ private readonly sync = (): void => {
42
+ const runtime = window.nyxwire
43
+ if (!runtime) return
44
+ const current = runtime.getFlavor()
45
+ const buttons = this.buttons
46
+ const active = buttons.find((button) => button.dataset.nwFlavorOption === current) ?? buttons[0]
47
+ for (const button of buttons) {
48
+ button.setAttribute('aria-pressed', String(button.dataset.nwFlavorOption === current))
49
+ button.tabIndex = button === active ? 0 : -1
50
+ button.disabled = false
51
+ }
52
+ }
53
+
54
+ private select(button: HTMLButtonElement): void {
55
+ const flavor = button.dataset.nwFlavorOption
56
+ if (isFlavorPreference(flavor)) window.nyxwire?.setFlavor(flavor)
57
+ }
58
+
59
+ private readonly click = (event: MouseEvent): void => {
60
+ const button = event.target instanceof Element
61
+ ? event.target.closest<HTMLButtonElement>('button[data-nw-flavor-option]')
62
+ : null
63
+ if (button) this.select(button)
64
+ }
65
+
66
+ private readonly keydown = (event: KeyboardEvent): void => {
67
+ const buttons = this.buttons
68
+ if (!(event.target instanceof HTMLButtonElement)) return
69
+ const index = buttons.indexOf(event.target)
70
+ if (index === -1) return
71
+ const last = buttons.length - 1
72
+ const directions: Readonly<Record<string, number>> = {
73
+ ArrowRight: index === last ? 0 : index + 1,
74
+ ArrowDown: index === last ? 0 : index + 1,
75
+ ArrowLeft: index === 0 ? last : index - 1,
76
+ ArrowUp: index === 0 ? last : index - 1,
77
+ Home: 0,
78
+ End: last,
79
+ }
80
+ const next = directions[event.key]
81
+ const target = next === undefined ? undefined : buttons[next]
82
+ if (!target) return
83
+ event.preventDefault()
84
+ this.select(target)
85
+ target.focus()
86
+ }
87
+
88
+ connectedCallback(): void {
89
+ this.addEventListener('click', this.click)
90
+ this.addEventListener('keydown', this.keydown)
91
+ document.addEventListener(FLAVOR_CHANGE_EVENT, this.sync)
92
+ this.sync()
93
+ }
94
+
95
+ disconnectedCallback(): void {
96
+ this.removeEventListener('click', this.click)
97
+ this.removeEventListener('keydown', this.keydown)
98
+ document.removeEventListener(FLAVOR_CHANGE_EVENT, this.sync)
99
+ }
100
+ }
101
+
102
+ if (!customElements.get('nw-flavor-select')) customElements.define('nw-flavor-select', NwFlavorSelect)
103
+ </script>
104
+
105
+ <style>
106
+ nw-flavor-select {
107
+ display: inline-block;
108
+ max-inline-size: 100%;
109
+ }
110
+ .nw-flavor-select {
111
+ display: inline-flex;
112
+ flex-wrap: wrap;
113
+ gap: var(--nw-space-1);
114
+ padding: var(--nw-space-1);
115
+ border: 1px solid var(--nw-line-strong);
116
+ border-radius: var(--nw-radius-md);
117
+ background: var(--nw-canvas-sunken);
118
+ }
119
+ .nw-flavor-option {
120
+ min-block-size: var(--nw-control-sm);
121
+ padding-inline: var(--nw-space-3);
122
+ border: 0;
123
+ border-radius: var(--nw-radius-sm);
124
+ background: transparent;
125
+ color: var(--nw-fg-muted);
126
+ font: inherit;
127
+ font-size: var(--nw-text-sm);
128
+ cursor: pointer;
129
+ transition:
130
+ background-color var(--nw-duration-fast) var(--nw-ease-standard),
131
+ color var(--nw-duration-fast) var(--nw-ease-standard);
132
+ }
133
+ .nw-flavor-option:disabled {
134
+ cursor: default;
135
+ }
136
+ .nw-flavor-option:enabled:hover {
137
+ background: var(--nw-panel-hover);
138
+ color: var(--nw-fg);
139
+ }
140
+ .nw-flavor-option:focus-visible {
141
+ outline: var(--nw-ring-width) solid var(--nw-ring);
142
+ outline-offset: var(--nw-ring-offset);
143
+ }
144
+ /* The html attribute is set before paint, so the active option is correct before this component hydrates. */
145
+ .nw-flavor-option[aria-pressed='true'],
146
+ :global(:root[data-nw-flavor-preference='auto']) .nw-flavor-option[data-nw-flavor-option='auto'],
147
+ :global(:root[data-nw-flavor-preference='abyss']) .nw-flavor-option[data-nw-flavor-option='abyss'],
148
+ :global(:root[data-nw-flavor-preference='nocturne']) .nw-flavor-option[data-nw-flavor-option='nocturne'],
149
+ :global(:root[data-nw-flavor-preference='twilight']) .nw-flavor-option[data-nw-flavor-option='twilight'],
150
+ :global(:root[data-nw-flavor-preference='lumen']) .nw-flavor-option[data-nw-flavor-option='lumen'] {
151
+ background: var(--nw-primary);
152
+ color: var(--nw-on-primary);
153
+ }
154
+ @media (prefers-reduced-motion: reduce) {
155
+ .nw-flavor-option {
156
+ transition: none;
157
+ }
158
+ }
159
+ @media (forced-colors: active) {
160
+ .nw-flavor-option[aria-pressed='true'] {
161
+ outline: 2px solid ButtonText;
162
+ }
163
+ }
164
+ </style>
@@ -0,0 +1,57 @@
1
+ ---
2
+ import { defaultFlavor, flavorMeta, palette } from '@nyxwire/palette'
3
+ import type { AccentName, FlavorName } from '@nyxwire/palette'
4
+
5
+ interface Props {
6
+ title?: string
7
+ description?: string
8
+ lang?: string
9
+ /** Server-rendered flavor, used until the flavor script resolves the visitor's choice (and without JS). */
10
+ flavor?: FlavorName
11
+ accent?: AccentName
12
+ class?: string
13
+ }
14
+
15
+ const {
16
+ title = 'Nyxwire',
17
+ description,
18
+ lang = 'en',
19
+ flavor,
20
+ accent,
21
+ class: className,
22
+ } = Astro.props
23
+ ---
24
+
25
+ <!doctype html>
26
+ <html lang={lang} data-flavor={flavor} data-theme={flavor ? (flavorMeta[flavor].dark ? 'dark' : 'light') : undefined} data-accent={accent}>
27
+ <head>
28
+ <meta charset="utf-8" />
29
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
30
+ <meta name="color-scheme" content="dark light" />
31
+ {flavor ? (
32
+ <meta name="theme-color" content={palette[flavor].base} data-nyxwire-theme-color />
33
+ ) : (
34
+ <>
35
+ <meta name="theme-color" content={palette[defaultFlavor].base} media="(prefers-color-scheme: dark)" data-nyxwire-theme-color />
36
+ <meta name="theme-color" content={palette.lumen.base} media="(prefers-color-scheme: light)" data-nyxwire-theme-color />
37
+ </>
38
+ )}
39
+ <title>{title}</title>
40
+ {description && <meta name="description" content={description} />}
41
+ <slot name="head" />
42
+ </head>
43
+ <body class:list={['nw-body', className]}>
44
+ <slot />
45
+ </body>
46
+ </html>
47
+
48
+ <style>
49
+ .nw-body {
50
+ margin: 0;
51
+ min-block-size: 100vh;
52
+ background: var(--nw-canvas);
53
+ color: var(--nw-fg);
54
+ font-family: var(--nw-font-sans);
55
+ line-height: var(--nw-leading-normal);
56
+ }
57
+ </style>
@@ -0,0 +1,169 @@
1
+ import { accentNames, flavorMeta, palette } from '@nyxwire/palette'
2
+ import type { AccentName, FlavorName } from '@nyxwire/palette'
3
+ import {
4
+ ACCENT_STORAGE_KEY,
5
+ FLAVOR_CHANGE_EVENT,
6
+ FLAVOR_STORAGE_KEY,
7
+ isFlavorPreference,
8
+ normalizeOptions,
9
+ } from './options.ts'
10
+ import type { FlavorConfig, FlavorPreference, NyxwireOptions } from './options.ts'
11
+
12
+ export interface FlavorChangeDetail {
13
+ readonly flavor: FlavorPreference
14
+ readonly resolved: FlavorName
15
+ readonly theme: 'dark' | 'light'
16
+ readonly accent: AccentName | null
17
+ }
18
+
19
+ export interface FlavorController {
20
+ getFlavor(): FlavorPreference
21
+ setFlavor(flavor: FlavorPreference): void
22
+ resolve(): FlavorName
23
+ }
24
+
25
+ export interface NyxwireRuntime extends FlavorController {
26
+ getAccent(): AccentName | null
27
+ /** `null` removes `data-accent`, restoring the palette default. */
28
+ setAccent(accent: AccentName | null): void
29
+ }
30
+
31
+ declare global {
32
+ interface Window {
33
+ nyxwire?: NyxwireRuntime
34
+ }
35
+ interface DocumentEventMap {
36
+ 'nyxwire:flavor': CustomEvent<FlavorChangeDetail>
37
+ }
38
+ }
39
+
40
+ export interface FlavorRuntimeConfig {
41
+ readonly defaultFlavor: FlavorPreference
42
+ readonly accent: AccentName | null
43
+ readonly persist: boolean
44
+ readonly flavors: FlavorConfig['flavors']
45
+ readonly palette: Readonly<Record<FlavorName, { readonly dark: boolean; readonly base: string }>>
46
+ readonly accents: readonly AccentName[]
47
+ readonly flavorKey: string
48
+ readonly accentKey: string
49
+ readonly event: string
50
+ }
51
+
52
+ export function resolveFlavor(
53
+ stored: unknown,
54
+ prefersLight: boolean,
55
+ options: NyxwireOptions = {},
56
+ ): FlavorName {
57
+ const { defaultFlavor, flavors } = normalizeOptions(options)
58
+ const preference = isFlavorPreference(stored) ? stored : defaultFlavor
59
+ return preference === 'auto' ? flavors[prefersLight ? 'light' : 'dark'] : preference
60
+ }
61
+
62
+ // Serialized with Function#toString and inlined in <head>: it must stay self-contained.
63
+ export function flavorRuntime(c: FlavorRuntimeConfig): void {
64
+ const root = document.documentElement
65
+ const media = matchMedia('(prefers-color-scheme: light)')
66
+ const isPreference = (v: unknown): v is FlavorPreference =>
67
+ v === 'auto' || (typeof v === 'string' && Object.hasOwn(c.palette, v))
68
+ const isAccent = (v: unknown): v is AccentName => c.accents.some((a) => a === v)
69
+ // Storage throws a DOMException when disabled (privacy mode, sandboxed frames); the page must still paint.
70
+ const read = (key: string): string | null => {
71
+ if (!c.persist) return null
72
+ try {
73
+ return localStorage.getItem(key)
74
+ } catch (error) {
75
+ if (!(error instanceof DOMException)) throw error
76
+ return null
77
+ }
78
+ }
79
+ const write = (key: string, value: string | null): void => {
80
+ if (!c.persist) return
81
+ try {
82
+ if (value === null) localStorage.removeItem(key)
83
+ else localStorage.setItem(key, value)
84
+ } catch (error) {
85
+ if (!(error instanceof DOMException)) throw error
86
+ }
87
+ }
88
+ const storedFlavor = read(c.flavorKey)
89
+ const storedAccent = read(c.accentKey)
90
+ const rootAccent = root.getAttribute('data-accent')
91
+ let preference = isPreference(storedFlavor) ? storedFlavor : c.defaultFlavor
92
+ let accent = isAccent(storedAccent)
93
+ ? storedAccent
94
+ : (c.accent ?? (isAccent(rootAccent) ? rootAccent : null))
95
+ const resolve = (): FlavorName =>
96
+ preference === 'auto' ? c.flavors[media.matches ? 'light' : 'dark'] : preference
97
+
98
+ const apply = (): void => {
99
+ const resolved = resolve()
100
+ const { dark, base } = c.palette[resolved]
101
+ const theme = dark ? 'dark' : 'light'
102
+ root.setAttribute('data-flavor', resolved)
103
+ root.setAttribute('data-nw-flavor-preference', preference)
104
+ root.setAttribute('data-theme', theme)
105
+ root.style.colorScheme = theme
106
+ for (const meta of document.querySelectorAll('meta[data-nyxwire-theme-color]')) {
107
+ meta.setAttribute('content', base)
108
+ meta.removeAttribute('media')
109
+ }
110
+ document.dispatchEvent(
111
+ new CustomEvent(c.event, { detail: { flavor: preference, resolved, theme, accent } }),
112
+ )
113
+ }
114
+
115
+ if (accent !== null) root.setAttribute('data-accent', accent)
116
+ window.nyxwire = {
117
+ getFlavor: () => preference,
118
+ resolve,
119
+ setFlavor(next) {
120
+ if (!isPreference(next)) {
121
+ throw new TypeError(
122
+ `Nyxwire: unknown flavor "${String(next)}" (expected auto or ${Object.keys(c.palette).join(', ')}).`,
123
+ )
124
+ }
125
+ preference = next
126
+ write(c.flavorKey, next)
127
+ apply()
128
+ },
129
+ getAccent: () => accent,
130
+ setAccent(next) {
131
+ if (next !== null && !isAccent(next)) {
132
+ throw new TypeError(
133
+ `Nyxwire: unknown accent "${String(next)}" (expected ${c.accents.join(', ')}).`,
134
+ )
135
+ }
136
+ accent = next
137
+ write(c.accentKey, next)
138
+ if (next === null) root.removeAttribute('data-accent')
139
+ else root.setAttribute('data-accent', next)
140
+ apply()
141
+ },
142
+ }
143
+ media.addEventListener('change', () => {
144
+ if (preference === 'auto') apply()
145
+ })
146
+ document.addEventListener('DOMContentLoaded', apply, { once: true })
147
+ apply()
148
+ }
149
+
150
+ export function buildFlavorScript(options: NyxwireOptions = {}): string {
151
+ const { defaultFlavor, flavors, accent, persist } = normalizeOptions(options)
152
+ const config: FlavorRuntimeConfig = {
153
+ defaultFlavor,
154
+ accent,
155
+ persist,
156
+ flavors,
157
+ palette: {
158
+ abyss: { dark: flavorMeta.abyss.dark, base: palette.abyss.base },
159
+ nocturne: { dark: flavorMeta.nocturne.dark, base: palette.nocturne.base },
160
+ twilight: { dark: flavorMeta.twilight.dark, base: palette.twilight.base },
161
+ lumen: { dark: flavorMeta.lumen.dark, base: palette.lumen.base },
162
+ },
163
+ accents: accentNames,
164
+ flavorKey: FLAVOR_STORAGE_KEY,
165
+ accentKey: ACCENT_STORAGE_KEY,
166
+ event: FLAVOR_CHANGE_EVENT,
167
+ }
168
+ return `(${flavorRuntime.toString()})(${JSON.stringify(config).replace(/</g, '\\u003c')});`
169
+ }
package/src/index.ts ADDED
@@ -0,0 +1,27 @@
1
+ import type { AstroIntegration } from 'astro'
2
+ import { buildFlavorScript } from './flavor-script.ts'
3
+ import { normalizeOptions } from './options.ts'
4
+ import type { NyxwireOptions } from './options.ts'
5
+
6
+ export * from './flavor-script.ts'
7
+ export * from './options.ts'
8
+ export type { AccentName, DarkFlavorName, FlavorName } from '@nyxwire/palette'
9
+
10
+ const stylesheet = {
11
+ full: 'import "@nyxwire/css";',
12
+ tokens: 'import "@nyxwire/css/tokens.css";\nimport "@nyxwire/css/fonts.css";',
13
+ } as const
14
+
15
+ export default function nyxwire(options: NyxwireOptions = {}): AstroIntegration {
16
+ const config = normalizeOptions(options)
17
+ const script = buildFlavorScript(options)
18
+ return {
19
+ name: '@nyxwire/astro',
20
+ hooks: {
21
+ 'astro:config:setup': ({ injectScript }) => {
22
+ injectScript('head-inline', script)
23
+ if (config.styles !== false) injectScript('page-ssr', stylesheet[config.styles])
24
+ },
25
+ },
26
+ }
27
+ }
package/src/options.ts ADDED
@@ -0,0 +1,131 @@
1
+ import { accentNames, defaultFlavor as paletteDefaultFlavor, flavorNames } from '@nyxwire/palette'
2
+ import type { AccentName, DarkFlavorName, FlavorName } from '@nyxwire/palette'
3
+
4
+ export type FlavorPreference = 'auto' | FlavorName
5
+ export type StyleMode = 'full' | 'tokens' | false
6
+
7
+ export interface NyxwireOptions {
8
+ readonly flavors?: { readonly dark?: DarkFlavorName; readonly light?: 'lumen' }
9
+ /** Preference used when no valid flavor is stored. */
10
+ readonly defaultFlavor?: FlavorPreference
11
+ /** Accent applied as `data-accent` on `<html>`; omit to keep the palette default (indigo). */
12
+ readonly accent?: AccentName
13
+ /** Remember the visitor's flavor and accent in localStorage. */
14
+ readonly persist?: boolean
15
+ readonly styles?: StyleMode
16
+ /** Existing on/off switch; use `styles` to select tokens alone. */
17
+ readonly css?: boolean
18
+ }
19
+
20
+ export interface NyxwireConfig {
21
+ readonly flavors: { readonly dark: DarkFlavorName; readonly light: 'lumen' }
22
+ readonly defaultFlavor: FlavorPreference
23
+ readonly accent: AccentName | null
24
+ readonly persist: boolean
25
+ readonly css: boolean
26
+ readonly styles: StyleMode
27
+ }
28
+
29
+ export type FlavorConfig = NyxwireConfig
30
+
31
+ export const FLAVOR_STORAGE_KEY = 'nyxwire-flavor'
32
+ export const ACCENT_STORAGE_KEY = 'nyxwire-accent'
33
+ export const FLAVOR_CHANGE_EVENT = 'nyxwire:flavor'
34
+ export const FLAVOR_EVENT = FLAVOR_CHANGE_EVENT
35
+ export const flavorIds: readonly FlavorName[] = flavorNames
36
+ export const FLAVOR_IDS = flavorIds
37
+ export const darkFlavorIds: readonly DarkFlavorName[] = flavorIds.filter((id) => id !== 'lumen')
38
+
39
+ const optionNames = ['flavors', 'defaultFlavor', 'accent', 'persist', 'styles', 'css'] as const
40
+
41
+ export class NyxwireOptionsError extends TypeError {
42
+ readonly option: string
43
+ readonly expected: string
44
+
45
+ constructor(option: string, expected: string, received: unknown) {
46
+ super(`@nyxwire/astro: ${option} must be ${expected}; received ${describe(received)}.`)
47
+ this.name = 'NyxwireOptionsError'
48
+ this.option = option
49
+ this.expected = expected
50
+ }
51
+ }
52
+
53
+ function describe(value: unknown): string {
54
+ if (value === null) return 'null'
55
+ if (Array.isArray(value)) return 'an array'
56
+ if (typeof value === 'string') return JSON.stringify(value)
57
+ if (typeof value === 'object') return 'an object'
58
+ return String(value)
59
+ }
60
+
61
+ const oneOf = (values: readonly string[]) => `one of ${values.map((v) => `"${v}"`).join(', ')}`
62
+
63
+ export function isFlavorName(value: unknown): value is FlavorName {
64
+ return flavorNames.some((name) => name === value)
65
+ }
66
+
67
+ export function isAccentName(value: unknown): value is AccentName {
68
+ return accentNames.some((name) => name === value)
69
+ }
70
+
71
+ export function isFlavorPreference(value: unknown): value is FlavorPreference {
72
+ return value === 'auto' || isFlavorName(value)
73
+ }
74
+
75
+ function record(value: unknown, name: string): Readonly<Record<string, unknown>> {
76
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
77
+ throw new NyxwireOptionsError(name, 'an object', value)
78
+ }
79
+ return Object.fromEntries(Object.entries(value))
80
+ }
81
+
82
+ export function normalizeOptions(options: unknown = {}): NyxwireConfig {
83
+ const input = record(options, 'options')
84
+ for (const key of Object.keys(input)) {
85
+ if (!optionNames.some((name) => name === key)) {
86
+ throw new NyxwireOptionsError(
87
+ `option "${key}"`,
88
+ `a known option (${optionNames.join(', ')})`,
89
+ key,
90
+ )
91
+ }
92
+ }
93
+
94
+ const variants = input['flavors'] === undefined ? {} : record(input['flavors'], 'flavors')
95
+ for (const key of Object.keys(variants)) {
96
+ if (key !== 'dark' && key !== 'light') {
97
+ throw new NyxwireOptionsError(`flavors.${key}`, 'dark or light', key)
98
+ }
99
+ }
100
+ const dark = variants['dark'] === undefined ? paletteDefaultFlavor : variants['dark']
101
+ if (!isFlavorName(dark) || dark === 'lumen') {
102
+ throw new NyxwireOptionsError('flavors.dark', oneOf(darkFlavorIds), dark)
103
+ }
104
+ const light = variants['light'] === undefined ? 'lumen' : variants['light']
105
+ if (light !== 'lumen') throw new NyxwireOptionsError('flavors.light', '"lumen"', light)
106
+ const defaultFlavor = input['defaultFlavor'] === undefined ? 'auto' : input['defaultFlavor']
107
+ if (!isFlavorPreference(defaultFlavor)) {
108
+ throw new NyxwireOptionsError('defaultFlavor', oneOf(['auto', ...flavorIds]), defaultFlavor)
109
+ }
110
+ const accent = input['accent']
111
+ if (accent !== undefined && !isAccentName(accent)) {
112
+ throw new NyxwireOptionsError('accent', oneOf(accentNames), accent)
113
+ }
114
+ const persist = input['persist'] === undefined ? true : input['persist']
115
+ if (typeof persist !== 'boolean') throw new NyxwireOptionsError('persist', 'a boolean', persist)
116
+ const css = input['css'] === undefined ? true : input['css']
117
+ if (typeof css !== 'boolean') throw new NyxwireOptionsError('css', 'a boolean', css)
118
+ const styles = input['styles'] === undefined ? (css ? 'full' : false) : input['styles']
119
+ if (styles !== 'full' && styles !== 'tokens' && styles !== false) {
120
+ throw new NyxwireOptionsError('styles', '"full", "tokens", or false', styles)
121
+ }
122
+
123
+ return {
124
+ flavors: { dark, light },
125
+ defaultFlavor,
126
+ accent: accent ?? null,
127
+ persist,
128
+ css: styles !== false,
129
+ styles,
130
+ }
131
+ }