@kinetis/vector-ui 0.10.1 → 0.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG.md +88 -0
  2. package/app/components/Vx/Action/Dialog.vue +15 -9
  3. package/app/components/Vx/Cell/RichText.vue +1 -1
  4. package/app/components/Vx/Import/Dialog.vue +14 -3
  5. package/app/components/Vx/Inbox.vue +10 -3
  6. package/app/components/Vx/Input/KeyValue.vue +9 -4
  7. package/app/components/Vx/Input/Number.vue +2 -1
  8. package/app/components/Vx/Input/Relation.vue +15 -5
  9. package/app/components/Vx/Input/Repeater.vue +15 -5
  10. package/app/components/Vx/Input/RichText.vue +2 -2
  11. package/app/components/Vx/Input/Upload.vue +5 -3
  12. package/app/components/Vx/List/BulkEdit.vue +5 -5
  13. package/app/components/Vx/List/FilterBar.vue +14 -10
  14. package/app/components/Vx/Resource/Audit.vue +4 -1
  15. package/app/components/Vx/Resource/Form.vue +23 -8
  16. package/app/components/Vx/Resource/RelationPanel.vue +2 -1
  17. package/app/components/Vx/Resource/Table.vue +32 -15
  18. package/app/components/Vx/Widget/Card.vue +2 -1
  19. package/app/components/Vx/Widget/Table.vue +22 -4
  20. package/app/components/Vx/Widget/Trend.vue +1 -1
  21. package/app/composables/useVectorApi.ts +70 -14
  22. package/app/composables/useVectorAuthStore.ts +32 -7
  23. package/app/composables/useVectorBranding.ts +1 -1
  24. package/app/composables/useVectorExtensions.ts +1 -1
  25. package/app/composables/useVectorFields.ts +7 -1
  26. package/app/composables/useVectorForm.ts +8 -3
  27. package/app/composables/useVectorIdle.ts +3 -1
  28. package/app/composables/useVectorImpersonation.ts +11 -11
  29. package/app/composables/useVectorInputs.ts +6 -6
  30. package/app/composables/useVectorJobs.ts +6 -3
  31. package/app/composables/useVectorLocale.ts +3 -5
  32. package/app/composables/useVectorResource.ts +37 -32
  33. package/app/composables/useVectorSchema.ts +9 -1
  34. package/app/i18n/ar/actions.ts +1 -0
  35. package/app/i18n/ar/shell.ts +3 -0
  36. package/app/i18n/de/actions.ts +1 -0
  37. package/app/i18n/de/shell.ts +3 -0
  38. package/app/i18n/en/actions.ts +1 -0
  39. package/app/i18n/en/shell.ts +3 -0
  40. package/app/i18n/es/actions.ts +1 -0
  41. package/app/i18n/es/shell.ts +3 -0
  42. package/app/i18n/fr/actions.ts +1 -0
  43. package/app/i18n/fr/shell.ts +3 -0
  44. package/app/i18n/he/actions.ts +1 -0
  45. package/app/i18n/he/shell.ts +3 -0
  46. package/app/i18n/index.ts +15 -1
  47. package/app/i18n/it/actions.ts +1 -0
  48. package/app/i18n/it/shell.ts +3 -0
  49. package/app/i18n/ja/actions.ts +1 -0
  50. package/app/i18n/ja/shell.ts +3 -0
  51. package/app/i18n/ko/actions.ts +1 -0
  52. package/app/i18n/ko/shell.ts +3 -0
  53. package/app/i18n/nl/actions.ts +1 -0
  54. package/app/i18n/nl/shell.ts +3 -0
  55. package/app/i18n/pl/actions.ts +1 -0
  56. package/app/i18n/pl/shell.ts +3 -0
  57. package/app/i18n/pt/actions.ts +1 -0
  58. package/app/i18n/pt/shell.ts +3 -0
  59. package/app/i18n/pt-BR/actions.ts +1 -0
  60. package/app/i18n/pt-BR/shell.ts +3 -0
  61. package/app/i18n/ru/actions.ts +1 -0
  62. package/app/i18n/ru/shell.ts +3 -0
  63. package/app/i18n/tr/actions.ts +1 -0
  64. package/app/i18n/tr/shell.ts +3 -0
  65. package/app/i18n/uk/actions.ts +1 -0
  66. package/app/i18n/uk/shell.ts +3 -0
  67. package/app/i18n/zh-Hans/actions.ts +1 -0
  68. package/app/i18n/zh-Hans/shell.ts +3 -0
  69. package/app/pages/jobs/index.vue +18 -4
  70. package/app/pages/login.vue +11 -4
  71. package/app/pages/settings.vue +4 -3
  72. package/app/plugins/vector-extensions.client.ts +1 -1
  73. package/app/plugins/vector-i18n.ts +2 -2
  74. package/app/utils/files.ts +5 -2
  75. package/app/utils/internal/paths.ts +12 -0
  76. package/app/utils/internal/patterns.ts +50 -0
  77. package/app/utils/internal/violations.ts +26 -0
  78. package/app/utils/richtext.ts +2 -2
  79. package/app/utils/rules.ts +2 -12
  80. package/package.json +1 -1
