@open-commune/web 0.2.13 → 0.2.15

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 (82) hide show
  1. package/app.config.ts +13 -0
  2. package/assets/css/main.css +119 -0
  3. package/components/data/lists/data-table.vue +203 -0
  4. package/components/data/lists/row-actions.vue +41 -0
  5. package/components/elements/badges/status-badge.vue +23 -0
  6. package/components/elements/media/media-image.vue +26 -0
  7. package/components/forms/fields/input-files-media.vue +87 -0
  8. package/components/forms/{inputs → fields}/input-filter-status.vue +2 -2
  9. package/components/forms/{inputs → fields}/input-search.vue +8 -2
  10. package/components/forms/fields/input-text-area.vue +86 -0
  11. package/components/forms/fields/input-text.vue +47 -0
  12. package/components/forms/fields/select-enum.vue +69 -0
  13. package/components/forms/handlers/handler-collections.vue +100 -170
  14. package/components/forms/handlers/handler-list.vue +187 -0
  15. package/components/forms/handlers/handler-members.vue +171 -0
  16. package/components/forms/handlers/handler-password-reset.vue +45 -0
  17. package/components/forms/handlers/handler-roles.vue +28 -166
  18. package/components/forms/handlers/handler-sessions.vue +77 -0
  19. package/components/forms/handlers/handler-tokens.vue +54 -69
  20. package/components/forms/layouts/form-default.vue +99 -0
  21. package/components/forms/layouts/form.vue +4 -0
  22. package/components/forms/layouts/forms-layout.vue +236 -0
  23. package/components/forms/layouts/forms-section.vue +186 -0
  24. package/components/forms/layouts/layout.vue +4 -0
  25. package/components/forms/layouts/modal.vue +4 -0
  26. package/components/forms/layouts/section.vue +4 -0
  27. package/components/layout/entrance-mark.vue +18 -0
  28. package/components/layout/navigations/primary/dropdown-publish.vue +6 -4
  29. package/components/layout/shell/shell-account-menu.vue +63 -0
  30. package/components/layout/shell/shell-header.vue +99 -0
  31. package/composables/core/domains/use-api-tokens.ts +80 -0
  32. package/composables/core/domains/use-auth.ts +162 -0
  33. package/composables/core/domains/use-definitions.ts +18 -5
  34. package/composables/core/domains/use-entries.ts +113 -3
  35. package/composables/core/domains/use-media.ts +24 -1
  36. package/composables/core/domains/use-members.ts +68 -0
  37. package/composables/core/domains/use-organization.ts +53 -0
  38. package/composables/use-models.js +1 -9
  39. package/constants/errors.ts +28 -0
  40. package/constants/forms/account.ts +62 -0
  41. package/constants/forms/collections.ts +39 -0
  42. package/constants/forms/members.ts +40 -0
  43. package/constants/forms/organization.ts +188 -0
  44. package/constants/forms/tokens.ts +15 -0
  45. package/constants/roles.ts +57 -0
  46. package/constants/settings.ts +26 -0
  47. package/constants/statuses.ts +8 -5
  48. package/layouts/default.vue +1 -2
  49. package/layouts/entrance.vue +1 -6
  50. package/layouts/record.vue +1 -2
  51. package/middleware/00.light-mode.global.ts +8 -0
  52. package/nuxt.config.ts +8 -0
  53. package/package.json +5 -3
  54. package/pages/[collection]/index.vue +92 -79
  55. package/pages/account.vue +40 -0
  56. package/pages/index/index.vue +54 -62
  57. package/pages/index/password/define/[token].vue +44 -68
  58. package/pages/index/password/recover/index.vue +43 -54
  59. package/pages/index/welcome/[token].vue +42 -79
  60. package/pages/index.vue +6 -37
  61. package/pages/settings.vue +26 -181
  62. package/plugins/00.appearance.client.ts +7 -0
  63. package/plugins/01.validation.client.ts +23 -0
  64. package/store/layout/workspace.js +4 -28
  65. package/utils/colors.ts +26 -0
  66. package/utils/errors.ts +13 -0
  67. package/utils/forms.ts +67 -0
  68. package/utils/list-columns.ts +90 -0
  69. package/utils/settings.ts +38 -0
  70. package/utils/statuses.ts +4 -0
  71. package/components/layout/navigations/primary.vue +0 -132
  72. package/models/entrance.js +0 -42
  73. package/models/role.js +0 -66
  74. package/models/token.js +0 -56
  75. package/models/user.js +0 -97
  76. package/pages/management/index.vue +0 -15
  77. package/pages/management/members.vue +0 -176
  78. package/pages/management/organizations.vue +0 -192
  79. package/pages/management/roles.vue +0 -183
  80. package/public/logo-black.svg +0 -1
  81. package/public/logo-white.svg +0 -1
  82. /package/components/forms/{inputs → fields}/input-filter.vue +0 -0
