@m3ui-vue/m3ui-vue 1.0.1 → 1.0.2

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,49 @@
1
+ import { THEME_KEY } from './useTheme'
2
+ import { CONTRAST_KEY, CSS_KEY, PALETTE_KEY, STYLE_ID, type ContrastLevel } from './useColorPalette'
3
+
4
+ export interface ThemeInitOptions {
5
+ /** `createM3UI`'s `palette`: the first-visit default, or forced with `persistPalette: false`. */
6
+ palette?: string
7
+ /** `createM3UI`'s `contrast`, with the same rules as `palette`. */
8
+ contrast?: ContrastLevel
9
+ /** `createM3UI`'s `persistPalette`. */
10
+ persistPalette?: boolean
11
+ }
12
+
13
+ /**
14
+ * A script to inline in `<head>` of a server-rendered page (Nuxt, Vite SSR), so dark mode, the palette and the
15
+ * contrast level are on `<html>` before the first paint instead of when the app's JS loads. It does what
16
+ * `useTheme` and `useColorPalette` do when they load in the browser (the stored choice, or the given
17
+ * `createM3UI` defaults), so pass it the same options as the plugin. A `seed` default can't be generated this
18
+ * early: its first visit still shows the baseline until the app loads (later visits use the cached CSS).
19
+ *
20
+ * ```ts
21
+ * useHead({ script: [{ innerHTML: themeInitScript({ palette: 'red' }) }] })
22
+ * ```
23
+ */
24
+ export function themeInitScript(options: ThemeInitOptions = {}): string {
25
+ const config = JSON.stringify({
26
+ keys: { theme: THEME_KEY, palette: PALETTE_KEY, contrast: CONTRAST_KEY, css: CSS_KEY },
27
+ styleId: STYLE_ID,
28
+ palette: options.palette ?? null,
29
+ contrast: options.contrast ?? null,
30
+ force: options.persistPalette === false,
31
+ }).replace(/</g, '\\u003c')
32
+ // Plain ES5, no dependencies: it runs before anything else. Storage can throw (blocked site data).
33
+ return `(function(o){
34
+ var d=document.documentElement;
35
+ function get(k){try{return localStorage.getItem(k)}catch(e){return null}}
36
+ function mq(q){return !!(window.matchMedia&&window.matchMedia(q).matches)}
37
+ var t=get(o.keys.theme)||'system';
38
+ d.classList.toggle('dark',t==='dark'||(t==='system'&&mq('(prefers-color-scheme: dark)')));
39
+ var saved=get(o.keys.palette);
40
+ var p=o.force&&o.palette?o.palette:(saved||o.palette);
41
+ if(p&&p===saved){try{var c=JSON.parse(get(o.keys.css));if(c&&c.id===p){var s=document.createElement('style');s.id=o.styleId;s.textContent=c.css;document.head.appendChild(s)}}catch(e){}}
42
+ if(p&&p!=='purple')d.setAttribute('data-palette',p);
43
+ var levels=['standard','medium','high','system'];
44
+ var stored=get(o.keys.contrast);
45
+ var l=o.force&&o.contrast?o.contrast:stored!=null?(levels.indexOf(stored)>-1?stored:'standard'):(o.contrast||'standard');
46
+ if(l==='system')l=mq('(prefers-contrast: more)')?'high':'standard';
47
+ if(l!=='standard')d.setAttribute('data-contrast',l);
48
+ })(${config})`
49
+ }
@@ -65,11 +65,11 @@ export interface ActiveSeed extends SeedOptions {
65
65
  seed: string
66
66
  }
67
67
 
68
- const PALETTE_KEY = 'm3-palette'
68
+ export const PALETTE_KEY = 'm3-palette'
69
69
  const SEED_KEY = 'm3-seed'
70
- const CONTRAST_KEY = 'm3-contrast'
70
+ export const CONTRAST_KEY = 'm3-contrast'
71
71
  // The generated CSS of the active palette, so a reload applies it before the generator has loaded
72
- const CSS_KEY = 'm3-palette-css'
72
+ export const CSS_KEY = 'm3-palette-css'
73
73
 
