@m3ui-vue/m3ui-vue 0.6.0 → 0.6.1

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,405 @@
1
+ <script setup lang="ts">
2
+ import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
3
+ import MIcon from './MIcon.vue'
4
+ import { useLocale } from '../composables/useLocale'
5
+
6
+ export interface LightboxItem {
7
+ src: string
8
+ alt?: string
9
+ caption?: string
10
+ }
11
+
12
+ interface OriginRect {
13
+ x: number
14
+ y: number
15
+ width: number
16
+ height: number
17
+ }
18
+
19
+ const props = withDefaults(
20
+ defineProps<{
21
+ modelValue?: boolean
22
+ /** Explicit gallery. Omit it to auto-detect `<img>` elements rendered in the default slot instead. */
23
+ items?: LightboxItem[]
24
+ index?: number
25
+ loop?: boolean
26
+ closeLabel?: string
27
+ /** Show a row of clickable thumbnails at the bottom for jumping directly to an image. */
28
+ showThumbnails?: boolean
29
+ /** Round the corners of the main opened image (the thumbnail strip keeps its own fixed rounding). */
30
+ rounded?: boolean
31
+ }>(),
32
+ {
33
+ modelValue: false,
34
+ index: 0,
35
+ loop: true,
36
+ showThumbnails: false,
37
+ rounded: true,
38
+ },
39
+ )
40
+
41
+ const emit = defineEmits<{
42
+ 'update:modelValue': [boolean]
43
+ 'update:index': [number]
44
+ change: [index: number]
45
+ }>()
46
+
47
+ const locale = useLocale()
48
+
49
+ const containerEl = ref<HTMLElement>()
50
+ const stageImageEl = ref<HTMLElement>()
51
+ const scannedItems = ref<LightboxItem[]>([])
52
+ const isOpen = ref(props.modelValue)
53
+ const currentIndex = ref(props.index)
54
+ const direction = ref(1)
55
+ // Set on open() when we have a clicked thumbnail to expand from (Discord-style); cleared once
56
+ // the opening transition has played so later next()/prev() use the plain slide instead.
57
+ const isFirstShow = ref(true)
58
+ let originRect: OriginRect | null = null
59
+
60
+ const galleryItems = computed(() => props.items ?? scannedItems.value)
61
+ const current = computed(() => galleryItems.value[currentIndex.value])
62
+ const hasMultiple = computed(() => galleryItems.value.length > 1)
63
+
64
+ watch(() => props.modelValue, (v) => { isOpen.value = v })
65
+ watch(() => props.index, (v) => { currentIndex.value = v })
66
+
67
+ function setIndex(i: number) {
68
+ currentIndex.value = i
69
+ emit('update:index', i)
70
+ emit('change', i)
71
+ }
72
+
73
+ function open(i = 0, sourceEl?: HTMLElement) {
74
+ originRect = sourceEl ? sourceEl.getBoundingClientRect() : null
75
+ isFirstShow.value = true
76
+ setIndex(i)
77
+ isOpen.value = true
78
+ emit('update:modelValue', true)
79
+ }
80
+
81
+ function close() {
82
+ isOpen.value = false
83
+ emit('update:modelValue', false)
84
+ }
85
+
86
+ function next() {
87
+ const len = galleryItems.value.length
88
+ if (!len) return
89
+ isFirstShow.value = false
90
+ direction.value = 1
91
+ if (currentIndex.value < len - 1) setIndex(currentIndex.value + 1)
92
+ else if (props.loop) setIndex(0)
93
+ }
94
+
95
+ function prev() {
96
+ const len = galleryItems.value.length
97
+ if (!len) return
98
+ isFirstShow.value = false
99
+ direction.value = -1
100
+ if (currentIndex.value > 0) setIndex(currentIndex.value - 1)
101
+ else if (props.loop) setIndex(len - 1)
102
+ }
103
+
104
+ function goTo(i: number) {
105
+ if (i === currentIndex.value) return
106
+ isFirstShow.value = false
107
+ direction.value = i > currentIndex.value ? 1 : -1
108
+ setIndex(i)
109
+ }
110
+
111
+ function onKeydown(e: KeyboardEvent) {
112
+ if (e.key === 'Escape') close()
113
+ else if (e.key === 'ArrowRight') next()
114
+ else if (e.key === 'ArrowLeft') prev()
115
+ }
116
+
117
+ watch(isOpen, (open) => {
118
+ if (open) {
119
+ document.addEventListener('keydown', onKeydown)
120
+ document.body.style.overflow = 'hidden'
121
+ } else {
122
+ document.removeEventListener('keydown', onKeydown)
123
+ document.body.style.overflow = ''
124
+ }
125
+ })
126
+
127
+ // ── Image transition: Discord-style expand from the clicked thumbnail on open, then a
128
+ // slide between images on next()/prev()/goTo(). Driven entirely from JS (css: false) since
129
+ // the "expand" transform depends on the clicked element's on-screen position/size, which
130
+ // plain CSS classes can't know about.
131
+ function transitionEndPromise(el: HTMLElement) {
132
+ return new Promise<void>((resolve) => {
133
+ const handler = (ev: TransitionEvent) => {
134
+ if (ev.target !== el) return
135
+ el.removeEventListener('transitionend', handler)
136
+ resolve()
137
+ }
138
+ el.addEventListener('transitionend', handler)
139
+ })
140
+ }
141
+
142
+ function onImageBeforeEnter(el: Element) {
143
+ const target = el as HTMLElement
144
+ if (isFirstShow.value) {
145
+ if (originRect) {
146
+ // Translate by the two boxes' centers (target fills the stage and centers the image via
147
+ // flex, so its center already coincides with the image's), but scale by the ratio against
148
+ // the actual rendered <img> size, not the full-stage wrapper's size.
149
+ const containerRect = target.getBoundingClientRect()
150
+ const imgRect = target.querySelector('img')?.getBoundingClientRect() ?? containerRect
151
+ const dx = originRect.x + originRect.width / 2 - (containerRect.left + containerRect.width / 2)
152
+ const dy = originRect.y + originRect.height / 2 - (containerRect.top + containerRect.height / 2)
153
+ const area = Math.max(imgRect.width * imgRect.height, 1)
154
+ const scale = Math.min(1, Math.max(0.05, Math.sqrt((originRect.width * originRect.height) / area)))
155
+ target.style.transform = `translate(${dx}px, ${dy}px) scale(${scale})`
156
+ } else {
157
+ target.style.transform = 'scale(0.92)'
158
+ }
159
+ } else {
160
+ target.style.transform = `translateX(${direction.value >= 0 ? 100 : -100}%)`
161
+ }
162
+ target.style.opacity = '0'
163
+ }
164
+
165
+ async function onImageEnter(el: Element, done: () => void) {
166
+ const target = el as HTMLElement
167
+ void target.offsetWidth // force reflow so the "from" styles above are committed first
168
+ if (isFirstShow.value) {
169
+ // Let the scrim fade in on its own first, Discord-style, before the image starts growing.
170
+ await new Promise((resolve) => setTimeout(resolve, 120))
171
+ }
172
+ target.style.transition = 'transform 0.32s cubic-bezier(0.2, 0, 0, 1), opacity 0.28s ease'
173
+ target.style.transform = ''
174
+ target.style.opacity = ''
175
+ await transitionEndPromise(target)
176
+ target.style.transition = ''
177
+ isFirstShow.value = false
178
+ done()
179
+ }
180
+
181
+ async function onImageLeave(el: Element, done: () => void) {
182
+ const target = el as HTMLElement
183
+ target.style.transition = 'transform 0.32s cubic-bezier(0.2, 0, 0, 1), opacity 0.28s ease'
184
+ target.style.transform = `translateX(${direction.value >= 0 ? -100 : 100}%)`
185
+ target.style.opacity = '0'
186
+ await transitionEndPromise(target)
187
+ done()
188
+ }
189
+
190
+ // ── Swipe/drag to navigate: follows the pointer 1:1 while held, then either commits to
191
+ // next()/prev() (which take over via the enter/leave hooks above, continuing smoothly from
192
+ // wherever the drag left off) or springs back to center if released short of the threshold.
193
+ let dragPointerId: number | null = null
194
+ let dragStartX = 0
195
+ let dragOffsetPx = 0
196
+ let dragStageWidth = 0
197
+ let isDragging = false
198
+
199
+ function onStagePointerDown(e: PointerEvent) {
200
+ if (!hasMultiple.value || e.button !== 0) return
201
+ const stage = e.currentTarget as HTMLElement
202
+ dragStageWidth = stage.clientWidth
203
+ dragStartX = e.clientX
204
+ dragOffsetPx = 0
205
+ dragPointerId = e.pointerId
206
+ isDragging = true
207
+ stage.setPointerCapture(e.pointerId)
208
+ if (stageImageEl.value) stageImageEl.value.style.transition = 'none'
209
+ }
210
+
211
+ function onStagePointerMove(e: PointerEvent) {
212
+ if (!isDragging || e.pointerId !== dragPointerId) return
213
+ dragOffsetPx = e.clientX - dragStartX
214
+ if (stageImageEl.value) stageImageEl.value.style.transform = `translateX(${dragOffsetPx}px)`
215
+ }
216
+
217
+ function endDrag(e: PointerEvent) {
218
+ if (!isDragging || e.pointerId !== dragPointerId) return
219
+ isDragging = false
220
+ const stage = e.currentTarget as HTMLElement
221
+ if (stage.hasPointerCapture(e.pointerId)) stage.releasePointerCapture(e.pointerId)
222
+
223
+ const threshold = Math.min(120, dragStageWidth * 0.25)
224
+ const offset = dragOffsetPx
225
+ dragOffsetPx = 0
226
+
227
+ if (offset <= -threshold) next()
228
+ else if (offset >= threshold) prev()
229
+ else if (stageImageEl.value) {
230
+ const el = stageImageEl.value
231
+ el.style.transition = 'transform 0.25s cubic-bezier(0.2, 0, 0, 1)'
232
+ el.style.transform = ''
233
+ const cleanup = (ev: TransitionEvent) => {
234
+ if (ev.target !== el) return
235
+ el.style.transition = ''
236
+ el.removeEventListener('transitionend', cleanup)
237
+ }
238
+ el.addEventListener('transitionend', cleanup)
239
+ }
240
+ }
241
+
242
+ // Auto-scan mode: pull <img> elements out of whatever is rendered in the default slot
243
+ // (e.g. MMarkdown output, a hand-rolled gallery grid) so this works without building an
244
+ // `items` array by hand. Opt an image out with `data-lightbox="false"`.
245
+ let observer: MutationObserver | null = null
246
+
247
+ function scan() {
248
+ if (props.items || !containerEl.value) return
249
+ const imgs = Array.from(containerEl.value.querySelectorAll('img')).filter(
250
+ (img) => img.dataset.lightbox !== 'false',
251
+ )
252
+ scannedItems.value = imgs.map((img) => ({
253
+ src: img.currentSrc || img.src,
254
+ alt: img.alt || undefined,
255
+ caption: img.dataset.caption || img.title || undefined,
256
+ }))
257
+ imgs.forEach((img, i) => {
258
+ img.style.cursor = 'zoom-in'
259
+ img.onclick = (e) => {
260
+ e.preventDefault()
261
+ open(i, img)
262
+ }
263
+ })
264
+ }
265
+
266
+ onMounted(() => {
267
+ if (props.items || !containerEl.value) return
268
+ scan()
269
+ observer = new MutationObserver(scan)
270
+ observer.observe(containerEl.value, {
271
+ childList: true,
272
+ subtree: true,
273
+ attributes: true,
274
+ attributeFilter: ['src'],
275
+ })
276
+ })
277
+
278
+ onBeforeUnmount(() => {
279
+ observer?.disconnect()
280
+ document.removeEventListener('keydown', onKeydown)
281
+ document.body.style.overflow = ''
282
+ })
283
+
284
+ defineExpose({ open, close, next, prev })
285
+ </script>
286
+
287
+ <template>
288
+ <div ref="containerEl" class="contents">
289
+ <slot />
290
+ </div>
291
+
292
+ <Teleport to="body">
293
+ <Transition name="m3-lightbox">
294
+ <div
295
+ v-if="isOpen"
296
+ class="fixed inset-0 z-[100] flex flex-col bg-black/90"
297
+ @click.self="close"
298
+ >
299
+ <span
300
+ v-if="hasMultiple"
301
+ class="absolute left-2 top-2 z-10 rounded-full bg-black/30 px-3 py-1 text-label-large text-white sm:left-4 sm:top-4"
302
+ >
303
+ {{ currentIndex + 1 }} / {{ galleryItems.length }}
304
+ </span>
305
+
306
+ <button
307
+ type="button"
308
+ class="absolute right-2 top-2 z-10 flex h-11 w-11 items-center justify-center rounded-full bg-black/30 text-white transition-colors hover:bg-black/50 sm:right-4 sm:top-4"
309
+ :aria-label="closeLabel ?? locale.close"
310
+ @click="close"
311
+ >
312
+ <MIcon name="close" :size="24" />
313
+ </button>
314
+
315
+ <div class="relative flex flex-1 items-center justify-center overflow-hidden" @click.self="close">
316
+ <button
317
+ v-if="hasMultiple"
318
+ type="button"
319
+ class="absolute left-2 top-1/2 z-10 flex h-11 w-11 -translate-y-1/2 items-center justify-center rounded-full bg-black/30 text-white transition-colors hover:bg-black/50 sm:left-4"
320
+ :aria-label="locale.previous"
321
+ @click.stop="prev"
322
+ >
323
+ <MIcon name="chevron_left" :size="28" />
324
+ </button>
325
+
326
+ <div
327
+ class="relative h-full w-full touch-pan-y overflow-hidden"
328
+ @pointerdown="onStagePointerDown"
329
+ @pointermove="onStagePointerMove"
330
+ @pointerup="endDrag"
331
+ @pointercancel="endDrag"
332
+ >
333
+ <Transition
334
+ :css="false"
335
+ @before-enter="onImageBeforeEnter"
336
+ @enter="onImageEnter"
337
+ @leave="onImageLeave"
338
+ >
339
+ <div
340
+ v-if="current"
341
+ :key="currentIndex"
342
+ ref="stageImageEl"
343
+ class="absolute inset-0 flex items-center justify-center p-4"
344
+ @click="close"
345
+ >
346
+ <img
347
+ :src="current.src"
348
+ :alt="current.alt ?? ''"
349
+ class="max-h-full max-w-full select-none object-contain"
350
+ :class="rounded ? 'rounded-2xl' : ''"
351
+ draggable="false"
352
+ @click.stop
353
+ />
354
+ </div>
355
+ </Transition>
356
+ </div>
357
+
358
+ <button
359
+ v-if="hasMultiple"
360
+ type="button"
361
+ class="absolute right-2 top-1/2 z-10 flex h-11 w-11 -translate-y-1/2 items-center justify-center rounded-full bg-black/30 text-white transition-colors hover:bg-black/50 sm:right-4"
362
+ :aria-label="locale.next"
363
+ @click.stop="next"
364
+ >
365
+ <MIcon name="chevron_right" :size="28" />
366
+ </button>
367
+ </div>
368
+
369
+ <p
370
+ v-if="current?.caption"
371
+ class="z-10 px-4 text-center text-body-medium text-white/90"
372
+ >
373
+ {{ current.caption }}
374
+ </p>
375
+
376
+ <div
377
+ v-if="showThumbnails && hasMultiple"
378
+ class="z-10 flex justify-center gap-2 overflow-x-auto p-4"
379
+ >
380
+ <button
381
+ v-for="(item, i) in galleryItems"
382
+ :key="i"
383
+ type="button"
384
+ class="h-14 w-14 shrink-0 overflow-hidden rounded-md ring-2 transition-opacity"
385
+ :class="i === currentIndex ? 'opacity-100 ring-white' : 'opacity-50 ring-transparent hover:opacity-80'"
386
+ @click="goTo(i)"
387
+ >
388
+ <img :src="item.src" :alt="item.alt ?? ''" class="h-full w-full object-cover" draggable="false" />
389
+ </button>
390
+ </div>
391
+ </div>
392
+ </Transition>
393
+ </Teleport>
394
+ </template>
395
+
396
+ <style scoped>
397
+ .m3-lightbox-enter-active,
398
+ .m3-lightbox-leave-active {
399
+ transition: opacity 0.2s ease;
400
+ }
401
+ .m3-lightbox-enter-from,
402
+ .m3-lightbox-leave-to {
403
+ opacity: 0;
404
+ }
405
+ </style>
@@ -41,10 +41,15 @@ export const palettes: Palette[] = [
41
41
 
42
42
  const current = ref(localStorage.getItem('m3-palette') ?? 'purple')
43
43
 
44
+ // Whether palette changes are written to localStorage. Defaults to true (existing behavior).
45
+ // An app can disable it via `createM3UI({ persistPalette: false })` or `useColorPalette().setPersistPalette(false)`
46
+ // so its chosen palette can't be overridden by a stored value on the next boot.
47
+ const persistEnabled = ref(true)
48
+
44
49
  export function useColorPalette() {
45
50
  watchEffect(() => {
46
51
  const id = current.value
47
- localStorage.setItem('m3-palette', id)
52
+ if (persistEnabled.value) localStorage.setItem('m3-palette', id)
48
53
 
49
54
  if (id === 'purple') {
50
55
  document.documentElement.removeAttribute('data-palette')
@@ -60,7 +65,12 @@ export function useColorPalette() {
60
65
  setTimeout(() => document.documentElement.classList.remove('theme-transitioning'), 300)
61
66
  }
62
67
 
63
- return { palette: current, palettes, set }
68
+ function setPersistPalette(enabled: boolean) {
69
+ persistEnabled.value = enabled
70
+ if (enabled) localStorage.setItem('m3-palette', current.value)
71
+ }
72
+
73
+ return { palette: current, palettes, set, persistPalette: persistEnabled, setPersistPalette }
64
74
  }
65
75
 
66
76
  // Apply on module load so palette is visible before any component mounts
@@ -68,3 +78,20 @@ const saved = localStorage.getItem('m3-palette')
68
78
  if (saved && saved !== 'purple') {
69
79
  document.documentElement.setAttribute('data-palette', saved)
70
80
  }
81
+
82
+ /**
83
+ * Internal: used by `createM3UI({ palette, persistPalette: false })` to force a palette on boot,
84
+ * bypassing whatever is already in localStorage, without waiting for a component to call
85
+ * `useColorPalette()` (which is what actually reacts to `current` via the watchEffect above).
86
+ * Not exported from the package's public entry points.
87
+ */
88
+ export function __forcePalette(id: string, persist: boolean) {
89
+ persistEnabled.value = persist
90
+ current.value = id
91
+ if (id === 'purple') {
92
+ document.documentElement.removeAttribute('data-palette')
93
+ } else {
94
+ document.documentElement.setAttribute('data-palette', id)
95
+ }
96
+ if (persist) localStorage.setItem('m3-palette', id)
97
+ }
package/src/index.ts CHANGED
@@ -77,6 +77,8 @@ export { default as MInfiniteScroll } from './components/MInfiniteScroll.vue'
77
77
  export { default as MJsonViewer } from './components/MJsonViewer.vue'
78
78
  export { default as MKanban } from './components/MKanban.vue'
79
79
  export { default as MKbd } from './components/MKbd.vue'
80
+ export { default as MLightbox } from './components/MLightbox.vue'
81
+ export type { LightboxItem } from './components/MLightbox.vue'
80
82
  export { default as MList } from './components/MList.vue'
81
83
  export { default as MListItem } from './components/MListItem.vue'
82
84
  export { default as MListSubheader } from './components/MListSubheader.vue'
package/src/plugin.ts CHANGED
@@ -1,10 +1,20 @@
1
1
  import type { App, MaybeRef } from 'vue'
2
2
  import type { Palette } from './composables/useColorPalette'
3
+ import { __forcePalette } from './composables/useColorPalette'
3
4
  import type { M3Locale } from './composables/useLocale'
4
5
  import { M3_LOCALE_KEY } from './composables/useLocale'
5
6
 
6
7
  export interface M3UIOptions {
7
8
  palette?: string
9
+ /**
10
+ * Set to `false` to make `palette` a hard default that always wins on boot, ignoring
11
+ * whatever is already stored in localStorage, and to stop future `useColorPalette().set()`
12
+ * calls from persisting either. Palette switching still works live within the session
13
+ * (`set()` still applies immediately) — only the "remember it for next time" part is disabled.
14
+ * Defaults to `true`, matching prior behavior (`palette` only seeds the very first visit,
15
+ * and any later choice persists and wins over it).
16
+ */
17
+ persistPalette?: boolean
8
18
  customPalettes?: Palette[]
9
19
  locale?: MaybeRef<Partial<M3Locale>>
10
20
  }
@@ -12,10 +22,12 @@ export interface M3UIOptions {
12
22
  export function createM3UI(options: M3UIOptions = {}) {
13
23
  return {
14
24
  install(app: App) {
15
- // `options.palette` is only the first-visit default — once the user picks a palette via
16
- // `useColorPalette().set()` it's persisted to localStorage, and that choice must win on
17
- // every later boot instead of being clobbered back to the plugin's static default.
18
- if (options.palette && options.palette !== 'purple' && !localStorage.getItem('m3-palette')) {
25
+ if (options.persistPalette === false) {
26
+ if (options.palette) __forcePalette(options.palette, false)
27
+ } else if (options.palette && options.palette !== 'purple' && !localStorage.getItem('m3-palette')) {
28
+ // `options.palette` is only the first-visit default — once the user picks a palette via
29
+ // `useColorPalette().set()` it's persisted to localStorage, and that choice must win on
30
+ // every later boot instead of being clobbered back to the plugin's static default.
19
31
  document.documentElement.setAttribute('data-palette', options.palette)
20
32
  localStorage.setItem('m3-palette', options.palette)
21
33
  }