@antelopejs/dms-lang 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -55,9 +55,9 @@ pnpm test
55
55
 
56
56
  The backend registers `frontend-vue/dms.frontend.ts` through `AddFrontendModule` with the Vue 3 renderer. The module declares `componentPrefix: "DmsLang"` and registers every component of `app/components` and `app/build/components` under it; the backend pages name them (`CustomComponent("DmsLangTranslationMatrix")`). `dms.frontend.build.ts` declares `app/composables`, `app/utils` and `app/types` for auto-import; `app/build/` is private and imported by path. Nuxt is not required; `@nuxt/ui` provides its Vue components through the adapter's Vite integration.
57
57
 
58
- The module compiles against the published `@antelopejs/interface-dms` package, its only DMS runtime dependency. The `@antelopejs/dms` backend and the `@antelopejs/dms-frontend` adapter are development dependencies, needed to run the tests and the playground. Run `pnpm install`, `pnpm build` and `pnpm test` here.
58
+ Its pages read the data they render with the DMS's `useApiData`, which a server render reads and hands to the browser with the page; the dialogs that ask the server for their wording read it when they open. The module requires `@antelopejs/dms` 0.9, `@antelopejs/interface-dms` 0.7 and `@antelopejs/dms-frontend` 0.6. The public language files (`/i18n/**`) are declared to the frontend server as a backend prefix without a session (`backendProxies`), so the DMS's own origin serves them. It compiles against the published `@antelopejs/interface-dms` package, its only DMS runtime dependency. The `@antelopejs/dms` backend and the `@antelopejs/dms-frontend` adapter are development dependencies, needed to run the tests and the playground. Run `pnpm install`, `pnpm build` and `pnpm test` here.
59
59
 
60
- `pnpm test:unit` checks locale discovery, the coverage, placeholder and message helpers of the frontend and the locale files. The backend tests (`src/test`: keys, workspaces, validation, coverage, summaries) run with `pnpm test` only: every backend file reaches an AntelopeJS interface (`@antelopejs/interface-api` for the errors, `@antelopejs/interface-dms` for the pages), and an interface refuses to load outside the AntelopeJS runtime. `pnpm test:frontend` compiles the module alongside the published core DMS frontend with the adapter's source verifier.
60
+ `pnpm test:unit` checks locale discovery, the coverage, placeholder and message helpers of the frontend and the locale files, and renders the workspace composables on a server with the installed adapter and `useApiData` (`tests/frontend-runtime.mjs`). The backend tests (`src/test`: keys, workspaces, validation, coverage, summaries) run with `pnpm test` only: every backend file reaches an AntelopeJS interface (`@antelopejs/interface-api` for the errors, `@antelopejs/interface-dms` for the pages), and an interface refuses to load outside the AntelopeJS runtime. `pnpm test:frontend` compiles the module alongside the published core DMS frontend with the adapter's source verifier.
61
61
 
62
62
  Run `pnpm dev` for the backend and `pnpm frontend:dev` for the Inertia workspace. The playground connects to MongoDB at `mongodb://localhost:27017`; set `MONGO_URL` to use another instance. The frontend workspace uses the `ajs dms` commands for development, preparation and production builds. Use `pnpm typecheck` for the backend; run `pnpm typecheck` in the generated Vite workspace for frontend types. The adapter owns the generated aliases, auto-import declarations and Vue compiler configuration.
63
63
 
package/dist/index.js CHANGED
@@ -22,6 +22,7 @@ exports.start = start;
22
22
  const node_path_1 = __importDefault(require("node:path"));
23
23
  const page_1 = require("@antelopejs/interface-dms/page");
24
24
  const config_1 = require("./utils/config");
25
+ const constants_1 = require("./utils/constants");
25
26
  const registry_1 = require("./utils/registry");
26
27
  __exportStar(require("./pages"), exports);
27
28
  __exportStar(require("./routes"), exports);
@@ -38,6 +39,7 @@ async function construct(config = {}) {
38
39
  renderer: { name: "vue", version: "3" },
39
40
  configKey: "dmsLang",
40
41
  priority: 0,
42
+ backendProxies: [{ path: `${constants_1.PUBLIC_PATH}/**`, auth: "none" }],
41
43
  });
42
44
  }
