@m3ui-vue/m3ui-vue 0.9.1 → 0.9.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.
Files changed (86) hide show
  1. package/README.md +41 -0
  2. package/dist/API.md +199 -54
  3. package/dist/{MTextField-pJU1vFaR.js → MTextField-Ck0oWDMk.js} +8 -2
  4. package/dist/MTextField-Ck0oWDMk.js.map +1 -0
  5. package/dist/api.json +1 -1
  6. package/dist/code-editor.js +1 -1
  7. package/dist/components/MBox.vue.d.ts +3 -3
  8. package/dist/components/MColorPicker.vue.d.ts +13 -1
  9. package/dist/components/MColorPickerModal.vue.d.ts +14 -2
  10. package/dist/components/MDragHandle.vue.d.ts +12 -0
  11. package/dist/components/MEmojiSelector.vue.d.ts +1 -1
  12. package/dist/components/MFab.vue.d.ts +1 -1
  13. package/dist/components/MFabMenu.vue.d.ts +1 -1
  14. package/dist/components/MListItem.vue.d.ts +5 -5
  15. package/dist/components/MOverlay.vue.d.ts +1 -1
  16. package/dist/components/MScrollField.vue.d.ts +40 -0
  17. package/dist/components/MScrollable.vue.d.ts +9 -0
  18. package/dist/components/MSplitter.vue.d.ts +2 -2
  19. package/dist/components/MSwipeToDismiss.vue.d.ts +49 -0
  20. package/dist/components/MTransition.vue.d.ts +34 -0
  21. package/dist/components/MWindow.vue.d.ts +1 -1
  22. package/dist/components/_MColorPanel.vue.d.ts +18 -0
  23. package/dist/composables/_colorUtils.d.ts +34 -0
  24. package/dist/composables/_themeColor.d.ts +1 -0
  25. package/dist/composables/_useSpring.d.ts +15 -0
  26. package/dist/composables/dynamicColor.d.ts +18 -0
  27. package/dist/composables/useColorPalette.d.ts +27 -0
  28. package/dist/composables/useLocale.d.ts +10 -0
  29. package/dist/index.d.ts +9 -1
  30. package/dist/locales/index.js +70 -0
  31. package/dist/locales/index.js.map +1 -1
  32. package/dist/m3ui-vue.css +1 -1
  33. package/dist/m3ui.js +4808 -3622
  34. package/dist/m3ui.js.map +1 -1
  35. package/dist/material-color-utilities-Cktu8DBU.js +3160 -0
  36. package/dist/material-color-utilities-Cktu8DBU.js.map +1 -0
  37. package/dist/plugin.d.ts +18 -0
  38. package/dist/rich-text-editor.js +2 -2
  39. package/dist/styles/palettes.css +546 -0
  40. package/dist/styles/theme.css +77 -0
  41. package/dist/styles.css +1 -1
  42. package/dist/{useLocale-Drihe5G2.js → useLocale-CFW8cIzL.js} +11 -1
  43. package/dist/useLocale-CFW8cIzL.js.map +1 -0
  44. package/package.json +2 -1
  45. package/src/__tests__/MButtonGroup.test.ts +51 -0
  46. package/src/__tests__/MColorPicker.test.ts +141 -0
  47. package/src/__tests__/MDragHandle.test.ts +57 -0
  48. package/src/__tests__/MListItemShape.test.ts +76 -0
  49. package/src/__tests__/MScrollField.test.ts +41 -0
  50. package/src/__tests__/MScrollable.test.ts +42 -0
  51. package/src/__tests__/MSwipeToDismiss.test.ts +104 -0
  52. package/src/__tests__/MTransition.test.ts +27 -0
  53. package/src/__tests__/dynamicColor.test.ts +191 -0
  54. package/src/components/MBox.vue +4 -2
  55. package/src/components/MButtonGroup.vue +116 -35
  56. package/src/components/MColorPicker.vue +114 -210
  57. package/src/components/MColorPickerModal.vue +50 -251
  58. package/src/components/MDragHandle.vue +54 -0
  59. package/src/components/MList.vue +33 -3
  60. package/src/components/MListItem.vue +75 -5
  61. package/src/components/MScrollField.vue +302 -0
  62. package/src/components/MScrollable.vue +160 -5
  63. package/src/components/MSplitter.vue +33 -10
  64. package/src/components/MSwipeToDismiss.vue +247 -0
  65. package/src/components/MTransition.vue +149 -0
  66. package/src/components/_MColorPanel.vue +478 -0
  67. package/src/composables/_colorUtils.ts +107 -0
  68. package/src/composables/_themeColor.ts +33 -0
  69. package/src/composables/_useSpring.ts +89 -0
  70. package/src/composables/dynamicColor.ts +85 -0
  71. package/src/composables/useColorPalette.ts +171 -25
  72. package/src/composables/useFieldBg.ts +6 -0
  73. package/src/composables/useLocale.ts +22 -0
  74. package/src/index.ts +9 -1
  75. package/src/locales/de.ts +10 -0
  76. package/src/locales/es.ts +10 -0
  77. package/src/locales/fr.ts +10 -0
  78. package/src/locales/ja.ts +10 -0
  79. package/src/locales/ko.ts +10 -0
  80. package/src/locales/pt.ts +10 -0
  81. package/src/locales/zh.ts +10 -0
  82. package/src/plugin.ts +28 -7
  83. package/src/styles/palettes.css +546 -0
  84. package/src/styles/theme.css +77 -0
  85. package/dist/MTextField-pJU1vFaR.js.map +0 -1
  86. package/dist/useLocale-Drihe5G2.js.map +0 -1
