@open-commune/web 0.2.14 → 0.2.16

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 (69) hide show
  1. package/app.config.ts +7 -0
  2. package/components/audience/audience-bar-list.vue +29 -0
  3. package/components/audience/audience-panel.vue +230 -0
  4. package/components/data/lists/data-table.vue +203 -0
  5. package/components/data/lists/row-actions.vue +41 -0
  6. package/components/elements/badges/status-badge.vue +23 -0
  7. package/components/elements/media/media-image.vue +26 -0
  8. package/components/forms/fields/input-files-media.vue +87 -0
  9. package/components/forms/{inputs → fields}/input-filter-status.vue +2 -2
  10. package/components/forms/{inputs → fields}/input-search.vue +8 -2
  11. package/components/forms/fields/input-text-area.vue +86 -0
  12. package/components/forms/fields/input-text.vue +47 -0
  13. package/components/forms/fields/select-enum.vue +69 -0
  14. package/components/forms/handlers/handler-collections.vue +100 -170
  15. package/components/forms/handlers/handler-list.vue +187 -0
  16. package/components/forms/handlers/handler-members.vue +171 -0
  17. package/components/forms/handlers/handler-password-reset.vue +45 -0
  18. package/components/forms/handlers/handler-roles.vue +28 -166
  19. package/components/forms/handlers/handler-sessions.vue +77 -0
  20. package/components/forms/handlers/handler-tokens.vue +54 -69
  21. package/components/forms/layouts/form-default.vue +99 -0
  22. package/components/forms/layouts/form.vue +4 -0
  23. package/components/forms/layouts/forms-layout.vue +236 -0
  24. package/components/forms/layouts/forms-section.vue +186 -0
  25. package/components/forms/layouts/layout.vue +4 -0
  26. package/components/forms/layouts/modal.vue +4 -0
  27. package/components/forms/layouts/section.vue +4 -0
  28. package/components/layout/shell/shell-account-menu.vue +10 -2
  29. package/composables/core/domains/use-api-tokens.ts +80 -0
  30. package/composables/core/domains/use-audience.ts +26 -0
  31. package/composables/core/domains/use-auth.ts +56 -2
  32. package/composables/core/domains/use-definitions.ts +18 -5
  33. package/composables/core/domains/use-entries.ts +125 -3
  34. package/composables/core/domains/use-media.ts +24 -1
  35. package/composables/core/domains/use-members.ts +68 -0
  36. package/composables/core/domains/use-organization.ts +53 -0
  37. package/composables/use-models.js +1 -7
  38. package/constants/errors.ts +29 -0
  39. package/constants/forms/account.ts +62 -0
  40. package/constants/forms/collections.ts +39 -0
  41. package/constants/forms/members.ts +40 -0
  42. package/constants/forms/organization.ts +188 -0
  43. package/constants/forms/tokens.ts +15 -0
  44. package/constants/roles.ts +57 -0
  45. package/constants/settings.ts +26 -0
  46. package/constants/statuses.ts +8 -5
  47. package/nuxt.config.ts +4 -1
  48. package/package.json +4 -3
  49. package/pages/[collection]/[record]/index.vue +7 -0
  50. package/pages/[collection]/index.vue +117 -97
  51. package/pages/account.vue +40 -0
  52. package/pages/overview.vue +106 -2
  53. package/pages/settings.vue +26 -181
  54. package/plugins/01.validation.client.ts +23 -0
  55. package/store/layout/workspace.js +4 -28
  56. package/utils/colors.ts +26 -0
  57. package/utils/errors.ts +13 -0
  58. package/utils/forms.ts +67 -0
  59. package/utils/list-columns.ts +90 -0
  60. package/utils/settings.ts +38 -0
  61. package/utils/statuses.ts +4 -0
  62. package/models/role.js +0 -66
  63. package/models/token.js +0 -56
  64. package/models/user.js +0 -97
  65. package/pages/management/index.vue +0 -15
  66. package/pages/management/members.vue +0 -176
  67. package/pages/management/organizations.vue +0 -192
  68. package/pages/management/roles.vue +0 -183
  69. /package/components/forms/{inputs → fields}/input-filter.vue +0 -0
