@quazardous/qdadm 2.37.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.
@@ -0,0 +1,353 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * YamlConfigEditor - edit a live YAML configuration end to end (#4303)
4
+ *
5
+ * Loads a document through an adapter, edits it in VanillaYamlEditor (text
6
+ * or form), and saves it as one gesture: the server's check, a before/after
7
+ * diff, a required reason, then a single save against the loaded revision.
8
+ * A save refused because someone saved meanwhile shows both versions. The
9
+ * history lists past revisions and loads one back to save it again.
10
+ *
11
+ * <YamlConfigEditor :adapter="restYamlAdapter('/api/filters')" @saved="…" />
12
+ *
13
+ * Leaving the page with unsaved changes asks first (`guard`, default on).
14
+ */
15
+ import { computed, onMounted, onUnmounted, ref, shallowRef } from 'vue'
16
+ import Textarea from 'primevue/textarea'
17
+ import { validate, type YamlEditorStatus, type YamlProblem } from '@quazardous/vanilla-yamleditor'
18
+ import QdButton from '../../base/QdButton.vue'
19
+ import QdMessage from '../../base/QdMessage.vue'
20
+ import SimpleDialog from '../../dialogs/SimpleDialog.vue'
21
+ import PayloadDiff from '../../display/PayloadDiff.vue'
22
+ import VanillaYamlEditor from './VanillaYamlEditor.vue'
23
+ import { YamlConflictError, normalizeProblems, type YamlConfigAdapter, type YamlConfigDocument, type YamlHistoryEntry, type YamlRevision } from './yamlConfigAdapter'
24
+ import { useI18n } from '../../../i18n/useI18n'
25
+ import { useUnsavedChangesGuard } from '../../../composables/useUnsavedChangesGuard'
26
+ import { registerGuardDialog, unregisterGuardDialog } from '../../../composables/useGuardStore'
27
+
28
+ interface Props {
29
+ adapter: YamlConfigAdapter
30
+ /** Read only, whatever the server says. */
31
+ readOnly?: boolean
32
+ height?: string
33
+ /** Ask before leaving the page with unsaved changes. */
34
+ guard?: boolean
35
+ }
36
+
37
+ const props = withDefaults(defineProps<Props>(), {
38
+ readOnly: false,
39
+ height: '28rem',
40
+ guard: true,
41
+ })
42
+
43
+ const emit = defineEmits<{
44
+ loaded: [doc: YamlConfigDocument]
45
+ saved: [result: { yaml: string; reason: string; revision?: YamlRevision }]
46
+ 'update:dirty': [dirty: boolean]
47
+ }>()
48
+
49
+ const { tOr } = useI18n()
50
+ const l = (key: string, fallback: string, params?: Record<string, unknown>) => tOr(`core.yamlEditor.${key}`, fallback, params as never)
51
+
52
+ const editorRef = ref<InstanceType<typeof VanillaYamlEditor> | null>(null)
53
+ const original = shallowRef<YamlConfigDocument | null>(null)
54
+ const text = ref('')
55
+ const status = shallowRef<YamlEditorStatus | null>(null)
56
+ const serverProblems = shallowRef<YamlProblem[]>([])
57
+ const loading = ref(true)
58
+ const checking = ref(false)
59
+ const saving = ref(false)
60
+ const message = ref<{ severity: 'success' | 'info' | 'warn' | 'error'; text: string } | null>(null)
61
+
62
+ const readOnly = computed(() => props.readOnly || !!original.value?.readOnly)
63
+ const dirty = computed(() => !!original.value && text.value !== original.value.yaml)
64
+ const syntaxErrors = computed(() => status.value?.syntaxErrors.length ?? 0)
65
+ const stateText = computed(() =>
66
+ loading.value ? l('loading', 'Loading') : readOnly.value ? l('readOnly', 'Read only') : dirty.value ? l('unsaved', 'Unsaved changes') : l('upToDate', 'Up to date')
67
+ )
68
+
69
+ async function load() {
70
+ loading.value = true
71
+ message.value = null
72
+ try {
73
+ const doc = await props.adapter.load()
74
+ original.value = doc
75
+ text.value = doc.yaml
76
+ serverProblems.value = []
77
+ emit('loaded', doc)
78
+ } catch (err) {
79
+ message.value = { severity: 'error', text: l('loadError', 'Could not load: {message}', { message: (err as Error).message }) }
80
+ } finally {
81
+ loading.value = false
82
+ }
83
+ }
84
+
85
+ onMounted(load)
86
+
87
+ function onStatus(next: YamlEditorStatus) {
88
+ status.value = next
89
+ emit('update:dirty', dirty.value)
90
+ }
91
+
92
+ /** Problems that block a save: errors, schema or server. */
93
+ const blocking = (list: YamlProblem[]) => list.filter((p) => (p.severity ?? 'error') === 'error')
94
+
95
+ async function runCheck(): Promise<boolean> {
96
+ if (syntaxErrors.value) {
97
+ message.value = { severity: 'error', text: l('syntaxErrors', '{count} syntax error | {count} syntax errors', { count: syntaxErrors.value }) }
98
+ return false
99
+ }
100
+ message.value = null
101
+ if (props.adapter.check) {
102
+ checking.value = true
103
+ try {
104
+ serverProblems.value = normalizeProblems(await props.adapter.check(text.value))
105
+ } catch (err) {
106
+ message.value = { severity: 'error', text: (err as Error).message }
107
+ return false
108
+ } finally {
109
+ checking.value = false
110
+ }
111
+ }
112
+ const schema = original.value?.schema
113
+ const local = schema ? validate(status.value?.value, schema) : []
114
+ const problems = blocking([...local, ...serverProblems.value])
115
+ const first = problems[0]
116
+ if (first) {
117
+ const where = first.path.length ? `${first.path.join('.')}: ` : ''
118
+ message.value = { severity: 'error', text: `${l('problems', '{count} problem | {count} problems', { count: problems.length })} — ${where}${first.message}` }
119
+ editorRef.value?.revealPath(first.path)
120
+ return false
121
+ }
122
+ message.value = { severity: 'success', text: l('checkOk', 'No problem found') }
123
+ return true
124
+ }
125
+
126
+ // --- Save: check → diff + reason → save ---
127
+
128
+ const reviewOpen = ref(false)
129
+ const reason = ref('')
130
+
131
+ async function startSave() {
132
+ if (!dirty.value) {
133
+ message.value = { severity: 'info', text: l('noChange', 'Nothing changed') }
134
+ return
135
+ }
136
+ if (!(await runCheck())) return
137
+ message.value = null
138
+ reviewOpen.value = true
139
+ }
140
+
141
+ async function confirmSave() {
142
+ if (!original.value || !reason.value.trim()) return
143
+ saving.value = true
144
+ const yaml = text.value
145
+ const why = reason.value.trim()
146
+ try {
147
+ const result = await props.adapter.save({ yaml, reason: why, revision: original.value.revision })
148
+ original.value = { ...original.value, yaml, revision: result.revision ?? original.value.revision }
149
+ reviewOpen.value = false
150
+ reason.value = ''
151
+ serverProblems.value = []
152
+ message.value = { severity: 'success', text: l('saved', 'Saved') }
153
+ emit('saved', { yaml, reason: why, revision: original.value.revision })
154
+ emit('update:dirty', false)
155
+ } catch (err) {
156
+ if (err instanceof YamlConflictError) {
157
+ conflict.value = err.current
158
+ reviewOpen.value = false
159
+ conflictOpen.value = true
160
+ } else {
161
+ message.value = { severity: 'error', text: l('saveError', 'Could not save: {message}', { message: (err as Error).message }) }
162
+ }
163
+ } finally {
164
+ saving.value = false
165
+ }
166
+ }
167
+
168
+ function revert() {
169
+ if (original.value) text.value = original.value.yaml
170
+ serverProblems.value = []
171
+ message.value = null
172
+ }
173
+
174
+ // --- Conflict ---
175
+
176
+ const conflictOpen = ref(false)
177
+ const conflict = shallowRef<YamlConfigDocument | null>(null)
178
+
179
+ function takeTheirs() {
180
+ if (!conflict.value) return
181
+ original.value = { ...original.value, ...conflict.value }
182
+ text.value = conflict.value.yaml
183
+ conflictOpen.value = false
184
+ }
185
+
186
+ function keepMine() {
187
+ if (!conflict.value) return
188
+ // Their version becomes the base: the review shows what mine changes on it
189
+ original.value = { ...original.value, ...conflict.value }
190
+ conflictOpen.value = false
191
+ reviewOpen.value = true
192
+ }
193
+
194
+ // --- History ---
195
+
196
+ const historyOpen = ref(false)
197
+ const historyLoading = ref(false)
198
+ const entries = shallowRef<YamlHistoryEntry[]>([])
199
+ const selected = shallowRef<YamlHistoryEntry | null>(null)
200
+
201
+ async function openHistory() {
202
+ if (!props.adapter.history) return
203
+ historyOpen.value = true
204
+ historyLoading.value = true
205
+ try {
206
+ entries.value = await props.adapter.history()
207
+ selected.value = entries.value[0] ?? null
208
+ } catch (err) {
209
+ message.value = { severity: 'error', text: (err as Error).message }
210
+ historyOpen.value = false
211
+ } finally {
212
+ historyLoading.value = false
213
+ }
214
+ }
215
+
216
+ function restore() {
217
+ if (!selected.value) return
218
+ text.value = selected.value.after
219
+ historyOpen.value = false
220
+ message.value = { severity: 'info', text: l('restored', 'Version {revision} loaded: review and save it to restore it', { revision: selected.value.revision }) }
221
+ }
222
+
223
+ const formatDate = (iso?: string) => {
224
+ if (!iso) return ''
225
+ const d = new Date(iso)
226
+ return Number.isNaN(d.getTime()) ? iso : d.toLocaleString()
227
+ }
228
+
229
+ // --- Leaving with unsaved changes ---
230
+
231
+ if (props.guard) {
232
+ const { guardDialog } = useUnsavedChangesGuard(dirty)
233
+ registerGuardDialog(guardDialog)
234
+ onUnmounted(() => unregisterGuardDialog(guardDialog))
235
+ }
236
+
237
+ defineExpose({ reload: load, check: runCheck, save: startSave, dirty })
238
+ </script>
239
+
240
+ <template>
241
+ <div class="qd-yaml-config">
242
+ <div class="qd-yaml-config-bar">
243
+ <span class="qd-yaml-config-state" :class="{ 'qd-yaml-config-state--dirty': dirty && !readOnly }">{{ stateText }}</span>
244
+ <QdButton
245
+ v-if="adapter.history"
246
+ icon="pi pi-history"
247
+ :label="l('history', 'History')"
248
+ severity="secondary"
249
+ text
250
+ size="small"
251
+ :disabled="loading"
252
+ @click="openHistory"
253
+ />
254
+ <QdButton
255
+ v-if="adapter.check && !readOnly"
256
+ icon="pi pi-check-circle"
257
+ :label="l('check', 'Check')"
258
+ severity="secondary"
259
+ outlined
260
+ size="small"
261
+ :loading="checking && !reviewOpen"
262
+ :disabled="loading || syntaxErrors > 0"
263
+ @click="runCheck"
264
+ />
265
+ <QdButton
266
+ v-if="dirty && !readOnly"
267
+ icon="pi pi-undo"
268
+ :label="l('revert', 'Discard changes')"
269
+ severity="secondary"
270
+ text
271
+ size="small"
272
+ @click="revert"
273
+ />
274
+ <QdButton
275
+ v-if="!readOnly"
276
+ icon="pi pi-save"
277
+ :label="l('save', 'Save…')"
278
+ size="small"
279
+ :disabled="loading || !dirty || syntaxErrors > 0"
280
+ :loading="checking"
281
+ @click="startSave"
282
+ />
283
+ </div>
284
+
285
+ <QdMessage v-if="message" :severity="message.severity" :closable="true" @close="message = null">{{ message.text }}</QdMessage>
286
+
287
+ <VanillaYamlEditor
288
+ v-if="original"
289
+ ref="editorRef"
290
+ v-model="text"
291
+ :schema="original.schema"
292
+ :problems="serverProblems"
293
+ :read-only="readOnly"
294
+ :height="height"
295
+ @status="onStatus"
296
+ />
297
+
298
+ <SimpleDialog
299
+ v-model:visible="reviewOpen"
300
+ :title="l('review', 'Review the change')"
301
+ width="60rem"
302
+ :cancel-label="l('cancel', 'Cancel')"
303
+ :confirm-label="l('confirmSave', 'Save')"
304
+ confirm-icon="pi pi-save"
305
+ :confirm-disabled="!reason.trim()"
306
+ :loading="saving"
307
+ @confirm="confirmSave"
308
+ >
309
+ <PayloadDiff :left="original?.yaml ?? ''" :right="text" format="text" :labels="[l('before', 'Before'), l('after', 'After')]" max-height="24rem" />
310
+ <div class="qd-yaml-config-reason">
311
+ <label for="qd-yaml-reason">{{ l('reason', 'Reason') }} *</label>
312
+ <Textarea id="qd-yaml-reason" v-model="reason" rows="3" auto-resize :placeholder="l('reasonPlaceholder', 'Why this change? It goes into the history.')" />
313
+ </div>
314
+ </SimpleDialog>
315
+
316
+ <SimpleDialog v-model:visible="conflictOpen" :title="l('conflictTitle', 'Changed meanwhile')" width="60rem" :show-confirm="false" :cancel-label="l('cancel', 'Cancel')">
317
+ <p>{{ l('conflictText', 'Someone saved this document after you opened it. Their version is on the left, yours on the right.') }}</p>
318
+ <PayloadDiff :left="conflict?.yaml ?? ''" :right="text" format="text" max-height="24rem" />
319
+ <template #actions>
320
+ <QdButton :label="l('takeTheirs', 'Load their version')" severity="secondary" outlined @click="takeTheirs" />
321
+ <QdButton :label="l('keepMine', 'Keep mine and save over it')" severity="warn" @click="keepMine" />
322
+ </template>
323
+ </SimpleDialog>
324
+
325
+ <SimpleDialog v-model:visible="historyOpen" :title="l('history', 'History')" width="72rem" :show-confirm="false" :cancel-label="l('cancel', 'Cancel')">
326
+ <p v-if="historyLoading">{{ l('loading', 'Loading') }}</p>
327
+ <p v-else-if="!entries.length">{{ l('historyEmpty', 'No history yet') }}</p>
328
+ <div v-else class="qd-yaml-history">
329
+ <div class="qd-yaml-history-list" role="listbox">
330
+ <button
331
+ v-for="entry in entries"
332
+ :key="String(entry.revision)"
333
+ type="button"
334
+ role="option"
335
+ class="qd-yaml-history-entry"
336
+ :class="{ 'qd-yaml-history-entry--active': entry === selected }"
337
+ :aria-selected="entry === selected"
338
+ @click="selected = entry"
339
+ >
340
+ <strong>{{ entry.reason || entry.revision }}</strong>
341
+ <span class="qd-yaml-history-meta">{{ [entry.author, formatDate(entry.date)].filter(Boolean).join(' · ') }}</span>
342
+ </button>
343
+ </div>
344
+ <div v-if="selected">
345
+ <PayloadDiff :left="selected.before ?? ''" :right="selected.after" format="text" :labels="[l('before', 'Before'), l('after', 'After')]" max-height="26rem" />
346
+ </div>
347
+ </div>
348
+ <template #actions>
349
+ <QdButton v-if="selected && !readOnly" icon="pi pi-replay" :label="l('restore', 'Load this version')" @click="restore" />
350
+ </template>
351
+ </SimpleDialog>
352
+ </div>
353
+ </template>
@@ -0,0 +1,141 @@
1
+ /**
2
+ * How YamlConfigEditor reaches the server (#4303): load, check, save with a
3
+ * reason against a revision, history. `restYamlAdapter` speaks this REST
4
+ * contract; any other transport implements YamlConfigAdapter.
5
+ *
6
+ * GET <url> → { yaml, schema?, revision?, readOnly? }
7
+ * POST <url>/check { yaml } → { problems: [{ path, message }] }
8
+ * PUT <url> { yaml, reason, revision } → { revision? }
9
+ * 409 → { yaml, revision } (the server's current version)
10
+ * GET <url>/history → [{ revision, author?, date?, reason?, before?, after }]
11
+ *
12
+ * With `path`, every call carries `?path=<a.b.c>`: the server serves and
13
+ * saves that part of the document only.
14
+ */
15
+ import { toPath, type JsonSchema, type YamlProblem } from '@quazardous/vanilla-yamleditor'
16
+
17
+ export type YamlRevision = string | number
18
+
19
+ export interface YamlConfigDocument {
20
+ yaml: string
21
+ schema?: JsonSchema
22
+ revision?: YamlRevision
23
+ /** The user may only read it. */
24
+ readOnly?: boolean
25
+ }
26
+
27
+ export interface YamlHistoryEntry {
28
+ revision: YamlRevision
29
+ author?: string
30
+ /** ISO date. */
31
+ date?: string
32
+ reason?: string
33
+ /** The text before this revision; absent for the first one. */
34
+ before?: string
35
+ /** The text this revision saved. */
36
+ after: string
37
+ }
38
+
39
+ export interface YamlSaveInput {
40
+ yaml: string
41
+ reason: string
42
+ revision?: YamlRevision
43
+ }
44
+
45
+ export interface YamlConfigAdapter {
46
+ load(): Promise<YamlConfigDocument>
47
+ /** The server's checks; without it, saving only runs the schema. */
48
+ check?(yaml: string): Promise<YamlProblem[]>
49
+ /** Throws YamlConflictError when the revision moved meanwhile. */
50
+ save(input: YamlSaveInput): Promise<{ revision?: YamlRevision }>
51
+ history?(): Promise<YamlHistoryEntry[]>
52
+ }
53
+
54
+ /** The document was saved by someone else since it was loaded. */
55
+ export class YamlConflictError extends Error {
56
+ /** The server's current version. */
57
+ readonly current: YamlConfigDocument
58
+
59
+ constructor(current: YamlConfigDocument) {
60
+ super('The document changed since it was loaded')
61
+ this.name = 'YamlConflictError'
62
+ this.current = current
63
+ }
64
+ }
65
+
66
+ /** A problem path from a server: an array, or `a.b[0].c` / `a/b/0`. */
67
+ export const normalizeProblemPath = toPath
68
+
69
+ /** Problems as an adapter may return them: a list, or `{ problems }`, with string or array paths. */
70
+ export function normalizeProblems(raw: unknown): YamlProblem[] {
71
+ const list = Array.isArray(raw) ? raw : Array.isArray((raw as { problems?: unknown })?.problems) ? (raw as { problems: unknown[] }).problems : []
72
+ return list
73
+ .filter((p): p is { path?: unknown; message?: unknown; severity?: unknown } => !!p && typeof p === 'object')
74
+ .map((p) => ({
75
+ path: normalizeProblemPath(p.path),
76
+ message: String(p.message ?? ''),
77
+ severity: p.severity === 'warning' ? ('warning' as const) : ('error' as const),
78
+ }))
79
+ }
80
+
81
+ export interface RestYamlAdapterOptions {
82
+ /** Edit part of the document: sent as `?path=`. */
83
+ path?: string | (string | number)[]
84
+ /** The app's fetch (auth headers, base URL…). Default: window.fetch. */
85
+ fetch?: typeof fetch
86
+ headers?: Record<string, string>
87
+ }
88
+
89
+ export function restYamlAdapter(url: string, options: RestYamlAdapterOptions = {}): YamlConfigAdapter {
90
+ const doFetch = options.fetch ?? ((input: RequestInfo | URL, init?: RequestInit) => fetch(input, init))
91
+ const path = Array.isArray(options.path) ? options.path.join('.') : options.path
92
+ const base = url.replace(/\/$/, '')
93
+ const at = (suffix = '') => {
94
+ const target = base + suffix
95
+ return path ? `${target}${target.includes('?') ? '&' : '?'}path=${encodeURIComponent(path)}` : target
96
+ }
97
+ const headers = { Accept: 'application/json', ...options.headers }
98
+
99
+ async function call(target: string, init: RequestInit = {}): Promise<{ status: number; body: unknown }> {
100
+ const res = await doFetch(target, { ...init, headers: { ...headers, ...(init.body ? { 'Content-Type': 'application/json' } : {}), ...(init.headers as Record<string, string>) } })
101
+ const text = await res.text()
102
+ let body: unknown = text
103
+ try {
104
+ body = text ? JSON.parse(text) : null
105
+ } catch {
106
+ // Not JSON: keep the text for the error message
107
+ }
108
+ if (!res.ok && res.status !== 409) {
109
+ const message = (body as { message?: string; detail?: string })?.message ?? (body as { detail?: string })?.detail ?? `${res.status} ${res.statusText}`
110
+ throw new Error(String(message))
111
+ }
112
+ return { status: res.status, body }
113
+ }
114
+
115
+ const toDocument = (body: unknown): YamlConfigDocument => {
116
+ const b = (body ?? {}) as Partial<YamlConfigDocument>
117
+ return { yaml: String(b.yaml ?? ''), schema: b.schema, revision: b.revision, readOnly: b.readOnly }
118
+ }
119
+
120
+ return {
121
+ async load() {
122
+ return toDocument((await call(at())).body)
123
+ },
124
+ async check(yaml) {
125
+ return normalizeProblems((await call(at('/check'), { method: 'POST', body: JSON.stringify({ yaml }) })).body)
126
+ },
127
+ async save(input) {
128
+ const { status, body } = await call(at(), { method: 'PUT', body: JSON.stringify(input) })
129
+ if (status === 409) {
130
+ const current = body && typeof body === 'object' && 'yaml' in body ? toDocument(body) : toDocument((await call(at())).body)
131
+ throw new YamlConflictError(current)
132
+ }
133
+ return { revision: (body as { revision?: YamlRevision } | null)?.revision }
134
+ },
135
+ async history() {
136
+ const { body } = await call(at('/history'))
137
+ const list = Array.isArray(body) ? body : ((body as { entries?: unknown[] })?.entries ?? [])
138
+ return list as YamlHistoryEntry[]
139
+ },
140
+ }
141
+ }
@@ -15,6 +15,7 @@ export { default as PageHeader } from './layout/PageHeader.vue'
15
15
  export { default as Breadcrumb } from './layout/Breadcrumb.vue'
16
16
  export { default as PageNav } from './layout/PageNav.vue'
17
17
  export { default as Zone } from './layout/Zone.vue'
18
+ export { default as CardsDashboard } from './layout/CardsDashboard.vue'
18
19
  export { default as SidebarBox } from './layout/SidebarBox.vue'
19
20
  export { default as NavlinksGroup } from './layout/NavlinksGroup.vue'
20
21