@quazardous/qdadm 2.38.0 → 2.39.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.
@@ -16,15 +16,22 @@
16
16
  * <p>Demo accounts: admin, user</p>
17
17
  * </template>
18
18
  * </LoginPage>
19
+ *
20
+ * Identity provider first (#4321): the SSO button leads, the local form is a
21
+ * fallback (open, collapsed or hidden):
22
+ * <LoginPage :sso="{ label: 'Sign in with Acme' }" local-fallback="collapsed"
23
+ * :provider-home="{ label: 'My Acme account', href: 'https://id.acme.test' }" />
19
24
  */
20
- import { ref, inject, computed, type PropType, type Component } from 'vue'
25
+ import { ref, inject, computed, nextTick, type PropType, type Component } from 'vue'
21
26
  import { useRouter } from 'vue-router'
22
27
  import Card from 'primevue/card'
23
28
  import InputText from 'primevue/inputtext'
24
29
  import Password from 'primevue/password'
25
30
  import QdButton from '../base/QdButton.vue'
31
+ import QdMessage from '../base/QdMessage.vue'
26
32
  import AppBanner from '../layout/AppBanner.vue'
27
33
  import { useI18n } from '../../i18n/useI18n'
34
+ import type { TranslateParams } from '../../i18n'
28
35
  import type { OrchestratorLike } from '../../entity/EntityManager.interface'
29
36
 
30
37
  /**
@@ -32,8 +39,46 @@ import type { OrchestratorLike } from '../../entity/EntityManager.interface'
32
39
  */
33
40
  interface AuthAdapter {
34
41
  login: (credentials: { username: string; password: string }) => Promise<LoginResult>
42
+ /** Redirect-based adapters (OAuthCodeAdapter): starts the provider's flow. */
43
+ beginLogin?: (redirectTo?: string) => Promise<void>
35
44
  }
36
45
 
46
+ /**
47
+ * The identity provider's button (#4321). `href` navigates (a server redirect),
48
+ * `start` runs the app's own flow; with neither, the auth adapter's
49
+ * `beginLogin()` is called.
50
+ */
51
+ export interface LoginSso {
52
+ label?: string
53
+ icon?: string
54
+ href?: string
55
+ start?: () => Promise<void>
56
+ }
57
+
58
+ /** A link to the provider's own portal (password, two-factor), in a new tab. */
59
+ export interface LoginProviderHome {
60
+ /** Default: core.login.providerHome ("My account") */
61
+ label?: string
62
+ href: string
63
+ }
64
+
65
+ /** Where the local form stands next to the SSO button. */
66
+ export type LoginLocalFallback = 'open' | 'collapsed' | 'hidden'
67
+
68
+ /**
69
+ * A text of the page (#4326): a string (static, `{name}` placeholders work) or
70
+ * a function called at render (dynamic: it follows the locale, a ref, the route).
71
+ */
72
+ export type LoginLabel =
73
+ | string
74
+ | ((ctx: { t: (key: string, fallback: string, params?: TranslateParams) => string; params: TranslateParams }) => string)
75
+
76
+ /** Every text of LoginPage, each one overridable. */
77
+ export type LoginLabelKey =
78
+ | 'username' | 'password' | 'submit' | 'or' | 'sso' | 'providerHome'
79
+ | 'localSection' | 'localFallback' | 'welcome' | 'loggedInAs' | 'failed'
80
+ | 'invalidCredentials' | 'noSso' | 'configError' | 'noAuthAdapter'
81
+
37
82
  /**
38
83
  * Login result from auth adapter
39
84
  */
@@ -154,6 +199,50 @@ const props = defineProps({
154
199
  welcomeToast: {
155
200
  type: Boolean,
156
201
  default: true
202
+ },
203
+ /** The identity provider's button, first on the page (#4321). */
204
+ sso: {
205
+ type: Object as PropType<LoginSso | null>,
206
+ default: null
207
+ },
208
+ /** A link to the provider's portal, beside the SSO button. */
209
+ providerHome: {
210
+ type: Object as PropType<LoginProviderHome | null>,
211
+ default: null
212
+ },
213
+ /** With `sso`: the local form shown, behind a disclosure, or not at all. */
214
+ localFallback: {
215
+ type: String as PropType<LoginLocalFallback>,
216
+ default: 'open'
217
+ },
218
+ /** The disclosure's label (default: core.login.localFallback) */
219
+ localFallbackLabel: {
220
+ type: String as PropType<string | null>,
221
+ default: null
222
+ },
223
+ /** A line under the title */
224
+ subtitle: {
225
+ type: String as PropType<string | null>,
226
+ default: null
227
+ },
228
+ /** The organisation's logo (image URL), small, beside the app's icon */
229
+ brandLogo: {
230
+ type: String as PropType<string | null>,
231
+ default: null
232
+ },
233
+ /** An error to show above the SSO button, e.g. the provider's `?error=` on return */
234
+ error: {
235
+ type: String as PropType<string | null>,
236
+ default: null
237
+ },
238
+ /**
239
+ * Any text of the page (#4326), static or dynamic. Wins over the single
240
+ * label props, which win over the i18n catalogue (core.login.*).
241
+ * `localSection: ''` drops the open local form's title for the bare "or".
242
+ */
243
+ labels: {
244
+ type: Object as PropType<Partial<Record<LoginLabelKey, LoginLabel>> | null>,
245
+ default: null
157
246
  }
158
247
  })
159
248
 
@@ -172,17 +261,66 @@ const username = ref<string>(props.defaultUsername)
172
261
  const password = ref<string>(props.defaultPassword)
173
262
  const loading = ref<boolean>(false)
174
263
 
175
- const labels = computed(() => ({
176
- username: props.usernameLabel ?? tOr('core.login.username', 'Username'),
177
- password: props.passwordLabel ?? tOr('core.login.password', 'Password'),
178
- submit: props.submitLabel ?? tOr('core.login.submit', 'Sign In'),
264
+ /**
265
+ * A text of the page: `labels[key]`, else the single prop given, else the
266
+ * catalogue (core.login.<key>), else the built-in default.
267
+ */
268
+ function label(key: LoginLabelKey, fallback: string, single?: string | null, params: TranslateParams = {}): string {
269
+ const custom = props.labels?.[key]
270
+ if (typeof custom === 'function') return custom({ t: tOr, params })
271
+ if (typeof custom === 'string') return custom.replace(/\{(\w+)\}/g, (m, name) => (name in params ? String(params[name]) : m))
272
+ if (single != null) return single
273
+ return tOr(`core.login.${key}`, fallback, params)
274
+ }
275
+
276
+ const texts = computed(() => ({
277
+ username: label('username', 'Username', props.usernameLabel),
278
+ password: label('password', 'Password', props.passwordLabel),
279
+ submit: label('submit', 'Sign In', props.submitLabel),
179
280
  }))
180
281
 
181
282
  const displayTitle = computed<string>(() => props.title || appConfig.name || 'Admin')
182
283
 
284
+ // Identity provider first (#4321). 'hidden' needs an SSO button, or there is no way in.
285
+ if (props.localFallback === 'hidden' && !props.sso) {
286
+ console.warn('[qdadm] LoginPage: localFallback "hidden" needs `sso`; the local form stays shown')
287
+ }
288
+ const localMode = computed<LoginLocalFallback>(() => (props.sso ? props.localFallback : 'open'))
289
+ const localOpen = ref<boolean>(localMode.value !== 'collapsed')
290
+ const ssoLoading = ref<boolean>(false)
291
+ const ssoError = ref<string | null>(null)
292
+ const shownError = computed<string | null>(() => ssoError.value ?? props.error)
293
+ const ssoLabel = computed<string>(() => label('sso', 'Sign in', props.sso?.label))
294
+ // The open local form's title, in place of the bare "or"; '' keeps the "or"
295
+ const localSection = computed<string>(() => label('localSection', 'Alternative login'))
296
+
297
+ async function openLocal(): Promise<void> {
298
+ localOpen.value = true
299
+ await nextTick()
300
+ document.getElementById('qdadm-username')?.focus()
301
+ }
302
+
303
+ async function handleSso(): Promise<void> {
304
+ const sso = props.sso
305
+ if (!sso || sso.href) return // an href is a plain link
306
+ ssoError.value = null
307
+ ssoLoading.value = true
308
+ try {
309
+ if (sso.start) await sso.start()
310
+ else if (authAdapter?.beginLogin) await authAdapter.beginLogin(props.redirectTo)
311
+ else throw new Error(label('noSso', 'No sign-in flow configured for this button'))
312
+ } catch (err) {
313
+ ssoError.value = err instanceof Error ? err.message : String(err)
314
+ emit('error', err)
315
+ } finally {
316
+ // A redirect leaves the page; anything else hands the button back
317
+ ssoLoading.value = false
318
+ }
319
+ }
320
+
183
321
  async function handleLogin(): Promise<void> {
184
322
  if (!authAdapter?.login) {
185
- orchestrator?.toast.error(tOr('core.login.configError', 'Configuration Error'), tOr('core.login.noAuthAdapter', 'No auth adapter configured'), 'LoginPage')
323
+ orchestrator?.toast.error(label('configError', 'Configuration Error'), label('noAuthAdapter', 'No auth adapter configured'), 'LoginPage')
186
324
  return
187
325
  }
188
326
 
@@ -197,8 +335,8 @@ async function handleLogin(): Promise<void> {
197
335
  orchestrator?.signals?.emit('auth:login', { user: result.user })
198
336
  if (props.welcomeToast) {
199
337
  orchestrator?.toast.success(
200
- tOr('core.login.welcome', 'Welcome'),
201
- tOr('core.login.loggedInAs', 'Logged in as {name}', { name: result.user?.username || result.user?.email || username.value }),
338
+ label('welcome', 'Welcome'),
339
+ label('loggedInAs', 'Logged in as {name}', null, { name: result.user?.username || result.user?.email || username.value }),
202
340
  'LoginPage'
203
341
  )
204
342
  }
@@ -212,14 +350,14 @@ async function handleLogin(): Promise<void> {
212
350
  const message = axiosError.response?.data?.error?.message
213
351
  || axiosError.response?.data?.message
214
352
  || axiosError.message
215
- || tOr('core.login.invalidCredentials', 'Invalid credentials')
353
+ || label('invalidCredentials', 'Invalid credentials')
216
354
 
217
355
  orchestrator?.signals?.emit('auth:login:error', {
218
356
  username: username.value,
219
357
  error: message,
220
358
  status: axiosError.response?.status
221
359
  })
222
- orchestrator?.toast.error(tOr('core.login.failed', 'Login Failed'), message, 'LoginPage')
360
+ orchestrator?.toast.error(label('failed', 'Login Failed'), message, 'LoginPage')
223
361
 
224
362
  emit('error', error)
225
363
  } finally {
@@ -239,13 +377,69 @@ async function handleLogin(): Promise<void> {
239
377
  <component v-if="logo" :is="logo" class="qdadm-login-logo" />
240
378
  <i v-else :class="icon" class="qdadm-login-icon"></i>
241
379
  </slot>
242
- <h1>{{ displayTitle }}</h1>
380
+ <div class="qdadm-login-titles">
381
+ <h1>{{ displayTitle }}</h1>
382
+ <p v-if="subtitle" class="qdadm-login-subtitle">{{ subtitle }}</p>
383
+ </div>
384
+ <slot name="brand">
385
+ <img v-if="brandLogo" :src="brandLogo" alt="" class="qdadm-login-brand" />
386
+ </slot>
243
387
  </div>
244
388
  </template>
245
389
  <template #content>
246
- <form @submit.prevent="handleLogin" class="qdadm-login-form" autocomplete="off">
390
+ <!-- Identity provider first (#4321): its button leads, the local form is the fallback -->
391
+ <div v-if="sso" class="qdadm-login-sso">
392
+ <QdMessage v-if="shownError" severity="error" :closable="false" class="qdadm-login-error">{{ shownError }}</QdMessage>
393
+ <QdButton
394
+ v-if="sso.href"
395
+ as="a"
396
+ :href="sso.href"
397
+ :label="ssoLabel"
398
+ :icon="sso.icon ?? 'pi pi-sign-in'"
399
+ class="w-full qdadm-login-sso-button"
400
+ />
401
+ <QdButton
402
+ v-else
403
+ type="button"
404
+ :label="ssoLabel"
405
+ :icon="sso.icon ?? 'pi pi-sign-in'"
406
+ class="w-full qdadm-login-sso-button"
407
+ :loading="ssoLoading"
408
+ @click="handleSso"
409
+ />
410
+ <a
411
+ v-if="providerHome"
412
+ :href="providerHome.href"
413
+ target="_blank"
414
+ rel="noopener noreferrer"
415
+ class="qdadm-login-provider-home"
416
+ >{{ label('providerHome', 'My account', providerHome.label || null) }} <i class="pi pi-external-link" aria-hidden="true"></i></a>
417
+ <div v-if="localMode === 'open'" class="qdadm-login-divider" :class="{ 'qdadm-login-section': localSection }">
418
+ <span>{{ localSection || label('or', 'or') }}</span>
419
+ </div>
420
+ <QdButton
421
+ v-else-if="localMode === 'collapsed'"
422
+ type="button"
423
+ text
424
+ size="small"
425
+ class="qdadm-login-fallback-toggle"
426
+ :icon="localOpen ? 'pi pi-chevron-down' : 'pi pi-chevron-right'"
427
+ :label="label('localFallback', 'Alternative login', localFallbackLabel)"
428
+ :aria-expanded="String(localOpen)"
429
+ aria-controls="qdadm-login-local"
430
+ @click="localOpen ? (localOpen = false) : openLocal()"
431
+ />
432
+ </div>
433
+ <form
434
+ v-if="localMode !== 'hidden'"
435
+ v-show="localOpen"
436
+ id="qdadm-login-local"
437
+ @submit.prevent="handleLogin"
438
+ class="qdadm-login-form"
439
+ autocomplete="off"
440
+ >
247
441
  <div class="qdadm-login-field">
248
- <label for="qdadm-username">{{ labels.username }}</label>
442
+ <label for="qdadm-username">{{ texts.username }}</label>
249
443
  <InputText
250
444
  v-model="username"
251
445
  id="qdadm-username"
@@ -255,7 +449,7 @@ async function handleLogin(): Promise<void> {
255
449
  />
256
450
  </div>
257
451
  <div class="qdadm-login-field">
258
- <label for="qdadm-password">{{ labels.password }}</label>
452
+ <label for="qdadm-password">{{ texts.password }}</label>
259
453
  <Password
260
454
  v-model="password"
261
455
  inputId="qdadm-password"
@@ -267,7 +461,7 @@ async function handleLogin(): Promise<void> {
267
461
  </div>
268
462
  <QdButton
269
463
  type="submit"
270
- :label="labels.submit"
464
+ :label="texts.submit"
271
465
  icon="pi pi-sign-in"
272
466
  class="w-full"
273
467
  :loading="loading"
@@ -275,19 +469,86 @@ async function handleLogin(): Promise<void> {
275
469
  <!-- Alternative sign-ins (#1775): SSO buttons go between the form
276
470
  and the footer, which is where users look for them. Rendered
277
471
  only when filled, so the divider never shows on its own. -->
472
+ <template v-if="!sso">
473
+ <div v-if="$slots.alternatives" class="qdadm-login-alternatives">
474
+ <div class="qdadm-login-divider"><span>{{ label('or', 'or') }}</span></div>
475
+ <slot name="alternatives"></slot>
476
+ </div>
477
+
478
+ <slot name="footer"></slot>
479
+ </template>
480
+ </form>
481
+ <!-- With sso the form may be collapsed or absent: what follows it stays shown -->
482
+ <div v-if="sso && ($slots.alternatives || $slots.footer)" class="qdadm-login-after">
278
483
  <div v-if="$slots.alternatives" class="qdadm-login-alternatives">
279
- <div class="qdadm-login-divider"><span>{{ tOr('core.login.or', 'or') }}</span></div>
280
484
  <slot name="alternatives"></slot>
281
485
  </div>
282
-
283
486
  <slot name="footer"></slot>
284
- </form>
487
+ </div>
285
488
  </template>
286
489
  </Card>
287
490
  </div>
288
491
  </template>
289
492
 
290
493
  <style scoped>
494
+ .qdadm-login-sso {
495
+ display: flex;
496
+ flex-direction: column;
497
+ gap: 0.75rem;
498
+ margin-bottom: 1rem;
499
+ }
500
+
501
+ .qdadm-login-error {
502
+ margin: 0;
503
+ }
504
+
505
+ .qdadm-login-provider-home {
506
+ align-self: center;
507
+ font-size: 0.875rem;
508
+ color: var(--p-primary-color);
509
+ text-decoration: none;
510
+ }
511
+
512
+ .qdadm-login-provider-home:hover {
513
+ text-decoration: underline;
514
+ }
515
+
516
+ .qdadm-login-provider-home .pi {
517
+ font-size: 0.75rem;
518
+ }
519
+
520
+ .qdadm-login-fallback-toggle {
521
+ align-self: center;
522
+ }
523
+
524
+ .qdadm-login-titles {
525
+ display: flex;
526
+ flex-direction: column;
527
+ gap: 0.125rem;
528
+ min-width: 0;
529
+ }
530
+
531
+ .qdadm-login-subtitle {
532
+ margin: 0;
533
+ font-size: 0.875rem;
534
+ font-weight: 400;
535
+ color: var(--p-text-muted-color, #6b7280);
536
+ }
537
+
538
+ .qdadm-login-brand {
539
+ height: 1.5rem;
540
+ width: auto;
541
+ margin-left: auto;
542
+ opacity: 0.9;
543
+ }
544
+
545
+ .qdadm-login-after {
546
+ display: flex;
547
+ flex-direction: column;
548
+ gap: 1rem;
549
+ margin-top: 1rem;
550
+ }
551
+
291
552
  .qdadm-login-alternatives {
292
553
  display: flex;
293
554
  flex-direction: column;
@@ -302,6 +563,11 @@ async function handleLogin(): Promise<void> {
302
563
  font-size: 0.875rem;
303
564
  }
304
565
 
566
+ .qdadm-login-section {
567
+ font-weight: 500;
568
+ color: var(--p-text-color);
569
+ }
570
+
305
571
  .qdadm-login-divider::before,
306
572
  .qdadm-login-divider::after {
307
573
  content: '';
@@ -1,3 +1,12 @@
1
+ <script lang="ts">
2
+ /**
3
+ * One completion per callback (#4329): the attempt is consumed on read, so a
4
+ * second mount of the same callback (any app remount) must await the first
5
+ * instead of calling completeLogin again. Keyed by code and state.
6
+ */
7
+ const completions = new Map<string, Promise<{ user?: unknown; redirectTo: string }>>()
8
+ </script>
9
+
1
10
  <script setup lang="ts">
2
11
  /**
3
12
  * OAuth callback landing page (#1775).
@@ -32,8 +41,11 @@ interface OAuthCapableAdapter {
32
41
  completeLogin: (
33
42
  query: Record<string, string | undefined>
34
43
  ) => Promise<{ user?: unknown; redirectTo: string }>
44
+ isAuthenticated?: () => boolean
35
45
  }
36
46
 
47
+ type Completion = Promise<{ user?: unknown; redirectTo: string }>
48
+
37
49
  interface SignalsLike {
38
50
  emit?: (signal: string, payload?: unknown) => unknown
39
51
  }
@@ -75,15 +87,31 @@ onMounted(async () => {
75
87
  ])
76
88
  ) as Record<string, string | undefined>
77
89
 
78
- const result = await authAdapter.completeLogin(query)
79
-
90
+ const key = query.code ? `${query.code}|${query.state ?? ''}` : null
91
+ let completion: Completion | undefined = key ? completions.get(key) : undefined
92
+ const first = !completion
93
+ if (!completion) {
94
+ completion = authAdapter.completeLogin(query)
95
+ if (key) completions.set(key, completion)
96
+ }
97
+ const result = await completion
98
+ const target = result.redirectTo || props.fallbackRedirect
99
+
100
+ // Navigate, THEN signal (#4329): auth:login remounts the whole app, and on
101
+ // the callback route that remount would run this page again
102
+ await router.replace(target)
103
+ if (!first) return // the first mount signals
80
104
  // Same signal the password form emits, so debug bar, SSE bridge and any
81
105
  // listener see one authentication event whichever door was used.
82
106
  signals?.emit?.('auth:login', { user: result.user })
83
107
  emit('success', result)
84
-
85
- await router.replace(result.redirectTo || props.fallbackRedirect)
86
108
  } catch (err) {
109
+ // Back on a used callback while signed in (reload, back button): nothing to
110
+ // refuse, the session is there
111
+ if (authAdapter.isAuthenticated?.()) {
112
+ await router.replace(props.fallbackRedirect)
113
+ return
114
+ }
87
115
  error.value = (err as Error)?.message ?? 'Sign-in failed'
88
116
  signals?.emit?.('auth:login:error', { error: error.value })
89
117
  emit('error', err)
@@ -0,0 +1,220 @@
1
+ /**
2
+ * useCardsArrangement — the user's arrangement of a card dashboard (#4320):
3
+ * order, hidden, pinned, kept in localStorage per dashboard and per user.
4
+ *
5
+ * The saved arrangement is reconciled with the cards the app declares on every
6
+ * load: unknown ids are dropped, a new card takes its default place, a
7
+ * required card is never hidden, a fixed card keeps its default place.
8
+ *
9
+ * The functions are pure; the composable wraps them with a ref and storage.
10
+ */
11
+ import { computed, ref, watch, type ComputedRef, type Ref } from 'vue'
12
+ import type { BlockCard } from '../zones/ZoneRegistry'
13
+
14
+ /** A card as the dashboard knows it: its id and its declaration, in default order. */
15
+ export interface CardDef {
16
+ id: string
17
+ card: BlockCard & { title: string }
18
+ }
19
+
20
+ export interface CardsArrangement {
21
+ v: 1
22
+ /** Every known card, hidden ones included: a restored card comes back where it was */
23
+ order: string[]
24
+ hidden: string[]
25
+ pinned: string[]
26
+ }
27
+
28
+ export interface CardsGroups {
29
+ pinned: CardDef[]
30
+ rest: CardDef[]
31
+ hidden: CardDef[]
32
+ }
33
+
34
+ export const CARDS_ARRANGEMENT_VERSION = 1
35
+
36
+ /** Migrations from an older saved version to the next; none yet. */
37
+ const MIGRATIONS: Record<number, (old: Record<string, unknown>) => Record<string, unknown>> = {}
38
+
39
+ export function defaultArrangement(cards: CardDef[]): CardsArrangement {
40
+ return {
41
+ v: 1,
42
+ order: cards.map((c) => c.id),
43
+ hidden: [],
44
+ pinned: cards.filter((c) => c.card.pinned).map((c) => c.id),
45
+ }
46
+ }
47
+
48
+ /** Fixed cards back at their default index, the others flowing around them. */
49
+ function placeFixed(order: string[], cards: CardDef[]): string[] {
50
+ const fixed = cards.map((c, i) => ({ c, i })).filter(({ c }) => c.card.fixed)
51
+ if (!fixed.length) return order
52
+ const fixedIds = new Set(fixed.map(({ c }) => c.id))
53
+ const out = order.filter((id) => !fixedIds.has(id))
54
+ for (const { c, i } of fixed) out.splice(Math.min(i, out.length), 0, c.id)
55
+ return out
56
+ }
57
+
58
+ /** Bring a saved arrangement (any shape, any version) in line with the declared cards. */
59
+ export function reconcileArrangement(saved: unknown, cards: CardDef[]): CardsArrangement {
60
+ const fallback = defaultArrangement(cards)
61
+ let data = saved && typeof saved === 'object' ? (saved as Record<string, unknown>) : null
62
+ if (!data) return fallback
63
+ for (let v = Number(data.v); v < CARDS_ARRANGEMENT_VERSION && MIGRATIONS[v]; v = Number(data.v)) data = MIGRATIONS[v]!(data)
64
+ if (data.v !== CARDS_ARRANGEMENT_VERSION) return fallback
65
+
66
+ const byId = new Map(cards.map((c) => [c.id, c]))
67
+ const ids = (list: unknown): string[] => (Array.isArray(list) ? list.filter((id): id is string => typeof id === 'string' && byId.has(id)) : [])
68
+ const savedOrder = [...new Set(ids(data.order))]
69
+ const known = new Set(savedOrder)
70
+
71
+ // A new card goes after its nearest earlier neighbour in the default order
72
+ const order = [...savedOrder]
73
+ cards.forEach((c, i) => {
74
+ if (known.has(c.id)) return
75
+ let at = 0
76
+ for (let j = i - 1; j >= 0; j--) {
77
+ const k = order.indexOf(cards[j]!.id)
78
+ if (k !== -1) {
79
+ at = k + 1
80
+ break
81
+ }
82
+ }
83
+ order.splice(at, 0, c.id)
84
+ })
85
+
86
+ const hidden = ids(data.hidden).filter((id) => !byId.get(id)!.card.required)
87
+ // A fixed card keeps its declared pin; a new card takes its default
88
+ const pinned = new Set(ids(data.pinned).filter((id) => !byId.get(id)!.card.fixed))
89
+ for (const c of cards) if (c.card.pinned && (c.card.fixed || !known.has(c.id))) pinned.add(c.id)
90
+ return { v: 1, order: placeFixed(order, cards), hidden: [...new Set(hidden)], pinned: order.filter((id) => pinned.has(id)) }
91
+ }
92
+
93
+ export function groupCards(arrangement: CardsArrangement, cards: CardDef[]): CardsGroups {
94
+ const byId = new Map(cards.map((c) => [c.id, c]))
95
+ const hidden = new Set(arrangement.hidden)
96
+ const pinned = new Set(arrangement.pinned)
97
+ const inOrder = arrangement.order.map((id) => byId.get(id)).filter((c): c is CardDef => !!c)
98
+ return {
99
+ pinned: inOrder.filter((c) => pinned.has(c.id) && !hidden.has(c.id)),
100
+ rest: inOrder.filter((c) => !pinned.has(c.id) && !hidden.has(c.id)),
101
+ hidden: inOrder.filter((c) => hidden.has(c.id)),
102
+ }
103
+ }
104
+
105
+ /** The visible group a card is in, as ids. */
106
+ function groupOf(arrangement: CardsArrangement, cards: CardDef[], id: string): string[] {
107
+ const g = groupCards(arrangement, cards)
108
+ const group = g.pinned.some((c) => c.id === id) ? g.pinned : g.rest
109
+ return group.map((c) => c.id)
110
+ }
111
+
112
+ /**
113
+ * Move a card to an index of its visible group. Fixed cards keep their index
114
+ * in the group; the others flow around them. Returns the same object when
115
+ * nothing moves.
116
+ */
117
+ export function moveCard(arrangement: CardsArrangement, cards: CardDef[], id: string, toIndex: number): CardsArrangement {
118
+ const byId = new Map(cards.map((c) => [c.id, c]))
119
+ if (byId.get(id)?.card.fixed) return arrangement
120
+ const group = groupOf(arrangement, cards, id)
121
+ const from = group.indexOf(id)
122
+ if (from === -1) return arrangement
123
+ const fixed = group.map((gid, i) => ({ gid, i })).filter(({ gid }) => byId.get(gid)?.card.fixed)
124
+ const movable = group.filter((gid) => !byId.get(gid)?.card.fixed && gid !== id)
125
+ // Target in the group's coordinates: the movable cards before it are its
126
+ // non-fixed slots
127
+ const target = Math.max(0, Math.min(toIndex, group.length - 1))
128
+ movable.splice(target - fixed.filter(({ i }) => i < target).length, 0, id)
129
+ for (const { gid, i } of fixed) movable.splice(i, 0, gid)
130
+ if (movable.every((gid, i) => gid === group[i])) return arrangement
131
+ // Write the group back into the slots its cards held in the full order
132
+ const slots = arrangement.order.map((oid, i) => (group.includes(oid) ? i : -1)).filter((i) => i !== -1)
133
+ const order = [...arrangement.order]
134
+ slots.forEach((slot, k) => (order[slot] = movable[k]!))
135
+ return { ...arrangement, order }
136
+ }
137
+
138
+ export function setPinned(arrangement: CardsArrangement, cards: CardDef[], id: string, pinned: boolean): CardsArrangement {
139
+ const card = cards.find((c) => c.id === id)
140
+ if (!card || card.card.fixed || arrangement.pinned.includes(id) === pinned) return arrangement
141
+ // It joins the end of its new group
142
+ const order = [...arrangement.order.filter((oid) => oid !== id), id]
143
+ const pinnedSet = new Set(arrangement.pinned)
144
+ if (pinned) pinnedSet.add(id)
145
+ else pinnedSet.delete(id)
146
+ return { ...arrangement, order: placeFixed(order, cards), pinned: order.filter((oid) => pinnedSet.has(oid)) }
147
+ }
148
+
149
+ export function setHidden(arrangement: CardsArrangement, cards: CardDef[], id: string, hidden: boolean): CardsArrangement {
150
+ const card = cards.find((c) => c.id === id)
151
+ if (!card || (hidden && card.card.required) || arrangement.hidden.includes(id) === hidden) return arrangement
152
+ return { ...arrangement, hidden: hidden ? [...arrangement.hidden, id] : arrangement.hidden.filter((h) => h !== id) }
153
+ }
154
+
155
+ function readStorage(key: string): unknown {
156
+ try {
157
+ const raw = globalThis.localStorage?.getItem(key)
158
+ return raw ? JSON.parse(raw) : null
159
+ } catch {
160
+ return null
161
+ }
162
+ }
163
+
164
+ function writeStorage(key: string, value: CardsArrangement | null): void {
165
+ try {
166
+ if (value) globalThis.localStorage?.setItem(key, JSON.stringify(value))
167
+ else globalThis.localStorage?.removeItem(key)
168
+ } catch {
169
+ // No storage (private window, quota, blocked): the arrangement lasts the page
170
+ }
171
+ }
172
+
173
+ export interface UseCardsArrangementReturn {
174
+ arrangement: Ref<CardsArrangement>
175
+ groups: ComputedRef<CardsGroups>
176
+ move: (id: string, toIndex: number) => boolean
177
+ pin: (id: string, pinned: boolean) => boolean
178
+ hide: (id: string, hidden: boolean) => boolean
179
+ /** Replace the arrangement without saving (a drag in progress) */
180
+ preview: (next: CardsArrangement) => void
181
+ /** Save what is shown */
182
+ commit: () => void
183
+ reset: () => void
184
+ }
185
+
186
+ /**
187
+ * @param storageKey - the localStorage key (dashboard and user in it)
188
+ * @param cards - the declared cards, in default order
189
+ */
190
+ export function useCardsArrangement(storageKey: Ref<string>, cards: Ref<CardDef[]>): UseCardsArrangementReturn {
191
+ const arrangement = ref<CardsArrangement>(reconcileArrangement(readStorage(storageKey.value), cards.value))
192
+ // A new user or a changed set of cards: read again, reconciled
193
+ watch([storageKey, cards], () => {
194
+ arrangement.value = reconcileArrangement(readStorage(storageKey.value), cards.value)
195
+ })
196
+ const groups = computed(() => groupCards(arrangement.value, cards.value))
197
+
198
+ const apply = (next: CardsArrangement): boolean => {
199
+ if (next === arrangement.value) return false
200
+ arrangement.value = next
201
+ writeStorage(storageKey.value, next)
202
+ return true
203
+ }
204
+
205
+ return {
206
+ arrangement,
207
+ groups,
208
+ move: (id, toIndex) => apply(moveCard(arrangement.value, cards.value, id, toIndex)),
209
+ pin: (id, pinned) => apply(setPinned(arrangement.value, cards.value, id, pinned)),
210
+ hide: (id, hidden) => apply(setHidden(arrangement.value, cards.value, id, hidden)),
211
+ preview: (next) => {
212
+ arrangement.value = next
213
+ },
214
+ commit: () => writeStorage(storageKey.value, arrangement.value),
215
+ reset: () => {
216
+ writeStorage(storageKey.value, null)
217
+ arrangement.value = defaultArrangement(cards.value)
218
+ },
219
+ }
220
+ }