@@ -1,79 +1,64 @@
1
1
  <template>
2
- <div class="relative block w-full">
3
- <button-secondary class="my-1" label="Ajouter un token" @click="_openModalForm" />
4
- <list-table
5
- :headers="TABLE_HEADERS"
6
- :items="tokens"
7
- :actions="['remove']"
8
- @remove="_removeToken($event)"
9
- />
10
- </div>
2
+ <handler-list
3
+ v-model:open="isModalOpen"
4
+ :rows="rows"
5
+ :loading="isLoading"
6
+ empty="Aucun token."
7
+ action-label="Ajouter un token"
8
+ :form="TOKEN_FORM"
9
+ :schema="apiTokenCreateDto"
10
+ title="Créer un token"
11
+ description="Entrez un nom pour votre token afin de l'identifier facilement."
12
+ submit-label="Créer"
13
+ @add="_openModalForm"
14
+ @submit="_createToken"
15
+ >
16
+ <template #row="{ row }">
17
+ <span class="min-w-0 flex-1 truncate text-sm font-medium text-highlighted">{{ row.name }}</span>
18
+ <span class="shrink-0 text-[13px] text-dimmed">{{ row.lastUsedAt }}</span>
19
+ <UButton
20
+ icon="i-lucide-trash-2"
21
+ color="neutral"
22
+ variant="ghost"
23
+ size="sm"
24
+ class="shrink-0 text-dimmed opacity-0 transition hover:text-error group-hover:opacity-100 focus-visible:opacity-100"
25
+ :aria-label="`Révoquer ${row.name}`"
26
+ @click="_removeToken(row.source)"
27
+ />
28
+ </template>
29
+ </handler-list>
11
30
  </template>
12
31
 
13
32
  <script setup>
14
- import listTable from '~/components/data/lists/data-lists-table'
15
- import buttonSecondary from '~/components/elements/buttons/secondary'
16
- import { useModalStore } from '~/store/layout/modal'
33
+ import { apiTokenCreateDto } from '@open-commune/core/dtos'
34
+ import handlerList from '~/components/forms/handlers/handler-list.vue'
35
+ import { DateTime } from 'luxon'
36
+ import { TOKEN_FORM } from '~/constants/forms/tokens'
17
37
 
18
- const { Token } = useModels()
19
- const { open } = useModalStore()
38
+ // Prepare composables
39
+ const $apiTokens = useApiTokens()
40
+ const { mutateAsync: createToken } = $apiTokens.create()
41
+ const { mutate: revokeToken } = $apiTokens.revoke()
20
42
 
21
- // Prepare constants
22
- const TABLE_HEADERS = [
23
- {
24
- title: 'Nom',
25
- property: 'name',
26
- component: 'data-text'
27
- },
28
- {
29
- title: 'Token',
30
- property: 'token',
31
- component: 'data-text'
32
- },
33
- {
34
- title: '',
35
- component: 'actions'
36
- }
37
- ]
43
+ // Prepare reactive
44
+ const isModalOpen = ref(false)
38
45
 
39
- // Prepare computed data
40
- const tokens = computed(() => Token.repo.all())
46
+ // Fetch data
47
+ const { data: tokens = [], isLoading } = $apiTokens.list()
41
48
 
42
- // Prepare methods
43
- const _createToken = async (data) => {
44
- await Token.create(data)
45
- }
46
-
47
- const _removeToken = async ({ _id }) => {
48
- await Token.remove(_id)
49
- }
49
+ // Prepare computed
50
+ const rows = computed(() => tokens.value?.map(token => ({
51
+ key: token.id,
52
+ name: token.name,
53
+ lastUsedAt: token.lastUsedAt
54
+ ? DateTime.fromISO(token.lastUsedAt).setLocale('fr').toRelative()
55
+ : 'Jamais utilisé',
56
+ source: token,
57
+ })))
50
58
 
