@7365admin1/layer-common 4.97.1-staging.729 → 4.97.1-staging.731
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/components/AccessCardQrTaggingPrintQr.vue +2 -1
- package/components/AreaFormDialog.vue +8 -4
- package/components/Layout/Header.vue +61 -1
- package/components/Layout/NavigationDrawer.vue +1 -1
- package/components/NavigationItem.vue +3 -3
- package/composables/useReportPdf.ts +9 -1
- package/composables/useUiLanguage.ts +95 -0
- package/nuxt.config.ts +14 -0
- package/package.json +2 -2
- package/plugins/ui-language.ts +30 -0
- package/utils/ui-translate-transform.ts +207 -0
- package/utils/ui-translate.ts +292 -0
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
<template>
|
|
2
|
-
|
|
2
|
+
<!-- translate="no": printed cards stay English (owner rule). -->
|
|
3
|
+
<v-container ref="printContent" fluid style="overflow-y: auto" translate="no">
|
|
3
4
|
<v-row no-gutters class="main-container">
|
|
4
5
|
<v-col v-for="(card, idx) in accessCards" :key="idx" cols="auto">
|
|
5
6
|
<div class="qr-box">
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
/>
|
|
59
59
|
<v-text-field
|
|
60
60
|
v-model="model"
|
|
61
|
-
:rules="[
|
|
61
|
+
:rules="[nameRequiredRule]"
|
|
62
62
|
class="filter-field mb-0"
|
|
63
63
|
/>
|
|
64
64
|
</v-col>
|
|
@@ -149,7 +149,6 @@
|
|
|
149
149
|
|
|
150
150
|
<script setup lang="ts">
|
|
151
151
|
import useUnits from '../composables/useUnits';
|
|
152
|
-
import useUtils from '../composables/useUtils';
|
|
153
152
|
|
|
154
153
|
const model = defineModel("name", { type: String, default: "" });
|
|
155
154
|
const typeModel = defineModel("type", { type: String, default: "Common" });
|
|
@@ -185,7 +184,8 @@ const valid = ref(false);
|
|
|
185
184
|
const submitting = ref(false);
|
|
186
185
|
const show = ref(false);
|
|
187
186
|
|
|
188
|
-
|
|
187
|
+
// Spaces only is still an empty name.
|
|
188
|
+
const nameRequiredRule = (v: any) => !!String(v ?? "").trim() || "Required";
|
|
189
189
|
|
|
190
190
|
const unitsRequiredRule = (v: any) => {
|
|
191
191
|
if (Array.isArray(v)) return v.length > 0 || "Select at least one unit";
|
|
@@ -237,7 +237,11 @@ async function submit() {
|
|
|
237
237
|
let ok = valid.value;
|
|
238
238
|
if (form && typeof form.validate === "function") {
|
|
239
239
|
try {
|
|
240
|
-
|
|
240
|
+
// Vuetify 3 resolves to `{ valid, errors }`, an object that is always
|
|
241
|
+
// truthy: reading it as the result let an empty name through and closed
|
|
242
|
+
// the popup without saving or saying anything (DV-1872).
|
|
243
|
+
const result = await form.validate();
|
|
244
|
+
ok = typeof result === "object" && result !== null ? !!result.valid : !!result;
|
|
241
245
|
} catch (e) {
|
|
242
246
|
ok = false;
|
|
243
247
|
}
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
<div ref="crumbEl" class="app-topbar-shell__crumb">
|
|
25
25
|
<span v-if="siteName" class="app-topbar-shell__site">{{ siteName }}</span>
|
|
26
26
|
<span v-if="siteName && moduleName" class="app-topbar-shell__sep">/</span>
|
|
27
|
-
<span class="app-topbar-shell__module">{{ moduleName }}</span>
|
|
27
|
+
<span class="app-topbar-shell__module">{{ $tr(moduleName) }}</span>
|
|
28
28
|
</div>
|
|
29
29
|
|
|
30
30
|
<template #append>
|
|
@@ -80,6 +80,38 @@
|
|
|
80
80
|
Manage Account
|
|
81
81
|
</button>
|
|
82
82
|
|
|
83
|
+
<!--
|
|
84
|
+
Interface language (composables/useUiLanguage.ts). Remembered per
|
|
85
|
+
browser; record content and reports stay as written.
|
|
86
|
+
-->
|
|
87
|
+
<button
|
|
88
|
+
type="button"
|
|
89
|
+
class="app-profile-menu__row"
|
|
90
|
+
:aria-expanded="languageOpen"
|
|
91
|
+
@click="languageOpen = !languageOpen"
|
|
92
|
+
>
|
|
93
|
+
<v-icon icon="mdi-translate" size="18" />
|
|
94
|
+
Language
|
|
95
|
+
<span class="app-profile-menu__value" translate="no">{{ currentLanguageName }}</span>
|
|
96
|
+
</button>
|
|
97
|
+
|
|
98
|
+
<div v-if="languageOpen" class="app-profile-menu__languages" role="listbox" translate="no">
|
|
99
|
+
<button
|
|
100
|
+
v-for="lang in languages"
|
|
101
|
+
:key="lang.code"
|
|
102
|
+
type="button"
|
|
103
|
+
role="option"
|
|
104
|
+
:aria-selected="lang.code === language"
|
|
105
|
+
:lang="lang.code"
|
|
106
|
+
class="app-profile-menu__row app-profile-menu__lang"
|
|
107
|
+
:class="{ 'app-profile-menu__lang--on': lang.code === language }"
|
|
108
|
+
@click="chooseLanguage(lang.code)"
|
|
109
|
+
>
|
|
110
|
+
{{ lang.nativeName }}
|
|
111
|
+
<v-icon v-if="lang.code === language" icon="mdi-check" size="16" class="ms-auto" />
|
|
112
|
+
</button>
|
|
113
|
+
</div>
|
|
114
|
+
|
|
83
115
|
<button
|
|
84
116
|
type="button"
|
|
85
117
|
class="app-profile-menu__row app-profile-menu__row--danger"
|
|
@@ -136,6 +168,17 @@ const { current, toggleTheme } = useThemePreference();
|
|
|
136
168
|
|
|
137
169
|
const { currentUser } = useLocalAuth();
|
|
138
170
|
|
|
171
|
+
const { languages, language, setLanguage } = useUiLanguage();
|
|
172
|
+
const languageOpen = ref(false);
|
|
173
|
+
const currentLanguageName = computed(
|
|
174
|
+
() => languages.find((l) => l.code === language.value)?.nativeName ?? "English"
|
|
175
|
+
);
|
|
176
|
+
|
|
177
|
+
function chooseLanguage(code: string) {
|
|
178
|
+
setLanguage(code);
|
|
179
|
+
languageOpen.value = false;
|
|
180
|
+
}
|
|
181
|
+
|
|
139
182
|
/**
|
|
140
183
|
* THE BREADCRUMB: `Site name / Current module`.
|
|
141
184
|
*
|
|
@@ -376,6 +419,23 @@ const { getNameInitials } = useUtils();
|
|
|
376
419
|
background: var(--hover);
|
|
377
420
|
}
|
|
378
421
|
|
|
422
|
+
.app-profile-menu__value {
|
|
423
|
+
margin-inline-start: auto;
|
|
424
|
+
color: var(--muted);
|
|
425
|
+
font-weight: 600;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
.app-profile-menu__languages {
|
|
429
|
+
max-height: 260px;
|
|
430
|
+
overflow-y: auto;
|
|
431
|
+
padding-inline-start: 18px;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
.app-profile-menu__lang--on {
|
|
435
|
+
color: var(--text);
|
|
436
|
+
font-weight: 800;
|
|
437
|
+
}
|
|
438
|
+
|
|
379
439
|
/* Logout is the design's red row: the colour lives on the label, and the
|
|
380
440
|
soft error background is what the hover paints. */
|
|
381
441
|
.app-profile-menu__row--danger {
|
|
@@ -91,7 +91,7 @@
|
|
|
91
91
|
v-for="({ item, section }, index) in sectionedItems"
|
|
92
92
|
:key="`${item.title}-${index}`"
|
|
93
93
|
>
|
|
94
|
-
<div v-if="section" class="brand-drawer__section">{{ section }}</div>
|
|
94
|
+
<div v-if="section" class="brand-drawer__section">{{ $tr(section) }}</div>
|
|
95
95
|
|
|
96
96
|
<v-tooltip location="right" :disabled="!item.disabled">
|
|
97
97
|
<template #activator="{ props: tooltipProps }">
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
class="nav-item"
|
|
15
15
|
@click.stop="onParentClick"
|
|
16
16
|
>
|
|
17
|
-
{{ title }}
|
|
17
|
+
{{ $tr(title) }}
|
|
18
18
|
</v-list-item>
|
|
19
19
|
</template>
|
|
20
20
|
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
color="primary"
|
|
36
36
|
class="nav-item"
|
|
37
37
|
>
|
|
38
|
-
{{ title }}
|
|
38
|
+
{{ $tr(title) }}
|
|
39
39
|
</v-list-item>
|
|
40
40
|
|
|
41
41
|
<v-list-item
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
color="primary"
|
|
46
46
|
class="nav-item"
|
|
47
47
|
>
|
|
48
|
-
{{ title }}
|
|
48
|
+
{{ $tr(title) }}
|
|
49
49
|
</v-list-item>
|
|
50
50
|
</template>
|
|
51
51
|
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import html2canvas from "html2canvas";
|
|
2
2
|
import jsPDF from "jspdf";
|
|
3
|
+
import useUiLanguage from "./useUiLanguage";
|
|
3
4
|
import { formatGeneratedAt, planPdfPages, type PdfTable } from "../utils/report-export";
|
|
4
5
|
|
|
5
6
|
export type ReportPdfMeta = {
|
|
@@ -141,7 +142,14 @@ function drawFooter(pdf: jsPDF, page: number, pages: number, generatedAt: string
|
|
|
141
142
|
}
|
|
142
143
|
|
|
143
144
|
export default function useReportPdf() {
|
|
144
|
-
|
|
145
|
+
const { withEnglish } = useUiLanguage();
|
|
146
|
+
|
|
147
|
+
// Reports stay English whatever the screen language (owner rule).
|
|
148
|
+
function exportReportPdf(report: HTMLElement, meta: ReportPdfMeta) {
|
|
149
|
+
return withEnglish(() => drawReportPdf(report, meta));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function drawReportPdf(report: HTMLElement, meta: ReportPdfMeta) {
|
|
145
153
|
let layout = { height: 0, breaks: [] as number[], tables: [] as PdfTable[] };
|
|
146
154
|
|
|
147
155
|
const canvas = await html2canvas(report, {
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { nextTick, ref } from "vue";
|
|
2
|
+
import { createUiTranslator, UI_LANGUAGES } from "../utils/ui-translate";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The web language picker (top bar > profile menu > Language).
|
|
6
|
+
*
|
|
7
|
+
* Interface text only: `utils/ui-translate-transform.ts` turns static template
|
|
8
|
+
* text into `$tr(...)` at build time, and `utils/ui-translate.ts` fetches,
|
|
9
|
+
* caches and falls back. Record content is never translated or sent.
|
|
10
|
+
* Reports and PDFs stay English (owner rule) - wrap their capture in
|
|
11
|
+
* `withEnglish`.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
type Engine = ReturnType<typeof createUiTranslator>;
|
|
15
|
+
|
|
16
|
+
let engine: Engine | null = null;
|
|
17
|
+
const revision = ref(0);
|
|
18
|
+
const language = ref("en");
|
|
19
|
+
|
|
20
|
+
function localStore() {
|
|
21
|
+
try {
|
|
22
|
+
return typeof window === "undefined" ? null : window.localStorage;
|
|
23
|
+
} catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function applyHtmlLang(code: string) {
|
|
29
|
+
if (typeof document !== "undefined") document.documentElement.lang = code;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Called once by plugins/ui-language.ts. */
|
|
33
|
+
export function installUiLanguage(deps: {
|
|
34
|
+
post: (q: string[], target: string) => Promise<any>;
|
|
35
|
+
getVersion: () => Promise<any>;
|
|
36
|
+
}) {
|
|
37
|
+
if (engine || typeof window === "undefined") return;
|
|
38
|
+
engine = createUiTranslator({
|
|
39
|
+
storage: localStore(),
|
|
40
|
+
post: deps.post,
|
|
41
|
+
getVersion: deps.getVersion,
|
|
42
|
+
onChange: () => {
|
|
43
|
+
revision.value++;
|
|
44
|
+
language.value = engine?.language ?? "en";
|
|
45
|
+
applyHtmlLang(language.value);
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
language.value = engine.language;
|
|
49
|
+
applyHtmlLang(language.value);
|
|
50
|
+
void engine.checkVersion();
|
|
51
|
+
|
|
52
|
+
// Printed pages stay English (owner rule): Vue re-renders in the microtask
|
|
53
|
+
// after `beforeprint`, before the browser lays out the print.
|
|
54
|
+
window.addEventListener("beforeprint", () => engine?.setForcedEnglish(true));
|
|
55
|
+
window.addEventListener("afterprint", () => engine?.setForcedEnglish(false));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Translate one interface label (reactive: re-renders when it arrives). */
|
|
59
|
+
export function uiTr<T>(text: T): T {
|
|
60
|
+
void revision.value;
|
|
61
|
+
return engine ? engine.tr(text) : text;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** v-data-table headers with translated column titles. */
|
|
65
|
+
export function uiTrHeaders<T>(headers: T): T {
|
|
66
|
+
void revision.value;
|
|
67
|
+
return engine ? engine.trHeaders(headers) : headers;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export default function useUiLanguage() {
|
|
71
|
+
function setLanguage(code: string) {
|
|
72
|
+
engine?.setLanguage(code);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Run `fn` with the page drawn in English (report / PDF capture). */
|
|
76
|
+
async function withEnglish<T>(fn: () => Promise<T> | T): Promise<T> {
|
|
77
|
+
if (!engine || engine.language === "en") return await fn();
|
|
78
|
+
engine.setForcedEnglish(true);
|
|
79
|
+
try {
|
|
80
|
+
await nextTick();
|
|
81
|
+
return await fn();
|
|
82
|
+
} finally {
|
|
83
|
+
engine.setForcedEnglish(false);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return { languages: UI_LANGUAGES, language, setLanguage, tr: uiTr, trHeaders: uiTrHeaders, withEnglish };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
declare module "vue" {
|
|
91
|
+
interface ComponentCustomProperties {
|
|
92
|
+
$tr: typeof uiTr;
|
|
93
|
+
$trHeaders: typeof uiTrHeaders;
|
|
94
|
+
}
|
|
95
|
+
}
|
package/nuxt.config.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// https://nuxt.com/docs/api/configuration/nuxt-config
|
|
2
2
|
import vuetify, { transformAssetUrls } from "vite-plugin-vuetify";
|
|
3
3
|
import { SECURITY_HEADERS } from "./utils/security-headers";
|
|
4
|
+
import { uiTranslateTransform } from "./utils/ui-translate-transform";
|
|
4
5
|
export default defineNuxtConfig({
|
|
5
6
|
ssr: false,
|
|
6
7
|
devtools: { enabled: false },
|
|
@@ -21,6 +22,11 @@ export default defineNuxtConfig({
|
|
|
21
22
|
...(process.env.API_CORE
|
|
22
23
|
? { "/api/client-logs": { proxy: `${process.env.API_CORE}/api/client-logs` } }
|
|
23
24
|
: {}),
|
|
25
|
+
// Interface-text translation for the language picker (composables/useUiLanguage.ts).
|
|
26
|
+
// Here, not per app, so every app that renders the picker can reach it.
|
|
27
|
+
...(process.env.API_CORE
|
|
28
|
+
? { "/api/translations/**": { proxy: `${process.env.API_CORE}/api/translations/**` } }
|
|
29
|
+
: {}),
|
|
24
30
|
},
|
|
25
31
|
build: {
|
|
26
32
|
transpile: ["vuetify"],
|
|
@@ -109,6 +115,14 @@ export default defineNuxtConfig({
|
|
|
109
115
|
"nuxt-signature-pad",
|
|
110
116
|
],
|
|
111
117
|
|
|
118
|
+
// Static template text -> `$tr(...)` for the language picker. Bound and
|
|
119
|
+
// interpolated values (record content) are never touched. See the file.
|
|
120
|
+
vue: {
|
|
121
|
+
compilerOptions: {
|
|
122
|
+
nodeTransforms: [uiTranslateTransform],
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
|
|
112
126
|
vite: {
|
|
113
127
|
// When this layer is `yarn link`ed into an app, its components resolve
|
|
114
128
|
// `vuetify` from the layer's own node_modules, so the page loads two
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@7365admin1/layer-common",
|
|
3
3
|
"license": "MIT",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"version": "4.97.1-staging.
|
|
5
|
+
"version": "4.97.1-staging.731",
|
|
6
6
|
"author": "7365admin1",
|
|
7
7
|
"main": "./nuxt.config.ts",
|
|
8
8
|
"//files": "What a consumer extending this layer actually loads. Without this npm ships the whole working tree - the changesets, the CI workflows, the render harness in tools/ and any scratch directory that happened to exist at publish time. Nuxt resolves a layer by directory, so every runtime directory below has to stay listed; adding a new top-level runtime directory means adding it here too.",
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"build": "nuxt build .playground",
|
|
38
38
|
"generate": "nuxt generate .playground",
|
|
39
39
|
"preview": "nuxt preview .playground",
|
|
40
|
-
"test": "esbuild composables/useANPRSettings.ts --format=esm --outfile=test/.build/useANPRSettings.mjs --log-level=error && esbuild composables/useSite.ts --format=esm --outfile=test/.build/useSite.mjs --log-level=error && esbuild composables/useSiteFeatureSettings.ts --format=esm --outfile=test/.build/useSiteFeatureSettings.mjs --log-level=error && esbuild composables/useVisitor.ts --format=esm --outfile=test/.build/useVisitor.mjs --log-level=error && esbuild composables/useVisitorSocket.ts --format=esm --outfile=test/.build/useVisitorSocket.mjs --log-level=error && esbuild composables/usePlateToastWindow.ts --format=esm --outfile=test/.build/usePlateToastWindow.mjs --log-level=error && esbuild utils/client-invite-modules.ts --bundle --platform=node --format=esm --outfile=test/.build/client-invite-modules.mjs --log-level=error && esbuild utils/robot-display.ts --bundle --platform=node --format=esm --outfile=test/.build/robot-display.mjs --log-level=error && esbuild utils/building-map.ts --bundle --platform=node --format=esm --outfile=test/.build/building-map.mjs --log-level=error && esbuild utils/robot-building.ts --bundle --platform=node --format=esm --outfile=test/.build/robot-building.mjs --log-level=error && esbuild utils/robot-fleet-core.ts --bundle --platform=node --format=esm --outfile=test/.build/robot-fleet-core.mjs --log-level=error && esbuild utils/rmf-editor.ts --bundle --platform=node --format=esm --outfile=test/.build/rmf-editor.mjs --log-level=error && node --experimental-strip-types --test \"test/*.test.mjs\" && yarn test:units",
|
|
40
|
+
"test": "esbuild composables/useANPRSettings.ts --format=esm --outfile=test/.build/useANPRSettings.mjs --log-level=error && esbuild composables/useSite.ts --format=esm --outfile=test/.build/useSite.mjs --log-level=error && esbuild composables/useSiteFeatureSettings.ts --format=esm --outfile=test/.build/useSiteFeatureSettings.mjs --log-level=error && esbuild composables/useVisitor.ts --format=esm --outfile=test/.build/useVisitor.mjs --log-level=error && esbuild composables/useVisitorSocket.ts --format=esm --outfile=test/.build/useVisitorSocket.mjs --log-level=error && esbuild composables/usePlateToastWindow.ts --format=esm --outfile=test/.build/usePlateToastWindow.mjs --log-level=error && esbuild utils/client-invite-modules.ts --bundle --platform=node --format=esm --outfile=test/.build/client-invite-modules.mjs --log-level=error && esbuild utils/robot-display.ts --bundle --platform=node --format=esm --outfile=test/.build/robot-display.mjs --log-level=error && esbuild utils/building-map.ts --bundle --platform=node --format=esm --outfile=test/.build/building-map.mjs --log-level=error && esbuild utils/robot-building.ts --bundle --platform=node --format=esm --outfile=test/.build/robot-building.mjs --log-level=error && esbuild utils/robot-fleet-core.ts --bundle --platform=node --format=esm --outfile=test/.build/robot-fleet-core.mjs --log-level=error && esbuild utils/rmf-editor.ts --bundle --platform=node --format=esm --outfile=test/.build/rmf-editor.mjs --log-level=error && esbuild utils/ui-translate.ts --bundle --platform=node --format=esm --outfile=test/.build/ui-translate.mjs --log-level=error && esbuild utils/ui-translate-transform.ts --bundle --platform=node --format=esm --outfile=test/.build/ui-translate-transform.mjs --log-level=error && node --experimental-strip-types --test \"test/*.test.mjs\" && yarn test:units",
|
|
41
41
|
"test:units": "node --experimental-strip-types --test \"utils/*.test.ts\"",
|
|
42
42
|
"release": "yarn run build && changeset publish"
|
|
43
43
|
},
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { installUiLanguage, uiTr, uiTrHeaders } from "../composables/useUiLanguage";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `$tr` / `$trHeaders` for every template (the build-time transform in
|
|
5
|
+
* utils/ui-translate-transform.ts emits calls to them). Installed on the
|
|
6
|
+
* server too so a template never meets an undefined `$tr`; the translator
|
|
7
|
+
* itself only starts in the browser.
|
|
8
|
+
*
|
|
9
|
+
* Plain `$fetch`, not `$api`: a refused translation must not retry, log out,
|
|
10
|
+
* re-read the role or log as a failed save - it just stays English.
|
|
11
|
+
*/
|
|
12
|
+
export default defineNuxtPlugin((nuxtApp) => {
|
|
13
|
+
nuxtApp.vueApp.config.globalProperties.$tr = uiTr;
|
|
14
|
+
nuxtApp.vueApp.config.globalProperties.$trHeaders = uiTrHeaders;
|
|
15
|
+
if (!import.meta.client) return;
|
|
16
|
+
|
|
17
|
+
const { cookieConfig } = useRuntimeConfig().public;
|
|
18
|
+
const sid = () => nuxtApp.runWithContext(() => useCookie("sid", cookieConfig).value ?? "");
|
|
19
|
+
|
|
20
|
+
function call(path: string, init: Record<string, any> = {}) {
|
|
21
|
+
const token = sid();
|
|
22
|
+
if (!token) return Promise.reject({ status: 401 });
|
|
23
|
+
return $fetch(path, { ...init, retry: 0, headers: { Authorization: token } });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
installUiLanguage({
|
|
27
|
+
post: (q, target) => call("/api/translations/v1", { method: "POST", body: { q, target } }),
|
|
28
|
+
getVersion: async () => ((await call("/api/translations/v1/version")) as any)?.version,
|
|
29
|
+
});
|
|
30
|
+
});
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Web interface translation, compile-time half (see `composables/useUiLanguage.ts`).
|
|
3
|
+
*
|
|
4
|
+
* A Vue template compiler node transform, registered in this layer's
|
|
5
|
+
* `nuxt.config.ts`, so it runs over every template of every app that extends
|
|
6
|
+
* the layer - the layer's components and each app's own pages alike.
|
|
7
|
+
*
|
|
8
|
+
* It rewrites only STATIC template text - words a developer typed into a
|
|
9
|
+
* template - into a `$tr("...")` call:
|
|
10
|
+
*
|
|
11
|
+
* <v-btn>Save</v-btn> -> <v-btn>{{ $tr("Save") }}</v-btn>
|
|
12
|
+
* <v-text-field label="Unit No." /> -> <v-text-field :label="$tr('Unit No.')" />
|
|
13
|
+
* <v-data-table :headers="headers" /> -> <v-data-table :headers="$trHeaders(headers)" />
|
|
14
|
+
*
|
|
15
|
+
* Anything bound or interpolated (`{{ item.name }}`, `:label="x"`) is record
|
|
16
|
+
* content or computed text and is NEVER touched, so names, NRIC, plates, units
|
|
17
|
+
* and typed text cannot reach the translation endpoint from here. That is the
|
|
18
|
+
* point of doing it at compile time rather than by walking the DOM.
|
|
19
|
+
*
|
|
20
|
+
* Static attributes are rewritten on native HTML elements, Vuetify components
|
|
21
|
+
* and the display-only layer components in DISPLAY_PROPS. Any other component
|
|
22
|
+
* may use a static prop in logic
|
|
23
|
+
* (`props.title.includes("anpr")`, `label === 'Me'`), and translating it there
|
|
24
|
+
* would change behaviour; those components translate where they display text.
|
|
25
|
+
*
|
|
26
|
+
* With English selected `$tr` returns its argument unchanged, so the rendered
|
|
27
|
+
* page is identical to before.
|
|
28
|
+
*
|
|
29
|
+
* Opt out: `translate="no"` or class `notranslate` on an element keeps it and
|
|
30
|
+
* everything inside it in English (print sheets, report areas).
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
// @vue/compiler-core NodeTypes / ConstantTypes (stable public enum values).
|
|
34
|
+
const ROOT = 0;
|
|
35
|
+
const ELEMENT = 1;
|
|
36
|
+
const TEXT = 2;
|
|
37
|
+
const SIMPLE_EXPRESSION = 4;
|
|
38
|
+
const INTERPOLATION = 5;
|
|
39
|
+
const ATTRIBUTE = 6;
|
|
40
|
+
const DIRECTIVE = 7;
|
|
41
|
+
const IF_BRANCH = 10;
|
|
42
|
+
const FOR = 11;
|
|
43
|
+
const NOT_CONSTANT = 0;
|
|
44
|
+
const CAN_STRINGIFY = 3;
|
|
45
|
+
|
|
46
|
+
/** Elements whose text is code, an icon name or not interface text. */
|
|
47
|
+
const SKIP_TAGS = new Set([
|
|
48
|
+
"script",
|
|
49
|
+
"style",
|
|
50
|
+
"code",
|
|
51
|
+
"pre",
|
|
52
|
+
"kbd",
|
|
53
|
+
"samp",
|
|
54
|
+
"textarea",
|
|
55
|
+
"svg",
|
|
56
|
+
"text",
|
|
57
|
+
"tspan",
|
|
58
|
+
"math",
|
|
59
|
+
"v-icon",
|
|
60
|
+
"VIcon",
|
|
61
|
+
"v-code",
|
|
62
|
+
"VCode",
|
|
63
|
+
"v-kbd",
|
|
64
|
+
"Icon",
|
|
65
|
+
"icon",
|
|
66
|
+
]);
|
|
67
|
+
|
|
68
|
+
/** Static attributes that are interface wording. */
|
|
69
|
+
const TEXT_ATTRS = new Set([
|
|
70
|
+
"label",
|
|
71
|
+
"placeholder",
|
|
72
|
+
"hint",
|
|
73
|
+
"title",
|
|
74
|
+
"subtitle",
|
|
75
|
+
"text",
|
|
76
|
+
"aria-label",
|
|
77
|
+
"alt",
|
|
78
|
+
"no-data-text",
|
|
79
|
+
"loading-text",
|
|
80
|
+
"prepend-text",
|
|
81
|
+
"append-text",
|
|
82
|
+
]);
|
|
83
|
+
|
|
84
|
+
const DATA_TABLES = new Set([
|
|
85
|
+
"v-data-table",
|
|
86
|
+
"v-data-table-server",
|
|
87
|
+
"v-data-table-virtual",
|
|
88
|
+
"VDataTable",
|
|
89
|
+
"VDataTableServer",
|
|
90
|
+
"VDataTableVirtual",
|
|
91
|
+
]);
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Layer components that only DISPLAY these props (checked: no logic reads
|
|
95
|
+
* them), so a static value at the call site is safe to translate.
|
|
96
|
+
*/
|
|
97
|
+
const DISPLAY_PROPS: Record<string, Set<string>> = {
|
|
98
|
+
PageHeader: new Set(["title", "subtitle"]),
|
|
99
|
+
AppField: new Set(["label", "placeholder", "hint"]),
|
|
100
|
+
AppSelect: new Set(["label", "placeholder", "hint"]),
|
|
101
|
+
AppDateField: new Set(["label", "placeholder", "hint"]),
|
|
102
|
+
AppKpiTile: new Set(["label"]),
|
|
103
|
+
DashboardPanel: new Set(["title"]),
|
|
104
|
+
AcceptDialog: new Set(["title"]),
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
/** Native element (`div`, `button`) or a Vuetify component (`v-btn`, `VBtn`). */
|
|
108
|
+
function rewritesAttributes(tag: string): boolean {
|
|
109
|
+
return /^[a-z][a-z0-9]*$/.test(tag) || /^v-[a-z]/.test(tag) || /^V[A-Z][A-Za-z]+$/.test(tag);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function attributesFor(tag: string): Set<string> | null {
|
|
113
|
+
const pascal = tag.includes("-") && !tag.startsWith("v-")
|
|
114
|
+
? tag.replace(/(^|-)([a-z])/g, (_m, _d, c) => c.toUpperCase())
|
|
115
|
+
: tag;
|
|
116
|
+
if (DISPLAY_PROPS[pascal]) return DISPLAY_PROPS[pascal];
|
|
117
|
+
return rewritesAttributes(tag) ? TEXT_ATTRS : null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Has words worth translating: a letter, and not an identifier / icon / url. */
|
|
121
|
+
export function isStaticInterfaceText(text: string): boolean {
|
|
122
|
+
const t = text.trim();
|
|
123
|
+
if (!t || t.length > 300) return false;
|
|
124
|
+
if (!/\p{L}/u.test(t)) return false;
|
|
125
|
+
if (t === "true" || t === "false") return false;
|
|
126
|
+
if (/^mdi-/.test(t)) return false;
|
|
127
|
+
if (/^[a-z0-9]+([-_.:/][a-z0-9]+)+$/.test(t)) return false; // kebab/snake ids, file names
|
|
128
|
+
if (/^(https?:|\/|#|\.)/.test(t)) return false;
|
|
129
|
+
return true;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function optedOut(node: any): boolean {
|
|
133
|
+
return (node.props ?? []).some(
|
|
134
|
+
(p: any) =>
|
|
135
|
+
p.type === ATTRIBUTE &&
|
|
136
|
+
((p.name === "translate" && p.value?.content === "no") ||
|
|
137
|
+
(p.name === "class" && /(^|\s)notranslate(\s|$)/.test(p.value?.content ?? ""))),
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function expression(content: string, loc: any) {
|
|
142
|
+
return { type: SIMPLE_EXPRESSION, content, isStatic: false, constType: NOT_CONSTANT, loc };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function rewriteAttributes(el: any, names: Set<string>) {
|
|
146
|
+
el.props = el.props.map((p: any) => {
|
|
147
|
+
if (p.type !== ATTRIBUTE || !names.has(p.name) || !p.value) return p;
|
|
148
|
+
if (!isStaticInterfaceText(p.value.content)) return p;
|
|
149
|
+
return {
|
|
150
|
+
type: DIRECTIVE,
|
|
151
|
+
name: "bind",
|
|
152
|
+
rawName: `:${p.name}`,
|
|
153
|
+
exp: expression(`$tr(${JSON.stringify(p.value.content)})`, p.value.loc),
|
|
154
|
+
arg: { type: SIMPLE_EXPRESSION, content: p.name, isStatic: true, constType: CAN_STRINGIFY, loc: p.nameLoc ?? p.loc },
|
|
155
|
+
modifiers: [],
|
|
156
|
+
loc: p.loc,
|
|
157
|
+
};
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function wrapHeaders(el: any) {
|
|
162
|
+
for (const p of el.props) {
|
|
163
|
+
if (p.type !== DIRECTIVE || p.name !== "bind" || p.arg?.content !== "headers") continue;
|
|
164
|
+
if (p.exp?.type !== SIMPLE_EXPRESSION || !p.exp.content.trim()) continue;
|
|
165
|
+
if (p.exp.content.startsWith("$trHeaders(")) continue; // already wrapped (v-if / v-for re-visit)
|
|
166
|
+
p.exp.content = `$trHeaders(${p.exp.content})`;
|
|
167
|
+
// Re-parse the new source; a cached AST would compile the old one.
|
|
168
|
+
p.exp.ast = undefined;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Runs on a parent before its children are visited, so the rewritten children
|
|
174
|
+
* then go through Vue's own expression transform like hand-written ones.
|
|
175
|
+
*/
|
|
176
|
+
export function uiTranslateTransform(node: any, context: any) {
|
|
177
|
+
// v-if / v-for replace an element (or <template>) with a branch / for node
|
|
178
|
+
// that holds its children, so those are parents too.
|
|
179
|
+
if (![ROOT, ELEMENT, IF_BRANCH, FOR].includes(node.type)) return;
|
|
180
|
+
if (context?.inVPre) return;
|
|
181
|
+
// Inside an opted-out or skipped element: nothing below it is rewritten.
|
|
182
|
+
if (context && context.__uiNoTr > 0) return;
|
|
183
|
+
if (node.type === ELEMENT && (SKIP_TAGS.has(node.tag) || optedOut(node))) {
|
|
184
|
+
if (!context) return;
|
|
185
|
+
context.__uiNoTr = (context.__uiNoTr ?? 0) + 1;
|
|
186
|
+
return () => {
|
|
187
|
+
context.__uiNoTr--;
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const children = node.children ?? [];
|
|
192
|
+
for (let i = 0; i < children.length; i++) {
|
|
193
|
+
const child = children[i];
|
|
194
|
+
if (child.type === TEXT) {
|
|
195
|
+
if (!isStaticInterfaceText(child.content)) continue;
|
|
196
|
+
children[i] = {
|
|
197
|
+
type: INTERPOLATION,
|
|
198
|
+
content: expression(`$tr(${JSON.stringify(child.content)})`, child.loc),
|
|
199
|
+
loc: child.loc,
|
|
200
|
+
};
|
|
201
|
+
} else if (child.type === ELEMENT && !SKIP_TAGS.has(child.tag) && !optedOut(child)) {
|
|
202
|
+
const names = attributesFor(child.tag);
|
|
203
|
+
if (names) rewriteAttributes(child, names);
|
|
204
|
+
if (DATA_TABLES.has(child.tag)) wrapHeaders(child);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Web interface translation, runtime half. Framework-free so it can be unit
|
|
3
|
+
* tested in plain Node (test/ui-translate.test.mjs); `composables/useUiLanguage.ts`
|
|
4
|
+
* wires it to Vue and the `/api/translations/v1` endpoint.
|
|
5
|
+
*
|
|
6
|
+
* - Strings come only from `$tr(...)` calls the template transform wrote for
|
|
7
|
+
* static template text, plus a few layer labels (menu titles, table headers).
|
|
8
|
+
* `isInterfaceText` is a second fence: anything that looks like an email,
|
|
9
|
+
* NRIC/FIN, plate, long number or is over the endpoint's 300 characters is
|
|
10
|
+
* never sent and stays as written.
|
|
11
|
+
* - Translations are cached per language in localStorage under the server's
|
|
12
|
+
* glossary `version`; a different version (GET .../version or a POST reply)
|
|
13
|
+
* drops every cached language, so a glossary fix reaches every browser.
|
|
14
|
+
* - Batches of at most 100 strings / 5000 characters (the endpoint's caps),
|
|
15
|
+
* debounced, and at most UI_TR_CLIENT_MAX requests per 5 minutes (server: 120).
|
|
16
|
+
* - Any failure leaves the English text in place.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
export type UiLanguage = { code: string; name: string; nativeName: string };
|
|
20
|
+
|
|
21
|
+
/** The same 18 languages the mobile apps offer (ma-mobile-app src/stores/useLanguage.ts). */
|
|
22
|
+
export const UI_LANGUAGES: UiLanguage[] = [
|
|
23
|
+
{ code: "en", name: "English", nativeName: "English" },
|
|
24
|
+
{ code: "zh", name: "Chinese (Simplified)", nativeName: "中文 (简体)" },
|
|
25
|
+
{ code: "zh-TW", name: "Chinese (Traditional)", nativeName: "中文 (繁體)" },
|
|
26
|
+
{ code: "ms", name: "Malay", nativeName: "Bahasa Melayu" },
|
|
27
|
+
{ code: "ta", name: "Tamil", nativeName: "தமிழ்" },
|
|
28
|
+
{ code: "hi", name: "Hindi", nativeName: "हिन्दी" },
|
|
29
|
+
{ code: "ar", name: "Arabic", nativeName: "العربية" },
|
|
30
|
+
{ code: "th", name: "Thai", nativeName: "ภาษาไทย" },
|
|
31
|
+
{ code: "vi", name: "Vietnamese", nativeName: "Tiếng Việt" },
|
|
32
|
+
{ code: "id", name: "Indonesian", nativeName: "Bahasa Indonesia" },
|
|
33
|
+
{ code: "ja", name: "Japanese", nativeName: "日本語" },
|
|
34
|
+
{ code: "ko", name: "Korean", nativeName: "한국어" },
|
|
35
|
+
{ code: "fr", name: "French", nativeName: "Français" },
|
|
36
|
+
{ code: "de", name: "German", nativeName: "Deutsch" },
|
|
37
|
+
{ code: "es", name: "Spanish", nativeName: "Español" },
|
|
38
|
+
{ code: "pt", name: "Portuguese", nativeName: "Português" },
|
|
39
|
+
{ code: "ru", name: "Russian", nativeName: "Русский" },
|
|
40
|
+
{ code: "tl", name: "Filipino", nativeName: "Filipino" },
|
|
41
|
+
];
|
|
42
|
+
|
|
43
|
+
export const UI_TR_LANG_KEY = "ui-lang";
|
|
44
|
+
export const UI_TR_VERSION_KEY = "ui-tr-version";
|
|
45
|
+
export const UI_TR_CACHE_PREFIX = "ui-tr:";
|
|
46
|
+
|
|
47
|
+
export const UI_TR_MAX_BATCH = 100;
|
|
48
|
+
export const UI_TR_MAX_CHARS = 5000;
|
|
49
|
+
export const UI_TR_MAX_TEXT = 300;
|
|
50
|
+
export const UI_TR_WINDOW_MS = 5 * 60 * 1000;
|
|
51
|
+
/** Requests per 5 minutes; the server allows 120 per session. */
|
|
52
|
+
export const UI_TR_CLIENT_MAX = 60;
|
|
53
|
+
export const UI_TR_DEBOUNCE_MS = 250;
|
|
54
|
+
|
|
55
|
+
/** Interface wording only. Record-like text is never sent. */
|
|
56
|
+
export function isInterfaceText(text: unknown): text is string {
|
|
57
|
+
if (typeof text !== "string") return false;
|
|
58
|
+
const t = text.trim();
|
|
59
|
+
if (!t || t.length > UI_TR_MAX_TEXT) return false;
|
|
60
|
+
if (!/\p{L}/u.test(t)) return false;
|
|
61
|
+
if (t.includes("@")) return false; // emails
|
|
62
|
+
if (/\b[STFGM]\d{7}[A-Z]\b/i.test(t)) return false; // NRIC / FIN
|
|
63
|
+
if (/\b[A-Z]{1,3}\d{1,4}[A-Z]?\b/.test(t)) return false; // plates, unit codes (SBA1234X, B2)
|
|
64
|
+
if (/\d{4,}/.test(t)) return false; // phone numbers, ids, long numbers
|
|
65
|
+
if (/#\d|\d+-\d+/.test(t)) return false; // unit numbers (#05-12), ranges of ids
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
type KV = {
|
|
70
|
+
getItem(k: string): string | null;
|
|
71
|
+
setItem(k: string, v: string): void;
|
|
72
|
+
removeItem(k: string): void;
|
|
73
|
+
key(i: number): string | null;
|
|
74
|
+
readonly length: number;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
export type TranslatorDeps = {
|
|
78
|
+
storage?: KV | null;
|
|
79
|
+
post: (q: string[], target: string) => Promise<{ translations?: unknown; version?: unknown }>;
|
|
80
|
+
getVersion: () => Promise<unknown>;
|
|
81
|
+
onChange: () => void;
|
|
82
|
+
now?: () => number;
|
|
83
|
+
schedule?: (fn: () => void, ms: number) => unknown;
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
function safe<T>(fn: () => T, fallback: T): T {
|
|
87
|
+
try {
|
|
88
|
+
return fn();
|
|
89
|
+
} catch {
|
|
90
|
+
return fallback;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function statusOf(error: any): number {
|
|
95
|
+
return Number(error?.statusCode ?? error?.status ?? error?.response?.status ?? 0);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function createUiTranslator(deps: TranslatorDeps) {
|
|
99
|
+
const storage = deps.storage ?? null;
|
|
100
|
+
const now = deps.now ?? (() => Date.now());
|
|
101
|
+
const schedule = deps.schedule ?? ((fn: () => void, ms: number) => setTimeout(fn, ms));
|
|
102
|
+
|
|
103
|
+
const known = new Set(UI_LANGUAGES.map((l) => l.code));
|
|
104
|
+
const stored = safe(() => storage?.getItem(UI_TR_LANG_KEY) ?? "", "");
|
|
105
|
+
let lang = known.has(stored) ? stored : "en";
|
|
106
|
+
let version = safe(() => storage?.getItem(UI_TR_VERSION_KEY) ?? "", "");
|
|
107
|
+
let dict: Record<string, string> = {};
|
|
108
|
+
let forcedEnglish = false;
|
|
109
|
+
|
|
110
|
+
const pending = new Set<string>();
|
|
111
|
+
const failed = new Set<string>();
|
|
112
|
+
const sent: number[] = [];
|
|
113
|
+
let timer = false;
|
|
114
|
+
let inFlight = false;
|
|
115
|
+
let blockedUntil = 0;
|
|
116
|
+
let stopped = false;
|
|
117
|
+
let versionChecked = false;
|
|
118
|
+
let revision = 0;
|
|
119
|
+
|
|
120
|
+
function changed() {
|
|
121
|
+
revision++;
|
|
122
|
+
deps.onChange();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function loadDict() {
|
|
126
|
+
dict = {};
|
|
127
|
+
if (lang === "en") return;
|
|
128
|
+
const raw = safe(() => storage?.getItem(UI_TR_CACHE_PREFIX + lang) ?? null, null);
|
|
129
|
+
if (!raw) return;
|
|
130
|
+
const parsed = safe(() => JSON.parse(raw), null);
|
|
131
|
+
if (parsed && parsed.v === version && parsed.m && typeof parsed.m === "object") dict = parsed.m;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function saveDict() {
|
|
135
|
+
safe(() => storage?.setItem(UI_TR_CACHE_PREFIX + lang, JSON.stringify({ v: version, m: dict })), undefined);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** A different glossary version: every cached language is stale. */
|
|
139
|
+
function adoptVersion(next: unknown) {
|
|
140
|
+
if (typeof next !== "string" || !next || next === version) return false;
|
|
141
|
+
safe(() => {
|
|
142
|
+
if (!storage) return;
|
|
143
|
+
const keys: string[] = [];
|
|
144
|
+
for (let i = 0; i < storage.length; i++) {
|
|
145
|
+
const k = storage.key(i);
|
|
146
|
+
if (k && k.startsWith(UI_TR_CACHE_PREFIX)) keys.push(k);
|
|
147
|
+
}
|
|
148
|
+
keys.forEach((k) => storage.removeItem(k));
|
|
149
|
+
}, undefined);
|
|
150
|
+
version = next;
|
|
151
|
+
safe(() => storage?.setItem(UI_TR_VERSION_KEY, next), undefined);
|
|
152
|
+
dict = {};
|
|
153
|
+
failed.clear();
|
|
154
|
+
return true;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function scheduleFlush(ms = UI_TR_DEBOUNCE_MS) {
|
|
158
|
+
if (timer) return;
|
|
159
|
+
timer = true;
|
|
160
|
+
schedule(() => {
|
|
161
|
+
timer = false;
|
|
162
|
+
void flush();
|
|
163
|
+
}, ms);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function flush() {
|
|
167
|
+
if (inFlight || stopped || lang === "en" || pending.size === 0) return;
|
|
168
|
+
const t = now();
|
|
169
|
+
if (t < blockedUntil) return scheduleFlush(blockedUntil - t);
|
|
170
|
+
while (sent.length && t - sent[0] > UI_TR_WINDOW_MS) sent.shift();
|
|
171
|
+
if (sent.length >= UI_TR_CLIENT_MAX) return scheduleFlush(UI_TR_WINDOW_MS - (t - sent[0]) + 50);
|
|
172
|
+
|
|
173
|
+
const batch: string[] = [];
|
|
174
|
+
let chars = 0;
|
|
175
|
+
for (const s of pending) {
|
|
176
|
+
if (batch.length >= UI_TR_MAX_BATCH || chars + s.length > UI_TR_MAX_CHARS) break;
|
|
177
|
+
batch.push(s);
|
|
178
|
+
chars += s.length;
|
|
179
|
+
}
|
|
180
|
+
batch.forEach((s) => pending.delete(s));
|
|
181
|
+
const target = lang;
|
|
182
|
+
inFlight = true;
|
|
183
|
+
sent.push(t);
|
|
184
|
+
try {
|
|
185
|
+
const reply = await deps.post(batch, target);
|
|
186
|
+
if (target !== lang) return; // language changed while waiting
|
|
187
|
+
adoptVersion(reply?.version);
|
|
188
|
+
const out = Array.isArray(reply?.translations) ? reply.translations : [];
|
|
189
|
+
batch.forEach((s, i) => {
|
|
190
|
+
const v = out[i];
|
|
191
|
+
if (typeof v === "string" && v.trim()) dict[s] = v;
|
|
192
|
+
else failed.add(s);
|
|
193
|
+
});
|
|
194
|
+
saveDict();
|
|
195
|
+
changed();
|
|
196
|
+
} catch (error) {
|
|
197
|
+
const status = statusOf(error);
|
|
198
|
+
if (status === 429) {
|
|
199
|
+
batch.forEach((s) => pending.add(s));
|
|
200
|
+
blockedUntil = now() + UI_TR_WINDOW_MS;
|
|
201
|
+
} else if (status === 401 || status === 403 || status === 501) {
|
|
202
|
+
stopped = true; // signed out / not configured: English for this page load
|
|
203
|
+
} else {
|
|
204
|
+
batch.forEach((s) => failed.add(s));
|
|
205
|
+
}
|
|
206
|
+
} finally {
|
|
207
|
+
inFlight = false;
|
|
208
|
+
if (pending.size) scheduleFlush(0);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async function checkVersion() {
|
|
213
|
+
if (versionChecked || lang === "en") return;
|
|
214
|
+
versionChecked = true;
|
|
215
|
+
try {
|
|
216
|
+
if (adoptVersion(await deps.getVersion())) changed();
|
|
217
|
+
} catch {
|
|
218
|
+
// Offline, signed out or an older API: keep the cache.
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function tr(text: unknown): any {
|
|
223
|
+
if (lang === "en" || forcedEnglish || !isInterfaceText(text)) return text;
|
|
224
|
+
const key = text.trim();
|
|
225
|
+
const hit = dict[key];
|
|
226
|
+
if (hit) {
|
|
227
|
+
const start = text.indexOf(key);
|
|
228
|
+
return text.slice(0, start) + hit + text.slice(start + key.length);
|
|
229
|
+
}
|
|
230
|
+
if (!failed.has(key) && !stopped) {
|
|
231
|
+
pending.add(key);
|
|
232
|
+
scheduleFlush();
|
|
233
|
+
}
|
|
234
|
+
return text;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const headerMemo = new WeakMap<object, { stamp: string; out: any[] }>();
|
|
238
|
+
|
|
239
|
+
/** Column titles of a v-data-table `headers` array (developer labels). */
|
|
240
|
+
function trHeaders(headers: any): any {
|
|
241
|
+
if (!Array.isArray(headers) || lang === "en" || forcedEnglish) return headers;
|
|
242
|
+
const stamp = `${lang}:${revision}`;
|
|
243
|
+
const memo = headerMemo.get(headers);
|
|
244
|
+
if (memo && memo.stamp === stamp) return memo.out;
|
|
245
|
+
const out = headers.map((h) => {
|
|
246
|
+
if (!h || typeof h !== "object") return h;
|
|
247
|
+
const next = { ...h };
|
|
248
|
+
if (typeof h.title === "string") next.title = tr(h.title);
|
|
249
|
+
if (Array.isArray(h.children)) next.children = trHeaders(h.children);
|
|
250
|
+
return next;
|
|
251
|
+
});
|
|
252
|
+
headerMemo.set(headers, { stamp, out });
|
|
253
|
+
return out;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function setLanguage(code: string) {
|
|
257
|
+
if (!known.has(code) || code === lang) return;
|
|
258
|
+
lang = code;
|
|
259
|
+
safe(() => storage?.setItem(UI_TR_LANG_KEY, code), undefined);
|
|
260
|
+
pending.clear();
|
|
261
|
+
stopped = false;
|
|
262
|
+
loadDict();
|
|
263
|
+
changed();
|
|
264
|
+
void checkVersion();
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function setForcedEnglish(on: boolean) {
|
|
268
|
+
if (forcedEnglish === on) return;
|
|
269
|
+
forcedEnglish = on;
|
|
270
|
+
changed();
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
loadDict();
|
|
274
|
+
|
|
275
|
+
return {
|
|
276
|
+
tr,
|
|
277
|
+
trHeaders,
|
|
278
|
+
setLanguage,
|
|
279
|
+
setForcedEnglish,
|
|
280
|
+
checkVersion,
|
|
281
|
+
flush,
|
|
282
|
+
get language() {
|
|
283
|
+
return lang;
|
|
284
|
+
},
|
|
285
|
+
get version() {
|
|
286
|
+
return version;
|
|
287
|
+
},
|
|
288
|
+
get pendingCount() {
|
|
289
|
+
return pending.size;
|
|
290
|
+
},
|
|
291
|
+
};
|
|
292
|
+
}
|