@@ -1,90 +1,53 @@
1
1
  <template>
2
- <div class="mt-12 text-center">
3
- <h2 class="inline-flex mt-6 text-sm font-semibold">
4
- Bienvenue !
5
- </h2>
6
- <p class="mt-4 font-light text-sm text-gray-600">
7
- Vous avez été invité·e à rejoindre l'espace d'administration.
8
- Choisissez votre nom d'affichage et un mot de passe robuste (10 caractères minimum).
9
- </p>
10
- <form class="mt-12 space-y-6" @submit.prevent="_createAccount">
11
- <input-text
12
- place-holder="Votre nom"
13
- name="name"
14
- autocomplete="name"
15
- :value="name"
16
- required
17
- @change="name = $event"
18
- />
19
- <input-text
20
- place-holder="Mot de passe"
21
- name="password"
22
- type="password"
23
- autocomplete="new-password"
24
- :value="password"
25
- required
26
- @change="password = $event"
27
- />
28
- <input-text
29
- place-holder="Confirmation"
30
- name="password-confirmation"
31
- type="password"
32
- autocomplete="new-password"
33
- :value="passwordConfirmation"
34
- required
35
- @change="passwordConfirmation = $event"
36
- />
37
- <button-primary
38
- type="submit"
39
- :label="isLoading ? 'Envoie en cours' : 'Créer mon compte'"
40
- :disabled="!name || !password || password !== passwordConfirmation"
41
- :loading="isLoading"
42
- class="w-full"
43
- />
44
- </form>
45
- </div>
2
+ <UAuthForm
3
+ title="Bienvenue !"
4
+ description="Vous avez été invité·e à rejoindre l'espace d'administration. Choisissez votre nom d'affichage et un mot de passe robuste."
5
+ :fields="FIELDS"
6
+ :schema="SCHEMA"
7
+ :submit="{ label: 'Accepter l\'invitation', color: 'neutral', loading: isLoading }"
8
+ @submit="_createAccount"
9
+ >
10
+ <template #leading>
11
+ <layout-entrance-mark />
12
+ </template>
13
+
14
+ <template #footer>
15
+ <div class="flex flex-col items-center gap-3">
16
+ <p class="text-xs text-dimmed">
17
+ Dix caractères minimum.
18
+ </p>
19
+ <UButton color="neutral" variant="link" label="← Retour à la connexion" to="/" />
20
+ </div>
21
+ </template>
22
+ </UAuthForm>
46
23
  </template>
47
24
 
48
25
  <script setup>
49
- import { useNotificationsStore } from '~/store/layout/notifications'
50
- import InputText from '~/components/forms/inputs/input-text'
51
- import ButtonPrimary from '~/components/elements/buttons/primary'
26
+ import * as z from 'zod'
27
+
28
+ // Prepare constants
29
+ const FIELDS = [
30
+ { name: 'name', type: 'text', label: 'Votre nom', placeholder: 'Votre nom', autocomplete: 'name', required: true },
31
+ { name: 'password', type: 'password', label: 'Mot de passe', placeholder: 'Mot de passe', autocomplete: 'new-password', required: true }
32
+ ]
33
+ const SCHEMA = z.object({
34
+ name: z.string().min(1, 'Votre nom est requis'),
35
+ password: z.string().min(10, '10 caractères minimum')
36
+ })
52
37
 