51
- const _openModalForm = (action, record) => {
52
- open({
53
- onSubmit: _createToken,
54
- details: {
55
- title: 'Créer un token',
56
- subTitle: 'Entrez un nom pour votre token afin de l\'identifier facilement.',
57
- acceptButton: 'Créer',
58
- closeButton: 'Annuler'
59
- },
60
- attributes: [
61
- {
62
- property: 'name',
63
- componentOptions: {
64
- placeHolder: 'ex: landing pages, mobile app, ... ',
65
- name: 'name'
66
- },
67
- component: 'input-text'
68
- }
69
- ]
70
- })
71
- }
72
-
73
- // Prepare lifecle hooks
74
- onMounted(async () => {
75
- if (!tokens.value.length) {
76
- await Token.list()
77
- }
78
- })
59
+ // Prepare methods
60
+ // The toast is the mutation's, success or failure: a refusal is said, not thrown.
61
+ const _createToken = ({ name }) => createToken(name).catch(() => {})
62
+ const _removeToken = ({ id, name }) => revokeToken({ id, name })
63
+ const _openModalForm = () => { isModalOpen.value = true }
79
64
  </script>
@@ -0,0 +1,99 @@
1
+ <template>
2
+ <div v-show="attributes.length" class="space-y-4">
3
+ <template v-for="({ property, control, standalone, componentOptions }, i) in controls" :key="i">
4
+ <!-- A standalone handler carries neither a value nor a label: it has
5
+ nothing to bind an error to, so it gets no field around it. -->
6
+ <component
7
+ :is="control"
8
+ v-if="standalone"
9
+ class="w-full"
10
+ v-bind="{ ...componentOptions, readOnly: componentOptions.readOnly || loading }"
11
+ />
12
+ <!-- Every other control gets its field HERE, label and `name`: the
13
+ control draws only its input, bound to the form's state, and the
14
+ field shows under it what the schema refuses. -->
15
+ <UFormField v-else :label="componentOptions.label" :name="property">
16
+ <component
17
+ :is="control"
18
+ v-model="state[property]"
19
+ class="w-full"
20
+ v-bind="{ ..._withoutLabel(componentOptions), readOnly: componentOptions.readOnly || loading }"
21
+ />
22
+ </UFormField>
23
+ </template>
24
+ </div>
25
+ </template>
26
+
27
+ <script setup>
28
+ import handlerCollections from '~/components/forms/handlers/handler-collections'
29
+ import handlerMembers from '~/components/forms/handlers/handler-members'
30
+ import handlerPasswordReset from '~/components/forms/handlers/handler-password-reset'
31
+ import handlerRoles from '~/components/forms/handlers/handler-roles'
32
+ import handlerSessions from '~/components/forms/handlers/handler-sessions'
33
+ import handlerTokens from '~/components/forms/handlers/handler-tokens'
34
+ import inputFilesMedia from '~/components/forms/fields/input-files-media'
35
+ import inputText from '~/components/forms/fields/input-text'
36
+ import inputTextArea from '~/components/forms/fields/input-text-area'
37
+ import selectEnum from '~/components/forms/fields/select-enum'
38
+ import { isStandalone } from '~/utils/forms'
39
+
40
+ // Prepare props
41
+ const $props = defineProps({
42
+ loading: {
43
+ type: Boolean,
44
+ default: false
45
+ },
46
+ attributes: {
47
+ type: Array,
48
+ default: () => []
49
+ },
50
+ /**
51
+ * The state of the enclosing `UForm`, keyed by property. The controls write
52
+ * into it: it is the form's one copy of what is being typed.
53
+ */
54
+ state: {
55
+ type: Object,
56
+ required: true
57
+ }
58
+ })
59
+
60
+ // Prepare constants
61
+ /**
62
+ * The controls a described form may name. The settings and the account are
63
+ * its only callers so far: the record's own controls join with the record page
64
+ * (A6), which retires the older `forms/inputs` it still renders today.
65
+ */
66
+ const CONTROLS = {
67
+ 'handler-collections': handlerCollections,
68
+ 'handler-members': handlerMembers,
69
+ 'handler-password-reset': handlerPasswordReset,
70
+ 'handler-roles': handlerRoles,
71
+ 'handler-sessions': handlerSessions,
72
+ 'handler-tokens': handlerTokens,
73
+ 'input-files-media': inputFilesMedia,
74
+ 'input-text': inputText,
75
+ 'input-text-area': inputTextArea,
76
+ 'select-enum': selectEnum,
77
+ }
78
+
79
+ // Prepare constants
80
+ const globals = getCurrentInstance()?.appContext.components ?? {}
81
+
82
+ // Prepare computed
83
+ // A control the catalogue does not know may be a layer's: a globally
84
+ // registered component, which owns its data like a handler. Anything else
85
+ // renders nothing.
86
+ const controls = computed(() => $props.attributes
87
+ .map(attribute => ({
88
+ ...attribute,
89
+ componentOptions: attribute.componentOptions ?? {},
90
+ control: CONTROLS[attribute.component] ?? (attribute.component in globals ? attribute.component : undefined),
91
+ standalone: isStandalone(attribute) || !(attribute.component in CONTROLS),
92
+ }))
93
+ .filter(({ control }) => control)
94
+ )
95
+
96
+ // Prepare methods
97
+ /** The label and the name are the field's, not the control's. */
98
+ const _withoutLabel = ({ label, name, ...options }) => options
99
+ </script>
@@ -1,3 +1,7 @@
1
+ <!-- Former form engine: only the record page renders it now. The settings use
2
+ forms-layout / forms-section / form-default and the fields under
3
+ components/forms/fields. Deleted with forms/inputs and forms/selects when
4
+ the record page is ported (A6). -->
1
5
  <template>