43
45
  async function start() {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAYA,8BAgBC;AAED,sBAEC;AAhCD,0DAA6B;AAC7B,yDAAmE;AACnE,2CAAsD;AACtD,+CAA4D;AAE5D,0CAAwB;AACxB,2CAAyB;AAMlB,KAAK,UAAU,SAAS,CAAC,SAAwB,EAAE;IACxD,MAAM,UAAU,GAAG,mBAAI,CAAC,IAAI,CAAC,SAAS,EAAE,iBAAiB,CAAC,CAAC;IAC3D,MAAM,aAAa,GAAG,mBAAI,CAAC,IAAI,CAAC,SAAS,EAAE,oBAAoB,CAAC,CAAC;IAEjE,IAAA,6BAAoB,EAAC;QACnB,aAAa;QACb,QAAQ,EAAE,MAAM,CAAC,QAAQ,IAAI,KAAK;KACnC,CAAC,CAAC;IAEH,MAAM,IAAA,wBAAiB,EAAC;QACtB,IAAI,EAAE,mCAAmC;QACzC,UAAU;QACV,QAAQ,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE;QACvC,SAAS,EAAE,SAAS;QACpB,QAAQ,EAAE,CAAC;KACZ,CAAC,CAAC;AACL,CAAC;AAEM,KAAK,UAAU,KAAK;IACzB,MAAM,IAAA,mCAAwB,GAAE,CAAC;AACnC,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAaA,8BAiBC;AAED,sBAEC;AAlCD,0DAA6B;AAC7B,yDAAmE;AACnE,2CAAsD;AACtD,iDAAgD;AAChD,+CAA4D;AAE5D,0CAAwB;AACxB,2CAAyB;AAMlB,KAAK,UAAU,SAAS,CAAC,SAAwB,EAAE;IACxD,MAAM,UAAU,GAAG,mBAAI,CAAC,IAAI,CAAC,SAAS,EAAE,iBAAiB,CAAC,CAAC;IAC3D,MAAM,aAAa,GAAG,mBAAI,CAAC,IAAI,CAAC,SAAS,EAAE,oBAAoB,CAAC,CAAC;IAEjE,IAAA,6BAAoB,EAAC;QACnB,aAAa;QACb,QAAQ,EAAE,MAAM,CAAC,QAAQ,IAAI,KAAK;KACnC,CAAC,CAAC;IAEH,MAAM,IAAA,wBAAiB,EAAC;QACtB,IAAI,EAAE,mCAAmC;QACzC,UAAU;QACV,QAAQ,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE;QACvC,SAAS,EAAE,SAAS;QACpB,QAAQ,EAAE,CAAC;QACX,cAAc,EAAE,CAAC,EAAE,IAAI,EAAE,GAAG,uBAAW,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;KAC9D,CAAC,CAAC;AACL,CAAC;AAEM,KAAK,UAAU,KAAK;IACzB,MAAM,IAAA,mCAAwB,GAAE,CAAC;AACnC,CAAC"}
@@ -126,27 +126,24 @@ function useFilterQuery() {
126
126
  function useColumnOrder() {
127
127
  const { selectedWorkspace } = useI18nWorkspaces()
128
128
  const { flat } = useWorkspaceFlat()
129
- const order = ref<string[]>([])
130
129
  const stored = useStorage<Partial<StoredColumns> | null>(
131
130
  () => `${COLUMNS_STORAGE}${selectedWorkspace.value}`,
132
131
  null,
133
132
  undefined,
134
133
  { serializer: StorageSerializers.object },
135
134
  )
136
- watch(
137
- () => `${selectedWorkspace.value}|${flat.value.locales.join(',')}`,
138
- () => {
139
- const { locales, defaultLocale } = flat.value
140
- order.value = restoredOrder(
141
- locales,
142
- defaultLocale,
143
- columnsOf(stored.value),
144
- )
145
- },
146
- { immediate: true },
135
+ const isMounted = ref(false)
136
+ onMounted(() => {
137
+ isMounted.value = true
138
+ })
139
+ const order = computed(() =>
140
+ restoredOrder(
141
+ flat.value.locales,
142
+ flat.value.defaultLocale,
143
+ isMounted.value ? columnsOf(stored.value) : null,
144
+ ),
147
145
  )
148
146
  function saveOrder(next: string[]) {
149
- order.value = next
150
147
  stored.value = {
151
148
  shown: next,
152
149
  hidden: flat.value.locales.filter((code) => !next.includes(code)),
@@ -159,7 +156,8 @@ function useColumnOrder() {
159
156
  * The view of the matrix a user chose: the filters live in the URL (a link
160
157
  * or a refresh shows the same keys, Back undoes a filter change made by a
161
158
  * link) and the columns shown, in their order, are remembered per workspace
162
- * in this browser.
159
+ * in this browser and applied once the page is mounted: a server render
160
+ * shows every language, as the browser's first render does.
163
161
  */
164
162
  export function useMatrixView() {
165
163
  const { flat } = useWorkspaceFlat()
@@ -9,6 +9,7 @@ import {
9
9
  } from '../utils/workspaces'
10
10
  import type { WorkspaceSort } from '../utils/workspaces'
11
11
  import LocaleTile from '../build/components/LocaleTile.vue'
12
+ import { useWorkspaceSummary } from '../composables/translation/useI18nWorkspaces'
12
13
 
13
14
  interface WorkspaceStat {
14
15
  id: string
@@ -42,8 +43,7 @@ const SORT_LABELS: Record<WorkspaceSort, string> = {
42
43
 
43
44
  const { t } = useI18n()
44
45
  const { formatCount } = useLangFormat()
45
- const { fetchSummary, selectedWorkspace, editable, fetchWorkspaces } =
46
- useI18nWorkspaces()
46
+ const { selectedWorkspace, editable } = useI18nWorkspaces()
47
47
  const { createWorkspace, importWorkspace } = useWorkspaceActions()
48
48
  const { typeIcon, typeLabel, kindIcon } = useWorkspaceTypes()
49
49
  const { pageAction, clearPageAction, selectWorkspace } = useWorkspaceRoute()
@@ -53,10 +53,17 @@ const { getPreference, setPreference } = usePreferences()
53
53
 
54
54
  const canCreate = computed(() => editable.value && allows('createWorkspace'))
55
55
 
56
- const summary = ref<WorkspaceStats[]>([])
57
- const isLoaded = ref(false)
58
- const hasError = ref(false)
59
- const isLoading = ref(false)
56
+ // The workspaces' figures, read with the page.
57
+ const summaryRead = useWorkspaceSummary()
58
+ const summary = computed<WorkspaceStats[]>(
59
+ () => summaryRead.data.value?.workspaces ?? [],
60
+ )
61
+ const isLoaded = computed(() => summaryRead.data.value !== null)
62
+ const isLoading = computed(() => summaryRead.pending.value)
63
+ // A failure kept while it is tried again still shows the skeleton.
64
+ const hasError = computed(
65
+ () => summaryRead.error.value != null && !isLoading.value,
66
+ )
60
67
  const search = ref('')
61
68
  const sort = computed<WorkspaceSort>({
62
69
  get: () => {
@@ -88,19 +95,8 @@ function isWorkspaceSort(value: unknown): value is WorkspaceSort {
88
95
  return typeof value === 'string' && Object.hasOwn(SORT_LABELS, value)
89
96
  }
90
97
 
91
- async function load() {
92
- isLoading.value = true
93
- try {
94
- const response = await fetchSummary()
95
- summary.value = response.workspaces
96
- editable.value = response.editable
97
- hasError.value = false
98
- isLoaded.value = true
99
- } catch {
100
- hasError.value = true
101
- } finally {
102
- isLoading.value = false
103
- }
98
+ function load() {
99
+ void summaryRead.refresh()
104
100
  }
105
101
 
106
102
  function statsOf(workspace: WorkspaceStats): WorkspaceStat[] {
@@ -212,10 +208,6 @@ watch(
212
208
  { immediate: true },
213
209
  )
214
210
 
215
- onMounted(() => {
216
- load()
217
- fetchWorkspaces()
218
- })
219
211
  </script>
220
212
 
221
213
  <template>
@@ -1,6 +1,5 @@
1
1
  <script setup lang="ts">
2
2
  import { useLangChanges } from '../composables/translation/useWorkspaceFlat'
3
- import { useDmsRouter, useDmsState } from '#dms/frontend-module'
4
3
  import type { DropdownMenuItem } from '@nuxt/ui'
5
4
  import type { WorkspaceSummary } from '../types/lang'
6
5
  import LocaleTile from '../build/components/LocaleTile.vue'
@@ -13,8 +12,7 @@ const MENU_FILTER_FIELDS = ['label', 'description', 'workspaceId', 'summary']
13
12
 
14
13
  const { t } = useI18n()
15
14
  const { formatCount } = useLangFormat()
16
- const { workspaces, editable, isLoaded, selectedWorkspace } =
17
- useI18nWorkspaces()
15
+ const { workspaces, editable, isLoaded, whenLoaded } = useI18nWorkspaces()
18
16
  const {
19
17
  current,
20
18
  isEditable,
@@ -25,14 +23,12 @@ const {
25
23
  } = useWorkspaceContext()
26
24
  useLangChanges()
27
25
  const {
28
- route,
29
26
  switchLink,
30
27
  queryWorkspace,
31
28
  pageAction,
32
29
  clearPageAction,
33
30
  currentPage,
34
31
  } = useWorkspaceRoute()
35
- const router = useDmsRouter()
36
32
 
37
33
  /** What the bar says about the workspace shown, from the workspace list. */
38
34
  const scope = computed(() => ({
@@ -178,44 +174,10 @@ const firstRunActions = computed(() => [
178
174
  },
179
175
  ])
180
176
 
181
- /**
182
- * The workspace a page opened without `?workspace=` was given: the one
183
- * remembered, or the project files once that one turns out to be gone.
184
- */
185
- const filledFromMemory = useDmsState<string>(
186
- 'dms-lang-workspace-filled',
187
- () => '',
188
- )
189
-
190
- function fillWorkspace(workspace: string): void {
191
- void router.replace(linkWithQuery(route.path, { ...route.query, workspace }))
177
+ if (import.meta.env.SSR && !queryWorkspace.value && !pageAction.value) {
178
+ await whenLoaded()
192
179
  }
193
-
194
- watch(
195
- [queryWorkspace, pageAction],
196
- ([workspace, action]) => {
197
- if (import.meta.env.SSR || workspace || action) return
198
- const isKnown = workspaces.value.some(
199
- (entry) => entry.id === selectedWorkspace.value,
200
- )
201
- const fallback =
202
- isKnown || !isLoaded.value ? selectedWorkspace.value : DEFAULT_WORKSPACE
203
- filledFromMemory.value = fallback
204
- fillWorkspace(fallback)
205
- },
206
- { immediate: true },
207
- )
208
-
209
- watch(
210
- [isUnknown, queryWorkspace],
211
- ([unknown, workspace]) => {
212
- if (import.meta.env.SSR || !unknown) return
213
- if (!workspace || workspace !== filledFromMemory.value) return
214
- filledFromMemory.value = ''
215
- fillWorkspace(DEFAULT_WORKSPACE)
216
- },
217
- { immediate: true },
218
- )
180
+ useWorkspaceFill()
219
181
 
220
182
  watch(
221
183
  [pageAction, isResolved],
@@ -1,7 +1,6 @@
1
1
  import { useDmsCookie, useDmsState } from '#dms/frontend-module'
2
2
  import type {
3
3
  FlatCounts,
4
- FlatTranslations,
5
4
  KeyRowResponse,
6
5
  ScopedWorkspace,
7
6
  WorkspaceDetails,
@@ -34,7 +33,7 @@ type KeyValues = Record<string, unknown>
34
33
  /** The routes of the module's API. */
35
34
  export const LANG_API = '/api/lang/translations'
36
35
  const API_BASE = LANG_API
37
- const ENDPOINTS = {
36
+ export const ENDPOINTS = {
38
37
  workspaces: `${API_BASE}/workspaces`,
39
38
  flat: `${API_BASE}/flat`,
40
39
  row: `${API_BASE}/row`,
@@ -86,23 +85,10 @@ function useWorkspacesState() {
86
85
  const lastWorkspace = useLastWorkspace()
87
86
  return {
88
87
  lastWorkspace,
89
- workspaces: useDmsState<ScopedWorkspace[]>(
90
- 'dms-lang-workspaces',
91
- () => [],
92
- ),
93
- editable: useDmsState<boolean>('dms-lang-workspaces-editable', () => false),
94
- permissions: useDmsState<WorkspacePermissionIds | null>(
95
- 'dms-lang-workspaces-permissions',
96
- () => null,
97
- ),
98
- publicBaseUrl: useDmsState<string>('dms-lang-public-base-url', () => ''),
99
- isLoading: useDmsState<boolean>('dms-lang-workspaces-loading', () => false),
100
- isLoaded: useDmsState<boolean>('dms-lang-workspaces-loaded', () => false),
101
88
  selectedWorkspace: useDmsState<string>(
102
89
  'dms-lang-selected-workspace',
103
90
  () => lastWorkspace.value || DEFAULT_WORKSPACE,
104
91
  ),
105
- requestSeq: useDmsState<number>('dms-lang-workspaces-seq', () => 0),
106
92
  }
107
93
  }
108
94
 
@@ -172,55 +158,70 @@ function useWorkspaceWrites() {
172
158
  }
173
159
  }
174
160
 
175
- function useWorkspaceReads() {
161
+ /** The backup file a download saves: a file the user keeps, not data a page shows. */
162
+ function useWorkspaceDownloads() {
176
163
  const { $authFetch } = useAuthFetch()
177
164
  return {
178
- fetchSummary: () => $authFetch<SummaryResponse>(ENDPOINTS.summary),
179
165
  fetchBackup: (workspace: string) =>
180
166
  $authFetch<WorkspaceBackup>(ENDPOINTS.backup, { query: { workspace } }),
181
- fetchFlat: (workspace: string) =>
182
- $authFetch<FlatTranslations>(ENDPOINTS.flat, { query: { workspace } }),
183
- fetchRow: (workspace: string, key: string) =>
184
- $authFetch<KeyRowResponse>(ENDPOINTS.row, { query: { workspace, key } }),
185
167
  }
186
168
  }
187
169
 
170
+ /** The workspaces with their figures, for the workspace list page. */
171
+ export const useWorkspaceSummary = () =>
172
+ useApiData<SummaryResponse>(ENDPOINTS.summary)
173
+
188
174
  /**
189
175
  * The workspaces of the module, the one selected for every page, and the
190
- * routes that read and change them. The selection follows the page URL
191
- * (`?workspace=`, see useWorkspaceRoute): a workspace the URL names but the
192
- * list lacks stays selected, so the page can say it does not exist.
176
+ * routes that read and change them. The list is read with the page, once for
177
+ * every block showing it: a server render hands it to the browser. The
178
+ * selection follows the page URL (`?workspace=`, see useWorkspaceRoute): a
179
+ * workspace the URL names but the list lacks stays selected, so the page can
180
+ * say it does not exist.
193
181
  */
194
182
  export const useI18nWorkspaces = () => {
195
- const { $authFetch } = useAuthFetch()
196
183
  const state = useWorkspacesState()
184
+ const list = useApiData<WorkspacesResponse>(ENDPOINTS.workspaces)
185
+ const workspaces = computed(() => list.data.value?.workspaces ?? [])
197
186
 
198
187
  function canUseWorkspaceId(id: string): boolean {
199
188
  return (
200
189
  isValidWorkspaceId(id) &&
201
- !state.workspaces.value.some((workspace) => workspace.id === id)
190
+ !workspaces.value.some((workspace) => workspace.id === id)
202
191
  )
203
192
  }
204
193
 
205
- function applyResponse(response: WorkspacesResponse): void {
206
- state.editable.value = response.editable
207
- state.workspaces.value = response.workspaces
208
- state.permissions.value = response.permissions
209
- state.publicBaseUrl.value = response.publicBaseUrl
210
- state.isLoaded.value = true
194
+ function mapWorkspace(
195
+ id: string,
196
+ change: (workspace: ScopedWorkspace) => ScopedWorkspace,
197
+ ): void {
198
+ const current = list.data.value
199
+ if (!current) return
200
+ list.data.value = {
201
+ ...current,
202
+ workspaces: current.workspaces.map((workspace) =>
203
+ workspace.id === id ? change(workspace) : workspace,
204
+ ),
205
+ }
211
206
  }
212
207
 
213
208
  /** Takes the figures a key write answered into the workspace list (the scope bar). */
214
209
  function patchCounts(id: string, counts: FlatCounts): void {
215
- state.workspaces.value = state.workspaces.value.map((workspace) =>
216
- workspace.id === id
217
- ? {
218
- ...workspace,
219
- totalKeys: counts.totalKeys,
220
- baseMissing: counts.baseMissing,
221
- }
222
- : workspace,
223
- )
210
+ mapWorkspace(id, (workspace) => ({
211
+ ...workspace,
212
+ totalKeys: counts.totalKeys,
213
+ baseMissing: counts.baseMissing,
214
+ }))
215
+ }
216
+
217
+ /** Takes the workspace a details write answered into the list, its figures kept. */
218
+ function patchSummary(summary: WorkspaceSummary): void {
219
+ mapWorkspace(summary.id, (workspace) => ({
220
+ ...summary,
221
+ totalKeys: workspace.totalKeys,
222
+ baseMissing: workspace.baseMissing,
223
+ translatedStrings: workspace.translatedStrings,
224
+ }))
224
225
  }
225
226
 
226
227
  /** Remembers the workspace a page without `?workspace=` opens on (a new tab, a menu link). */
@@ -228,37 +229,31 @@ export const useI18nWorkspaces = () => {
228
229
  if (state.lastWorkspace.value !== id) state.lastWorkspace.value = id
229
230
  }
230
231
 
232
+ /** Reads the list again, after a write or a change heard from elsewhere. */
231
233
  async function fetchWorkspaces(): Promise<ScopedWorkspace[]> {
232
- state.requestSeq.value += 1
233
- const sequence = state.requestSeq.value
234
- state.isLoading.value = true
235
- try {
236
- const response = await $authFetch<WorkspacesResponse>(
237
- ENDPOINTS.workspaces,
238
- )
239
- if (sequence !== state.requestSeq.value) return state.workspaces.value
240
- applyResponse(response)
241
- return state.workspaces.value
242
- } catch {
243
- return state.workspaces.value
244
- } finally {
245
- if (sequence === state.requestSeq.value) state.isLoading.value = false
246
- }
234
+ await list.refresh()
235
+ return workspaces.value
247
236
  }
248
237
 
249
238
  return {
250
- workspaces: state.workspaces,
251
- editable: state.editable,
252
- permissions: readonly(state.permissions),
253
- publicBaseUrl: readonly(state.publicBaseUrl),
239
+ workspaces,
240
+ editable: computed(() => list.data.value?.editable ?? false),
241
+ permissions: computed(() => list.data.value?.permissions ?? null),
242
+ publicBaseUrl: computed(() => list.data.value?.publicBaseUrl ?? ''),
254
243
  selectedWorkspace: state.selectedWorkspace,
255
- isLoading: readonly(state.isLoading),
256
- isLoaded: readonly(state.isLoaded),
244
+ isLoading: computed(() => list.pending.value),
245
+ /** The list was read once: the page can tell a workspace it lacks. */
246
+ isLoaded: computed(() => list.data.value !== null),
247
+ /** Resolves once the list was read: what a server render waits for. */
248
+ whenLoaded: async (): Promise<void> => {
249
+ await list
250
+ },
257
251
  fetchWorkspaces,
258
252
  patchCounts,
253
+ patchSummary,
259
254
  canUseWorkspaceId,
260
255
  rememberWorkspace,
261
- ...useWorkspaceReads(),
256
+ ...useWorkspaceDownloads(),
262
257
  ...useWorkspaceWrites(),
263
258
  ...useKeyWrites(),
264
259
  }
@@ -42,7 +42,7 @@ async function moduleRows(
42
42
  context: KeyActionsContext,
43
43
  ): Promise<FlatTranslationRow[]> {
44
44
  if (!context.isDefault.value) return []
45
- return (await context.translations.load(MODULES_WORKSPACE)).rows
45
+ return (await context.translations.loadModules()).rows
46
46
  }
47
47
 
48
48
  async function addKey(context: KeyActionsContext): Promise<string[]> {
@@ -8,7 +8,7 @@ interface LanguageActionsContext {
8
8
  t: ReturnType<typeof useI18n>['t']
9
9
  toast: ReturnType<typeof useToast>
10
10
  overlay: ReturnType<typeof useOverlay>
11
- confirmServed: ReturnType<typeof useServedConfirm>
11
+ confirmFrom: ReturnType<typeof useConfirmFrom>['confirmFrom']
12
12
  formatCount: ReturnType<typeof useLangFormat>['formatCount']
13
13
  workspaces: ReturnType<typeof useI18nWorkspaces>
14
14
  translations: ReturnType<typeof useWorkspaceFlat>
@@ -99,10 +99,11 @@ async function removeLanguage(
99
99
  ): Promise<boolean> {
100
100
  const workspace = context.workspaces.selectedWorkspace.value
101
101
  const route = languageRoute(context, code)
102
- const removed = await context.confirmServed(
103
- `${route}/${REMOVAL_CONFIRM}`,
104
- () => context.workspaces.removeLocale(workspace, code),
105
- )
102
+ const removed = await context.confirmFrom(`${route}/${REMOVAL_CONFIRM}`, {
103
+ onConfirm: async () => {
104
+ await context.workspaces.removeLocale(workspace, code)
105
+ },
106
+ })
106
107
  if (!removed) return false
107
108
  notify(context, context.t('dms_lang.language_remove.done'))
108
109
  await dialogsLeft(context)
@@ -122,9 +123,11 @@ async function makeBase(
122
123
  ): Promise<boolean> {
123
124
  const workspace = context.workspaces.selectedWorkspace.value
124
125
  const route = languageRoute(context, code)
125
- const confirmed = await context.confirmServed(`${route}/${BASE_CONFIRM}`, () =>
126
- context.workspaces.setDefaultLocale(workspace, code),
127
- )
126
+ const confirmed = await context.confirmFrom(`${route}/${BASE_CONFIRM}`, {
127
+ onConfirm: async () => {
128
+ await context.workspaces.setDefaultLocale(workspace, code)
129
+ },
130
+ })
128
131
  if (!confirmed) return false
129
132
  await context.translations.refresh()
130
133
  notify(
@@ -141,7 +144,7 @@ export const useLanguageActions = () => {
141
144
  t: useI18n().t,
142
145
  toast: useToast(),
143
146
  overlay: useOverlay(),
144
- confirmServed: useServedConfirm(),
147
+ confirmFrom: useConfirmFrom().confirmFrom,
145
148
  formatCount: useLangFormat().formatCount,
146
149
  workspaces: useI18nWorkspaces(),
147
150
  translations: useWorkspaceFlat(),
@@ -146,13 +146,11 @@ async function updateDetails(
146
146
  id: string,
147
147
  change: DetailsChange,
148
148
  ): Promise<boolean> {
149
- const ok = await context.failures.tryMutate(
150
- () => context.workspaces.updateWorkspace(id, change),
149
+ const { workspaces } = context
150
+ return context.failures.tryMutate(
151
+ async () => workspaces.patchSummary(await workspaces.updateWorkspace(id, change)),
151
152
  { title: context.t('dms_lang.workspace_details.save_failed') },
152
153
  )
153
- if (!ok) return false
154
- await context.workspaces.fetchWorkspaces()
155
- return true
156
154
  }
157
155
 
158
156
  async function downloadBackup(
@@ -0,0 +1,50 @@
1
+ import { useDmsRouter, useDmsState } from '#dms/frontend-module'
2
+
3
+ /**
4
+ * Gives a page opened without `?workspace=` (a menu link, a new tab) the
5
+ * workspace remembered, or the project files once that one turns out to be
6
+ * gone. A server render redirects to it, so the page renders its data at
7
+ * once; call it once the workspace list is in, which a server render awaits.
8
+ */
9
+ export const useWorkspaceFill = () => {
10
+ const router = useDmsRouter()
11
+ const { workspaces, isLoaded, selectedWorkspace } = useI18nWorkspaces()
12
+ const { isUnknown } = useWorkspaceContext()
13
+ const { route, queryWorkspace, pageAction } = useWorkspaceRoute()
14
+ const filledFromMemory = useDmsState<string>(
15
+ 'dms-lang-workspace-filled',
16
+ () => '',
17
+ )
18
+
19
+ function fillWorkspace(workspace: string): void {
20
+ void router.replace(
21
+ linkWithQuery(route.path, { ...route.query, workspace }),
22
+ )
23
+ }
24
+
25
+ watch(
26
+ [queryWorkspace, pageAction],
27
+ ([workspace, action]) => {
28
+ if (workspace || action) return
29
+ const isKnown = workspaces.value.some(
30
+ (entry) => entry.id === selectedWorkspace.value,
31
+ )
32
+ const fallback =
33
+ isKnown || !isLoaded.value ? selectedWorkspace.value : DEFAULT_WORKSPACE
34
+ filledFromMemory.value = fallback
35
+ fillWorkspace(fallback)
36
+ },
37
+ { immediate: true },
38
+ )
39
+
40
+ watch(
41
+ [isUnknown, queryWorkspace],
42
+ ([unknown, workspace]) => {
43
+ if (import.meta.env.SSR || !unknown) return
44
+ if (!workspace || workspace !== filledFromMemory.value) return
45
+ filledFromMemory.value = ''
46
+ fillWorkspace(DEFAULT_WORKSPACE)
47
+ },
48
+ { immediate: true },
49
+ )
50
+ }
@@ -1,8 +1,7 @@
1
- import type { EffectScope, Ref } from 'vue'
1
+ import type { EffectScope, MaybeRefOrGetter, Ref } from 'vue'
2
2
  import { useEventListener } from '@vueuse/core'
3
- import { useDmsState } from '#dms/frontend-module'
3
+ import type { DmsAsyncDataResult } from '#dms/frontend-module'
4
4
  import type {
5
- FlatCounts,
6
5
  FlatTranslationRow,
7
6
  FlatTranslations,
8
7
  KeyRowResponse,
@@ -12,12 +11,11 @@ import { EMPTY_FLAT, withRow } from '../../utils/translations'
12
11
  /** Realtime topic the backend publishes on after each write. */
13
12
  export const LANG_REALTIME_TOPIC = 'dms-lang.translations'
14
13
 
15
- /** Data older than this is fetched again when the tab comes back into view. */
14
+ /** Data older than this is read again when the tab comes back into view. */
16
15
  const STALE_AFTER_MS = 5000
17
- /** Realtime messages arriving together trigger a single reload. */
16
+ /** Realtime messages arriving together trigger a single read. */
18
17
  const REALTIME_DEBOUNCE_MS = 300
19
- /** Longer than a page change: no page of the module listened meanwhile, its data may have moved. */
20
- const UNTRACKED_GRACE_MS = 1000
18
+ const FLAT_KEY_PREFIX = 'dms-lang-flat:'
21
19
 
22
20
  /** What the backend says about a write: the workspace, the tab that made it, the keys it changed. */
23
21
  interface ChangedPayload {
@@ -26,219 +24,194 @@ interface ChangedPayload {
26
24
  keys?: string[]
27
25
  }
28
26
 
29
- /** The changes heard since the last reload, by workspace: the keys, or `null` to read it all again. */
30
- type PendingChanges = Map<string, Set<string> | null>
27
+ /** The keys a realtime change named, or `null` to read the workspace whole. */
28
+ type ChangedKeys = Set<string> | null
31
29
 
32
- interface FlatStore {
33
- entries: Ref<Record<string, FlatTranslations>>
34
- pending: Ref<Record<string, boolean>>
35
- failed: Ref<Record<string, boolean>>
36
- touchedAt: Ref<Record<string, number>>
37
- }
30
+ type AuthFetch = ReturnType<typeof useAuthFetch>['$authFetch']
38
31
 
39
- interface FlatLoader {
40
- store: FlatStore
41
- selectedWorkspace: Ref<string>
42
- fetchWorkspaces: () => Promise<unknown>
43
- patchCounts: (workspace: string, counts: FlatCounts) => void
44
- fetchFlat: (workspace: string) => Promise<FlatTranslations>
45
- fetchRow: (workspace: string, key: string) => Promise<KeyRowResponse>
32
+ /** What reading a workspace's translations needs. */
33
+ interface FlatReadContext {
34
+ workspace: string
35
+ current: FlatTranslations | null
36
+ authFetch: AuthFetch
37
+ signal: AbortSignal
46
38
  }
47
39
 
48
- function useFlatStore(): FlatStore {
49
- return {
50
- entries: useDmsState<Record<string, FlatTranslations>>(
51
- 'dms-lang-flat',
52
- () => ({}),
53
- ),
54
- pending: useDmsState<Record<string, boolean>>(
55
- 'dms-lang-flat-pending',
56
- () => ({}),
57
- ),
58
- failed: useDmsState<Record<string, boolean>>(
59
- 'dms-lang-flat-failed',
60
- () => ({}),
61
- ),
62
- touchedAt: useDmsState<Record<string, number>>(
63
- 'dms-lang-flat-touched',
64
- () => ({}),
65
- ),
66
- }
40
+ type FlatRead = DmsAsyncDataResult<FlatTranslations>
41
+
42
+ /** How a caller reads the translations of a workspace. */
43
+ interface FlatReadOptions {
44
+ /** `false` reads nothing until `execute()` or another caller reads the workspace. */
45
+ immediate?: boolean
67
46
  }
68
47
 
69
- const requests = new Map<string, Promise<void>>()
70
- const changes: PendingChanges = new Map()
48
+ /** The keys the realtime changes named since the last read, by workspace; read once. */
49
+ const changedKeys = new Map<string, ChangedKeys>()
50
+ /** Bumped once a burst of realtime changes is heard: the readers read again. */
51
+ const heardChanges = ref(0)
52
+ /** Bumped when the tab comes back into view after a while: the readers read again. */
53
+ const tabReturns = ref(0)
54
+ /** When each workspace was last read, for the read on the tab's return. */
55
+ const readAt = new Map<string, number>()
71
56
  let realtimeTimer: ReturnType<typeof setTimeout> | undefined
72
57
  let syncScope: EffectScope | undefined
73
58
  let syncUsers = 0
74
- let stoppedAt: number | undefined
75
59
 
76
- function setFlag(
77
- flags: Ref<Record<string, boolean>>,
78
- workspace: string,
79
- value: boolean,
80
- ) {
81
- flags.value = { ...flags.value, [workspace]: value }
82
- }
60
+ const flatKey = (workspace: string) => `${FLAT_KEY_PREFIX}${workspace}`
83
61
 
84
- function setEntry(
85
- store: FlatStore,
86
- workspace: string,
87
- flat: FlatTranslations,
88
- ): void {
89
- store.entries.value = { ...store.entries.value, [workspace]: flat }
90
- store.touchedAt.value = { ...store.touchedAt.value, [workspace]: Date.now() }
62
+ function fetchFlat(context: FlatReadContext): Promise<FlatTranslations> {
63
+ return context.authFetch<FlatTranslations>(ENDPOINTS.flat, {
64
+ query: { workspace: context.workspace },
65
+ signal: context.signal,
66
+ })
91
67
  }
92
68
 
93
- async function request(loader: FlatLoader, workspace: string): Promise<void> {
94
- const { store } = loader
95
- setFlag(store.pending, workspace, true)
96
- try {
97
- setEntry(store, workspace, await loader.fetchFlat(workspace))
98
- setFlag(store.failed, workspace, false)
99
- } catch {
100
- setFlag(store.failed, workspace, true)
101
- } finally {
102
- setFlag(store.pending, workspace, false)
103
- requests.delete(workspace)
69
+ /** The rows the changes named, read one by one into the translations held. */
70
+ async function readRows(
71
+ context: FlatReadContext,
72
+ current: FlatTranslations,
73
+ keys: Set<string>,
74
+ ): Promise<FlatTranslations> {
75
+ let flat = current
76
+ for (const key of keys) {
77
+ const response = await context.authFetch<KeyRowResponse>(ENDPOINTS.row, {
78
+ query: { workspace: context.workspace, key },
79
+ signal: context.signal,
80
+ })
81
+ flat = { ...withRow(flat, key, response.row), ...response.counts }
104
82
  }
83
+ return flat
105
84
  }
106
85
 
107
- function fetchOnce(loader: FlatLoader, workspace: string): Promise<void> {
108
- const running = requests.get(workspace)
109
- if (running) return running
110
- const next = request(loader, workspace)
111
- requests.set(workspace, next)
112
- return next
113
- }
114
-
115
- /** Puts a row as the server now has it (none once the key is gone), with the figures it changed. */
116
- function applyRow(
117
- loader: FlatLoader,
118
- workspace: string,
119
- key: string,
120
- response: KeyRowResponse,
121
- before?: string,
122
- ): void {
123
- const current = loader.store.entries.value[workspace]
124
- if (!current) return
125
- const flat = withRow(current, key, response.row, before)
126
- setEntry(loader.store, workspace, { ...flat, ...response.counts })
127
- loader.patchCounts(workspace, response.counts)
128
- }
129
-
130
- async function readRows(
131
- loader: FlatLoader,
132
- workspace: string,
133
- keys: Set<string>,
134
- ): Promise<void> {
86
+ /**
87
+ * Reads the translations of a workspace: just the rows a realtime change
88
+ * named when the workspace is held, else (or once a row fails) all of them.
89
+ */
90
+ async function readFlat(context: FlatReadContext): Promise<FlatTranslations> {
91
+ const keys = changedKeys.get(context.workspace)
92
+ changedKeys.delete(context.workspace)
93
+ readAt.set(context.workspace, Date.now())
94
+ if (!keys || !context.current) return fetchFlat(context)
135
95
  try {
136
- for (const key of keys)
137
- applyRow(loader, workspace, key, await loader.fetchRow(workspace, key))
96
+ return await readRows(context, context.current, keys)
138
97
  } catch {
139
- await fetchOnce(loader, workspace)
98
+ return fetchFlat(context)
140
99
  }
141
100
  }
142
101
 
143
- function readChanges(loader: FlatLoader): void {
144
- const heard = [...changes]
145
- changes.clear()
146
- void loader.fetchWorkspaces()
147
- for (const [workspace, keys] of heard) {
148
- if (!loader.store.entries.value[workspace]) continue
149
- void (keys ? readRows(loader, workspace, keys) : fetchOnce(loader, workspace))
102
+ /**
103
+ * The translations of one workspace, shared by every caller of the
104
+ * workspace: one request however many sections read it. They follow the
105
+ * module's realtime changes on their own (`useLangChanges`), row by row,
106
+ * rather than the page's refreshes.
107
+ */
108
+ function useFlatRead(
109
+ workspace: MaybeRefOrGetter<string>,
110
+ options: FlatReadOptions = {},
111
+ ): FlatRead {
112
+ const key = () => {
113
+ const id = toValue(workspace)
114
+ return id ? flatKey(id) : null
150
115
  }
116
+ // The first run starts within the call, before its result is returned.
117
+ let held: FlatRead | undefined
118
+ const read = useApiData<FlatTranslations>(
119
+ key,
120
+ ({ $authFetch, signal }): Promise<FlatTranslations> =>
121
+ readFlat({
122
+ workspace: toValue(workspace),
123
+ current: held && !held.placeholder.value ? held.data.value : null,
124
+ authFetch: $authFetch,
125
+ signal,
126
+ }),
127
+ { immediate: options.immediate, refreshOnPageRefresh: false },
128
+ )
129
+ held = read
130
+ return read
151
131
  }
152
132
 
153
- function recordChange(loader: FlatLoader, payload: ChangedPayload): void {
154
- const workspace = payload.workspace || loader.selectedWorkspace.value
155
- const known = changes.get(workspace)
133
+
134
+ function recordChange(workspace: string, payload: ChangedPayload): void {
135
+ const known = changedKeys.get(workspace)
156
136
  const isWhole = !payload.keys?.length || known === null
157
- changes.set(
137
+ changedKeys.set(
158
138
  workspace,
159
139
  isWhole ? null : new Set([...(known ?? []), ...(payload.keys ?? [])]),
160
140
  )
161
141
  clearTimeout(realtimeTimer)
162
- realtimeTimer = setTimeout(() => readChanges(loader), REALTIME_DEBOUNCE_MS)
142
+ realtimeTimer = setTimeout(() => {
143
+ heardChanges.value += 1
144
+ }, REALTIME_DEBOUNCE_MS)
163
145
  }
164
146
 
165
147
  /**
166
- * A change another tab or user made: the workspace list is read again, and
167
- * the translations in memory follow, just the rows it names when it names
168
- * keys. The tab that made the change already has its answer: its echo is
169
- * skipped.
148
+ * A change another tab or user made to the workspace on screen: its
149
+ * translations follow, just the rows it names when it names keys. The tab
150
+ * that made the change already has its answer: its echo is skipped. The
151
+ * workspace list and the figures follow with the page, which the same
152
+ * topic refreshes.
170
153
  */
171
154
  function onRealtimeChange(
172
- loader: FlatLoader,
155
+ selectedWorkspace: string,
173
156
  payload: ChangedPayload | undefined,
174
157
  ownSession: string | undefined,
175
158
  ): void {
176
159
  if (payload?.session && payload.session === ownSession) return
177
- recordChange(loader, payload ?? {})
160
+ const workspace = payload?.workspace || selectedWorkspace
161
+ if (workspace === selectedWorkspace) recordChange(workspace, payload ?? {})
178
162
  }
179
163
 
180
- /** Reads the selected workspace again when the tab comes back after a while. */
181
- function revalidate(loader: FlatLoader): void {
182
- const workspace = loader.selectedWorkspace.value
183
- const touchedAt = loader.store.touchedAt.value[workspace]
184
- if (touchedAt !== undefined && Date.now() - touchedAt < STALE_AFTER_MS)
185
- return
186
- void loader.fetchWorkspaces()
187
- if (loader.store.entries.value[workspace]) void fetchOnce(loader, workspace)
188
- }
189
-
190
- /** Forgets the translations kept while no page of the module was listening to its changes. */
191
- function forgetUntracked(store: FlatStore): void {
192
- if (stoppedAt === undefined || Date.now() - stoppedAt < UNTRACKED_GRACE_MS)
193
- return
194
- store.entries.value = {}
195
- }
196
-
197
- function startSync(loader: FlatLoader): EffectScope {
198
- forgetUntracked(loader.store)
164
+ function startSync(selectedWorkspace: Ref<string>): EffectScope {
199
165
  const scope = effectScope(true)
200
166
  const { sessionId } = useUserRealtime()
201
167
  scope.run(() => {
202
168
  useRealtimeTopic(LANG_REALTIME_TOPIC, (event) => {
203
169
  if ('type' in event)
204
170
  onRealtimeChange(
205
- loader,
171
+ selectedWorkspace.value,
206
172
  event.payload as ChangedPayload | undefined,
207
173
  sessionId.value,
208
174
  )
209
175
  })
176
+ watch(selectedWorkspace, () => changedKeys.clear())
210
177
  useEventListener(document, 'visibilitychange', () => {
211
- if (document.visibilityState === 'visible') revalidate(loader)
178
+ if (document.visibilityState !== 'visible') return
179
+ if (isStale(selectedWorkspace.value)) tabReturns.value += 1
212
180
  })
213
181
  })
214
182
  return scope
215
183
  }
216
184
 
217
- function useFlatLoader(): FlatLoader {
218
- const workspaces = useI18nWorkspaces()
219
- return {
220
- store: useFlatStore(),
221
- selectedWorkspace: workspaces.selectedWorkspace,
222
- fetchWorkspaces: workspaces.fetchWorkspaces,
223
- patchCounts: workspaces.patchCounts,
224
- fetchFlat: workspaces.fetchFlat,
225
- fetchRow: workspaces.fetchRow,
226
- }
185
+ /** Whether the workspace was read long enough ago to read it again on the tab's return. */
186
+ function isStale(workspace: string): boolean {
187
+ const at = readAt.get(workspace)
188
+ return at === undefined || Date.now() - at >= STALE_AFTER_MS
227
189
  }
228
190
 
229
191
  /**
230
192
  * The flat translations of the selected workspace, shared by every component
231
- * of the page: one request per workspace however many sections read it, and
232
- * the row a write answers put in place so every section follows. Reading
233
- * them has no side effect: the matrix and the queue load them with
234
- * `useWorkspaceFlatSync`.
193
+ * of the page, and the row a write answers put in place so every section
194
+ * follows. Reading them has no side effect: the matrix and the queue load
195
+ * them with `useWorkspaceFlatSync`.
235
196
  */
236
197
  export const useWorkspaceFlat = () => {
237
- const loader = useFlatLoader()
238
- const { store, selectedWorkspace } = loader
198
+ const workspaces = useI18nWorkspaces()
199
+ const { selectedWorkspace } = workspaces
200
+ const selected = useFlatRead(selectedWorkspace, { immediate: false })
201
+ const modules = useFlatRead(MODULES_WORKSPACE, { immediate: false })
202
+
203
+ function readOf(workspace: string): FlatRead | undefined {
204
+ if (workspace === selectedWorkspace.value) return selected
205
+ return workspace === MODULES_WORKSPACE ? modules : undefined
206
+ }
239
207
 
240
208
  function flatOf(workspace: string): FlatTranslations {
241
- return store.entries.value[workspace] ?? EMPTY_FLAT
209
+ return readOf(workspace)?.data.value ?? EMPTY_FLAT
210
+ }
211
+
212
+ function setFlat(workspace: string, flat: FlatTranslations): void {
213
+ const read = readOf(workspace)
214
+ if (read?.data.value) read.data.value = flat
242
215
  }
243
216
 
244
217
  /** Puts a row in place without new figures: a text read from a refusal, a key gone elsewhere. */
@@ -247,87 +220,88 @@ export const useWorkspaceFlat = () => {
247
220
  key: string,
248
221
  row: FlatTranslationRow | undefined,
249
222
  ) {
250
- const current = store.entries.value[workspace]
251
- if (current) setEntry(store, workspace, withRow(current, key, row))
223
+ setFlat(workspace, withRow(flatOf(workspace), key, row))
224
+ }
225
+
226
+ /**
227
+ * Puts what a key write answered in place of `key`: its row (a new one
228
+ * before the `before` sibling) and the figures it changed.
229
+ */
230
+ function applyRow(
231
+ workspace: string,
232
+ key: string,
233
+ response: KeyRowResponse,
234
+ before?: string,
235
+ ) {
236
+ const flat = withRow(flatOf(workspace), key, response.row, before)
237
+ setFlat(workspace, { ...flat, ...response.counts })
238
+ workspaces.patchCounts(workspace, response.counts)
252
239
  }
253
240
 
254
241
  return {
255
- flat: computed(() => flatOf(selectedWorkspace.value)),
242
+ flat: computed(() => selected.data.value ?? EMPTY_FLAT),
256
243
  flatOf,
257
- isLoading: computed(
258
- () => store.pending.value[selectedWorkspace.value] === true,
259
- ),
260
- isLoaded: computed(
261
- () => store.entries.value[selectedWorkspace.value] !== undefined,
262
- ),
263
- hasError: computed(
264
- () => store.failed.value[selectedWorkspace.value] === true,
265
- ),
266
- /** The translations of a workspace, read once and then kept in step. */
267
- load: async (workspace: string) => {
268
- if (!store.entries.value[workspace]) await fetchOnce(loader, workspace)
269
- return flatOf(workspace)
244
+ isLoading: computed(() => selected.pending.value),
245
+ isLoaded: computed(() => selected.data.value !== null),
246
+ hasError: computed(() => selected.error.value != null),
247
+ /** The translations of the installed modules' workspace, read once and then kept. */
248
+ loadModules: async () => {
249
+ if (modules.data.value === null) await modules.execute()
250
+ return modules.data.value ?? EMPTY_FLAT
270
251
  },
271
252
  /** Reads the translations of the selected workspace and the workspace list again. */
272
253
  reload: async () => {
273
- const workspace = selectedWorkspace.value
274
- await Promise.all([fetchOnce(loader, workspace), loader.fetchWorkspaces()])
275
- },
276
- /** After a write of this tab: the workspace list, and the translations when the page holds them. */
277
- refresh: async () => {
278
- const workspace = selectedWorkspace.value
279
- const flat = store.entries.value[workspace]
280
- ? fetchOnce(loader, workspace)
281
- : undefined
282
- await Promise.all([flat, loader.fetchWorkspaces()])
254
+ await Promise.all([selected.refresh(), workspaces.fetchWorkspaces()])
283
255
  },
284
256
  /**
285
- * Puts what a key write answered in place of `key`: its row (a new one
286
- * before the `before` sibling) and the figures it changed.
257
+ * After a write of this tab whose answer the next step reads (the
258
+ * language just added, the new base): the workspace list, and the
259
+ * translations when the page holds them, which the page's refresh leaves.
287
260
  */
288
- applyRow: (
289
- workspace: string,
290
- key: string,
291
- response: KeyRowResponse,
292
- before?: string,
293
- ) => applyRow(loader, workspace, key, response, before),
261
+ refresh: async () => {
262
+ const flat = selected.data.value === null ? undefined : selected.refresh()
263
+ await Promise.all([flat, workspaces.fetchWorkspaces()])
264
+ },
265
+ applyRow,
294
266
  replaceRow,
295
267
  }
296
268
  }
297
269
 
298
270
  /**
299
- * Keeps the workspace data of the page in step with the other tabs and
300
- * users, once per page however many of its blocks mount it: the workspace
301
- * list and the translations in memory follow the module's realtime changes
302
- * and are read again when the tab comes back into view.
271
+ * Keeps the translations of the page in step with the other tabs and
272
+ * users, once per page however many of its blocks mount it: they follow the
273
+ * module's realtime changes and are read again when the tab comes back into
274
+ * view after a while.
303
275
  */
304
276
  export function useLangChanges(): void {
305
277
  if (import.meta.env.SSR) return
306
- const loader = useFlatLoader()
307
- if (syncUsers === 0) syncScope = startSync(loader)
278
+ const { selectedWorkspace, fetchWorkspaces } = useI18nWorkspaces()
279
+ const selected = useFlatRead(selectedWorkspace, { immediate: false })
280
+ const readAgain = () => {
281
+ if (selected.data.value !== null) void selected.refresh({ dedupe: 'defer' })
282
+ }
283
+ watch(heardChanges, readAgain)
284
+ watch(tabReturns, () => {
285
+ void fetchWorkspaces()
286
+ readAgain()
287
+ })
288
+ if (syncUsers === 0) syncScope = startSync(selectedWorkspace)
308
289
  syncUsers += 1
309
290
  onBeforeUnmount(() => {
310
291
  syncUsers -= 1
311
292
  if (syncUsers > 0) return
312
293
  syncScope?.stop()
313
294
  syncScope = undefined
314
- stoppedAt = Date.now()
315
295
  })
316
296
  }
317
297
 
318
298
  /**
319
- * Loads the translations of the selected workspace, for the pages that list
320
- * them (the matrix, the queue), and follows the selected workspace.
299
+ * Reads the translations of the selected workspace, for the pages that list
300
+ * them (the matrix, the queue): a server render reads them and hands them to
301
+ * the browser. They follow the selected workspace.
321
302
  */
322
303
  export function useWorkspaceFlatSync(): void {
323
- if (import.meta.env.SSR) return
324
- const loader = useFlatLoader()
325
- const load = () => {
326
- const workspace = loader.selectedWorkspace.value
327
- if (workspace && !loader.store.entries.value[workspace])
328
- void fetchOnce(loader, workspace)
329
- }
304
+ const { selectedWorkspace } = useI18nWorkspaces()
305
+ useFlatRead(selectedWorkspace)
330
306
  useLangChanges()
331
- onMounted(load)
332
- watch(loader.selectedWorkspace, load)
333
307
  }
@@ -21,14 +21,8 @@ const LOCALE_QUERY = 'locale'
21
21
  export const useWorkspaceRoute = () => {
22
22
  const route = useDmsRoute()
23
23
  const router = useDmsRouter()
24
- const {
25
- selectedWorkspace,
26
- workspaces,
27
- isLoaded,
28
- isLoading,
29
- fetchWorkspaces,
30
- rememberWorkspace,
31
- } = useI18nWorkspaces()
24
+ const { selectedWorkspace, workspaces, rememberWorkspace } =
25
+ useI18nWorkspaces()
32
26
 
33
27
  const queryWorkspace = computed(() => route.query.workspace || '')
34
28
  const pageAction = computed(() => route.query[PAGE_ACTION_QUERY] || '')
@@ -55,10 +49,6 @@ export const useWorkspaceRoute = () => {
55
49
  }
56
50
  })
57
51
 
58
- onMounted(() => {
59
- if (!isLoaded.value && !isLoading.value) fetchWorkspaces()
60
- })
61
-
62
52
  /** The language the queue opens on in a workspace: the current one when it is there, else its first translation. */
63
53
  function queueLocaleOf(workspace: string, locale: string): string {
64
54
  const target = workspaces.value.find((entry) => entry.id === workspace)
@@ -7,7 +7,7 @@
7
7
  "license": "Apache-2.0",
8
8
  "packageManager": "pnpm@10.6.5",
9
9
  "engines": {
10
- "@antelopejs/dms-frontend": ">=0.5.2 <0.6.0"
10
+ "@antelopejs/dms-frontend": ">=0.6.0 <0.7.0"
11
11
  },
12
12
  "scripts": {
13
13
  "build": "ajs dms build",
@@ -19,7 +19,7 @@
19
19
  },
20
20
  "devDependencies": {
21
21
  "@antelopejs/core": "1.14.0",
22
- "@antelopejs/dms-frontend": "0.5.6",
22
+ "@antelopejs/dms-frontend": "0.6.0",
23
23
  "@eslint/js": "^9",
24
24
  "@typescript-eslint/eslint-plugin": "^8",
25
25
  "@typescript-eslint/parser": "^8",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@antelopejs/dms-lang",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -48,14 +48,14 @@
48
48
  "@antelopejs/interface-api": ">=0.0.14 <1.0.0",
49
49
  "@antelopejs/interface-api-util": ">=0.1.2 <1.0.0",
50
50
  "@antelopejs/interface-core": ">=0.1.1 <1.0.0",
51
- "@antelopejs/interface-dms": ">=0.6.0 <1.0.0",
51
+ "@antelopejs/interface-dms": ">=0.7.0 <1.0.0",
52
52
  "@intlify/message-compiler": "^11.1.12",
53
53
  "zod": "~3.24.2"
54
54
  },
55
55
  "devDependencies": {
56
56
  "@antelopejs/core": "1.14.0",
57
- "@antelopejs/dms": ">=0.8.0 <0.9.0",
58
- "@antelopejs/dms-frontend": "0.5.6",
57
+ "@antelopejs/dms": ">=0.9.0 <1.0.0",
58
+ "@antelopejs/dms-frontend": "0.6.0",
59
59
  "@antelopejs/tooling-configs": ">=0.0.7 <1.0.0",
60
60
  "@types/chai": "^5.2.3",
61
61
  "@types/mocha": "^10.0.10",
@@ -1,152 +0,0 @@
1
- /** A text of a served dialog: an i18n key with `$`, else a literal with `{param}` fill-ins. */
2
- type ServedText = string
3
-
4
- const KEY_PREFIX = '$'
5
- const PARAM_PATTERN = /{(\w+)}/g
6
-
7
- interface ServedImpact {
8
- icon: string
9
- label: ServedText
10
- count?: number | string
11
- }
12
-
13
- interface ServedDownload {
14
- type: 'download'
15
- url: string
16
- filename?: string
17
- }
18
-
19
- interface ServedSecondaryAction {
20
- label: ServedText
21
- icon?: string
22
- target: ServedDownload
23
- }
24
-
25
- /** A confirmation dialog as a `confirm: { from }` route serves it (interface-dms `ConfirmDialogSerialized`). */
26
- export interface ServedDialog {
27
- title: ServedText
28
- description?: ServedText
29
- params?: Record<string, unknown>
30
- color?: 'primary' | 'warning' | 'error' | 'neutral'
31
- icon?: string
32
- confirmLabel?: ServedText
33
- cancelLabel?: ServedText
34
- confirmText?: string
35
- impact?: ServedImpact[]
36
- secondaryAction?: ServedSecondaryAction
37
- }
38
-
39
- type ConfirmRun = () => Promise<unknown>
40
-
41
- type Params = Record<string, unknown>
42
-
43
- /** What resolving and running a served dialog needs from the DMS. */
44
- interface ServedContext {
45
- t: ReturnType<typeof useI18n>['t']
46
- authFetch: ReturnType<typeof useAuthFetch>['$authFetch']
47
- }
48
-
49
- function fillLiteral(text: string, params: Params): string {
50
- return text.replace(PARAM_PATTERN, (match, name: string) =>
51
- params[name] === undefined ? match : String(params[name]),
52
- )
53
- }
54
-
55
- function resolveText(
56
- { t }: ServedContext,
57
- value: ServedText,
58
- params: Params,
59
- ): string {
60
- if (!value.startsWith(KEY_PREFIX)) return fillLiteral(value, params)
61
- const key = value.slice(KEY_PREFIX.length)
62
- const { count } = params
63
- return typeof count === 'number' ? t(key, params, count) : t(key, params)
64
- }
65
-
66
- /** Fetches a served download with the user's session and saves it. */
67
- async function download(
68
- context: ServedContext,
69
- target: ServedDownload,
70
- params: Params,
71
- ): Promise<void> {
72
- const url = interpolateUrl(target.url, params)
73
- const response = await context.authFetch.raw<Blob, 'blob'>(url, {
74
- responseType: 'blob',
75
- })
76
- const objectUrl = URL.createObjectURL(response._data ?? new Blob([]))
77
- try {
78
- downloadFile(objectUrl, interpolateRowText(target.filename ?? '', params))
79
- } finally {
80
- URL.revokeObjectURL(objectUrl)
81
- }
82
- }
83
-
84
- function secondaryOf(
85
- context: ServedContext,
86
- dialog: ServedDialog,
87
- params: Params,
88
- ) {
89
- const action = dialog.secondaryAction
90
- if (!action) return undefined
91
- return {
92
- label: resolveText(context, action.label, params),
93
- icon: action.icon,
94
- run: () => download(context, action.target, params),
95
- }
96
- }
97
-
98
- /** A served dialog with its texts resolved, ready for `useConfirm()`. */
99
- function confirmOptionsOf(context: ServedContext, dialog: ServedDialog) {
100
- const params = dialog.params ?? {}
101
- const text = (value?: ServedText) =>
102
- value === undefined ? undefined : resolveText(context, value, params)
103
- return {
104
- title: text(dialog.title) ?? '',
105
- description: text(dialog.description),
106
- color: dialog.color,
107
- icon: dialog.icon,
108
- confirmLabel: text(dialog.confirmLabel),
109
- cancelLabel: text(dialog.cancelLabel),
110
- confirmText: dialog.confirmText,
111
- impact: dialog.impact?.map((entry) => ({
112
- ...entry,
113
- label: text(entry.label) ?? '',
114
- })),
115
- secondaryAction: secondaryOf(context, dialog, params),
116
- }
117
- }
118
-
119
- /**
120
- * Asks with the dialog the server words for an action (the one a table row
121
- * action asks with, through `confirm: { from }`), so the action asks the
122
- * same question wherever it starts: its texts, its impact, the code to type
123
- * and its download. Resolves whether the user confirmed and `run` succeeded.
124
- */
125
- export function useServedConfirm() {
126
- const context: ServedContext = {
127
- t: useI18n().t,
128
- authFetch: useAuthFetch().$authFetch,
129
- }
130
- const { confirm } = useConfirm()
131
- const { reportFailure } = useMutationToast()
132
-
133
- async function loadDialog(url: string): Promise<ServedDialog | null> {
134
- try {
135
- return await context.authFetch<ServedDialog>(url)
136
- } catch (error) {
137
- reportFailure(error)
138
- return null
139
- }
140
- }
141
-
142
- return async (url: string, run: ConfirmRun): Promise<boolean> => {
143
- const dialog = await loadDialog(url)
144
- if (!dialog) return false
145
- return confirm({
146
- ...confirmOptionsOf(context, dialog),
147
- onConfirm: async () => {
148
- await run()
149
- },
150
- })
151
- }
152
- }