74
74
  function read<T>(key: string): T | null {
75
75
  try {
@@ -126,6 +126,7 @@ function applyContrast(level: Exclude<ContrastLevel, 'system'>) {
126
126
  const persistEnabled = ref(true)
127
127
 
128
128
  function applyAttribute(id: string) {
129
+ if (typeof document === 'undefined') return
129
130
  if (id === 'purple') document.documentElement.removeAttribute('data-palette')
130
131
  else document.documentElement.setAttribute('data-palette', id)
131
132
  }
@@ -134,9 +135,10 @@ function applyAttribute(id: string) {
134
135
  // One <style> element holds the generated CSS of the active palette (a seed, or a custom palette
135
136
  // without CSS of its own).
136
137
 
137
- const STYLE_ID = 'm3-dynamic-palette'
138
+ export const STYLE_ID = 'm3-dynamic-palette'
138
139
 
139
140
  function injectCss(css: string) {
141
+ if (typeof document === 'undefined') return
140
142
  let el = document.getElementById(STYLE_ID) as HTMLStyleElement | null
141
143
  if (!el) {
142
144
  el = document.createElement('style')
@@ -148,6 +150,7 @@ function injectCss(css: string) {
148
150
 
149
151
  /** Whether a stylesheet (other than our generated one) already styles `[data-palette='<id>']`. */
150
152
  function hasPaletteCss(id: string): boolean {
153
+ if (typeof document === 'undefined') return false
151
154
  const needles = [`[data-palette="${id}"]`, `[data-palette='${id}']`, `[data-palette=${id}]`]
152
155
  const scan = (rules: CSSRuleList): boolean => {
153
156
  for (const rule of Array.from(rules)) {
@@ -289,8 +292,9 @@ export function useColorPalette() {
289
292
  }
290
293
  }
291
294
 
292
- // Apply on module load so the palette is visible before any component mounts, a generated one included
293
- {
295
+ // Apply on module load so the palette is visible before any component mounts, a generated one included (not on
296
+ // the server: the client does it when the module loads there)
297
+ if (typeof document !== 'undefined') {
294
298
  const saved = read<string>(PALETTE_KEY)
295
299
  const cached = read<{ id: string; css: string }>(CSS_KEY)
296
300
  if (saved && cached && cached.id === saved) injectCss(cached.css)
@@ -3,7 +3,12 @@ import { themeTransition } from './_themeTransition'
3
3
 
4
4
  export type Theme = 'light' | 'dark' | 'system'
5
5
 
6
- const theme = ref<Theme>((localStorage.getItem('m3-theme') as Theme) ?? 'system')
6
+ export const THEME_KEY = 'm3-theme'
7
+
8
+ // No DOM on the server (SSR): nothing is read or applied there, the client does it when the module loads.
9
+ const inBrowser = typeof window !== 'undefined'
10
+
11
+ const theme = ref<Theme>((inBrowser ? localStorage.getItem(THEME_KEY) as Theme : null) ?? 'system')
7
12
 
8
13
  let _appliedDark: boolean | null = null
9
14
 
@@ -20,22 +25,23 @@ function applyTheme(t: Theme) {
20
25
  }
21
26
 
22
27
  // Apply immediately on module load (before any component mounts) — no animation
23
- applyTheme(theme.value)
28
+ if (inBrowser) applyTheme(theme.value)
24
29
 
25
30
  export function useTheme() {
26
- const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
31
+ const mediaQuery = inBrowser ? window.matchMedia('(prefers-color-scheme: dark)') : null
27
32
 
28
33
  function onSystemChange() {
29
34
  if (theme.value === 'system') applyTheme('system')
30
35
  }
31
36
 
32
37
  watchEffect(() => {
33
- localStorage.setItem('m3-theme', theme.value)
38
+ if (!inBrowser) return
39
+ localStorage.setItem(THEME_KEY, theme.value)
34
40
  applyTheme(theme.value)
35
41
  })
36
42
 
37
- onMounted(() => mediaQuery.addEventListener('change', onSystemChange))
38
- onUnmounted(() => mediaQuery.removeEventListener('change', onSystemChange))
43
+ onMounted(() => mediaQuery?.addEventListener('change', onSystemChange))
44
+ onUnmounted(() => mediaQuery?.removeEventListener('change', onSystemChange))
39
45
 
40
46
  function cycle() {
41
47
  const order: Theme[] = ['light', 'dark', 'system']
@@ -1,4 +1,5 @@
1
1
  import { computed, onMounted, onUnmounted, ref, toValue, watch, type MaybeRefOrGetter, type Ref } from 'vue'
2
+ import { isHydrating } from './_hydration'
2
3
 
3
4
  /*
4
5
  * M3 window size classes, with the breakpoints from androidx `WindowSizeClass`
@@ -48,10 +49,19 @@ function updateWindow() {
48
49
  export function useWindowSizeClass(target?: MaybeRefOrGetter<HTMLElement | null | undefined>): WindowSizeClassInfo {
49
50
  let width: Ref<number>
50
51
  let height: Ref<number>
52
+ // Hydrating server-rendered HTML: start from the server's size (none, so compact) to match it, then measure
53
+ const hydrating = isHydrating()
51
54
 
52
55
  if (target === undefined) {
53
- width = winWidth
54
- height = winHeight
56
+ if (hydrating) {
57
+ const mounted = ref(false)
58
+ onMounted(() => { mounted.value = true })
59
+ width = computed(() => (mounted.value ? winWidth.value : 0)) as Ref<number>
60
+ height = computed(() => (mounted.value ? winHeight.value : 0)) as Ref<number>
61
+ } else {
62
+ width = winWidth
63
+ height = winHeight
64
+ }
55
65
  onMounted(() => {
56
66
  if (winListeners++ === 0) {
57
67
  updateWindow()
@@ -63,8 +73,8 @@ export function useWindowSizeClass(target?: MaybeRefOrGetter<HTMLElement | null
63
73
  })
64
74
  } else {
65
75
  // Until the element is measured, guess from the window so the first paint is usually right.
66
- width = ref(winWidth.value)
67
- height = ref(winHeight.value)
76
+ width = ref(hydrating ? 0 : winWidth.value)
77
+ height = ref(hydrating ? 0 : winHeight.value)
68
78
  let observer: ResizeObserver | undefined
69
79
  const observe = (el: HTMLElement | null | undefined) => {
70
80
  observer?.disconnect()
package/src/index.ts CHANGED
@@ -8,6 +8,8 @@ export type { Theme } from './composables/useTheme'
8
8
  export { useColorPalette, palettes } from './composables/useColorPalette'
9
9
  export type { Palette, ActiveSeed, ContrastLevel } from './composables/useColorPalette'
10
10
  export { SEED_PALETTE } from './composables/useColorPalette'
11
+ export { themeInitScript } from './composables/themeInitScript'
12
+ export type { ThemeInitOptions } from './composables/themeInitScript'
11
13
  export { generateScheme, schemeToCss, schemeRoles } from './composables/dynamicColor'
12
14
  export type { SchemeVariant, SeedOptions, GeneratedScheme } from './composables/dynamicColor'
13
15
  export { useToast } from './composables/useToast'
package/src/plugin.ts CHANGED
@@ -7,6 +7,7 @@ import { syncThemeColor } from './composables/_themeColor'
7
7
  import type { M3Locale } from './composables/useLocale'
8
8
  import { M3_LOCALE_KEY, __setAppLocale } from './composables/useLocale'
9
9
  import { vRipple } from './directives/vRipple'
10
+ import { M3_HYDRATING_KEY } from './composables/_hydration'
10
11
 
11
12
  export interface M3UIOptions {
12
13
  palette?: string
@@ -50,29 +51,41 @@ export interface M3UIOptions {
50
51
  * mode (they keep their own dark bar); installed apps (PWA) still get it.
51
52
  */
52
53
  themeColor?: 'surface' | 'surface-container' | 'primary' | (string & {})
54
+ /**
55
+ * Server-side rendering: tells the components whether the app is still hydrating the server's HTML (Nuxt's
56
+ * `() => nuxtApp.isHydrating`, which `@m3ui-vue/nuxt` passes). The adaptive layouts (`MNavigationSuite`,
57
+ * `MListDetail`, `MSupportingPane`) and `useWindowSizeClass()` then render their first frame at the server's size
58
+ * (compact: it has no window) so it matches the HTML, and adapt once mounted.
59
+ */
60
+ isHydrating?: () => boolean
53
61
  }
54
62
 
55
63
  export function createM3UI(options: M3UIOptions = {}) {
56
64
  return {
57
65
  install(app: App) {
58
66
  app.directive('ripple', vRipple)
67
+ if (options.isHydrating) app.provide(M3_HYDRATING_KEY, options.isHydrating)
59
68
  for (const custom of options.customPalettes ?? []) {
60
69
  const i = palettes.findIndex((p) => p.id === custom.id)
61
70
  if (i === -1) palettes.push(custom)
62
71
  else palettes[i] = custom
63
72
  }
64
- if (options.persistPalette === false) {
65
- if (options.palette) __forcePalette(options.palette, false)
66
- else if (options.seed) void __defaultSeed(options.seed, options.seedOptions, false)
67
- } else if (!localStorage.getItem('m3-palette')) {
68
- // `palette`/`seed` are only the first-visit default — once the user picks a palette via
69
- // `useColorPalette().set()` (or a seed via `setSeed()`) it's persisted to localStorage, and that choice
70
- // must win on every later boot instead of being clobbered back to the plugin's static default.
71
- if (options.palette && options.palette !== 'purple') __defaultPalette(options.palette)
72
- else if (!options.palette && options.seed) void __defaultSeed(options.seed, options.seedOptions, true)
73
+ // Palette, seed, contrast and theme-color live on the page and in localStorage: on the server (SSR) there's
74
+ // neither, and the client applies them when it installs the plugin
75
+ if (typeof window !== 'undefined') {
76
+ if (options.persistPalette === false) {
77
+ if (options.palette) __forcePalette(options.palette, false)
78
+ else if (options.seed) void __defaultSeed(options.seed, options.seedOptions, false)
79
+ } else if (!localStorage.getItem('m3-palette')) {
80
+ // `palette`/`seed` are only the first-visit default — once the user picks a palette via
81
+ // `useColorPalette().set()` (or a seed via `setSeed()`) it's persisted to localStorage, and that choice
82
+ // must win on every later boot instead of being clobbered back to the plugin's static default.
83
+ if (options.palette && options.palette !== 'purple') __defaultPalette(options.palette)
84
+ else if (!options.palette && options.seed) void __defaultSeed(options.seed, options.seedOptions, true)
85
+ }
86
+ if (options.contrast) __defaultContrast(options.contrast, options.persistPalette !== false)
87
+ if (options.themeColor) syncThemeColor(options.themeColor)
73
88
  }
74
- if (options.contrast) __defaultContrast(options.contrast, options.persistPalette !== false)
75
- if (options.themeColor) syncThemeColor(options.themeColor)
76
89
  if (options.locale) {
77
90
  app.provide(M3_LOCALE_KEY, options.locale)
78
91
  __setAppLocale(options.locale)