53
- // Flux invitation Open Commune : la validité du jeton est vérifiée au moment de
54
- // l'acceptation (auth.acceptInvitation) — plus d'étape « confirmation d'email »
55
- // préalable.
56
- //
57
- // L'écran porte désormais le formulaire au lieu de renvoyer sur
58
- // /password/define : cette page-là ne sert plus qu'à la réinitialisation, où
59
- // il n'y a pas de nom à demander.
60
- const notificationsStore = useNotificationsStore()
38
+ // Prepare composables
61
39
  const $route = useRoute()
62
- const $router = useRouter()
63
- const { Entrance } = useModels()
40
+ const $auth = useAuth()
64
41
 
65
- // Prepare data
66
- const name = ref('')
67
- const password = ref('')
68
- const passwordConfirmation = ref('')
69
- const isLoading = ref(false)
42
+ // Prepare computed
43
+ const isLoading = computed(() => $auth.isAcceptingInvitation.value)
70
44
 
71
45
  // Prepare methods
72
- const _createAccount = async () => {
73
- isLoading.value = true
74
- try {
75
- const { token } = $route.params
76
- await Entrance.acceptInvitation({ token, name: name.value, password: password.value })
77
- notificationsStore.add({ icon: 'iconoir:password-cursor', type: 'success', title: 'Compte activé, connectez-vous.' })
78
- $router.push('/')
79
- } catch (err) {
80
- console.log(err)
81
- notificationsStore.add({
82
- icon: 'iconoir:password-error',
83
- type: 'warn',
84
- title: 'Invitation invalide ou mot de passe trop court (10 caractères minimum).'
85
- })
86
- } finally {
87
- isLoading.value = false
88
- }
46
+ const _createAccount = async (event) => {
47
+ await $auth.acceptInvitation({
48
+ token: $route.params.token,
49
+ name: event.data.name,
50
+ password: event.data.password
51
+ })
89
52
  }
90
53
  </script>
package/pages/index.vue CHANGED
@@ -1,44 +1,13 @@
1
1
  <template>
2
- <div class="min-h-screen bg-white flex">
3
- <div class="m-auto w-full max-w-lg lg:w-96">
4
- <div class="flex flex-col items-center space-y-2 mb-4">
5
- <img
6
- src="/logo-black.svg"
7
- alt="Logo"
8
- class="dark:hidden h-16 w-auto"
9
- >
10
- <img
11
- src="/logo-white.svg"
12
- alt="Logo"
13
- class="hidden h-24 w-auto"
14
- >
15
- <p v-if="demoEnv" class="text-sm text-gray-400 w-full border-t border-gray-100 text-center pt-2">
16
- <span class="bg-black rounded-lg text-white px-4 text-xs py-0.5 h-5 mx-auto">
17
- beta
18
- </span>
19
- </p>
2
+ <div class="entrance flex min-h-screen items-center justify-center bg-default px-4 py-12">
3
+ <div class="w-full max-w-sm">
4
+ <div class="entrance-card rounded-xl bg-elevated p-8 shadow-sm">
5
+ <nuxt-page />
20
6
  </div>
21
- <nuxt-page />
22
7
  </div>
23
8
  </div>
24
9
  </template>
25
10
 
26
11
  <script setup>
27
- const $config = useRuntimeConfig()
28
-
29
- definePageMeta({
30
- layout: 'entrance',
31
- auth: {
32
- unauthenticatedOnly: true,
33
- navigateAuthenticatedTo: '/overview',
34
- }
35
- })
36
-
37
- // Prepare computed
38
- // L'image d'instance est COMMUNE à tous les clients : rien de spécifique n'y est
39
- // cuit. L'hôte servi est donc la seule source fiable pour distinguer une démo.
40
- const demoEnv = computed(() => {
41
- const host = import.meta.client ? window.location.host : ''
42
- return host.includes('.beta') || host.includes('localhost')
43
- })
44
- </script>
12
+ definePageMeta({ layout: 'entrance' })
13
+ </script>
@@ -1,197 +1,42 @@
1
1
  <template>
2
- <forms-layout
3
- v-bind="{ record, ...ORGANIZATION_FORM }"
4
- class="mt-4"
5
- />
2
+ <forms-layout v-bind="{ record, layout }" :schema="organizationUpdateDto" :active-tab="activeTab" one-page />
6
3
  </template>
7
4
 
8
5
  <script setup>
9
- import { useWorkspaceStore } from '~/store/layout/workspace'
10
- import formsLayout from '~/components/forms/layouts/layout'
6
+ import { organizationUpdateDto } from '@open-commune/core/dtos'
7
+ import formsLayout from '~/components/forms/layouts/forms-layout'
8
+ import { ORGANIZATION_FORM } from '~/constants/forms/organization'
9
+ import { SETTINGS_SECTIONS } from '~/constants/settings'
10
+ import { layerSectionTab, sectionRoute, sectionTitleFromSlug } from '~/utils/settings'
11
+
12
+ // Prepare composables
13
+ const $route = useRoute()
14
+ const $organization = useOrganization()
15
+ const { settings } = useAppConfig()
11
16
 
12
17
  definePageMeta({
13
18
  permissions: ['manage:all'],
14
- preFetch: ['Organization'],
15
19
  headings: {
16
20
  title: 'Paramètres',
17
21
  description: 'Retrouvez ici tous les paramètres de l\'organisation.'
18
22
  }
19
23
  })
20
24
 
21
- const $workspaceStore = useWorkspaceStore()
22
- const ORGANIZATION_FORM = ref({
23
- layout: [
24
- {
25
- icon: '',
26
- sections: [
27
- {
28
- componentOptions: {
29
- title: 'Logo de l\'organization',
30
- description: 'Cliquez sur votre logo pour ajouter une image depuis vos fichiers.',
31
- hint: 'Le logo est optionnel mais fortement recommandé.',
32
- attributes: [
33
- {
34
- property: 'logo',
35
- componentOptions: {
36
- name: 'cover',
37
- limit: 1,
38
- label: 'Logo de l\'organization'
39
- },
40
- component: 'input-files-media'
41
- }
42
- ]
43
- },
44
- component: 'form-section-default'
45
- },
46
- {
47
- componentOptions: {
48
- title: 'Nom de l\'organization',
49
- description: 'Ces informations seront visibles publiquement, soyez donc attentif avec ce que vous partagerez.',
50
- hint: 'Merci de ne pas dépasser 128 charactères.',
51
- attributes: [
52
- {
53
- property: 'name',
54
- componentOptions: {
55
- previewSlug: false,
56
- editableSlug: false,
57
- trim: true,
58
- placeHolder: 'Nom de l\'organisation',
59
- required: true
60
- },
61
- component: 'input-text'
62
- }
63
- ]
64
- },
65
- component: 'form-section-default'
66
- }
67
- // {
68
- // componentOptions: {
69
- // title: 'Localisation de l\'organization',
70
- // description: 'Ces informations seront visibles publiquement, soyez donc attentif avec ce que vous partagerez.',
71
- // attributes: [
72
- // {
73
- // property: 'location',
74
- // componentOptions: {
75
- // placeHolder: 'Localisation de l\'organisation',
76
- // name: 'organization'
77
- // },
78
- // component: 'input-location'
79
- // }
80
- // ]
81
- // },
82
- // component: 'form-section-default'
83
- // }
84
- ],
85
- title: 'General'
86
- },
87
- {
88
- icon: '',
89
- sections: [
90
- {
91
- componentOptions: {
92
- title: 'Collections',
93
- description: 'Ces collections permettent de définir les différents jeux de données de l\'organisation.',
94
- hint: '🚦 Soyez vigilant lorsque vous modifiez ce champs.',
95
- attributes: [
96
- {
97
- property: 'collections',
98
- componentOptions: {},
99
- component: 'handler-collections'
100
- }
101
- ],
102
- noAction: true
103
- },
104
- component: 'form-section-default'
105
- }
106
- ],
107
- title: 'Collections'
108
- },
109
- {
110
- icon: '',
111
- sections: [
112
- {
113
- componentOptions: {
114
- title: 'Les thématiques',
115
- description: 'Vous pouvez modifier ici les thématiques de cette organisation.',
116
- attributes: [
117
- {
118
- componentOptions: {
119
- collection: 'labels',
120
- alwaysPublish: true
121
- },
122
- component: 'handler-records'
123
- }
124
- ],
125
- noAction: true
126
- },
127
- component: 'form-section-default'
128
- }
129
- ],
130
- title: 'Thématiques'
131
- },
132
- {
133
- icon: '',
134
- sections: [
135
- {
136
- componentOptions: {
137
- title: 'Deployment settings',
138
- description: 'Renseignez la définition du déploiement.',
139
- attributes: [
140
- {
141
- property: 'deployment',
142
- componentOptions: {
143
- label: 'Paramètres de déploiement',
144
- name: 'deployment'
145
- },
146
- component: 'input-json'
147
- }
148
- ]
149
- },
150
- component: 'form-section-default'
151
- },
152
- {
153
- componentOptions: {
154
- title: 'Tokens de déploiement',
155
- description: 'Ces tokens permettent d\'autres applications à accéder à un contenu restreint de cette organisation.Soyez attentif!',
156
- attributes: [
157
- {
158
- componentOptions: {},
159
- component: 'handler-tokens'
160
- }
161
- ],
162
- noAction: true
163
- },
164
- component: 'form-section-default'
165
- }
166
- ],
167
- title: 'Déploiement'
168
- },
169
- {
170
- icon: '',
171
- sections: [
172
- {
173
- componentOptions: {
174
- title: 'Configuration de l\'injecteur',
175
- description: 'Définissez les différentes pipelines de données ici',
176
- attributes: [
177
- {
178
- property: 'injector',
179
- componentOptions: {
180
- label: 'Définition de l\'injecteur',
181
- name: 'injector'
182
- },
183
- component: 'input-json'
184
- }
185
- ]
186
- },
187
- component: 'form-section-default'
188
- },
189
- ],
190
- title: 'Synchronisation des données'
191
- }
192
- ]
193
- })
25
+ // Fetch data
26
+ const { data: record } = $organization.query()
194
27
 
195
28
  // Prepare computed
196
- const record = computed(() => $workspaceStore.workspace)
29
+ // One page, and each section still an address: the rail links to it, and the
30
+ // page scrolls there, so a section can be bookmarked or sent.
31
+ // The product's sections, then the ones a layer declares in its app config.
32
+ const sections = computed(() => [
33
+ ...SETTINGS_SECTIONS,
34
+ ...settings.sections.map(({ label, slug }) => ({ title: label, label, slug })),
35
+ ])
36
+ const layout = computed(() => [...ORGANIZATION_FORM.layout, ...settings.sections.map(layerSectionTab)].map((tab) => {
37
+ const section = sections.value.find(({ title }) => title === tab.title)
38
+ return { ...tab, label: section?.label, anchor: section?.slug || 'general', to: sectionRoute(section?.slug ?? '') }
39
+ }))
40
+ // Nothing to scroll to on a bare /settings: the page opens at its top.
41
+ const activeTab = computed(() => ($route.query.section ? sectionTitleFromSlug($route.query.section, sections.value) : ''))
197
42
  </script>
@@ -0,0 +1,7 @@
1
+ // Writes the instance's appearance on the document root, before anything
2
+ // paints: the tokens of assets/css/main.css are keyed on this attribute.
3
+ export default defineNuxtPlugin(() => {
4
+ const { appearance } = useRuntimeConfig().public
5
+ // `default` names the default aloud, for a layer whose own default is another.
6
+ if (appearance && appearance !== 'default') document.documentElement.dataset.appearance = String(appearance)
7
+ })
@@ -0,0 +1,23 @@
1
+ import { config } from 'zod/v4/core'
2
+ import fr from 'zod/v4/locales/fr.js'
3
+
4
+ // The forms validate with the core's own schemas, and Zod words its refusals:
5
+ // in French, like the rest of the admin. The one locale, by its own path — the
6
+ // `z.locales` namespace would ship them all.
7
+ //
8
+ // Three refusals are reworded: they are the ones a form meets every day, and
9
+ // Zod describes them as a type error (« chaîne de caractères attendu, indéfini
10
+ // reçu ») where a person left a field empty.
11
+ export default defineNuxtPlugin(() => {
12
+ config({
13
+ ...fr(),
14
+ customError: (issue) => {
15
+ const empty = issue.input === undefined || issue.input === null || issue.input === ''
16
+ if (empty && (issue.code === 'invalid_type' || issue.code === 'too_small' || issue.code === 'invalid_value')) {
17
+ return 'Ce champ est requis.'
18
+ }
19
+ if (issue.code === 'invalid_value') return 'Choisissez une valeur de la liste.'
20
+ return undefined
21
+ },
22
+ })
23
+ })
@@ -1,32 +1,8 @@
1
1
  import { defineStore } from 'pinia'
2
+ import { ROLES } from '~/constants/roles'
2
3
 
3
- // Single-tenant : les permissions dérivent du rôle Open Commune de l'utilisateur.
4
- // `manage:all` est un joker CASL (toute action sur tout sujet).
5
- //
6
- // `redacteur` reprend EXACTEMENT le rôle legacy « Éditeur de contenu », que
7
- // portaient tous les agents des collectivités. La première version n'avait
8
- // retenu que les records : les agents perdaient la publication du site, la
9
- // médiathèque et la lecture des collections — le bouton « Publier » avait donc
10
- // disparu pour tous sauf les comptes admin.
11
- const ROLE_PERMISSIONS = {
12
- admin: ['manage:all'],
13
- redacteur: [
14
- 'entrance:self',
15
- 'read:organizations',
16
- 'read:collections',
17
- 'read:records',
18
- 'create:records',
19
- 'update:records',
20
- 'delete:records',
21
- 'publish:records',
22
- 'read:media',
23
- 'create:media',
24
- 'update:media',
25
- 'delete:media',
26
- 'read:deployments',
27
- 'create:deployments'
28
- ]
29
- }
4
+ // Single-tenant : les permissions dérivent du rôle Open Commune de l'utilisateur,
5
+ // déclaré une seule fois dans `constants/roles` (l'écran Rôles lit la même liste).
30
6
 
31
7
  export const useWorkspaceStore = defineStore('layout/workspace', () => {
32
8
  const $session = useSession()
@@ -50,7 +26,7 @@ export const useWorkspaceStore = defineStore('layout/workspace', () => {
50
26
  const user = $session.user.value
51
27
  $abilities.assignAbilities([
52
28
  'entrance:self',
53
- ...(ROLE_PERMISSIONS[user?.role] ?? [])
29
+ ...(ROLES.find(({ id }) => id === user?.role)?.permissions ?? [])
54
30
  ])
55
31
  }
56
32
 
@@ -0,0 +1,26 @@
1
+ /** A neutral fill for a label without a colour, or with a white one. */
2
+ const FALLBACK = '#e5e7eb';
3
+
4
+ const channelsOf = (color: string): number[] | undefined => {
5
+ const hex = color.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i)?.[1];
6
+ if (!hex) return color.match(/\d+/g)?.map(Number);
7
+ const full = hex.length === 3 ? [...hex].map((c) => c + c).join('') : hex;
8
+ return [full.slice(0, 2), full.slice(2, 4), full.slice(4, 6)].map((part) => parseInt(part, 16));
9
+ };
10
+
11
+ /**
12
+ * The fill an editor chose for a label, and the ink that reads on it: black
13
+ * on a light colour, white on a dark one (relative luminance, WCAG).
14
+ */
15
+ export const swatchOf = (value?: string | null) => {
16
+ const color = (value ?? '').trim();
17
+ const backgroundColor =
18
+ !color || ['#ffffff', '#fff', 'white'].includes(color.toLowerCase()) ? FALLBACK : color;
19
+ const [r, g, b] = channelsOf(backgroundColor) ?? [];
20
+ const light =
21
+ r === undefined ||
22
+ g === undefined ||
23
+ b === undefined ||
24
+ (r * 0.299 + g * 0.587 + b * 0.114) / 255 > 0.5;
25
+ return { backgroundColor, color: light ? '#000' : '#fff' };
26
+ };
@@ -0,0 +1,13 @@
1
+ import { isErrorType } from '@open-commune/core/dtos';
2
+ import { REFUSALS } from '~/constants/errors';
3
+
4
+ /**
5
+ * What the core said when it refused, in the admin's words. The core sends
6
+ * the `type` of its domain error beside the transport code. A failure that is
7
+ * not one of its refusals (the network, an unexpected crash) answers with the
8
+ * caller's sentence.
9
+ */
10
+ export const refusalOf = (error: unknown, fallback: string): string => {
11
+ const type = (error as { data?: { type?: unknown } } | undefined)?.data?.type;
12
+ return isErrorType(type) ? REFUSALS[type] : fallback;
13
+ };
package/utils/forms.ts ADDED
@@ -0,0 +1,67 @@
1
+ import { cloneFnJSON, objectPick } from '@vueuse/core';
2
+ import type { FormControl } from '~/types';
3
+
4
+ /**
5
+ * Controls that own their data and edit no value: the admin tables, the
6
+ * members, the roles. They get neither a field nor a place in a form's state.
7
+ */
8
+ const STANDALONE_CONTROLS = new Set([
9
+ 'handler-collections',
10
+ 'handler-members',
11
+ 'handler-password-reset',
12
+ 'handler-roles',
13
+ 'handler-sessions',
14
+ 'handler-tokens',
15
+ ]);
16
+
17
+ export const isStandalone = ({ component }: FormControl) => STANDALONE_CONTROLS.has(component);
18
+
19
+ /** The properties a described form edits, in the order it shows them. */
20
+ export const propertiesOf = (controls: FormControl[] = []) =>
21
+ controls
22
+ .filter((control) => control.property && !isStandalone(control))
23
+ .map(({ property }) => property as string);
24
+
25
+ type Values = Record<string, unknown>;
26
+
27
+ /**
28
+ * Compared as JSON, the way the values travel: `null` and an absent value
29
+ * are the same emptiness, and a ProseMirror document is compared in depth.
30
+ */
31
+ export const sameValue = (left: unknown, right: unknown) =>
32
+ JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
33
+
34
+ /**
35
+ * What a form starts from: the record's own value for each property it edits,
36
+ * copied, so typing never writes into the cache the record came from. An entry
37
+ * keeps its declared fields in `data`; a form knows only one level.
38
+ */
39
+ export const valuesOf = (record: Values | null | undefined, properties: string[]): Values => {
40
+ const flat = { ...(record ?? {}), ...((record?.data as Values | undefined) ?? {}) };
41
+ return cloneFnJSON(objectPick(flat, properties));
42
+ };
43
+
44
+ /** What differs from where the form started: the only thing a save sends. */
45
+ export const changesOf = (state: Values, baseline: Values): Values =>
46
+ Object.fromEntries(
47
+ Object.entries(state).filter(([property, value]) => !sameValue(value, baseline[property])),
48
+ );
49
+
50
+ /** A Zod object, as far as a form needs to know one. */
51
+ interface ObjectSchema {
52
+ shape: Record<string, unknown>;
53
+ pick: (keys: Record<string, true>) => unknown;
54
+ }
55
+
56
+ /**
57
+ * The server's own schema, narrowed to what ONE form edits: a card of the
58
+ * settings saves two fields of the organization, not the organization. A
59
+ * property the schema does not know is left to the server alone.
60
+ */
61
+ export const narrowSchema = (schema: unknown, properties: string[]) => {
62
+ const object = schema as ObjectSchema | undefined;
63
+ if (!object?.shape || typeof object.pick !== 'function') return undefined;
64
+ const known = properties.filter((property) => property in object.shape);
65
+ if (!known.length) return undefined;
66
+ return object.pick(Object.fromEntries(known.map((property) => [property, true as const])));
67
+ };