@open-commune/web 0.2.14 → 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 (63) hide show
  1. package/app.config.ts +7 -0
  2. package/components/data/lists/data-table.vue +203 -0
  3. package/components/data/lists/row-actions.vue +41 -0
  4. package/components/elements/badges/status-badge.vue +23 -0
  5. package/components/elements/media/media-image.vue +26 -0
  6. package/components/forms/fields/input-files-media.vue +87 -0
  7. package/components/forms/{inputs → fields}/input-filter-status.vue +2 -2
  8. package/components/forms/{inputs → fields}/input-search.vue +8 -2
  9. package/components/forms/fields/input-text-area.vue +86 -0
  10. package/components/forms/fields/input-text.vue +47 -0
  11. package/components/forms/fields/select-enum.vue +69 -0
  12. package/components/forms/handlers/handler-collections.vue +100 -170
  13. package/components/forms/handlers/handler-list.vue +187 -0
  14. package/components/forms/handlers/handler-members.vue +171 -0
  15. package/components/forms/handlers/handler-password-reset.vue +45 -0
  16. package/components/forms/handlers/handler-roles.vue +28 -166
  17. package/components/forms/handlers/handler-sessions.vue +77 -0
  18. package/components/forms/handlers/handler-tokens.vue +54 -69
  19. package/components/forms/layouts/form-default.vue +99 -0
  20. package/components/forms/layouts/form.vue +4 -0
  21. package/components/forms/layouts/forms-layout.vue +236 -0
  22. package/components/forms/layouts/forms-section.vue +186 -0
  23. package/components/forms/layouts/layout.vue +4 -0
  24. package/components/forms/layouts/modal.vue +4 -0
  25. package/components/forms/layouts/section.vue +4 -0
  26. package/components/layout/shell/shell-account-menu.vue +10 -2
  27. package/composables/core/domains/use-api-tokens.ts +80 -0
  28. package/composables/core/domains/use-auth.ts +56 -2
  29. package/composables/core/domains/use-definitions.ts +18 -5
  30. package/composables/core/domains/use-entries.ts +113 -3
  31. package/composables/core/domains/use-media.ts +24 -1
  32. package/composables/core/domains/use-members.ts +68 -0
  33. package/composables/core/domains/use-organization.ts +53 -0
  34. package/composables/use-models.js +1 -7
  35. package/constants/errors.ts +28 -0
  36. package/constants/forms/account.ts +62 -0
  37. package/constants/forms/collections.ts +39 -0
  38. package/constants/forms/members.ts +40 -0
  39. package/constants/forms/organization.ts +188 -0
  40. package/constants/forms/tokens.ts +15 -0
  41. package/constants/roles.ts +57 -0
  42. package/constants/settings.ts +26 -0
  43. package/constants/statuses.ts +8 -5
  44. package/package.json +3 -3
  45. package/pages/[collection]/index.vue +92 -79
  46. package/pages/account.vue +40 -0
  47. package/pages/settings.vue +26 -181
  48. package/plugins/01.validation.client.ts +23 -0
  49. package/store/layout/workspace.js +4 -28
  50. package/utils/colors.ts +26 -0
  51. package/utils/errors.ts +13 -0
  52. package/utils/forms.ts +67 -0
  53. package/utils/list-columns.ts +90 -0
  54. package/utils/settings.ts +38 -0
  55. package/utils/statuses.ts +4 -0
  56. package/models/role.js +0 -66
  57. package/models/token.js +0 -56
  58. package/models/user.js +0 -97
  59. package/pages/management/index.vue +0 -15
  60. package/pages/management/members.vue +0 -176
  61. package/pages/management/organizations.vue +0 -192
  62. package/pages/management/roles.vue +0 -183
  63. /package/components/forms/{inputs → fields}/input-filter.vue +0 -0
@@ -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"
@@ -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
  <form class="border border-gray-200 sm:rounded-md" @submit.prevent="">
3
7
  <div class="py-6 px-4 space-y-6 sm:p-6">
@@ -19,6 +19,14 @@
19
19
  <p class="mt-0.5 truncate text-[13px] text-muted">{{ user?.email }}</p>
20
20
  </div>
21
21
 
22
+ <NuxtLink
23
+ to="/account"
24
+ class="block px-4 py-2.5 text-[13px] text-highlighted hover:bg-muted"
25
+ @click="open = false"
26
+ >
27
+ Mon compte
28
+ </NuxtLink>
29
+
22
30
  <button
23
31
  type="button"
24
32
  class="w-full cursor-pointer px-4 py-2.5 text-left text-[13px] text-error hover:bg-muted"
@@ -33,8 +41,8 @@
33
41
 
