@7365admin1/layer-common 4.97.1-staging.730 → 4.97.1-staging.732

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.
@@ -1,5 +1,6 @@
1
1
  <template>
2
- <v-container ref="printContent" fluid style="overflow-y: auto">
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">
@@ -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
- async function exportReportPdf(report: HTMLElement, meta: ReportPdfMeta) {
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,101 @@
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
+ /** The shared-domain cookie, so the choice follows the user across the apps. */
37
+ sharedLanguage?: () => string | undefined;
38
+ shareLanguage?: (code: string) => void;
39
+ }) {
40
+ if (engine || typeof window === "undefined") return;
41
+ engine = createUiTranslator({
42
+ storage: localStore(),
43
+ post: deps.post,
44
+ getVersion: deps.getVersion,
45
+ initialLanguage: deps.sharedLanguage?.(),
46
+ onChange: () => {
47
+ revision.value++;
48
+ const code = engine?.language ?? "en";
49
+ if (code !== language.value) deps.shareLanguage?.(code);
50
+ language.value = code;
51
+ applyHtmlLang(code);
52
+ },
53
+ });
54
+ language.value = engine.language;
55
+ applyHtmlLang(language.value);
56
+ void engine.checkVersion();
57
+
58
+ // Printed pages stay English (owner rule): Vue re-renders in the microtask
59
+ // after `beforeprint`, before the browser lays out the print.
60
+ window.addEventListener("beforeprint", () => engine?.setForcedEnglish(true));
61
+ window.addEventListener("afterprint", () => engine?.setForcedEnglish(false));
62
+ }
63
+
64
+ /** Translate one interface label (reactive: re-renders when it arrives). */
65
+ export function uiTr<T>(text: T): T {
66
+ void revision.value;
67
+ return engine ? engine.tr(text) : text;
68
+ }
69
+
70
+ /** v-data-table headers with translated column titles. */
71
+ export function uiTrHeaders<T>(headers: T): T {
72
+ void revision.value;
73
+ return engine ? engine.trHeaders(headers) : headers;
74
+ }
75
+
76
+ export default function useUiLanguage() {
77
+ function setLanguage(code: string) {
78
+ engine?.setLanguage(code);
79
+ }
80
+
81
+ /** Run `fn` with the page drawn in English (report / PDF capture). */
82
+ async function withEnglish<T>(fn: () => Promise<T> | T): Promise<T> {
83
+ if (!engine || engine.language === "en") return await fn();
84
+ engine.setForcedEnglish(true);
85
+ try {
86
+ await nextTick();
87
+ return await fn();
88
+ } finally {
89
+ engine.setForcedEnglish(false);
90
+ }
91
+ }
92
+
93
+ return { languages: UI_LANGUAGES, language, setLanguage, tr: uiTr, trHeaders: uiTrHeaders, withEnglish };
94
+ }
95
+
96
+ declare module "vue" {
97
+ interface ComponentCustomProperties {
98
+ $tr: typeof uiTr;
99
+ $trHeaders: typeof uiTrHeaders;
100
+ }
101
+ }
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.730",
5
+ "version": "4.97.1-staging.732",
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,39 @@
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
+ // Same domain-wide cookie pattern as the theme (useThemePreference): one
27
+ // choice for all eleven apps, not one per app host.
28
+ const langCookie = () =>
29
+ nuxtApp.runWithContext(() => useCookie<string | null>("ui-lang", { ...cookieConfig, maxAge: 365 * 24 * 60 * 60 }));
30
+
31
+ installUiLanguage({
32
+ sharedLanguage: () => langCookie().value ?? undefined,
33
+ shareLanguage: (code) => {
34
+ langCookie().value = code;
35
+ },
36
+ post: (q, target) => call("/api/translations/v1", { method: "POST", body: { q, target } }),
37
+ getVersion: async () => ((await call("/api/translations/v1/version")) as any)?.version,
38
+ });
39
+ });
@@ -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,294 @@
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
+ /** Language chosen in another app of the same domain (shared cookie); wins over storage. */
83
+ initialLanguage?: string;
84
+ now?: () => number;
85
+ schedule?: (fn: () => void, ms: number) => unknown;
86
+ };
87
+
88
+ function safe<T>(fn: () => T, fallback: T): T {
89
+ try {
90
+ return fn();
91
+ } catch {
92
+ return fallback;
93
+ }
94
+ }
95
+
96
+ function statusOf(error: any): number {
97
+ return Number(error?.statusCode ?? error?.status ?? error?.response?.status ?? 0);
98
+ }
99
+
100
+ export function createUiTranslator(deps: TranslatorDeps) {
101
+ const storage = deps.storage ?? null;
102
+ const now = deps.now ?? (() => Date.now());
103
+ const schedule = deps.schedule ?? ((fn: () => void, ms: number) => setTimeout(fn, ms));
104
+
105
+ const known = new Set(UI_LANGUAGES.map((l) => l.code));
106
+ const stored = deps.initialLanguage || safe(() => storage?.getItem(UI_TR_LANG_KEY) ?? "", "");
107
+ let lang = known.has(stored) ? stored : "en";
108
+ let version = safe(() => storage?.getItem(UI_TR_VERSION_KEY) ?? "", "");
109
+ let dict: Record<string, string> = {};
110
+ let forcedEnglish = false;
111
+
112
+ const pending = new Set<string>();
113
+ const failed = new Set<string>();
114
+ const sent: number[] = [];
115
+ let timer = false;
116
+ let inFlight = false;
117
+ let blockedUntil = 0;
118
+ let stopped = false;
119
+ let versionChecked = false;
120
+ let revision = 0;
121
+
122
+ function changed() {
123
+ revision++;
124
+ deps.onChange();
125
+ }
126
+
127
+ function loadDict() {
128
+ dict = {};
129
+ if (lang === "en") return;
130
+ const raw = safe(() => storage?.getItem(UI_TR_CACHE_PREFIX + lang) ?? null, null);
131
+ if (!raw) return;
132
+ const parsed = safe(() => JSON.parse(raw), null);
133
+ if (parsed && parsed.v === version && parsed.m && typeof parsed.m === "object") dict = parsed.m;
134
+ }
135
+
136
+ function saveDict() {
137
+ safe(() => storage?.setItem(UI_TR_CACHE_PREFIX + lang, JSON.stringify({ v: version, m: dict })), undefined);
138
+ }
139
+
140
+ /** A different glossary version: every cached language is stale. */
141
+ function adoptVersion(next: unknown) {
142
+ if (typeof next !== "string" || !next || next === version) return false;
143
+ safe(() => {
144
+ if (!storage) return;
145
+ const keys: string[] = [];
146
+ for (let i = 0; i < storage.length; i++) {
147
+ const k = storage.key(i);
148
+ if (k && k.startsWith(UI_TR_CACHE_PREFIX)) keys.push(k);
149
+ }
150
+ keys.forEach((k) => storage.removeItem(k));
151
+ }, undefined);
152
+ version = next;
153
+ safe(() => storage?.setItem(UI_TR_VERSION_KEY, next), undefined);
154
+ dict = {};
155
+ failed.clear();
156
+ return true;
157
+ }
158
+
159
+ function scheduleFlush(ms = UI_TR_DEBOUNCE_MS) {
160
+ if (timer) return;
161
+ timer = true;
162
+ schedule(() => {
163
+ timer = false;
164
+ void flush();
165
+ }, ms);
166
+ }
167
+
168
+ async function flush() {
169
+ if (inFlight || stopped || lang === "en" || pending.size === 0) return;
170
+ const t = now();
171
+ if (t < blockedUntil) return scheduleFlush(blockedUntil - t);
172
+ while (sent.length && t - sent[0] > UI_TR_WINDOW_MS) sent.shift();
173
+ if (sent.length >= UI_TR_CLIENT_MAX) return scheduleFlush(UI_TR_WINDOW_MS - (t - sent[0]) + 50);
174
+
175
+ const batch: string[] = [];
176
+ let chars = 0;
177
+ for (const s of pending) {
178
+ if (batch.length >= UI_TR_MAX_BATCH || chars + s.length > UI_TR_MAX_CHARS) break;
179
+ batch.push(s);
180
+ chars += s.length;
181
+ }
182
+ batch.forEach((s) => pending.delete(s));
183
+ const target = lang;
184
+ inFlight = true;
185
+ sent.push(t);
186
+ try {
187
+ const reply = await deps.post(batch, target);
188
+ if (target !== lang) return; // language changed while waiting
189
+ adoptVersion(reply?.version);
190
+ const out = Array.isArray(reply?.translations) ? reply.translations : [];
191
+ batch.forEach((s, i) => {
192
+ const v = out[i];
193
+ if (typeof v === "string" && v.trim()) dict[s] = v;
194
+ else failed.add(s);
195
+ });
196
+ saveDict();
197
+ changed();
198
+ } catch (error) {
199
+ const status = statusOf(error);
200
+ if (status === 429) {
201
+ batch.forEach((s) => pending.add(s));
202
+ blockedUntil = now() + UI_TR_WINDOW_MS;
203
+ } else if (status === 401 || status === 403 || status === 501) {
204
+ stopped = true; // signed out / not configured: English for this page load
205
+ } else {
206
+ batch.forEach((s) => failed.add(s));
207
+ }
208
+ } finally {
209
+ inFlight = false;
210
+ if (pending.size) scheduleFlush(0);
211
+ }
212
+ }
213
+
214
+ async function checkVersion() {
215
+ if (versionChecked || lang === "en") return;
216
+ versionChecked = true;
217
+ try {
218
+ if (adoptVersion(await deps.getVersion())) changed();
219
+ } catch {
220
+ // Offline, signed out or an older API: keep the cache.
221
+ }
222
+ }
223
+
224
+ function tr(text: unknown): any {
225
+ if (lang === "en" || forcedEnglish || !isInterfaceText(text)) return text;
226
+ const key = text.trim();
227
+ const hit = dict[key];
228
+ if (hit) {
229
+ const start = text.indexOf(key);
230
+ return text.slice(0, start) + hit + text.slice(start + key.length);
231
+ }
232
+ if (!failed.has(key) && !stopped) {
233
+ pending.add(key);
234
+ scheduleFlush();
235
+ }
236
+ return text;
237
+ }
238
+
239
+ const headerMemo = new WeakMap<object, { stamp: string; out: any[] }>();
240
+
241
+ /** Column titles of a v-data-table `headers` array (developer labels). */
242
+ function trHeaders(headers: any): any {
243
+ if (!Array.isArray(headers) || lang === "en" || forcedEnglish) return headers;
244
+ const stamp = `${lang}:${revision}`;
245
+ const memo = headerMemo.get(headers);
246
+ if (memo && memo.stamp === stamp) return memo.out;
247
+ const out = headers.map((h) => {
248
+ if (!h || typeof h !== "object") return h;
249
+ const next = { ...h };
250
+ if (typeof h.title === "string") next.title = tr(h.title);
251
+ if (Array.isArray(h.children)) next.children = trHeaders(h.children);
252
+ return next;
253
+ });
254
+ headerMemo.set(headers, { stamp, out });
255
+ return out;
256
+ }
257
+
258
+ function setLanguage(code: string) {
259
+ if (!known.has(code) || code === lang) return;
260
+ lang = code;
261
+ safe(() => storage?.setItem(UI_TR_LANG_KEY, code), undefined);
262
+ pending.clear();
263
+ stopped = false;
264
+ loadDict();
265
+ changed();
266
+ void checkVersion();
267
+ }
268
+
269
+ function setForcedEnglish(on: boolean) {
270
+ if (forcedEnglish === on) return;
271
+ forcedEnglish = on;
272
+ changed();
273
+ }
274
+
275
+ loadDict();
276
+
277
+ return {
278
+ tr,
279
+ trHeaders,
280
+ setLanguage,
281
+ setForcedEnglish,
282
+ checkVersion,
283
+ flush,
284
+ get language() {
285
+ return lang;
286
+ },
287
+ get version() {
288
+ return version;
289
+ },
290
+ get pendingCount() {
291
+ return pending.size;
292
+ },
293
+ };
294
+ }