@quazardous/qdadm 2.40.0 → 2.42.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.
@@ -5,9 +5,16 @@
5
5
  * Status, progress (indeterminate without a figure), current step, the live
6
6
  * log, then the result or the error, a link to the task, and cancel when the
7
7
  * backend allows it. Closing it does not stop anything: the run goes on in
8
- * the tray. TaskHost renders it; a page may render its own with a #result slot.
8
+ * the tray. TaskHost renders it; a page may render its own.
9
+ *
10
+ * The window (#4334) moves by its title bar, resizes by its corner and goes
11
+ * full screen (Escape leaves full screen first); its size, position and full
12
+ * screen are kept per app. Under 640px it stays a plain 96vw dialog. Options
13
+ * and slots come layered: qdadm's defaults, the app's (configureTasks), the
14
+ * task kind's, then these props. Slots `header`, `before-log`, `after-log`,
15
+ * `actions` and `result` get `{ run, kind, final }`.
9
16
  */
10
- import { computed, onBeforeUnmount, ref } from 'vue'
17
+ import { computed, inject, onBeforeUnmount, onMounted, ref, useSlots, watch, type Component } from 'vue'
11
18
  import { RouterLink } from 'vue-router'
12
19
  import Dialog from 'primevue/dialog'
13
20
  import ProgressBar from 'primevue/progressbar'
@@ -16,29 +23,47 @@ import LogStream from '../display/LogStream.vue'
16
23
  import JsonViewer from '../editors/JsonViewer.vue'
17
24
  import { useI18n } from '../../i18n/useI18n'
18
25
  import { getTaskStore } from '../../tasks/taskStore'
26
+ import { resolveTaskUi, type TaskDialogOptions, type TaskDialogSlotName } from '../../tasks/taskUi'
19
27
 
20
28
  interface Props {
21
29
  runId: string | null
30
+ /** Window options over the app's and the kind's */
31
+ options?: TaskDialogOptions | null
32
+ /** Shorthand for options.width */
22
33
  width?: string
23
34
  }
24
35
 
25
- const props = withDefaults(defineProps<Props>(), { width: '46rem' })
36
+ const props = withDefaults(defineProps<Props>(), { options: null, width: undefined })
26
37
  const emit = defineEmits<{ close: [] }>()
38
+ const slots = useSlots()
27
39
 
28
40
  const { t } = useI18n()
29
41
  const store = getTaskStore()
42
+ const appConfig = inject<{ name?: string }>('qdadmApp', {})
30
43
 
31
44
  const run = computed(() => (props.runId ? store.state.runs.find((r) => r.id === props.runId) ?? null : null))
32
45
  const def = computed(() => (props.runId ? store.definition(props.runId) : undefined))
33
46
  const final = computed(() => (run.value ? store.isFinal(run.value.status) : false))
34
47
  const logSource = computed(() => (run.value?.taskId != null && def.value?.log ? def.value.log(run.value.taskId) : null))
48
+ /** The log's download name: the kind and the task, e.g. "deploy-42.log" */
49
+ const logFilename = computed(() => {
50
+ const r = run.value
51
+ const name = `${r?.kind ?? 'task'}-${r?.taskId ?? r?.id ?? 'log'}`.replace(/[^\w.-]+/g, '_')
52
+ return `${name}.log`
53
+ })
35
54
  const link = computed(() => (run.value?.taskId != null && def.value?.to ? def.value.to(run.value.taskId) : null))
36
55
  const canCancel = computed(() => !!def.value?.cancel && !final.value && run.value?.taskId != null)
37
56
  const resultIsObject = computed(() => run.value?.result !== null && typeof run.value?.result === 'object')
38
57
 
58
+ const ui = computed(() => resolveTaskUi(def.value, { ...props.options, ...(props.width ? { width: props.width } : {}) }))
59
+ const opts = computed(() => ui.value.dialog)
60
+ const slotProps = computed(() => ({ run: run.value, kind: run.value?.kind ?? null, final: final.value }))
61
+ /** A page's slot, else the component the app or the kind gave for it */
62
+ const slotComponent = (name: TaskDialogSlotName): Component | null => (slots[name] ? null : (ui.value.slots[name] ?? null))
63
+ const has = (name: TaskDialogSlotName) => !!slots[name] || !!ui.value.slots[name]
64
+
39
65
  const now = ref(Date.now())
40
66
  const ticker = setInterval(() => (now.value = Date.now()), 1000)
41
- onBeforeUnmount(() => clearInterval(ticker))
42
67
 
43
68
  const elapsed = computed(() => {
44
69
  if (!run.value) return ''
@@ -46,11 +71,159 @@ const elapsed = computed(() => {
46
71
  const s = Math.round(ms / 1000)
47
72
  return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${s % 60} s`
48
73
  })
74
+
75
+ // ── The window (#4334) ────────────────────────────────────────────────────
76
+ const narrowQuery = typeof window !== 'undefined' && window.matchMedia ? window.matchMedia('(max-width: 640px)') : null
77
+ const narrow = ref(!!narrowQuery?.matches)
78
+ const onNarrow = (e: MediaQueryListEvent) => (narrow.value = e.matches)
79
+ onMounted(() => narrowQuery?.addEventListener?.('change', onNarrow))
80
+
81
+ const draggable = computed(() => opts.value.draggable && !narrow.value)
82
+ const resizable = computed(() => opts.value.resizable && !narrow.value)
83
+ const maximizable = computed(() => opts.value.maximizable)
84
+ const remember = computed(() => opts.value.rememberLayout && !narrow.value)
85
+
86
+ const dialog = ref<{ container?: HTMLElement | null; maximized?: boolean; maximize?: (e?: Event) => void } | null>(null)
87
+ const maximized = ref(false)
88
+ const layoutKey = computed(() => `qdadm.tasks.dialog.${(appConfig.name ?? 'app').toLowerCase().replace(/[^a-z0-9]+/g, '-')}`)
89
+
90
+ interface Layout {
91
+ width?: number
92
+ height?: number
93
+ left?: number
94
+ top?: number
95
+ maximized?: boolean
96
+ }
97
+
98
+ function readLayout(): Layout {
99
+ try {
100
+ const raw = globalThis.localStorage?.getItem(layoutKey.value)
101
+ return raw ? (JSON.parse(raw) as Layout) : {}
102
+ } catch {
103
+ return {}
104
+ }
105
+ }
106
+
107
+ function saveLayout(patch: Layout): void {
108
+ if (!remember.value) return
109
+ try {
110
+ globalThis.localStorage?.setItem(layoutKey.value, JSON.stringify({ ...readLayout(), ...patch }))
111
+ } catch {
112
+ // No storage: the layout lasts the page
113
+ }
114
+ }
115
+
116
+ const container = () => dialog.value?.container ?? null
117
+ // The restored size goes through the bound style, or a re-render puts the default width back
118
+ const size = ref<{ width?: string; height?: string }>({})
119
+
120
+ function onShow(): void {
121
+ if (!remember.value) return
122
+ const saved = readLayout()
123
+ const el = container()
124
+ if (el) {
125
+ const vw = window.innerWidth
126
+ const vh = window.innerHeight
127
+ // Clamped to this viewport: a layout saved on a larger screen stays reachable
128
+ if (resizable.value && saved.width && saved.height) {
129
+ size.value = { width: `${Math.min(saved.width, vw * 0.96)}px`, height: `${Math.min(saved.height, vh * 0.9)}px` }
130
+ }
131
+ if (draggable.value && saved.left !== undefined && saved.top !== undefined) {
132
+ const r = el.getBoundingClientRect()
133
+ el.style.position = 'fixed'
134
+ el.style.margin = '0'
135
+ el.style.left = `${Math.max(0, Math.min(saved.left, vw - r.width))}px`
136
+ el.style.top = `${Math.max(0, Math.min(saved.top, vh - Math.min(r.height, vh)))}px`
137
+ }
138
+ }
139
+ if (saved.maximized && maximizable.value && !dialog.value?.maximized) dialog.value?.maximize?.()
140
+ }
141
+
142
+ function onDragEnd(): void {
143
+ const el = container()
144
+ if (!el) return
145
+ const r = el.getBoundingClientRect()
146
+ saveLayout({ left: Math.round(r.left), top: Math.round(r.top) })
147
+ }
148
+
149
+ // A native corner resize writes px into the inline style: that is the user's size
150
+ function onPointerUp(): void {
151
+ const el = container()
152
+ if (!el || !run.value || maximized.value || !resizable.value) return
153
+ if (!el.style.height.endsWith('px')) return
154
+ const r = el.getBoundingClientRect()
155
+ size.value = { width: `${Math.round(r.width)}px`, height: `${Math.round(r.height)}px` }
156
+ saveLayout({ width: Math.round(r.width), height: Math.round(r.height) })
157
+ }
158
+
159
+ function onMaximize(): void {
160
+ maximized.value = true
161
+ saveLayout({ maximized: true })
162
+ }
163
+
164
+ function onUnmaximize(): void {
165
+ maximized.value = false
166
+ saveLayout({ maximized: false })
167
+ }
168
+
169
+ // Escape leaves full screen first, then closes
170
+ function onKeyDown(event: KeyboardEvent): void {
171
+ if (event.key !== 'Escape' || !run.value) return
172
+ if (maximized.value) dialog.value?.maximize?.(event)
173
+ else emit('close')
174
+ }
175
+
176
+ watch(
177
+ () => !!run.value,
178
+ (open) => {
179
+ if (open) {
180
+ window.addEventListener('pointerup', onPointerUp)
181
+ window.addEventListener('keydown', onKeyDown)
182
+ } else {
183
+ window.removeEventListener('pointerup', onPointerUp)
184
+ window.removeEventListener('keydown', onKeyDown)
185
+ maximized.value = false
186
+ size.value = {}
187
+ }
188
+ },
189
+ { immediate: true }
190
+ )
191
+
192
+ onBeforeUnmount(() => {
193
+ clearInterval(ticker)
194
+ narrowQuery?.removeEventListener?.('change', onNarrow)
195
+ window.removeEventListener('pointerup', onPointerUp)
196
+ window.removeEventListener('keydown', onKeyDown)
197
+ })
49
198
  </script>
50
199
 
51
200
  <template>
52
- <Dialog :visible="!!run" modal :header="run?.label" :style="{ width }" :breakpoints="{ '640px': '96vw' }"
53
- class="qd-task-dialog" @update:visible="(v: boolean) => !v && emit('close')">
201
+ <Dialog
202
+ ref="dialog"
203
+ :visible="!!run"
204
+ :modal="opts.modal"
205
+ :header="run?.label"
206
+ :style="{ width: size.width ?? opts.width, height: size.height }"
207
+ :breakpoints="{ '640px': '96vw' }"
208
+ :draggable="draggable"
209
+ :maximizable="maximizable"
210
+ :close-on-escape="false"
211
+ :position="opts.position"
212
+ class="qd-task-dialog"
213
+ :class="[opts.class, { 'qd-task-dialog--resizable': resizable && !maximized }]"
214
+ @update:visible="(v: boolean) => !v && emit('close')"
215
+ @show="onShow"
216
+ @dragend="onDragEnd"
217
+ @maximize="onMaximize"
218
+ @unmaximize="onUnmaximize"
219
+ >
220
+ <template v-if="has('header')" #header>
221
+ <div class="qd-task-header">
222
+ <slot name="header" v-bind="slotProps">
223
+ <component :is="slotComponent('header')!" v-bind="slotProps" />
224
+ </slot>
225
+ </div>
226
+ </template>
54
227
  <template v-if="run">
55
228
  <div class="qd-task-head">
56
229
  <span class="qd-task-status" :class="`qd-task-status--${run.status}`">
@@ -63,30 +236,41 @@ const elapsed = computed(() => {
63
236
  <span class="qd-task-elapsed">{{ elapsed }}</span>
64
237
  <span v-if="run.taskId !== null" class="qd-task-id">#{{ run.taskId }}</span>
65
238
  </div>
66
-
67
239
  <ProgressBar v-if="!final" class="qd-task-progress" :mode="run.progress === null ? 'indeterminate' : 'determinate'"
68
240
  :value="Math.round(run.progress ?? 0)" :show-value="run.progress !== null" />
69
241
  <div v-if="run.step" class="qd-task-step">{{ run.step }}</div>
70
-
71
- <LogStream v-if="logSource" :key="run.id" class="qd-task-log" :source="logSource" height="16rem"
242
+ <div v-if="has('before-log')" class="qd-task-before-log">
243
+ <slot name="before-log" v-bind="slotProps">
244
+ <component :is="slotComponent('before-log')!" v-bind="slotProps" />
245
+ </slot>
246
+ </div>
247
+ <LogStream v-if="logSource" :key="run.id" class="qd-task-log" :source="logSource" :filename="logFilename" height="16rem"
72
248
  error-pattern="error|fatal|failed" @done="store.poke(run.id)" />
73
-
249
+ <div v-if="has('after-log')" class="qd-task-after-log">
250
+ <slot name="after-log" v-bind="slotProps">
251
+ <component :is="slotComponent('after-log')!" v-bind="slotProps" />
252
+ </slot>
253
+ </div>
74
254
  <div v-if="run.status === 'failed' && run.error" class="qd-task-error"><i class="pi pi-exclamation-triangle" /> {{ run.error }}</div>
75
255
  <div v-else-if="!final && run.error" class="qd-task-warning">{{ t('core.task.readError', { error: run.error }) }}</div>
76
-
77
256
  <div v-if="run.status === 'succeeded' && run.result !== null" class="qd-task-result">
78
- <slot name="result" :run="run">
79
- <JsonViewer v-if="resultIsObject" :model-value="(run.result as never)" height="12rem" />
257
+ <slot name="result" v-bind="slotProps">
258
+ <component :is="slotComponent('result')!" v-if="slotComponent('result')" v-bind="slotProps" />
259
+ <JsonViewer v-else-if="resultIsObject" :model-value="(run.result as never)" height="12rem" />
80
260
  <span v-else>{{ run.result }}</span>
81
261
  </slot>
82
262
  </div>
83
263
  </template>
84
-
85
264
  <template #footer>
86
265
  <RouterLink v-if="link" :to="(link as never)" class="qd-task-link" @click="emit('close')">
87
266
  <i class="pi pi-external-link" /> {{ t('core.task.open') }}
88
267
  </RouterLink>
89
268
  <span class="qd-task-spacer" />
269
+ <template v-if="has('actions') && run">
270
+ <slot name="actions" v-bind="slotProps">
271
+ <component :is="slotComponent('actions')!" v-bind="slotProps" />
272
+ </slot>
273
+ </template>
90
274
  <QdButton v-if="canCancel" severity="danger" text :loading="run?.cancelling" icon="pi pi-stop-circle"
91
275
  :label="t('core.task.cancel')" @click="run && store.cancel(run.id)" />
92
276
  <QdButton :label="final ? t('core.task.close') : t('core.task.background')" severity="secondary" @click="emit('close')" />
@@ -6,6 +6,10 @@
6
6
  * dangerous task. AppLayout mounts one; an app with its own layout mounts
7
7
  * it once, near the root. Without a host, a task that asks for confirmation
8
8
  * does not start.
9
+ *
10
+ * The follow dialog is TaskDialog, or the `component` the run's kind or the
11
+ * app gives (#4334), with props `{ runId, options }` and a `close` event. The
12
+ * host's slots go to TaskDialog.
9
13
  */
10
14
  import { computed, onBeforeUnmount, ref, watch } from 'vue'
11
15
  import InputText from 'primevue/inputtext'
@@ -14,6 +18,7 @@ import TaskDialog from './TaskDialog.vue'
14
18
  import { useI18n } from '../../i18n/useI18n'
15
19
  import { useTaskRunner } from '../../tasks/useTaskRunner'
16
20
  import { getTaskStore } from '../../tasks/taskStore'
21
+ import { resolveTaskUi } from '../../tasks/taskUi'
17
22
  import { useTaskNotifications } from '../../tasks/useTaskNotifications'
18
23
 
19
24
  useTaskRunner()
@@ -25,6 +30,12 @@ const { t } = useI18n()
25
30
  store.state.hosts++
26
31
  onBeforeUnmount(() => store.state.hosts--)
27
32
 
33
+ // The open run's dialog: a replacement from its kind or the app, else TaskDialog
34
+ const dialogComponent = computed(() => {
35
+ const id = store.state.openId
36
+ return (id ? resolveTaskUi(store.definition(id)).component : resolveTaskUi().component) ?? TaskDialog
37
+ })
38
+
28
39
  const pending = computed(() => store.state.pendingConfirm)
29
40
  const typed = ref('')
30
41
  watch(pending, () => (typed.value = ''))
@@ -34,7 +45,11 @@ const severity = computed(() => pending.value?.confirm.severity ?? (expected.val
34
45
  </script>
35
46
 
36
47
  <template>
37
- <TaskDialog :run-id="store.state.openId" @close="store.open(null)" />
48
+ <component :is="dialogComponent" :run-id="store.state.openId" :options="null" @close="store.open(null)">
49
+ <template v-for="(_, name) in $slots" #[name]="slotProps">
50
+ <slot :name="name" v-bind="slotProps ?? {}" />
51
+ </template>
52
+ </component>
38
53
  <SimpleDialog :visible="!!pending" :title="pending?.label ?? ''" :confirm-label="pending?.confirm.accept ?? t('core.task.start')"
39
54
  :confirm-severity="severity" :confirm-disabled="!confirmable" :cancel-label="t('core.task.dontStart')"
40
55
  @confirm="store.answerConfirm(true)" @cancel="store.answerConfirm(false)"
@@ -3,16 +3,19 @@
3
3
  * TaskTray - the running tasks, in the sidebar (#4114)
4
4
  *
5
5
  * Shown while there is a run to show. Each run reopens its dialog; finished
6
- * ones can be cleared.
6
+ * ones can be cleared. A row's content can be replaced (#4334): the `item`
7
+ * slot, or `configureTasks({ tray: { item } })`, gets `{ run }`.
7
8
  */
8
9
  import { computed, ref } from 'vue'
9
10
  import Popover from 'primevue/popover'
10
11
  import QdButton from '../base/QdButton.vue'
11
12
  import { useI18n } from '../../i18n/useI18n'
12
13
  import { getTaskStore } from '../../tasks/taskStore'
14
+ import { getTaskUi } from '../../tasks/taskUi'
13
15
  import { useTaskTrayVisible } from '../../tasks/useTaskNotifications'
14
16
 
15
17
  const store = getTaskStore()
18
+ const taskUi = getTaskUi()
16
19
  // With the notification zone on, running tasks show there instead (#4171)
17
20
  const visible = useTaskTrayVisible()
18
21
  const { t } = useI18n()
@@ -43,11 +46,16 @@ const icon = (status: string) =>
43
46
  <ul class="qd-task-list">
44
47
  <li v-for="r in runs" :key="r.id">
45
48
  <button type="button" class="qd-task-item" :class="`qd-task-item--${r.status}`" @click="openRun(r.id)">
46
- <i :class="icon(r.status)" />
47
- <span class="qd-task-item-label">{{ r.label }}</span>
48
- <span class="qd-task-item-state">
49
- {{ r.progress !== null && !store.isFinal(r.status) ? `${Math.round(r.progress)} %` : t(`core.task.status.${r.status}`) }}
50
- </span>
49
+ <slot name="item" :run="r">
50
+ <component :is="taskUi.tray.item" v-if="taskUi.tray?.item" :run="r" />
51
+ <template v-else>
52
+ <i :class="icon(r.status)" />
53
+ <span class="qd-task-item-label">{{ r.label }}</span>
54
+ <span class="qd-task-item-state">
55
+ {{ r.progress !== null && !store.isFinal(r.status) ? `${Math.round(r.progress)} %` : t(`core.task.status.${r.status}`) }}
56
+ </span>
57
+ </template>
58
+ </slot>
51
59
  </button>
52
60
  </li>
53
61
  </ul>
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * useCardsArrangement — the user's arrangement of a card dashboard (#4320):
3
- * order, hidden, pinned, kept in localStorage per dashboard and per user.
3
+ * order, hidden, pinned, kept per dashboard and per user in a storage the app
4
+ * may provide (#4338: the server, per account); localStorage by default.
4
5
  *
5
6
  * The saved arrangement is reconciled with the cards the app declares on every
6
7
  * load: unknown ids are dropped, a new card takes its default place, a
@@ -8,7 +9,7 @@
8
9
  *
9
10
  * The functions are pure; the composable wraps them with a ref and storage.
10
11
  */
11
- import { computed, ref, watch, type ComputedRef, type Ref } from 'vue'
12
+ import { computed, onScopeDispose, ref, watch, type ComputedRef, type Ref } from 'vue'
12
13
  import type { BlockCard } from '../zones/ZoneRegistry'
13
14
 
14
15
  /** A card as the dashboard knows it: its id and its declaration, in default order. */
@@ -152,69 +153,204 @@ export function setHidden(arrangement: CardsArrangement, cards: CardDef[], id: s
152
153
  return { ...arrangement, hidden: hidden ? [...arrangement.hidden, id] : arrangement.hidden.filter((h) => h !== id) }
153
154
  }
154
155
 
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
- }
156
+ /**
157
+ * Where arrangements are kept (#4338). `load` may answer at once (localStorage)
158
+ * or with a promise (a server); whatever it gives back is reconciled with the
159
+ * declared cards, so an old or partial shape is fine. `save(key, null)`: back
160
+ * to the defaults.
161
+ */
162
+ export interface CardsArrangementStorage {
163
+ load(key: string): unknown | Promise<unknown>
164
+ save(key: string, arrangement: CardsArrangement | null): void | Promise<void>
162
165
  }
163
166
 
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
- }
167
+ /** The default storage: localStorage; no storage at all (private window, blocked): the arrangement lasts the page */
168
+ export const localArrangementStorage: CardsArrangementStorage = {
169
+ load(key) {
170
+ try {
171
+ const raw = globalThis.localStorage?.getItem(key)
172
+ return raw ? JSON.parse(raw) : null
173
+ } catch {
174
+ return null
175
+ }
176
+ },
177
+ save(key, value) {
178
+ try {
179
+ if (value) globalThis.localStorage?.setItem(key, JSON.stringify(value))
180
+ else globalThis.localStorage?.removeItem(key)
181
+ } catch {
182
+ // Quota or blocked: the arrangement lasts the page
183
+ }
184
+ },
185
+ }
186
+
187
+ const isThenable = (v: unknown): v is PromiseLike<unknown> => !!v && typeof (v as { then?: unknown }).then === 'function'
188
+
189
+ export interface UseCardsArrangementOptions {
190
+ /** The storage, or a getter read at each load and save (default: localArrangementStorage) */
191
+ storage?: CardsArrangementStorage | (() => CardsArrangementStorage)
192
+ /** Save at each change (default true); false: only `commit()` and `reset()` save */
193
+ autoSave?: boolean
194
+ /** Ms an async load may take while `loading` holds the cards back (default 150) */
195
+ loadGrace?: number
196
+ /** A load or a save failed (default: a console warning) */
197
+ onError?: (op: 'load' | 'save', error: unknown) => void
171
198
  }
172
199
 
173
200
  export interface UseCardsArrangementReturn {
174
201
  arrangement: Ref<CardsArrangement>
175
202
  groups: ComputedRef<CardsGroups>
203
+ /** An async load is in its grace: hold the cards back rather than show the defaults */
204
+ loading: Ref<boolean>
205
+ saving: Ref<boolean>
206
+ /** What is shown differs from what the storage holds */
207
+ dirty: ComputedRef<boolean>
176
208
  move: (id: string, toIndex: number) => boolean
177
209
  pin: (id: string, pinned: boolean) => boolean
178
210
  hide: (id: string, hidden: boolean) => boolean
179
211
  /** Replace the arrangement without saving (a drag in progress) */
180
212
  preview: (next: CardsArrangement) => void
181
- /** Save what is shown */
182
- commit: () => void
183
- reset: () => void
213
+ /** Save what is shown; false when the storage failed */
214
+ commit: () => Promise<boolean>
215
+ /** Back to the defaults, in the storage too; false when the storage failed */
216
+ reset: () => Promise<boolean>
184
217
  }
185
218
 
186
219
  /**
187
- * @param storageKey - the localStorage key (dashboard and user in it)
220
+ * @param storageKey - the storage key (dashboard and user in it)
188
221
  * @param cards - the declared cards, in default order
189
222
  */
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)
223
+ export function useCardsArrangement(
224
+ storageKey: Ref<string>,
225
+ cards: Ref<CardDef[]>,
226
+ options: UseCardsArrangementOptions = {}
227
+ ): UseCardsArrangementReturn {
228
+ const storage = (): CardsArrangementStorage =>
229
+ (typeof options.storage === 'function' ? options.storage() : options.storage) ?? localArrangementStorage
230
+ const autoSave = options.autoSave ?? true
231
+ const onError =
232
+ options.onError ?? ((op, err) => console.warn(`[qdadm] CardsDashboard: the arrangement could not ${op === 'load' ? 'be loaded' : 'be saved'}:`, err))
233
+
234
+ /** What the storage holds, as it gave it (reconciled again when the cards change) */
235
+ let stored: unknown = null
236
+ /** The user changed something since the last load: a late answer must not undo it */
237
+ let touched = false
238
+ let loadToken = 0
239
+ let graceTimer: ReturnType<typeof setTimeout> | null = null
240
+
241
+ const arrangement = ref<CardsArrangement>(defaultArrangement(cards.value))
242
+ const savedJson = ref(JSON.stringify(arrangement.value))
243
+ const loading = ref(false)
244
+ const saving = ref(false)
245
+ const dirty = computed(() => JSON.stringify(arrangement.value) !== savedJson.value)
246
+
247
+ function settle(raw: unknown): void {
248
+ stored = raw
249
+ arrangement.value = reconcileArrangement(raw, cards.value)
250
+ savedJson.value = JSON.stringify(arrangement.value)
251
+ }
252
+
253
+ function stopGrace(): void {
254
+ if (graceTimer) clearTimeout(graceTimer)
255
+ graceTimer = null
256
+ loading.value = false
257
+ }
258
+
259
+ function load(): void {
260
+ const token = ++loadToken
261
+ const key = storageKey.value
262
+ touched = false
263
+ stopGrace()
264
+ let answer: unknown
265
+ try {
266
+ answer = storage().load(key)
267
+ } catch (err) {
268
+ onError('load', err)
269
+ settle(null)
270
+ return
271
+ }
272
+ if (!isThenable(answer)) return settle(answer)
273
+ // Async: the defaults wait out the grace, then show until the answer
274
+ settle(null)
275
+ loading.value = true
276
+ graceTimer = setTimeout(stopGrace, options.loadGrace ?? 150)
277
+ Promise.resolve(answer).then(
278
+ (raw) => {
279
+ if (token !== loadToken) return // another key since
280
+ stopGrace()
281
+ if (touched) {
282
+ stored = raw
283
+ savedJson.value = JSON.stringify(reconcileArrangement(raw, cards.value))
284
+ } else settle(raw)
285
+ },
286
+ (err) => {
287
+ if (token !== loadToken) return
288
+ stopGrace()
289
+ onError('load', err)
290
+ }
291
+ )
292
+ }
293
+
294
+ load()
295
+ // A new user: load again
296
+ watch(storageKey, load)
297
+ // A changed set of cards: reconciled again, from what is shown if the user changed it
298
+ watch(cards, () => {
299
+ const saved = reconcileArrangement(stored, cards.value)
300
+ savedJson.value = JSON.stringify(saved)
301
+ arrangement.value = touched ? reconcileArrangement(arrangement.value, cards.value) : saved
195
302
  })
303
+ onScopeDispose(() => {
304
+ loadToken++
305
+ stopGrace()
306
+ })
307
+
308
+ async function write(value: CardsArrangement | null): Promise<boolean> {
309
+ const key = storageKey.value
310
+ saving.value = true
311
+ try {
312
+ await storage().save(key, value)
313
+ if (key === storageKey.value) {
314
+ stored = value
315
+ savedJson.value = JSON.stringify(value ?? defaultArrangement(cards.value))
316
+ }
317
+ return true
318
+ } catch (err) {
319
+ onError('save', err)
320
+ return false
321
+ } finally {
322
+ saving.value = false
323
+ }
324
+ }
325
+
196
326
  const groups = computed(() => groupCards(arrangement.value, cards.value))
197
327
 
198
328
  const apply = (next: CardsArrangement): boolean => {
199
329
  if (next === arrangement.value) return false
330
+ touched = true
200
331
  arrangement.value = next
201
- writeStorage(storageKey.value, next)
332
+ if (autoSave) void write(next)
202
333
  return true
203
334
  }
204
335
 
205
336
  return {
206
337
  arrangement,
207
338
  groups,
339
+ loading,
340
+ saving,
341
+ dirty,
208
342
  move: (id, toIndex) => apply(moveCard(arrangement.value, cards.value, id, toIndex)),
209
343
  pin: (id, pinned) => apply(setPinned(arrangement.value, cards.value, id, pinned)),
210
344
  hide: (id, hidden) => apply(setHidden(arrangement.value, cards.value, id, hidden)),
211
345
  preview: (next) => {
346
+ touched = true
212
347
  arrangement.value = next
213
348
  },
214
- commit: () => writeStorage(storageKey.value, arrangement.value),
349
+ commit: () => write(arrangement.value),
215
350
  reset: () => {
216
- writeStorage(storageKey.value, null)
351
+ touched = true
217
352
  arrangement.value = defaultArrangement(cards.value)
353
+ return write(null)
218
354
  },
219
355
  }
220
356
  }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The app's card dashboards (#4338): where arrangements are kept, set once at
3
+ * boot. A CardsDashboard's own `storage` / `load-grace` props win.
4
+ *
5
+ * configureDashboards({
6
+ * storage: {
7
+ * load: (key) => api.get(`/me/dashboards/${key}`).then((r) => r.data, () => null),
8
+ * save: (key, arrangement) => api.put(`/me/dashboards/${key}`, arrangement),
9
+ * },
10
+ * })
11
+ */
12
+ import type { CardsArrangementStorage } from '../composables/useCardsArrangement'
13
+
14
+ export interface DashboardsOptions {
15
+ /** Where arrangements are kept (default: localStorage) */
16
+ storage?: CardsArrangementStorage
17
+ /** Ms an async load may take before the default order shows (default 150) */
18
+ loadGrace?: number
19
+ }
20
+
21
+ const app: DashboardsOptions = {}
22
+
23
+ /** Later calls merge over earlier ones. */
24
+ export function configureDashboards(options: DashboardsOptions): void {
25
+ Object.assign(app, options)
26
+ }
27
+
28
+ export function getDashboardsConfig(): Readonly<DashboardsOptions> {
29
+ return app
30
+ }
31
+
32
+ /** For tests: back to qdadm's defaults. */
33
+ export function resetDashboards(): void {
34
+ delete app.storage
35
+ delete app.loadGrace
36
+ }