2
6
  <div v-show="attributes.length" class="space-y-4">
3
7
  <div
@@ -0,0 +1,236 @@
1
+ <template>
2
+ <div class="lg:grid lg:grid-cols-[14rem_minmax(0,1fr)] lg:gap-x-6">
3
+ <div
4
+ v-if="tabs.length"
5
+ class="flex flex-col gap-3 px-2 sm:px-6 lg:sticky lg:top-6 lg:self-start lg:px-0"
6
+ >
7
+ <!-- The collection list's search: a magnifier that opens over the rail.
8
+ On a single page it filters the cards too, so a search lands on the
9
+ setting itself: « logo » leaves the logo card alone on screen. -->
10
+ <input-search
11
+ v-if="onePage"
12
+ v-model="search"
13
+ placeholder="Rechercher un paramètre"
14
+ open-class="w-full"
15
+ :debounce="0"
16
+ />
17
+ <UNavigationMenu
18
+ v-if="navigationItems.length"
19
+ orientation="vertical"
20
+ :items="navigationItems"
21
+ :ui="{
22
+ list: 'gap-0.5',
23
+ // Same size as the rest of the navigation: a rail has no scale of its own.
24
+ link: 'px-3 py-2 text-sm before:rounded-md',
25
+ }"
26
+ />
27
+ </div>
28
+
29
+ <!-- One page: every tab is a group of cards, and the rail is its table of
30
+ contents. No heading over a group: its cards are titled already, and
31
+ the rail says where one is. -->
32
+ <div
33
+ v-if="onePage"
34
+ class="mt-6 flex flex-col gap-10 sm:px-6 lg:mt-0 lg:px-0"
35
+ >
36
+ <section
37
+ v-for="group in visibleGroups"
38
+ :id="group.anchor"
39
+ :key="group.title"
40
+ ref="groupElements"
41
+ :data-title="group.title"
42
+ class="flex scroll-mt-6 flex-col gap-6"
43
+ >
44
+ <forms-section
45
+ v-for="({ componentOptions }, i) in group.sections"
46
+ :key="`${group.title}-${i}`"
47
+ v-bind="{ record, schema, ...componentOptions }"
48
+ />
49
+ </section>
50
+ <p v-if="!visibleGroups.length" class="text-sm text-muted">
51
+ Aucun paramètre ne correspond à « {{ search }} ».
52
+ <UButton
53
+ variant="link"
54
+ color="neutral"
55
+ class="p-0 align-baseline"
56
+ label="Effacer la recherche"
57
+ @click="search = ''"
58
+ />
59
+ </p>
60
+ </div>
61
+
62
+ <div
63
+ v-else
64
+ class="mt-6 space-y-6 sm:px-6 lg:mt-0 lg:px-0"
65
+ :class="tabs.length ? '' : 'lg:col-span-2'"
66
+ >
67
+ <forms-section
68
+ v-for="({ componentOptions }, i) in currentSections"
69
+ :key="`form-layout-${i}`"
70
+ v-bind="{ record, schema, ...componentOptions }"
71
+ />
72
+ </div>
73
+ </div>
74
+ </template>
75
+
76
+ <script setup>
77
+ import inputSearch from '~/components/forms/fields/input-search'
78
+ import formsSection from '~/components/forms/layouts/forms-section'
79
+
80
+ // Prepare props
81
+ const $props = defineProps({
82
+ record: {
83
+ type: Object,
84
+ default: () => ({})
85
+ },
86
+ layout: {
87
+ type: Array,
88
+ default: () => []
89
+ },
90
+ // The server's schema for `record`: each section narrows it to its fields.
91
+ schema: {
92
+ type: Object,
93
+ default: undefined
94
+ },
95
+ // Section shown, or scrolled to, when the caller drives it from the URL
96
+ // (settings screen).
97
+ activeTab: {
98
+ type: String,
99
+ default: ''
100
+ },
101
+ /**
102
+ * Every tab on one page, the rail as its table of contents, and a search
103
+ * that filters both. Without it, one tab at a time.
104
+ */
105
+ onePage: {
106
+ type: Boolean,
107
+ default: false
108
+ }
109
+ })
110
+
111
+ // Prepare reactive
112
+ const selectedTab = ref('')
113
+ const search = ref('')
114
+ // The group under the top of the window, while scrolling a single page.
115
+ const spiedTab = ref('')
116
+ // The group asked for by the rail or the URL, until the reader scrolls on:
117
+ // near the bottom of the page a short group never reaches the top.
118
+ const pinnedTab = ref('')
119
+ const groupElements = useTemplateRef('groupElements')
120
+
121
+ // Prepare methods
122
+ /** Lower case, no accents: « deploiement » finds Déploiement. */
123
+ const _fold = text => String(text ?? '').normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase().trim()
124
+
125
+ /** What a search may land on in one card: its title, its text, its fields. */
126
+ const _sectionText = ({ componentOptions: options = {} }) => [
127
+ options.title,
128
+ options.description,
129
+ ...(options.attributes ?? []).map(({ componentOptions: field = {} }) => field.label),
130
+ ].filter(Boolean).join(' ')
131
+
132
+ /**
133
+ * The current item gets a grey ground and the strong ink; the others keep a
134
+ * readable grey and only darken on hover — a ground lighting up as the pointer
135
+ * crosses the rail made it flicker.
136
+ */
137
+ const _mark = item => ({
138
+ ...item,
139
+ class: item.active
140
+ ? 'font-medium text-highlighted before:bg-accented'
141
+ : 'font-normal text-toned hover:text-highlighted hover:before:bg-transparent',
142
+ })
143
+
144
+ // Prepare computed
145
+ const tabs = computed(() => $props.layout.map(({ title, label, anchor, to, sections }) => ({
146
+ title,
147
+ label: label || title,
148
+ anchor: anchor || _fold(title).replace(/\W+/g, '-'),
149
+ to,
150
+ sections: sections ?? [],
151
+ })))
152
+
153
+ const currentSections = computed(() => tabs.value.find(({ title }) => title === selectedTab.value)?.sections || [])
154
+
155
+ /**
156
+ * The groups a search leaves. A tab whose name matches keeps all its cards;
157
+ * otherwise only the cards that hold the words are kept, and a tab left with
158
+ * none disappears, from the page and from the rail.
159
+ */
160
+ const visibleGroups = computed(() => {
161
+ const wanted = _fold(search.value)
162
+ if (!wanted) return tabs.value
163
+ return tabs.value
164
+ .map(tab => _fold(`${tab.label} ${tab.title}`).includes(wanted)
165
+ ? tab
166
+ : { ...tab, sections: tab.sections.filter(section => _fold(_sectionText(section)).includes(wanted)) })
167
+ .filter(tab => tab.sections.length)
168
+ })
169
+
170
+ const currentTab = computed(() => ($props.onePage ? pinnedTab.value || spiedTab.value : '') || selectedTab.value)
171
+
172
+ /**
173
+ * One rail, whatever it points at. A rail knows nothing of settings, of forms
174
+ * or of records: its entries are either routes (`to`) or in-page sections
175
+ * (`onSelect`).
176
+ */
177
+ const navigationItems = computed(() => [
178
+ ($props.onePage ? visibleGroups.value : tabs.value).map(({ title, label, to }) => _mark({
179
+ label,
180
+ ...(to ? { to } : {}),
181
+ // On one page the rail scrolls, even to the section already in the URL.
182
+ onSelect: () => ($props.onePage ? _scrollTo(title) : (selectedTab.value = title)),
183
+ active: title === currentTab.value,
184
+ })),
185
+ ].filter(group => group.length))
186
+
187
+ // Prepare watchers
188
+ // Without its own navigation the form has nobody to pick the first tab for it.
189
+ watchEffect(() => {
190
+ const wanted = $props.activeTab
191
+ if (wanted && tabs.value.some(({ title }) => title === wanted)) {
192
+ selectedTab.value = wanted
193
+ } else if (!selectedTab.value && tabs.value.length) {
194
+ selectedTab.value = tabs.value[0].title
195
+ }
196
+ })
197
+
198
+ // On one page, a section in the URL is a place to scroll to: the rail's links
199
+ // change it, and so does an old address landing here.
200
+ async function _scrollTo(title, behavior = 'smooth') {
201
+ pinnedTab.value = title
202
+ await nextTick()
203
+ const element = groupElements.value?.find(({ dataset }) => dataset.title === title)
204
+ element?.scrollIntoView({ behavior, block: 'start' })
205
+ }
206
+ watch(() => $props.activeTab, (wanted) => {
207
+ if ($props.onePage && wanted) _scrollTo(wanted)
208
+ })
209
+ // Landing on an address: the lists above the section fill in after the first
210
+ // paint and push it down, so the page goes there once more when they have.
211
+ onMounted(() => {
212
+ if (!$props.onePage || !$props.activeTab) return
213
+ _scrollTo($props.activeTab, 'instant')
214
+ setTimeout(() => _scrollTo($props.activeTab, 'instant'), 600)
215
+ })
216
+
217
+ // The rail follows the reading: the current group is the last one whose top
218
+ // has gone past the top of the window, or the last of all at the bottom.
219
+ const _spy = () => {
220
+ const elements = groupElements.value ?? []
221
+ if (!elements.length) return
222
+ const atBottom = window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 4
223
+ const passed = atBottom
224
+ ? elements.at(-1)
225
+ : elements.filter(element => element.getBoundingClientRect().top <= 96).at(-1)
226
+ spiedTab.value = passed?.dataset.title ?? elements[0].dataset.title
227
+ }
228
+ if ($props.onePage) {
229
+ useEventListener(window, 'scroll', _spy, { passive: true })
230
+ // Only the reader's own scrolling unpins: the page's smooth scroll does not.
231
+ for (const event of ['wheel', 'touchmove', 'keydown']) {
232
+ useEventListener(window, event, () => { pinnedTab.value = '' }, { passive: true })
233
+ }
234
+ watch(visibleGroups, () => nextTick(_spy))
235
+ }
236
+ </script>
@@ -0,0 +1,186 @@
1
+ <template>
2
+ <!-- `novalidate` silences the browser's own bubbles: the schema is the
3
+ server's, and what it refuses is said under the field it refuses. -->
4
+ <UForm
5
+ novalidate
6
+ :state="state"
7
+ :schema="narrowed"
8
+ :class="frameless ? '' : 'bg-elevated shadow-card sm:rounded-lg dark:shadow-none dark:ring dark:ring-[var(--ui-border)] plain:bg-default plain:ring plain:ring-default'"
9
+ @submit="_save"
10
+ >
11
+ <div :class="frameless ? 'space-y-6' : 'py-6 px-4 space-y-6 sm:p-6'">
12
+ <!-- The action sits ON the title row: it acts on what the title names,
13
+ and a button alone on a line below the description read as orphaned.
14
+ A section declared as DATA has no caller to fill this slot, which is
15
+ why a handler mounted inside used to reach it by injection; those
16
+ handlers now draw their own button, next to their own list. -->
17
+ <div class="flex items-start justify-between gap-4">
18
+ <div>
19
+ <h3 v-show="title" class="text-base leading-6 font-semibold text-highlighted">
20
+ {{ title }}
21
+ </h3>
22
+ <p v-show="description" class="mt-1 text-sm text-muted">
23
+ {{ description }}
24
+ </p>
25
+ </div>
26
+ <slot name="action" />
27
+ </div>
28
+ <form-default
29
+ v-if="attributes.length"
30
+ :state="state"
31
+ :attributes="attributes"
32
+ :loading="isLoading"
33
+ />
34
+ <slot />
35
+ </div>
36
+ <!-- The footer lives ON the card, not in a cream band: the hint is an
37
+ aside, not a status bar. It goes left in small grey; the button stays
38
+ right. -->
39
+ <div
40
+ v-show="hint || (attributes.length && !noAction)"
41
+ class="flex flex-row items-center gap-4 px-4 pb-5 sm:px-6"
42
+ :class="hint ? 'justify-between' : 'justify-end'"
43
+ >
44
+ <p v-show="hint" class="text-[13px] text-dimmed">
45
+ {{ hint }}
46
+ </p>
47
+ <UButton
48
+ v-show="attributes.length && !noAction"
49
+ color="neutral"
50
+ size="lg"
51
+ type="submit"
52
+ :label="formButtonLabel"
53
+ :loading="isLoading"
54
+ :disabled="isLoading"
55
+ />
56
+ </div>
57
+ </UForm>
58
+ </template>
59
+
60
+ <script setup>
61
+ import formDefault from '~/components/forms/layouts/form-default'
62
+ import { refusalOf } from '~/utils/errors'
63
+ import { changesOf, narrowSchema, propertiesOf, sameValue, valuesOf } from '~/utils/forms'
64
+
65
+ // Prepare props
66
+ const $props = defineProps({
67
+ record: {
68
+ type: Object,
69
+ default: () => ({})
70
+ },
71
+ title: {
72
+ type: String,
73
+ default: ''
74
+ },
75
+ description: {
76
+ type: String,
77
+ default: ''
78
+ },
79
+ attributes: {
80
+ type: Array,
81
+ default: () => []
82
+ },
83
+ hint: {
84
+ type: String,
85
+ default: ''
86
+ },
87
+ formButtonLabel: {
88
+ type: String,
89
+ default: 'Enregistrer'
90
+ },
91
+ /**
92
+ * Render the fields without the card around them — no border, no ground, no
93
+ * padding. A section whose content draws its own card would otherwise sit in
94
+ * a second one.
95
+ */
96
+ frameless: {
97
+ type: Boolean,
98
+ default: false,
99
+ },
100
+ noAction: {
101
+ type: Boolean,
102
+ default: false
103
+ },
104
+ /**
105
+ * The server's schema for the record this section edits: the core's DTO
106
+ * itself. The section narrows it to its own fields.
107
+ */
108
+ schema: {
109
+ type: Object,
110
+ default: undefined
111
+ },
112
+ /**
113
+ * Where this section saves, when it is not the organization — the account
114
+ * screen, for one. Receives the changed fields, and nothing else.
115
+ */
116
+ onSave: {
117
+ type: Function,
118
+ default: null
119
+ }
120
+ })
121
+
122
+ // Prepare composables
123
+ const $toast = useToast()
124
+ const { mutateAsync: updateOrganization } = useOrganization().update()
125
+
126
+ // Prepare reactive
127
+ const isLoading = ref(false)
128
+ /** What the controls write into: one value per property the section edits. */
129
+ const state = reactive({})
130
+ /** Where the form started from: what a save compares against. */
131
+ const baseline = ref({})
132
+
133
+ // Prepare computed
134
+ const properties = computed(() => propertiesOf($props.attributes))
135
+ const narrowed = computed(() => narrowSchema($props.schema, properties.value))
136
+
137
+ // Prepare methods
138
+ const _save = async () => {
139
+ if ($props.noAction) return
140
+ // Only what was changed leaves: a card saves its fields, not the record.
141
+ // Nothing changed, nothing to say to the server.
142
+ const changes = changesOf(state, baseline.value)
143
+ if (!Object.keys(changes).length) return
144
+ isLoading.value = true
145
+ try {
146
+ if ($props.onSave) {
147
+ await $props.onSave(changes)
148
+ } else {
149
+ await updateOrganization(changes)
150
+ }
151
+ // A section that delegates lets its caller announce: only the caller
152
+ // knows what was saved, and two toasts for one action read as two saves.
153
+ if (!$props.onSave) $toast.add({ title: `${$props.title} à jour` })
154
+ } catch (error) {
155
+ // The schema already refused, under its field, what it could. What is
156
+ // left is the server's own refusal, or the network: it is SAID, in the
157
+ // words of the core's error when it sent one, and what was typed stays
158
+ // on screen.
159
+ console.error('[save] refused:', error)
160
+ $toast.add({
161
+ color: 'error',
162
+ title: "L'enregistrement a échoué",
163
+ description: refusalOf(error, "Le serveur a refusé la modification. Vos changements sont toujours à l'écran."),
164
+ })
165
+ } finally {
166
+ setTimeout(() => { isLoading.value = false }, 500)
167
+ }
168
+ }
169
+
170
+ // Prepare watchers
171
+ // The record arrives after the screen, and comes back after each save. A
172
+ // value the reader has not touched follows it; one being typed is left alone,
173
+ // so a refetch never erases a sentence in progress.
174
+ watch(
175
+ [() => $props.record, properties],
176
+ () => {
177
+ const incoming = valuesOf($props.record, properties.value)
178
+ for (const property of properties.value) {
179
+ const untouched = sameValue(state[property], baseline.value[property])
180
+ if (untouched) state[property] = incoming[property]
181
+ }
182
+ baseline.value = incoming
183
+ },
184
+ { immediate: true, deep: true }
185
+ )
186
+ </script>
@@ -1,3 +1,7 @@
1
+ <!-- Former form engine: only the record page renders it now. The settings use
2
+ forms-layout / forms-section / form-default and the fields under
3
+ components/forms/fields. Deleted with forms/inputs and forms/selects when
4
+ the record page is ported (A6). -->
1
5
  <template>
2
6
  <div class="lg:grid lg:grid-flow-row lg:auto-rows-max lg:grid-cols-12 lg:gap-x-5">
3
7
  <navigation
@@ -1,3 +1,7 @@
1
+ <!-- Former form engine: only the record page renders it now. The settings use
2
+ forms-layout / forms-section / form-default and the fields under
3
+ components/forms/fields. Deleted with forms/inputs and forms/selects when
4
+ the record page is ported (A6). -->
1
5
  <template>
2
6
  <transition
3
7
  enter-active-class="ease-out duration-200"