34
42
  <script setup>
35
43
  /**
36
- * What concerns the signed-in person, in one place: who they are and signing
37
- * out. Help sits beside it in the header. A theme choice joins them when the
44
+ * What concerns the signed-in person, in one place: who they are, their account
45
+ * and signing out. Help sits beside it in the header. A theme choice joins them when the
38
46
  * admin leaves the light mode it is held to (`middleware/00.light-mode.global.ts`).
39
47
  * Without a name, the avatar's initial is the email's first letter.
40
48
  */
@@ -0,0 +1,80 @@
1
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query'
2
+
3
+ /**
4
+ * API tokens — what a theme's build uses to read the content.
5
+ *
6
+ * They are stored HASHED: the plaintext exists once, in the create response.
7
+ * A deliberate difference from the legacy, which kept them in clear and could
8
+ * therefore show them again.
9
+ *
10
+ * A write owns everything around it — its invalidation AND its toast, success
11
+ * or failure. It is a mutation factory: the screen calls it in its setup, then
12
+ * `mutate`, and has nothing left to write.
13
+ */
14
+ export default function useApiTokens() {
15
+ const trpc = useTrpc()
16
+ const queryClient = useQueryClient()
17
+
18
+ const invalidate = () => queryClient.invalidateQueries({ queryKey: ['api-tokens'] })
19
+
20
+ /** The tokens in service — a revoked one has no business on screen. */
21
+ const list = () =>
22
+ useQuery({
23
+ queryKey: ['api-tokens'],
24
+ queryFn: async () => (await trpc.apiTokens.list.query()).filter(({ revokedAt }) => !revokedAt),
25
+ })
26
+
27
+ /**
28
+ * Creates one, and SHOWS it.
29
+ *
30
+ * The plaintext exists ONLY in this answer: the server keeps a hash and can
31
+ * never give it back. So it is said at the moment it exists, said to be the
32
+ * only time, and the toast never expires — closing it is the agent's move,
33
+ * not a timer's.
34
+ */
35
+ const create = () => {
36
+ const toast = useToast()
37
+ return useMutation({
38
+ mutationFn: (name: string) => trpc.apiTokens.create.mutate({ name }),
39
+ onSuccess: ({ token }) => {
40
+ invalidate()
41
+ toast.add({
42
+ color: 'success',
43
+ title: 'Token créé',
44
+ description: `${token} — copiez-le maintenant, il ne sera plus affiché.`,
45
+ duration: 0,
46
+ })
47
+ },
48
+ onError: (_error, name) => toast.add({
49
+ color: 'error',
50
+ title: `Le token « ${name} » n'a pas pu être créé`,
51
+ description: 'Le serveur a refusé la création. Réessayez dans un instant.',
52
+ }),
53
+ })
54
+ }
55
+
56
+ /**
57
+ * Revokes one, and says so either way: a refused revocation leaves a live
58
+ * token behind a screen that would otherwise show nothing.
59
+ *
60
+ * The NAME travels beside the id for the sentence alone — « le token » tout
61
+ * court ne dit pas lequel est resté actif.
62
+ */
63
+ const revoke = () => {
64
+ const toast = useToast()
65
+ return useMutation({
66
+ mutationFn: ({ id }: { id: string; name: string }) => trpc.apiTokens.revoke.mutate({ id }),
67
+ onSuccess: (_result, { name }) => {
68
+ invalidate()
69
+ toast.add({ title: `Token « ${name} » révoqué.` })
70
+ },
71
+ onError: (_error, { name }) => toast.add({
72
+ color: 'error',
73
+ title: `Le token « ${name} » n'a pas pu être révoqué`,
74
+ description: 'Il reste actif. Réessayez, et prévenez un administrateur si cela persiste.',
75
+ }),
76
+ })
77
+ }
78
+
79
+ return { list, create, revoke }
80
+ }
@@ -1,6 +1,13 @@
1
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query'
2
+ import type { PublicUser } from '@open-commune/core'
3
+
4
+ /** Prefix invalidated by every write on the sessions of this member. */
5
+ const SESSIONS_KEY = ['auth', 'sessions']
6
+
1
7
  /**
2
- * The entrance flows that need no session: accepting an invitation, asking for
3
- * a password reset, defining the new password.
8
+ * The entrance flows that need no session (accepting an invitation, asking for
9
+ * a password reset, defining the new password), and what a signed-in member
10
+ * changes on their own account: their name, their open sessions.
4
11
  *
5
12
  * A write owns what surrounds it, whole: its `catch`, its `is…` pending flag,
6
13
  * the sentence it puts on screen and the redirection that follows — none of
@@ -97,7 +104,54 @@ export default function useAuth() {
97
104
  return true
98
105
  }
99
106
 
107
+ /**
108
+ * A member renames themself. Not their email — it identifies the account —
109
+ * nor their role, which the server's DTO REFUSES rather than ignores.
110
+ *
111
+ * The session carries the name shown everywhere else, so it follows here:
112
+ * every caller would otherwise have to remember to keep it in step.
113
+ */
114
+ const updateOwnProfile = () =>
115
+ useMutation({
116
+ mutationFn: async (name: string): Promise<PublicUser> =>
117
+ (await trpc.users.updateOwnProfile.mutate({ name })).user,
118
+ onSuccess: (user) => { useSession().user.value = user },
119
+ })
120
+
121
+ /**
122
+ * This member's open sessions — the current one is flagged. A query and not
123
+ * a bare call: the list carries its own `isLoading`, and `revoke` invalidates
124
+ * it, so no screen reloads it by hand. Call it from a setup.
125
+ */
126
+ const sessions = () => {
127
+ const queryClient = useQueryClient()
128
+
129
+ const query = useQuery({
130
+ queryKey: SESSIONS_KEY,
131
+ queryFn: () => trpc.auth.sessions.list.query(),
132
+ })
133
+
134
+ /** Closes one session remotely. The server refuses other people's. */
135
+ const toast = useToast()
136
+ const { mutate: revoke, isPending: isRevoking } = useMutation({
137
+ mutationFn: (id: string) => trpc.auth.sessions.revoke.mutate({ id }),
138
+ onSuccess: async () => {
139
+ await queryClient.invalidateQueries({ queryKey: SESSIONS_KEY })
140
+ toast.add({ title: 'Session fermée.' })
141
+ },
142
+ onError: () => toast.add({
143
+ color: 'error',
144
+ title: 'La session n\'a pas pu être fermée.',
145
+ description: 'Réessayez dans un instant.',
146
+ }),
147
+ })
148
+
149
+ return { ...query, revoke, isRevoking }
150
+ }
151
+
100
152
  return {
153
+ updateOwnProfile,
154
+ sessions,
101
155
  acceptInvitation,
102
156
  isAcceptingInvitation: readonly(isAcceptingInvitation),
103
157
  requestPasswordReset,
@@ -1,6 +1,6 @@
1
1
  import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query'
2
2
  import { buildDataSchema, type FieldDefinition } from '@open-commune/core/collections/utils'
3
- import { computed, unref, type MaybeRef } from 'vue'
3
+ import { computed, toValue, unref, type MaybeRef, type MaybeRefOrGetter } from 'vue'
4
4
 
5
5
  /**
6
6
  * Collection-definition domain composable — the only data surface pages use.
@@ -18,15 +18,28 @@ export default function useDefinitions() {
18
18
  queryFn: () => trpc.collections.list.query(),
19
19
  })
20
20
 
21
- const get = (idOrSlug: MaybeRef<string>) =>
21
+ /**
22
+ * One definition, by id or by slug: the server takes either. A getter is
23
+ * welcome, because a page is reused from one collection to the next. While
24
+ * it travels, the list already in cache answers, so a screen that opens on
25
+ * a collection the navigation has listed never waits.
26
+ */
27
+ const get = (idOrSlug: MaybeRefOrGetter<string | undefined>) =>
22
28
  useQuery({
23
- queryKey: computed(() => ['definitions', unref(idOrSlug)]),
24
- queryFn: () => trpc.collections.get.query({ idOrSlug: unref(idOrSlug) }),
29
+ queryKey: computed(() => ['definitions', toValue(idOrSlug)]),
30
+ queryFn: () => trpc.collections.get.query({ idOrSlug: toValue(idOrSlug)! }),
31
+ enabled: computed(() => Boolean(toValue(idOrSlug))),
32
+ placeholderData: () =>
33
+ queryClient
34
+ .getQueryData<Awaited<ReturnType<typeof trpc.collections.list.query>>>(['definitions'])
35
+ ?.find(({ id, slug }) => [id, slug].includes(toValue(idOrSlug)!)),
25
36
  })
26
37
 
38
+ // A write invalidates the list: the settings' collection table refreshes
39
+ // through its key. Call the factory in a setup, then `mutateAsync`.
27
40
  const create = () =>
28
41
  useMutation({
29
- mutationFn: (input: Record<string, unknown>) => trpc.collections.create.mutate(input),
42
+ mutationFn: (input: Parameters<typeof trpc.collections.create.mutate>[0]) => trpc.collections.create.mutate(input),
30
43
  onSuccess: invalidate,
31
44
  })
32
45