@@ -0,0 +1,478 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * Internal: the picking UI shared by MColorPicker (in its dropdown) and MColorPickerModal (in its dialog).
4
+ * Saturation/brightness area, hue and opacity sliders, eyedropper, HEX/RGB/HSL fields, recent and preset
5
+ * swatches. Emits on every change; the parent decides when that becomes the real value.
6
+ */
7
+ import { computed, onMounted, ref, watch } from 'vue'
8
+ import MIcon from './MIcon.vue'
9
+ import MIconButton from './MIconButton.vue'
10
+ import { useLocale } from '../composables/useLocale'
11
+ import {
12
+ hslToHsv, hsvToHsl, hsvToRgb, inkFor, normalizeHex, parseHex, recentColors, rgbToHsv, toHex, type Rgba,
13
+ } from '../composables/_colorUtils'
14
+
15
+ const props = defineProps<{
16
+ modelValue: string
17
+ presets: string[]
18
+ alpha: boolean
19
+ recent: boolean
20
+ eyedropper: boolean
21
+ /** Shown as the left half of the preview, click to restore */
22
+ original?: string
23
+ }>()
24
+
25
+ const emit = defineEmits<{ 'update:modelValue': [string] }>()
26
+ const t = useLocale()
27
+
28
+ // ── State: HSV + alpha, kept here so hue survives grays and black ──────────────────────────
29
+ const h = ref(0)
30
+ const s = ref(100)
31
+ const v = ref(100)
32
+ const a = ref(1)
33
+
34
+ const hex = computed(() => toHex(hsvToRgb({ h: h.value, s: s.value, v: v.value }, props.alpha ? a.value : 1)))
35
+ const opaqueHex = computed(() => toHex(hsvToRgb({ h: h.value, s: s.value, v: v.value })))
36
+ const hueColor = computed(() => `hsl(${h.value}, 100%, 50%)`)
37
+
38
+ function setFromRgb(c: Rgba) {
39
+ const hsv = rgbToHsv(c)
40
+ // A gray has no hue and black no saturation: keep the ones we had, so the thumbs don't jump
41
+ if (hsv.v > 0 && hsv.s > 0) h.value = hsv.h
42
+ if (hsv.v > 0) s.value = hsv.s
43
+ v.value = hsv.v
44
+ a.value = props.alpha ? c.a : 1
45
+ }
46
+
47
+ let lastEmitted = ''
48
+ function commit() {
49
+ lastEmitted = hex.value
50
+ if (hex.value !== normalizeHex(props.modelValue)) emit('update:modelValue', hex.value)
51
+ }
52
+
53
+ watch(() => props.modelValue, (val) => {
54
+ const n = normalizeHex(val)
55
+ if (!n || n === lastEmitted) return
56
+ setFromRgb(parseHex(n)!)
57
+ lastEmitted = n
58
+ }, { immediate: true })
59
+
60
+ function pick(color: string) {
61
+ const c = parseHex(color)
62
+ if (!c) return
63
+ setFromRgb(c)
64
+ commit()
65
+ }
66
+
67
+ // ── Pointer: area and sliders ──────────────────────────────────────────────────────────────
68
+ type Target = 'area' | 'hue' | 'alpha'
69
+ const areaEl = ref<HTMLElement>()
70
+ const hueEl = ref<HTMLElement>()
71
+ const alphaEl = ref<HTMLElement>()
72
+ const dragging = ref<Target | null>(null)
73
+ // The slider handles travel between the centers of the track's round ends (24px track)
74
+ const THUMB_INSET = 12
75
+
76
+ const clamp = (n: number, min: number, max: number) => Math.min(max, Math.max(min, n))
77
+
78
+ function update(target: Target, e: PointerEvent) {
79
+ const el = target === 'area' ? areaEl.value : target === 'hue' ? hueEl.value : alphaEl.value
80
+ if (!el) return
81
+ const r = el.getBoundingClientRect()
82
+ if (target === 'area') {
83
+ s.value = clamp(((e.clientX - r.left) / r.width) * 100, 0, 100)
84
+ v.value = clamp((1 - (e.clientY - r.top) / r.height) * 100, 0, 100)
85
+ } else {
86
+ const p = clamp((e.clientX - r.left - THUMB_INSET) / (r.width - THUMB_INSET * 2), 0, 1)
87
+ if (target === 'hue') h.value = p * 360
88
+ else a.value = Math.round(p * 100) / 100
89
+ }
90
+ commit()
91
+ }
92
+
93
+ function onPointerDown(target: Target, e: PointerEvent) {
94
+ if (e.button !== 0) return
95
+ e.preventDefault()
96
+ ;(e.currentTarget as HTMLElement).focus({ preventScroll: true })
97
+ ;(e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId)
98
+ dragging.value = target
99
+ update(target, e)
100
+ }
101
+ function onPointerMove(target: Target, e: PointerEvent) {
102
+ if (dragging.value === target) update(target, e)
103
+ }
104
+ function onPointerUp() {
105
+ dragging.value = null
106
+ }
107
+
108
+ // ── Keyboard ───────────────────────────────────────────────────────────────────────────────
109
+ function onKeydown(target: Target, e: KeyboardEvent) {
110
+ const step = e.shiftKey ? 10 : 1
111
+ const dx = e.key === 'ArrowRight' ? step : e.key === 'ArrowLeft' ? -step : 0
112
+ const dy = e.key === 'ArrowUp' ? step : e.key === 'ArrowDown' ? -step : 0
113
+ if (target === 'area') {
114
+ if (!dx && !dy) return
115
+ s.value = clamp(s.value + dx, 0, 100)
116
+ v.value = clamp(v.value + dy, 0, 100)
117
+ } else {
118
+ const max = target === 'hue' ? 360 : 100
119
+ const cur = target === 'hue' ? h.value : a.value * 100
120
+ let next: number
121
+ if (e.key === 'Home') next = 0
122
+ else if (e.key === 'End') next = max
123
+ else if (dx || dy) next = clamp(cur + (dx || dy), 0, max)
124
+ else return
125
+ if (target === 'hue') h.value = next
126
+ else a.value = Math.round(next) / 100
127
+ }
128
+ e.preventDefault()
129
+ commit()
130
+ }
131
+
132
+ // ── Eyedropper (Chromium only; the button isn't shown elsewhere) ─────────────────────────────
133
+ const canEyedrop = ref(false)
134
+ onMounted(() => { canEyedrop.value = 'EyeDropper' in window })
135
+
136
+ async function pickFromScreen() {
137
+ try {
138
+ const Ctor = (window as unknown as { EyeDropper: new () => { open(): Promise<{ sRGBHex: string }> } }).EyeDropper
139
+ const { sRGBHex } = await new Ctor().open()
140
+ const c = parseHex(sRGBHex)
141
+ if (c) { setFromRgb({ ...c, a: a.value }); commit() }
142
+ } catch { /* cancelled */ }
143
+ }
144
+
145
+ // ── Text fields ─────────────────────────────────────────────────────────────────────────────
146
+ type Format = 'hex' | 'rgb' | 'hsl'
147
+ const formats: { id: Format; label: string }[] = [
148
+ { id: 'hex', label: 'HEX' }, { id: 'rgb', label: 'RGB' }, { id: 'hsl', label: 'HSL' },
149
+ ]
150
+ const format = ref<Format>('hex')
151
+ const formatLabel = computed(() => formats.find((f) => f.id === format.value)!.label)
152
+ function cycleFormat() {
153
+ format.value = formats[(formats.findIndex((f) => f.id === format.value) + 1) % formats.length]!.id
154
+ editing.value = null
155
+ }
156
+
157
+ interface Field { key: string; label: string; display: string; max: number; apply: (n: number) => void }
158
+
159
+ function setHsv(next: { h: number; s: number; v: number }) {
160
+ h.value = next.h; s.value = next.s; v.value = next.v
161
+ }
162
+
163
+ const alphaField = computed<Field>(() => ({
164
+ key: 'a', label: 'A', display: String(Math.round(a.value * 100)), max: 100,
165
+ apply: (n) => { a.value = n / 100 },
166
+ }))
167
+
168
+ const fields = computed<Field[]>(() => {
169
+ const list: Field[] = []
170
+ if (format.value === 'rgb') {
171
+ const rgb = hsvToRgb({ h: h.value, s: s.value, v: v.value })
172
+ const round = { r: Math.round(rgb.r), g: Math.round(rgb.g), b: Math.round(rgb.b), a: a.value }
173
+ for (const ch of ['r', 'g', 'b'] as const) {
174
+ list.push({
175
+ key: ch, label: ch.toUpperCase(), display: String(round[ch]), max: 255,
176
+ apply: (n) => setFromRgb({ ...round, [ch]: n }),
177
+ })
178
+ }
179
+ } else if (format.value === 'hsl') {
180
+ const hsl = hsvToHsl({ h: h.value, s: s.value, v: v.value })
181
+ const round = { h: Math.round(hsl.h), s: Math.round(hsl.s), l: Math.round(hsl.l) }
182
+ for (const ch of ['h', 's', 'l'] as const) {
183
+ list.push({
184
+ key: ch, label: ch.toUpperCase(), display: String(round[ch]), max: ch === 'h' ? 360 : 100,
185
+ // Straight from HSL to HSV, so a hue typed on a gray isn't lost
186
+ apply: (n) => setHsv(hslToHsv({ ...round, [ch]: n })),
187
+ })
188
+ }
189
+ }
190
+ if (props.alpha && format.value !== 'hex') list.push(alphaField.value)
191
+ return list
192
+ })
193
+
194
+ // While a field is focused it shows what the user typed, not the reformatted value
195
+ const editing = ref<{ key: string; text: string } | null>(null)
196
+ const shown = (key: string, display: string) => (editing.value?.key === key ? editing.value.text : display)
197
+
198
+ function onHexInput(e: Event) {
199
+ const text = (e.target as HTMLInputElement).value
200
+ editing.value = { key: 'hex', text }
201
+ const c = parseHex(text)
202
+ if (c) { setFromRgb(c); commit() }
203
+ }
204
+
205
+ function onFieldInput(f: Field, e: Event) {
206
+ const text = (e.target as HTMLInputElement).value
207
+ editing.value = { key: f.key, text }
208
+ if (!/^\d+$/.test(text.trim())) return
209
+ const n = Number(text)
210
+ if (n > f.max) return
211
+ f.apply(n)
212
+ commit()
213
+ }
214
+
215
+ function onFieldKeydown(f: Field, e: KeyboardEvent) {
216
+ if (e.key === 'Enter') { editing.value = null; return }
217
+ if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return
218
+ e.preventDefault()
219
+ const step = (e.shiftKey ? 10 : 1) * (e.key === 'ArrowUp' ? 1 : -1)
220
+ f.apply(clamp(Number(f.display) + step, 0, f.max))
221
+ editing.value = null
222
+ commit()
223
+ }
224
+
225
+ // ── Swatches ────────────────────────────────────────────────────────────────────────────────
226
+ const recents = computed(() => (props.recent ? recentColors.value : []))
227
+ const isSelected = (color: string) => normalizeHex(color) === hex.value
228
+ // Swatches and preview segments paint the color over a checkerboard in one background, so a translucent color
229
+ // shows it and the edge is a single antialiased shape (nested clipped layers looked jagged in Firefox)
230
+ const CHECKER = 'repeating-conic-gradient(#d4d4d4 0 25%, #fff 0 50%) 0 0 / 8px 8px'
231
+ const fill = (color: string) => `linear-gradient(${color}, ${color}), ${CHECKER}`
232
+ // Over a mostly transparent color the checkerboard (light) is what's behind the text
233
+ const previewInk = computed(() => (a.value < 0.5 ? '#000000' : inkFor(opaqueHex.value)))
234
+ const showOriginal = computed(() => !!props.original && !!normalizeHex(props.original) && normalizeHex(props.original) !== hex.value)
235
+
236
+ defineExpose({ focus: () => areaEl.value?.focus({ preventScroll: true }) })
237
+ </script>
238
+
239
+ <template>
240
+ <div class="flex flex-col gap-4">
241
+ <!-- Saturation (x) / brightness (y) -->
242
+ <div
243
+ ref="areaEl"
244
+ role="slider"
245
+ tabindex="0"
246
+ :aria-label="`${t.colorSaturation}, ${t.colorBrightness}`"
247
+ :aria-valuenow="Math.round(s)"
248
+ aria-valuemin="0"
249
+ aria-valuemax="100"
250
+ :aria-valuetext="`${t.colorSaturation} ${Math.round(s)}%, ${t.colorBrightness} ${Math.round(v)}%`"
251
+ class="relative h-40 w-full shrink-0 cursor-crosshair touch-none rounded-md outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
252
+ :style="{ background: `linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, ${hueColor})` }"
253
+ @pointerdown="onPointerDown('area', $event)"
254
+ @pointermove="onPointerMove('area', $event)"
255
+ @pointerup="onPointerUp"
256
+ @pointercancel="onPointerUp"
257
+ @keydown="onKeydown('area', $event)"
258
+ >
259
+ <span
260
+ class="m3-cp-area-thumb pointer-events-none absolute size-5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white transition-[scale] duration-150"
261
+ :class="dragging === 'area' ? 'scale-125' : ''"
262
+ :style="{ left: `${s}%`, top: `${100 - v}%`, backgroundColor: opaqueHex }"
263
+ />
264
+ </div>
265
+
266
+ <!-- Hue / opacity: thick tracks with M3 Expressive's bar handle -->
267
+ <div class="flex flex-col gap-1">
268
+ <div
269
+ ref="hueEl"
270
+ role="slider"
271
+ tabindex="0"
272
+ :aria-label="t.colorHue"
273
+ :aria-valuenow="Math.round(h)"
274
+ aria-valuemin="0"
275
+ aria-valuemax="360"
276
+ class="m3-cp-slider group"
277
+ @pointerdown="onPointerDown('hue', $event)"
278
+ @pointermove="onPointerMove('hue', $event)"
279
+ @pointerup="onPointerUp"
280
+ @pointercancel="onPointerUp"
281
+ @keydown="onKeydown('hue', $event)"
282
+ >
283
+ <span class="m3-cp-track m3-cp-hue" />
284
+ <span
285
+ class="m3-cp-handle"
286
+ :class="{ 'm3-cp-handle-pressed': dragging === 'hue' }"
287
+ :style="{ left: `calc(${THUMB_INSET}px + ${h / 360} * (100% - ${THUMB_INSET * 2}px))` }"
288
+ />
289
+ </div>
290
+ <div
291
+ v-if="alpha"
292
+ ref="alphaEl"
293
+ role="slider"
294
+ tabindex="0"
295
+ :aria-label="t.colorAlpha"
296
+ :aria-valuenow="Math.round(a * 100)"
297
+ aria-valuemin="0"
298
+ aria-valuemax="100"
299
+ :aria-valuetext="`${Math.round(a * 100)}%`"
300
+ class="m3-cp-slider group"
301
+ @pointerdown="onPointerDown('alpha', $event)"
302
+ @pointermove="onPointerMove('alpha', $event)"
303
+ @pointerup="onPointerUp"
304
+ @pointercancel="onPointerUp"
305
+ @keydown="onKeydown('alpha', $event)"
306
+ >
307
+ <span class="m3-cp-track" :style="{ background: `linear-gradient(to right, transparent, ${opaqueHex}), ${CHECKER}` }" />
308
+ <span
309
+ class="m3-cp-handle"
310
+ :class="{ 'm3-cp-handle-pressed': dragging === 'alpha' }"
311
+ :style="{ left: `calc(${THUMB_INSET}px + ${a} * (100% - ${THUMB_INSET * 2}px))` }"
312
+ />
313
+ </div>
314
+ </div>
315
+
316
+ <!-- Preview (original | new) and eyedropper -->
317
+ <div class="flex items-center gap-2">
318
+ <div class="flex h-10 min-w-0 flex-1">
319
+ <button
320
+ v-if="showOriginal"
321
+ type="button"
322
+ class="m3-cp-swatch flex w-12 shrink-0 cursor-pointer items-center justify-center rounded-l-full outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
323
+ :style="{ background: fill(original!) }"
324
+ :aria-label="t.colorOriginal"
325
+ :title="t.colorOriginal"
326
+ @click="pick(original!)"
327
+ >
328
+ <MIcon name="undo" :size="18" :style="{ color: inkFor(original!) }" />
329
+ </button>
330
+ <span
331
+ class="m3-cp-swatch flex min-w-0 flex-1 items-center px-4 font-mono text-label-large transition-[border-radius] duration-200"
332
+ :class="showOriginal ? 'rounded-r-full' : 'rounded-full'"
333
+ :style="{ background: fill(hex), color: previewInk }"
334
+ >{{ hex }}</span>
335
+ </div>
336
+ <MIconButton v-if="eyedropper && canEyedrop" icon="colorize" variant="tonal" :label="t.colorEyedropper" @click="pickFromScreen" />
337
+ </div>
338
+
339
+ <!-- Format + fields -->
340
+ <div class="flex items-start gap-2">
341
+ <button
342
+ type="button"
343
+ class="flex h-10 shrink-0 cursor-pointer items-center gap-0.5 rounded-full bg-secondary-container pr-2 pl-3 text-label-large text-on-secondary-container outline-none transition-[background-color] duration-150 hover:bg-[color-mix(in_srgb,var(--color-secondary-container),var(--color-on-secondary-container)_8%)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
344
+ :aria-label="`${t.colorFormat}: ${formatLabel}`"
345
+ @click="cycleFormat"
346
+ >
347
+ {{ formatLabel }}
348
+ <MIcon name="unfold_more" :size="18" />
349
+ </button>
350
+ <input
351
+ v-if="format === 'hex'"
352
+ type="text"
353
+ spellcheck="false"
354
+ autocomplete="off"
355
+ :maxlength="alpha ? 9 : 7"
356
+ aria-label="HEX"
357
+ :value="shown('hex', hex)"
358
+ class="m3-cp-field min-w-0 flex-1 font-mono text-body-medium"
359
+ @input="onHexInput"
360
+ @blur="editing = null"
361
+ @keydown.enter="editing = null"
362
+ />
363
+ <label v-for="f in fields" :key="f.key" class="flex min-w-0 flex-1 flex-col items-center gap-1">
364
+ <input
365
+ type="text"
366
+ inputmode="numeric"
367
+ autocomplete="off"
368
+ :maxlength="3"
369
+ :aria-label="f.label"
370
+ :value="shown(f.key, f.display)"
371
+ class="m3-cp-field w-full font-mono text-body-medium"
372
+ @input="onFieldInput(f, $event)"
373
+ @keydown="onFieldKeydown(f, $event)"
374
+ @blur="editing = null"
375
+ />
376
+ <span class="text-label-small text-on-surface-variant">{{ f.label }}</span>
377
+ </label>
378
+ </div>
379
+
380
+ <!-- Swatches: rounded squares that morph into a circle when selected -->
381
+ <template v-for="group in [{ id: 'recent', label: t.colorRecent, colors: recents }, { id: 'presets', label: t.colorPresets, colors: presets }]" :key="group.id">
382
+ <div v-if="group.colors.length" role="group" :aria-label="group.label" class="flex flex-col gap-2">
383
+ <span v-if="recents.length" class="text-label-medium text-on-surface-variant">{{ group.label }}</span>
384
+ <div class="grid grid-cols-7 gap-2">
385
+ <button
386
+ v-for="color in group.colors"
387
+ :key="color"
388
+ type="button"
389
+ class="m3-cp-swatch m3-cp-morph flex aspect-square cursor-pointer items-center justify-center outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
390
+ :class="{ 'm3-cp-morph-selected': isSelected(color) }"
391
+ :style="{ background: fill(color) }"
392
+ :aria-label="color"
393
+ :aria-pressed="isSelected(color)"
394
+ @click="pick(color)"
395
+ >
396
+ <MIcon v-if="isSelected(color)" name="check" :size="18" :style="{ color: inkFor(color) }" />
397
+ </button>
398
+ </div>
399
+ </div>
400
+ </template>
401
+ </div>
402
+ </template>
403
+
404
+ <style scoped>
405
+ .m3-cp-hue {
406
+ background: linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);
407
+ }
408
+ /* Hairline so white swatches show on light surfaces and black ones on dark */
409
+ .m3-cp-swatch {
410
+ box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--color-on-surface) 12%, transparent);
411
+ }
412
+ .m3-cp-morph {
413
+ border-radius: 30%;
414
+ transition: border-radius 250ms cubic-bezier(0.2, 0, 0, 1);
415
+ }
416
+ .m3-cp-morph:hover {
417
+ border-radius: 40%;
418
+ }
419
+ .m3-cp-morph-selected,
420
+ .m3-cp-morph-selected:hover {
421
+ border-radius: 50%;
422
+ }
423
+ .m3-cp-area-thumb {
424
+ box-shadow: 0 0 0 1px rgb(0 0 0 / 0.2), 0 1px 3px 1px rgb(0 0 0 / 0.25);
425
+ }
426
+ .m3-cp-slider {
427
+ position: relative;
428
+ height: 32px;
429
+ cursor: pointer;
430
+ touch-action: none;
431
+ outline: none;
432
+ }
433
+ .m3-cp-track {
434
+ position: absolute;
435
+ inset: 4px 0;
436
+ border-radius: 9999px;
437
+ box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--color-on-surface) 12%, transparent);
438
+ }
439
+ /* After M3 Expressive's slider handle: a bar taller than the track that narrows while pressed */
440
+ .m3-cp-handle {
441
+ position: absolute;
442
+ top: 0;
443
+ width: 6px;
444
+ height: 32px;
445
+ translate: -50% 0;
446
+ border-radius: 9999px;
447
+ background: #fff;
448
+ box-shadow: 0 0 0 1px rgb(0 0 0 / 0.2), 0 1px 3px rgb(0 0 0 / 0.3);
449
+ pointer-events: none;
450
+ transition: width 150ms cubic-bezier(0.2, 0, 0, 1);
451
+ }
452
+ .m3-cp-handle-pressed {
453
+ width: 4px;
454
+ }
455
+ .group:focus-visible .m3-cp-handle {
456
+ outline: 2px solid var(--color-primary);
457
+ outline-offset: 2px;
458
+ }
459
+ .m3-cp-field {
460
+ height: 40px;
461
+ border-radius: var(--radius-sm);
462
+ border: none;
463
+ background: var(--color-surface-container-highest);
464
+ padding: 0 8px;
465
+ text-align: center;
466
+ color: var(--color-on-surface);
467
+ caret-color: var(--color-primary);
468
+ outline: 2px solid transparent;
469
+ outline-offset: -2px;
470
+ transition: outline-color 150ms;
471
+ }
472
+ .m3-cp-field:hover {
473
+ outline-color: color-mix(in srgb, var(--color-on-surface) 12%, transparent);
474
+ }
475
+ .m3-cp-field:focus {
476
+ outline-color: var(--color-primary);
477
+ }
478
+ </style>
@@ -0,0 +1,107 @@
1
+ // Internal color math shared by MColorPicker and MColorPickerModal (through _MColorPanel).
2
+ // Not exported from index.ts.
3
+ import { ref } from 'vue'
4
+
5
+ export interface Rgba { r: number; g: number; b: number; a: number }
6
+ /** h 0–360, s/v 0–100 */
7
+ export interface Hsv { h: number; s: number; v: number }
8
+ /** h 0–360, s/l 0–100 */
9
+ export interface Hsl { h: number; s: number; l: number }
10
+
11
+ /** Parses `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa` (the `#` is optional). r/g/b 0–255, a 0–1. */
12
+ export function parseHex(input: string): Rgba | null {
13
+ let c = input.trim().replace(/^#/, '')
14
+ if (!/^([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(c)) return null
15
+ if (c.length <= 4) c = [...c].map((ch) => ch + ch).join('')
16
+ const n = (i: number) => parseInt(c.substring(i, i + 2), 16)
17
+ return { r: n(0), g: n(2), b: n(4), a: c.length === 8 ? n(6) / 255 : 1 }
18
+ }
19
+
20
+ /** `#rrggbb`, or `#rrggbbaa` when a < 1. Lowercase. */
21
+ export function toHex({ r, g, b, a }: Rgba): string {
22
+ const h = (n: number) => Math.round(Math.max(0, Math.min(255, n))).toString(16).padStart(2, '0')
23
+ return `#${h(r)}${h(g)}${h(b)}${a < 1 ? h(a * 255) : ''}`
24
+ }
25
+
26
+ /** Lowercase canonical form of a hex string, or '' when it isn't one. */
27
+ export function normalizeHex(input: string): string {
28
+ const c = parseHex(input)
29
+ return c ? toHex(c) : ''
30
+ }
31
+
32
+ export function rgbToHsv({ r, g, b }: Rgba): Hsv {
33
+ r /= 255; g /= 255; b /= 255
34
+ const max = Math.max(r, g, b), d = max - Math.min(r, g, b)
35
+ let h = 0
36
+ if (d !== 0) {
37
+ if (max === r) h = ((g - b) / d + 6) % 6
38
+ else if (max === g) h = (b - r) / d + 2
39
+ else h = (r - g) / d + 4
40
+ h *= 60
41
+ }
42
+ return { h, s: max === 0 ? 0 : (d / max) * 100, v: max * 100 }
43
+ }
44
+
45
+ export function hsvToRgb({ h, s, v }: Hsv, a = 1): Rgba {
46
+ s /= 100; v /= 100
47
+ const f = (n: number) => {
48
+ const k = (n + h / 60) % 6
49
+ return (v - v * s * Math.max(0, Math.min(k, 4 - k, 1))) * 255
50
+ }
51
+ return { r: f(5), g: f(3), b: f(1), a }
52
+ }
53
+
54
+ export function hsvToHsl({ h, s, v }: Hsv): Hsl {
55
+ s /= 100; v /= 100
56
+ const l = v * (1 - s / 2)
57
+ const sl = l === 0 || l === 1 ? 0 : (v - l) / Math.min(l, 1 - l)
58
+ return { h, s: sl * 100, l: l * 100 }
59
+ }
60
+
61
+ export function hslToHsv({ h, s, l }: Hsl): Hsv {
62
+ s /= 100; l /= 100
63
+ const v = l + s * Math.min(l, 1 - l)
64
+ return { h, s: v === 0 ? 0 : 2 * (1 - l / v) * 100, v: v * 100 }
65
+ }
66
+
67
+ /** Black or white, whichever reads better on the color (WCAG relative luminance). */
68
+ export function inkFor(hex: string): '#000000' | '#ffffff' {
69
+ const c = parseHex(hex)
70
+ if (!c) return '#000000'
71
+ const lin = (n: number) => {
72
+ n /= 255
73
+ return n <= 0.03928 ? n / 12.92 : ((n + 0.055) / 1.055) ** 2.4
74
+ }
75
+ const lum = 0.2126 * lin(c.r) + 0.7152 * lin(c.g) + 0.0722 * lin(c.b)
76
+ // Contrast against black beats contrast against white above ~0.179
77
+ return lum > 0.179 ? '#000000' : '#ffffff'
78
+ }
79
+
80
+ // ── Recent colors (per viewer, localStorage, shared by every picker on the page) ──────────────
81
+
82
+ const RECENT_KEY = 'm3-color-recent'
83
+
84
+ function readRecents(): string[] {
85
+ try {
86
+ const v = JSON.parse(localStorage.getItem(RECENT_KEY) ?? '[]')
87
+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string' && !!parseHex(x)) : []
88
+ } catch {
89
+ return []
90
+ }
91
+ }
92
+
93
+ export const recentColors = ref<string[]>(readRecents())
94
+
95
+ export function pushRecentColor(hex: string, limit: number) {
96
+ const c = normalizeHex(hex)
97
+ if (!c) return
98
+ recentColors.value = [c, ...recentColors.value.filter((x) => x !== c)].slice(0, Math.max(limit, 0))
99
+ try { localStorage.setItem(RECENT_KEY, JSON.stringify(recentColors.value)) } catch { /* storage blocked */ }
100
+ }
101
+
102
+ /** Default swatches for both pickers: the Material 2014 palette's 500 tones plus grey, black and white (3 rows of 7) */
103
+ export const defaultColorPresets = [
104
+ '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5', '#2196f3', '#03a9f4',
105
+ '#00bcd4', '#009688', '#4caf50', '#8bc34a', '#cddc39', '#ffeb3b', '#ffc107',
106
+ '#ff9800', '#ff5722', '#795548', '#607d8b', '#9e9e9e', '#000000', '#ffffff',
107
+ ]
@@ -0,0 +1,33 @@
1
+ // Internal: keeps <meta name="theme-color"> (the browser bar / status bar color on phones) in sync with a color
2
+ // role of the active palette, dark mode and seed included. Started by createM3UI({ themeColor }).
3
+
4
+ let observer: MutationObserver | undefined
5
+
6
+ function metas(): HTMLMetaElement[] {
7
+ const found = Array.from(document.querySelectorAll<HTMLMetaElement>('meta[name="theme-color"]'))
8
+ if (found.length) return found
9
+ const meta = document.createElement('meta')
10
+ meta.name = 'theme-color'
11
+ document.head.appendChild(meta)
12
+ return [meta]
13
+ }
14
+
15
+ function update(role: string) {
16
+ const color = getComputedStyle(document.documentElement).getPropertyValue(`--color-${role}`).trim()
17
+ if (!color) return
18
+ for (const meta of metas()) {
19
+ // A media-scoped pair (light/dark) would fight the live value: one meta, kept current, replaces them
20
+ meta.removeAttribute('media')
21
+ if (meta.content !== color) meta.content = color
22
+ }
23
+ }
24
+
25
+ export function syncThemeColor(role: string) {
26
+ if (typeof document === 'undefined') return
27
+ observer?.disconnect()
28
+ update(role)
29
+ // Palette (data-palette), dark mode and palette switches (class: dark, theme-transitioning) all land on <html>;
30
+ // a new seed also toggles theme-transitioning, after its CSS is in place
31
+ observer = new MutationObserver(() => update(role))
32
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-palette'] })
33
+ }