@@ -1,6 +1,7 @@
1
1
  <script setup lang="ts">
2
2
  import { fieldProps, type VectorAction, type VectorExportFormat, type VectorField, type VectorFilterGroup, type VectorFilterQuery, type VectorFilters, type VectorListState, type VectorPage, type VectorRecord, type VectorResource, type VectorSelection, type VectorSort, type VectorSavedView } from '#vector/app/types/vector'
3
3
  import type { VectorPageStep } from '#vector/app/composables/useVectorCursorPager'
4
+ import { violationsOf } from '#vector/app/utils/internal/violations'
4
5
 
5
6
  // The list view: a server-driven table whose every option — page, size,
6
7
  // sort, filters, search, grouping, columns — becomes one list request,
@@ -92,6 +93,12 @@ let requestId = 0
92
93
  /** Whether the next load goes back to the first page: a changed search, filter, sort or page size asked for it. */
93
94
  let restart = false
94
95
 
96
+ /** How many pages a step moves from the current one. */
97
+ function pageOffset(step: VectorPageStep): number {
98
+ if (step === 'forward') return 1
99
+ return step === 'back' ? -1 : 0
100
+ }
101
+
95
102
  /**
96
103
  * Loads the page shown now, or the one $step away on a list that is not
97
104
  * counted. The step is taken only once its page has arrived: a request
@@ -121,7 +128,7 @@ async function load(step: VectorPageStep = 'stay') {
121
128
  return
122
129
  }
123
130
 
124
- const target = step === 'first' ? 1 : page.value + (step === 'forward' ? 1 : step === 'back' ? -1 : 0)
131
+ const target = step === 'first' ? 1 : page.value + pageOffset(step)
125
132
  const sort: VectorSort[] = sortBy.value.map(s => ({ field: s.key, order: s.order === 'desc' ? 'desc' : 'asc' }))
126
133
  const result: VectorPage = await client.list({
127
134
  page: target, perPage: itemsPerPage.value, sort, filter: rawFilters(), q: term.value || undefined,
@@ -204,7 +211,7 @@ function decodeFilter(filter: VectorFilterQuery, known: Set<string>) {
204
211
  } else if (key === 'and' && Array.isArray(spec)) {
205
212
  for (const child of spec) {
206
213
  const inner = decodeFilter(child, known)
207
- for (const [name, ops] of Object.entries(inner.filters)) out.filters[name] = { ...(out.filters[name] ?? {}), ...ops }
214
+ for (const [name, ops] of Object.entries(inner.filters)) out.filters[name] = { ...out.filters[name], ...ops }
208
215
  out.groups.push(...inner.groups)
209
216
  out.advanced.push(...inner.advanced)
210
217
  }
@@ -231,7 +238,8 @@ function applyView(view: VectorSavedView | null) {
231
238
  // a cursor list orders by the identifier: a view's grouping, sort and summaries do not apply to it
232
239
  group.value = !byCursor.value && s.group && known.has(s.group) ? s.group : null
233
240
  const sorts = s.sort ? s.sort.split(',').map(e => ({ key: e.replace(/^-/, ''), order: e.startsWith('-') ? 'desc' as const : 'asc' as const })).filter(x => known.has(x.key)) : []
234
- sortBy.value = byCursor.value ? [] : sorts.length ? sorts : props.resource.table.defaultSort.map(x => ({ key: x.field, order: x.order }))
241
+ if (byCursor.value) sortBy.value = []
242
+ else sortBy.value = sorts.length ? sorts : props.resource.table.defaultSort.map(x => ({ key: x.field, order: x.order }))
235
243
  if (s.columns) columns.value = s.columns.split(',').filter(c => props.resource.table.columns.includes(c))
236
244
  itemsPerPage.value = s.perPage ?? props.resource.table.perPage
237
245
  summaries.value = !byCursor.value && (s.summaries ?? summaries.value)
@@ -261,6 +269,12 @@ const standaloneActions = computed(() => props.resource.actions.filter(a => a.sh
261
269
  const dialogAction = ref<VectorAction | null>(null)
262
270
  const bulkEditing = ref(false)
263
271
 
272
+ /** What confirming an operation warns of: nothing for a restore. */
273
+ function operationWarning(op: 'delete' | 'restore' | 'forceDelete'): string | undefined {
274
+ if (op === 'restore') return undefined
275
+ return props.resource.softDelete && op === 'delete' ? t('list.operation.toTrash') : t('list.operation.irreversible')
276
+ }
277
+
264
278
  async function operation(op: 'delete' | 'restore' | 'forceDelete') {
265
279
  const n = selectionCount.value
266
280
  const subject = noun(n === 1 ? props.resource.labelSingular : props.resource.label)
@@ -268,7 +282,7 @@ async function operation(op: 'delete' | 'restore' | 'forceDelete') {
268
282
  ? { delete: t('list.operation.deleteAllTitle', { noun: subject }), restore: t('list.operation.restoreAllTitle', { noun: subject }), forceDelete: t('list.operation.forceDeleteAllTitle', { noun: subject }) }
269
283
  : { delete: t('list.operation.deleteTitle', { count: n, noun: subject }), restore: t('list.operation.restoreTitle', { count: n, noun: subject }), forceDelete: t('list.operation.forceDeleteTitle', { count: n, noun: subject }) }
270
284
 
271
- if (!await confirm({ title: titles[op], text: op === 'restore' ? undefined : (props.resource.softDelete && op === 'delete' ? t('list.operation.toTrash') : t('list.operation.irreversible')), confirmText: op === 'restore' ? t('common.restore') : t('common.delete'), destructive: op !== 'restore' })) return
285
+ if (!await confirm({ title: titles[op], text: operationWarning(op), confirmText: op === 'restore' ? t('common.restore') : t('common.delete'), destructive: op !== 'restore' })) return
272
286
 
273
287
  try {
274
288
  const { affected } = await client.batch(op, selection.value)
@@ -310,12 +324,16 @@ function actionDone() {
310
324
  // --- rendering helpers ------------------------------------------------
311
325
  const groupField = computed(() => props.resource.fields.find(f => f.name === group.value) ?? null)
312
326
 
327
+ /** The currency a money summary is shown in: the field's own, else the first row's, else euros. */
328
+ function summaryCurrency(field: VectorField): string {
329
+ const p = fieldProps(field)
330
+ if (typeof p.currency === 'string') return p.currency
331
+ return typeof p.currencyField === 'string' ? String(items.value[0]?.[p.currencyField] ?? 'EUR') : 'EUR'
332
+ }
333
+
313
334
  function formatSummary(field: VectorField, value: number | null): string {
314
335
  if (value === null) return t('common.none')
315
- if (field.type === 'money') {
316
- const p = fieldProps(field)
317
- return formatMoney(Math.round(value), typeof p.currency === 'string' ? p.currency : (typeof p.currencyField === 'string' ? String(items.value[0]?.[p.currencyField] ?? 'EUR') : 'EUR'))
318
- }
336
+ if (field.type === 'money') return formatMoney(Math.round(value), summaryCurrency(field))
319
337
  return formatNumber(value, field.summary === 'avg' ? 2 : undefined)
320
338
  }
321
339
 
@@ -387,11 +405,11 @@ async function saveChanges() {
387
405
  discardChanges()
388
406
  await load()
389
407
  } catch (error) {
390
- const failure = error as { status?: number, statusCode?: number, data?: { errors?: { path: (string | number)[], message: string }[] } } | null
408
+ const failure = error as { status?: number, statusCode?: number, data?: { errors?: unknown } } | null
391
409
  const status = failure?.status ?? failure?.statusCode
392
410
 
393
411
  if (status === 422 && Array.isArray(failure?.data?.errors)) {
394
- for (const violation of failure.data.errors) {
412
+ for (const violation of violationsOf(failure.data.errors)) {
395
413
  const [, index, field] = violation.path
396
414
  const change = typeof index === 'number' ? list[index] : undefined
397
415
  if (change && typeof field === 'string' && field in change.values) cellErrors[cellKey(change.id, field)] = violation.message
@@ -517,18 +535,17 @@ onBeforeUnmount(() => window.removeEventListener('beforeunload', warnBeforeUnloa
517
535
  @update:model-value="(v: unknown) => setCell(item, field, v)"
518
536
  />
519
537
  </div>
520
- <span
538
+ <button
521
539
  v-else-if="field.inline && item._trashed !== true && resource.permissions.update"
540
+ type="button"
522
541
  class="vx-inline-cell"
523
- role="button"
524
- tabindex="0"
525
542
  :aria-label="t('list.inline.editLabel', { label: field.label })"
526
543
  @click.stop="startEdit(item, field)"
527
544
  @keydown.enter.stop.prevent="startEdit(item, field)"
528
545
  >
529
546
  <VxCell :field="field" :value="item[field.name]" :record="item" :resource="resource" context="index" />
530
547
  <v-icon icon="mdi-pencil-outline" size="x-small" class="vx-inline-pencil" />
531
- </span>
548
+ </button>
532
549
  <span v-else :class="{ 'text-disabled': item._trashed === true }">
533
550
  <VxCell :field="field" :value="item[field.name]" :record="item" :resource="resource" context="index" />
534
551
  </span>
@@ -591,7 +608,7 @@ onBeforeUnmount(() => window.removeEventListener('beforeunload', warnBeforeUnloa
591
608
  </template>
592
609
 
593
610
  <style scoped>
594
- .vx-inline-cell { display: inline-flex; align-items: center; gap: 4px; cursor: text; border-radius: 4px; padding: 2px 4px; margin: -2px -4px; }
611
+ .vx-inline-cell { display: inline-flex; align-items: center; gap: 4px; cursor: text; border-radius: 4px; padding: 2px 4px; margin: -2px -4px; border: 0; background: none; color: inherit; font: inherit; text-align: inherit; }
595
612
  .vx-inline-cell:hover, .vx-inline-cell:focus-visible { outline: 1px dashed rgba(var(--v-theme-primary), 0.6); }
596
613
  .vx-inline-pencil { opacity: 0; }
597
614
  .vx-inline-cell:hover .vx-inline-pencil, .vx-inline-cell:focus-visible .vx-inline-pencil { opacity: 0.6; }
@@ -47,7 +47,8 @@ const builtIn: Record<string, Component> = {
47
47
 
48
48
  const component = computed(() => {
49
49
  const override = appConfig.vector.widgets[props.widget.type] ?? useVectorExtensions().widgets.get(props.widget.type)
50
- return override ? (typeof override === 'string' ? resolveComponent(override) : override) : builtIn[props.widget.type] ?? builtIn.stat!
50
+ if (!override) return builtIn[props.widget.type] ?? builtIn.stat!
51
+ return typeof override === 'string' ? resolveComponent(override) : override
51
52
  })
52
53
  </script>
53
54
 
@@ -1,13 +1,22 @@
1
1
  <script setup lang="ts">
2
2
  import type { VectorWidgetData } from '#vector/app/types/vector'
3
+ import { isAdminPath } from '#vector/app/utils/internal/paths'
3
4
 
4
5
  const props = defineProps<{ data: VectorWidgetData }>()
5
6
  const appConfig = useAppConfig()
6
7
  const { t } = useVectorT()
7
8
  const rows = computed(() => props.data.rows ?? [])
8
9
 
9
- function open(row: Record<string, unknown>) {
10
- if (typeof row._link === 'string') navigateTo(`${appConfig.vector.basePath}${row._link}`)
10
+ // a row with a link opens it, by mouse or by keyboard: only a path of this admin, as a notification's link
11
+ const linked = (row: Record<string, unknown>): row is { _link: string } => typeof row._link === 'string' && isAdminPath(row._link)
12
+
13
+ async function open(row: Record<string, unknown>) {
14
+ if (!linked(row)) return
15
+ try {
16
+ await navigateTo(`${appConfig.vector.basePath}${row._link}`)
17
+ } catch (error) {
18
+ useVectorNotifications().error(vectorErrorMessage(error))
19
+ }
11
20
  }
12
21
  </script>
13
22
 
@@ -15,10 +24,19 @@ function open(row: Record<string, unknown>) {
15
24
  <div>
16
25
  <v-table density="compact" hover>
17
26
  <thead>
18
- <tr><th v-for="col in data.columns ?? []" :key="col.key" :class="col.align === 'end' ? 'text-end' : ''">{{ col.label }}</th></tr>
27
+ <tr><th v-for="col in data.columns ?? []" :key="col.key" scope="col" :class="col.align === 'end' ? 'text-end' : ''">{{ col.label }}</th></tr>
19
28
  </thead>
20
29
  <tbody>
21
- <tr v-for="(row, i) in rows" :key="i" :style="typeof row._link === 'string' ? 'cursor: pointer' : ''" @click="open(row)">
30
+ <tr
31
+ v-for="(row, i) in rows"
32
+ :key="i"
33
+ :style="linked(row) ? 'cursor: pointer' : ''"
34
+ :tabindex="linked(row) ? 0 : undefined"
35
+ :role="linked(row) ? 'link' : undefined"
36
+ @click="open(row)"
37
+ @keydown.enter.self.prevent="open(row)"
38
+ @keydown.space.self.prevent="open(row)"
39
+ >
22
40
  <td v-for="col in data.columns ?? []" :key="col.key" :class="col.align === 'end' ? 'text-end' : ''">{{ row[col.key] }}</td>
23
41
  </tr>
24
42
  <tr v-if="rows.length === 0"><td :colspan="(data.columns ?? []).length" class="text-medium-emphasis">{{ t('dashboard.table.empty') }}</td></tr>
@@ -25,7 +25,7 @@ const hover = ref<number | null>(null)
25
25
  <span v-if="data.total !== null && data.total !== undefined" class="font-weight-medium">{{ t('dashboard.trend.total', { value: formatWidgetValue(data.total, data.format) }) }}</span>
26
26
  <span>{{ points[points.length - 1]?.x ?? '' }}</span>
27
27
  </div>
28
- <svg :viewBox="`0 0 ${width} ${height}`" preserveAspectRatio="none" class="w-100" style="height: 140px" @mouseleave="hover = null">
28
+ <svg aria-hidden="true" :viewBox="`0 0 ${width} ${height}`" preserveAspectRatio="none" class="w-100" style="height: 140px" @mouseleave="hover = null">
29
29
  <path :d="area" fill="rgb(var(--v-theme-primary))" fill-opacity="0.12" />
30
30
  <path :d="path" fill="none" stroke="rgb(var(--v-theme-primary))" stroke-width="2" vector-effect="non-scaling-stroke" />
31
31
  <rect v-for="(p, i) in points" :key="p.x" :x="(i * (width / Math.max(1, points.length - 1))) - width / Math.max(1, points.length - 1) / 2" y="0" :width="width / Math.max(1, points.length - 1)" :height="height" fill="transparent" @mouseenter="hover = i" />
@@ -1,14 +1,22 @@
1
1
  import type { $Fetch } from 'nitropack'
2
2
 
3
+ // The sign-out a 401 started, and the token whose session it ends: every
4
+ // request refused with that token (several waiting on one failed renewal)
5
+ // joins it rather than signing out again. One per module is one per session,
6
+ // the UI running in the browser only.
7
+ let ending: { token: string | null | undefined, done: Promise<void> } | null = null
8
+
3
9
  /**
4
10
  * The one HTTP client every Vector request goes through. Bearer mode
5
11
  * attaches the in-memory token — renewed first when it has under two
6
- * minutes left — and on a 401 renews it once and repeats the request,
7
- * sending the user to the login page only when that fails too (a 401
8
- * means the request did nothing, so repeating even a POST is safe);
9
- * cookie mode (hosted) rides the application's session cookie,
10
- * sends the CSRF token on every unsafe method, and hands a 401 to the
11
- * application's own login URL.
12
+ * minutes left — and on a 401 renews it once and repeats the request
13
+ * (a 401 for a token another request already renewed only repeats it),
14
+ * sending the user to the login page — once, however many requests
15
+ * that renewal failed — only when that fails too (a 401 means the
16
+ * request did nothing, so repeating even a POST is safe); cookie mode
17
+ * (hosted) rides the application's session cookie, sends the CSRF token
18
+ * on every unsafe method, and hands a 401 to the application's own login
19
+ * URL.
12
20
  */
13
21
  export function useVectorApi(): $Fetch {
14
22
  const config = useRuntimeConfig()
@@ -29,13 +37,20 @@ export function useVectorApi(): $Fetch {
29
37
  }
30
38
  } else {
31
39
  const token = await auth.fresh()
40
+ if (token !== null) ending = null // a new session: its own 401 signs out again
41
+ // which token, and whose, this request carried, for its 401
42
+ Object.assign(options, { vectorToken: token, vectorUser: auth.user === null ? null : String(auth.user.id) })
32
43
  if (token) options.headers.set('Authorization', `Bearer ${token}`)
33
44
  }
34
45
  },
35
46
  async onResponseError({ response, options }) {
36
- const once = options as typeof options & { vectorRenewed?: boolean }
47
+ const once = options as typeof options & { vectorRenewed?: boolean, vectorToken?: string | null, vectorUser?: string | null }
48
+ // the session changed since this request left: renewed for the same user (another request's 401 did it)
49
+ // repeats it without renewing again; another user's session (an impersonation ended) is not this request's
50
+ const moved = auth.token !== once.vectorToken
51
+ const renewedSince = moved && auth.token !== null && auth.user !== null && String(auth.user.id) === once.vectorUser
37
52
 
38
- if (response.status === 401 && !runtime.hosted && !once.vectorRenewed && auth.canRefresh && await auth.refresh()) {
53
+ if (response.status === 401 && !runtime.hosted && !once.vectorRenewed && (renewedSince || (!moved && auth.canRefresh && await auth.refresh()))) {
39
54
  // repeated once, with the renewed token (onRequest sets it)
40
55
  once.vectorRenewed = true
41
56
  options.retry = 1
@@ -51,23 +66,64 @@ export function useVectorApi(): $Fetch {
51
66
  return
52
67
  }
53
68
 
54
- auth.clear()
55
- // back to this page after signing in again, as the route middleware would send a visitor
56
- const current = router.currentRoute.value.fullPath
57
- await navigateTo({ path: `${appConfig.vector.basePath || ''}/login`, query: current.startsWith(`${appConfig.vector.basePath || ''}/login`) ? {} : { redirect: current } })
69
+ // the session this token belonged to is already ending: join that
70
+ if (ending !== null && ending.token === once.vectorToken) {
71
+ await ending.done
72
+
73
+ return
74
+ }
75
+
76
+ // refused for a session since replaced by another user's: that one is not this 401's to end
77
+ if (moved && auth.token !== null) return
78
+
79
+ ending = { token: once.vectorToken, done: end() }
80
+ await ending.done
58
81
  }
59
82
  },
60
83
  }) as $Fetch
84
+
85
+ /**
86
+ * Ends the session a 401 refused. An impersonation (never renewed)
87
+ * falls back to the signer's own session, renewed with their refresh
88
+ * token, without repeating the request as them; otherwise, or when
89
+ * that fails, the login page, saying why for an impersonation.
90
+ */
91
+ async function end(): Promise<void> {
92
+ const impersonating = auth.impersonating
93
+ const base = appConfig.vector.basePath || ''
94
+
95
+ try {
96
+ if (impersonating && await auth.resume()) {
97
+ // as stopping the impersonation does: the signer's own preferences and descriptor, and the dashboard
98
+ useState('vector.impersonator').value = null
99
+ useVectorPreferences().clear()
100
+ useVectorNotifications().notify(vt('shell.impersonation.ended'))
101
+ await useVectorSchema().load(true).catch(() => undefined)
102
+ await navigateTo(base || '/')
103
+
104
+ return
105
+ }
106
+
107
+ auth.clear()
108
+ // back to this page after signing in again, as the route middleware would send a visitor
109
+ const current = router.currentRoute.value.fullPath
110
+ const redirect = current.startsWith(`${base}/login`) ? {} : { redirect: current }
111
+ await navigateTo({ path: `${base}/login`, query: impersonating ? { ...redirect, reason: 'impersonation' } : redirect })
112
+ } catch {
113
+ // the navigation failed: the session is already ended
114
+ }
115
+ }
61
116
  }
62
117
 
63
- /** The message a failed request should show, from either Kinetis error shape. */
118
+ /** The message a failed request should show, from either Kinetis error shape: `error`, or problem+json's `detail`, then its `title`. */
64
119
  export function vectorErrorMessage(error: unknown): string {
65
- const failure = error as { data?: { error?: string, detail?: string }, message?: string } | null
120
+ const failure = error as { data?: { error?: string, detail?: string, title?: string }, message?: string } | null
66
121
  const data = failure?.data
67
122
 
68
123
  if (data && typeof data === 'object') {
69
124
  if (typeof data.error === 'string') return data.error
70
125
  if (typeof data.detail === 'string') return data.detail
126
+ if (typeof data.title === 'string') return data.title
71
127
  }
72
128
 
73
129
  return typeof failure?.message === 'string' ? failure.message : String(error)
@@ -46,7 +46,9 @@ const MAX_DELAY = 2 ** 31 - 1
46
46
  * 401; a failed renewal signs the user out. Logout revokes the refresh
47
47
  * token (`POST /auth/logout`). An impersonation token is never renewed:
48
48
  * the refresh token is the signed-in user's own, used only while the
49
- * session is theirs. Hosted mode rides the application's session instead.
49
+ * session is theirs or to end an impersonation that ran out, back in
50
+ * their own session (`resume`). Hosted mode rides the application's
51
+ * session instead.
50
52
  */
51
53
  export const useVectorAuthStore = defineStore('vectorAuth', {
52
54
  state: () => ({
@@ -55,7 +57,7 @@ export const useVectorAuthStore = defineStore('vectorAuth', {
55
57
  user: null as VectorUser | null,
56
58
  refreshToken: null as string | null,
57
59
  refreshExpiresAt: 0,
58
- /** Whose refresh token it is: the user who signed in. */
60
+ /** The user who signed in: whose refresh token it is, when there is one. */
59
61
  refreshSubject: null as string | null,
60
62
  restored: false,
61
63
  hosted: false,
@@ -67,11 +69,17 @@ export const useVectorAuthStore = defineStore('vectorAuth', {
67
69
  && state.refreshExpiresAt > Date.now()
68
70
  && state.user !== null
69
71
  && String(state.user.id) === state.refreshSubject,
72
+ /** Whether the session is another user's than the one who signed in: an impersonation. */
73
+ impersonating: state => state.user !== null && state.refreshSubject !== null && String(state.user.id) !== state.refreshSubject,
74
+ /** Whether an impersonation can end in the signer's own session: their refresh token is live. */
75
+ canResume(state): boolean {
76
+ return this.impersonating && state.refreshToken !== null && state.refreshExpiresAt > Date.now()
77
+ },
70
78
  // A getter is cached until the state changes, and the clock is not
71
79
  // state: the session's own timer (expireAt) renews or clears the
72
80
  // token when it runs out, which is the change that updates this.
73
81
  isAuthenticated(state): boolean {
74
- return state.hosted || (state.token !== null && state.expiresAt > Date.now()) || this.canRefresh
82
+ return state.hosted || (state.token !== null && state.expiresAt > Date.now()) || this.canRefresh || this.canResume
75
83
  },
76
84
  },
77
85
 
@@ -104,7 +112,7 @@ export const useVectorAuthStore = defineStore('vectorAuth', {
104
112
  this.user = saved.user
105
113
  this.refreshToken = refreshable ? saved.refreshToken! : null
106
114
  this.refreshExpiresAt = refreshable ? saved.refreshExpiresAt! : 0
107
- this.refreshSubject = refreshable ? saved.refreshSubject ?? null : null
115
+ this.refreshSubject = saved.refreshSubject ?? null
108
116
  this.expireAt(saved.expiresAt)
109
117
  }
110
118
  }
@@ -131,6 +139,22 @@ export const useVectorAuthStore = defineStore('vectorAuth', {
131
139
  refresh(): Promise<boolean> {
132
140
  if (!this.canRefresh) return Promise.resolve(false)
133
141
 
142
+ return this.renew()
143
+ },
144
+
145
+ /**
146
+ * Ends an impersonation the API no longer accepts: the signer's own
147
+ * session is renewed with their refresh token. False when it cannot
148
+ * be, and the session ended when the renewal is refused.
149
+ */
150
+ resume(): Promise<boolean> {
151
+ if (!this.canResume) return Promise.resolve(false)
152
+
153
+ return this.renew()
154
+ },
155
+
156
+ /** POST /auth/refresh with the refresh token, once at a time however many callers ask: `refresh` and `resume` decide when. */
157
+ renew(): Promise<boolean> {
134
158
  refreshing ??= (async () => {
135
159
  try {
136
160
  const config = useRuntimeConfig()
@@ -196,7 +220,8 @@ export const useVectorAuthStore = defineStore('vectorAuth', {
196
220
  if (this.expiresAt !== expiresAt) return // a newer token has its own timer
197
221
  if (Date.now() < due) this.expireAt(expiresAt) // past setTimeout's range: wait again
198
222
  else if (this.canRefresh) void this.refresh()
199
- else this.clear()
223
+ // an impersonation that ran out is left to lapse: the next request's 401 resumes the signer's own session
224
+ else if (!this.canResume) this.clear()
200
225
  }, Math.min(MAX_DELAY, Math.max(0, due - Date.now())))
201
226
  },
202
227
 
@@ -229,13 +254,13 @@ export const useVectorAuthStore = defineStore('vectorAuth', {
229
254
  if (response.refreshToken) {
230
255
  this.refreshToken = response.refreshToken
231
256
  this.refreshExpiresAt = Date.now() + (response.refreshExpiresIn ?? 0) * 1000
232
- this.refreshSubject = String(response.user.id)
233
257
  } else {
234
258
  this.refreshToken = null
235
259
  this.refreshExpiresAt = 0
236
- this.refreshSubject = null
237
260
  }
238
261
 
262
+ this.refreshSubject = String(response.user.id)
263
+
239
264
  this.expireAt(this.expiresAt)
240
265
  this.save()
241
266
  },
@@ -21,7 +21,7 @@ export function useVectorBranding() {
21
21
  primaryColorDark: null,
22
22
  theme: null,
23
23
  footerText: null,
24
- ...(schema.value?.branding ?? hosted ?? {}),
24
+ ...(schema.value?.branding ?? hosted),
25
25
  }))
26
26
 
27
27
  /** Pushes the colours into Vuetify's theme and picks the default theme once per session. */
@@ -38,7 +38,7 @@ export function useVectorPages() {
38
38
  const { pages } = useVectorExtensions()
39
39
 
40
40
  return computed<Record<string, VectorPageDefinition>>(() => ({
41
- ...(appConfig.vector.pages ?? {}),
41
+ ...appConfig.vector.pages,
42
42
  ...Object.fromEntries(pages.entries()),
43
43
  }))
44
44
  }
@@ -38,6 +38,12 @@ const cells: Record<string, Component> = {
38
38
  manyToMany: defineAsyncComponent(() => import('#vector/app/components/Vx/Cell/Count.vue')),
39
39
  }
40
40
 
41
+ /** The cell type a computed field is shown as: what it is computed as, text as a string. */
42
+ function computedCell(field: VectorField): string {
43
+ const as = field.computed?.as
44
+ return as === 'text' ? 'string' : as ?? 'string'
45
+ }
46
+
41
47
  export function useVectorFields() {
42
48
  const appConfig = useAppConfig()
43
49
 
@@ -59,7 +65,7 @@ export function useVectorFields() {
59
65
  }
60
66
 
61
67
  // a computed value is shown by the cell of what it is computed as
62
- const type = field.type === 'computed' ? (field.computed?.as === 'text' ? 'string' : field.computed?.as ?? 'string') : field.type
68
+ const type = field.type === 'computed' ? computedCell(field) : field.type
63
69
 
64
70
  return cells[type] ?? cells.string!
65
71
  }
@@ -1,4 +1,5 @@
1
1
  import type { VectorField } from '#vector/app/types/vector'
2
+ import { violationsOf } from '#vector/app/utils/internal/violations'
2
3
 
3
4
  /** The value a fresh input holds: the field's default, or the type's empty value. */
4
5
  export function initialValue(field: VectorField): unknown {
@@ -10,7 +11,10 @@ export function initialValue(field: VectorField): unknown {
10
11
 
11
12
  /**
12
13
  * Maps the framework's 422 document onto field names; returns the
13
- * message that names no field, if any.
14
+ * message that names no field, if any. A violation deeper in a value
15
+ * (`tags.2`) shows on its field: the loose field lists this serves
16
+ * (settings, bulk edit, action dialogs) hold no repeater, the one input
17
+ * that takes a deeper key (`Vx/Resource/Form.vue` maps those).
14
18
  */
15
19
  export function applyViolations(error: unknown, values: Record<string, unknown>, serverErrors: Record<string, string[]>): string | null {
16
20
  const failure = error as { status?: number, statusCode?: number, data?: { errors?: unknown } } | null
@@ -22,11 +26,12 @@ export function applyViolations(error: unknown, values: Record<string, unknown>,
22
26
 
23
27
  let general: string | null = null
24
28
 
25
- for (const violation of violations as { path: (string | number)[], message: string }[]) {
29
+ for (const violation of violationsOf(violations)) {
26
30
  const key = String(violation.path[0] ?? '')
27
31
 
28
32
  if (key && key in values) {
29
- (serverErrors[key] ??= []).push(`${violation.message.charAt(0).toUpperCase()}${violation.message.slice(1)}`)
33
+ serverErrors[key] ??= []
34
+ serverErrors[key].push(`${violation.message.charAt(0).toUpperCase()}${violation.message.slice(1)}`)
30
35
  } else {
31
36
  general = violation.message
32
37
  }
@@ -14,7 +14,9 @@ import { useEventListener, useIdle } from '@vueuse/core'
14
14
  export function useVectorIdle(onIdle: () => void | Promise<void>): void {
15
15
  const minutes = useAppConfig().vector.idleMinutes
16
16
 
17
- if (!import.meta.client || !(minutes > 0)) return
17
+ const enabled = minutes > 0
18
+
19
+ if (!import.meta.client || !enabled) return
18
20
 
19
21
  const timeout = minutes * 60_000
20
22
  const { idle, lastActive, reset } = useIdle(timeout, { listenForVisibilityChange: false })
@@ -49,17 +49,6 @@ export function useVectorImpersonation() {
49
49
  }
50
50
  }
51
51
 
52
- /** The `sub` of a JWT, read without verifying it: the server already did, and this only labels the session. */
53
- function subjectOf(token: string): string | null {
54
- try {
55
- const payload = JSON.parse(atob(token.split('.')[1]?.replace(/-/g, '+').replace(/_/g, '/') ?? '')) as { sub?: unknown }
56
-
57
- return typeof payload.sub === 'string' || typeof payload.sub === 'number' ? String(payload.sub) : null
58
- } catch {
59
- return null
60
- }
61
- }
62
-
63
52
  async function start(userId: number | string) {
64
53
  await apply(await api<Swap>(`/vector/impersonate/${encodeURIComponent(String(userId))}`, { method: 'POST' }))
65
54
  }
@@ -76,3 +65,14 @@ export function useVectorImpersonation() {
76
65
 
77
66
  return { impersonator, start, stop, refresh }
78
67
  }
68
+
69
+ /** The `sub` of a JWT, read without verifying it: the server already did, and this only labels the session. */
70
+ function subjectOf(token: string): string | null {
71
+ try {
72
+ const payload = JSON.parse(atob(token.split('.')[1]?.replaceAll('-', '+').replaceAll('_', '/') ?? '')) as { sub?: unknown }
73
+
74
+ return typeof payload.sub === 'string' || typeof payload.sub === 'number' ? String(payload.sub) : null
75
+ } catch {
76
+ return null
77
+ }
78
+ }
@@ -32,6 +32,12 @@ const inputs: Record<string, Component> = {
32
32
  hasMany: defineAsyncComponent(() => import('#vector/app/components/Vx/Input/Repeater.vue')),
33
33
  }
34
34
 
35
+ /** Whether a field is edited in this operation at all. */
36
+ function editable(field: VectorField, operation: 'create' | 'update'): boolean {
37
+ if (field.type === 'hasMany') return !!field.repeater && field.views.includes(operation)
38
+ return !field.readonly && field.views.includes(operation) && !['id', 'hasOne'].includes(field.type)
39
+ }
40
+
35
41
  export function useVectorInputs() {
36
42
  const appConfig = useAppConfig()
37
43
 
@@ -51,11 +57,5 @@ export function useVectorInputs() {
51
57
  return overrides[field.type] ?? inputs[field.type] ?? inputs.string!
52
58
  }
53
59
 
54
- /** Whether a field is edited in this operation at all. */
55
- function editable(field: VectorField, operation: 'create' | 'update'): boolean {
56
- if (field.type === 'hasMany') return !!field.repeater && field.views.includes(operation)
57
- return !field.readonly && field.views.includes(operation) && !['id', 'hasOne'].includes(field.type)
58
- }
59
-
60
60
  return { inputFor, editable }
61
61
  }
@@ -28,12 +28,15 @@ export function useVectorJobs() {
28
28
  return job
29
29
  }
30
30
 
31
+ // the wait ends on the timer or the abort, and takes its listener off the signal either way
31
32
  await new Promise<void>((resolve) => {
32
- const timer = setTimeout(resolve, delay)
33
- signal?.addEventListener('abort', () => {
33
+ const done = () => {
34
34
  clearTimeout(timer)
35
+ signal?.removeEventListener('abort', done)
35
36
  resolve()
36
- }, { once: true })
37
+ }
38
+ const timer = setTimeout(done, delay)
39
+ signal?.addEventListener('abort', done, { once: true })
37
40
  })
38
41
 
39
42
  if (signal?.aborted) {
@@ -1,5 +1,5 @@
1
1
  import type { VectorLocale, VectorSchemaI18n } from '#vector/app/types/vector'
2
- import { isRtl, vuetifyLocale } from '#vector/app/i18n'
2
+ import { isRtl, knownVuetifyLocale, textDirection } from '#vector/app/i18n'
3
3
 
4
4
  // The latest language the user picked: an earlier pick still in flight
5
5
  // must not apply its answer over it. The UI runs in the browser only, one
@@ -25,15 +25,13 @@ export function useVectorLocale() {
25
25
 
26
26
  const vuetify = nuxtApp.$vuetify as { locale?: { current: { value: string }, messages: { value: Record<string, unknown> } } } | undefined
27
27
  if (vuetify?.locale) {
28
- const tag = vuetifyLocale(code)
29
- const known = vuetify.locale.messages.value
30
- vuetify.locale.current.value = known[tag] ? tag : (known[code.split('-')[0]!] ? code.split('-')[0]! : 'en')
28
+ vuetify.locale.current.value = knownVuetifyLocale(code, vuetify.locale.messages.value)
31
29
  }
32
30
 
33
31
  if (import.meta.client) {
34
32
  const known = locales.value.find(l => l.code === code)
35
33
  document.documentElement.lang = code
36
- document.documentElement.dir = known ? known.dir : (isRtl(code) ? 'rtl' : 'ltr')
34
+ document.documentElement.dir = known ? known.dir : textDirection(code)
37
35
  try {
38
36
  window.localStorage.setItem('vector.locale', code)
39
37
  } catch {