@inglorious/ssx 2.2.0 → 2.3.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 +1 -1
- package/package.json +7 -7
- package/src/build/pages.js +3 -0
- package/src/build/pages.test.js +18 -3
- package/src/client.js +4 -0
- package/src/render/index.js +13 -3
- package/src/render/layout.js +3 -1
- package/src/render/layout.test.js +7 -2
- package/src/render/render.test.js +109 -0
- package/src/scripts/app.js +34 -12
- package/src/scripts/app.test.js +50 -10
- package/src/ssr/index.js +3 -0
- package/src/utils/i18n.js +84 -0
- package/src/utils/i18n.test.js +121 -0
- package/src/utils/page-head.js +127 -0
- package/src/utils/page-head.test.js +202 -0
- package/types/client.d.ts +22 -0
- package/types/i18n.d.ts +0 -6
package/README.md
CHANGED
|
@@ -312,7 +312,7 @@ Notes:
|
|
|
312
312
|
|
|
313
313
|
- The default locale is not prefixed (`/about`, not `/en/about`).
|
|
314
314
|
- Locale-prefixed routes are handled in both build output and client-side navigation.
|
|
315
|
-
- SSX picks the locale; to translate strings (catalogues, plurals, dates, markup in translations), use [`@inglorious/i18n`](https://www.npmjs.com/package/@inglorious/i18n)
|
|
315
|
+
- SSX picks the locale; to translate strings (catalogues, plurals, dates, markup in translations), use [`@inglorious/i18n`](https://www.npmjs.com/package/@inglorious/i18n) with its entity named `i18n`. SSX switches it to the locale of each page and loads that catalogue before `load` runs and the page renders, on the server and before the client hydrates, so translations always match the URL rather than the browser's language. Translate inside `render`, `load` or a `metadata` function rather than when a module is imported, so each page gets its own language.
|
|
316
316
|
|
|
317
317
|
### ⚛️ Entity-Based State and Behavior
|
|
318
318
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inglorious/ssx",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"description": "Server-Side-X. Xecution? Xperience? Who knows.",
|
|
5
5
|
"author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
|
|
6
6
|
"license": "MIT",
|
|
@@ -32,9 +32,9 @@
|
|
|
32
32
|
"./serve": "./src/serve/index.js",
|
|
33
33
|
"./ssr": "./src/ssr/index.js",
|
|
34
34
|
"./markdown": "./src/utils/markdown.js",
|
|
35
|
-
"./
|
|
36
|
-
"types": "./types/
|
|
37
|
-
"import": "./src/
|
|
35
|
+
"./client": {
|
|
36
|
+
"types": "./types/client.d.ts",
|
|
37
|
+
"import": "./src/client.js"
|
|
38
38
|
}
|
|
39
39
|
},
|
|
40
40
|
"files": [
|
|
@@ -49,9 +49,9 @@
|
|
|
49
49
|
},
|
|
50
50
|
"sideEffects": false,
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"@inglorious/store": "12.
|
|
52
|
+
"@inglorious/store": "12.1.0",
|
|
53
53
|
"@inglorious/utils": "5.1.0",
|
|
54
|
-
"@inglorious/web": "6.
|
|
54
|
+
"@inglorious/web": "6.10.0",
|
|
55
55
|
"@lit-labs/ssr": "^4.1.0",
|
|
56
56
|
"commander": "^15.0.0",
|
|
57
57
|
"connect": "^3.7.0",
|
|
@@ -70,7 +70,7 @@
|
|
|
70
70
|
},
|
|
71
71
|
"devDependencies": {
|
|
72
72
|
"@inglorious/eslint-config": "1.2.0",
|
|
73
|
-
"@inglorious/logo": "3.0.
|
|
73
|
+
"@inglorious/logo": "3.0.25",
|
|
74
74
|
"prettier": "^3.9.6",
|
|
75
75
|
"vitest": "^5.0.0"
|
|
76
76
|
},
|
package/src/build/pages.js
CHANGED
|
@@ -2,6 +2,7 @@ import path from "node:path"
|
|
|
2
2
|
import { pathToFileURL } from "node:url"
|
|
3
3
|
|
|
4
4
|
import { renderPage } from "../render/index.js"
|
|
5
|
+
import { waitForLocale } from "../utils/i18n.js"
|
|
5
6
|
import { extractPageMetadata } from "./metadata.js"
|
|
6
7
|
|
|
7
8
|
/**
|
|
@@ -42,6 +43,8 @@ export async function generatePages(store, pages, options = {}, loader) {
|
|
|
42
43
|
if (page.locale) {
|
|
43
44
|
entity.locale = page.locale
|
|
44
45
|
}
|
|
46
|
+
// Translations in the page's locale, for `load` and the render.
|
|
47
|
+
await waitForLocale(store, page.locale)
|
|
45
48
|
|
|
46
49
|
if (module.load) {
|
|
47
50
|
await module.load(entity, page)
|
package/src/build/pages.test.js
CHANGED
|
@@ -42,7 +42,11 @@ describe("generatePages", () => {
|
|
|
42
42
|
|
|
43
43
|
it("should generate HTML and metadata by default", async () => {
|
|
44
44
|
const store = {
|
|
45
|
-
_api: {
|
|
45
|
+
_api: {
|
|
46
|
+
getEntities: vi.fn(() => []),
|
|
47
|
+
getEntity: vi.fn(() => ({})),
|
|
48
|
+
getType: vi.fn(),
|
|
49
|
+
},
|
|
46
50
|
}
|
|
47
51
|
const pages = [{ path: "/p1", filePath: pageFile, moduleName: "p1" }]
|
|
48
52
|
|
|
@@ -60,7 +64,11 @@ describe("generatePages", () => {
|
|
|
60
64
|
|
|
61
65
|
it("should skip HTML generation when disabled", async () => {
|
|
62
66
|
const store = {
|
|
63
|
-
_api: {
|
|
67
|
+
_api: {
|
|
68
|
+
getEntities: vi.fn(() => []),
|
|
69
|
+
getEntity: vi.fn(() => ({})),
|
|
70
|
+
getType: vi.fn(),
|
|
71
|
+
},
|
|
64
72
|
}
|
|
65
73
|
const pages = [{ path: "/p2", filePath: pageFile, moduleName: "p2" }]
|
|
66
74
|
|
|
@@ -76,7 +84,11 @@ describe("generatePages", () => {
|
|
|
76
84
|
|
|
77
85
|
it("should skip metadata generation when disabled", async () => {
|
|
78
86
|
const store = {
|
|
79
|
-
_api: {
|
|
87
|
+
_api: {
|
|
88
|
+
getEntities: vi.fn(() => []),
|
|
89
|
+
getEntity: vi.fn(() => ({})),
|
|
90
|
+
getType: vi.fn(),
|
|
91
|
+
},
|
|
80
92
|
}
|
|
81
93
|
const pages = [{ path: "/p3", filePath: pageFile, moduleName: "p3" }]
|
|
82
94
|
|
|
@@ -97,6 +109,7 @@ describe("generatePages", () => {
|
|
|
97
109
|
_api: {
|
|
98
110
|
getEntities: vi.fn(() => [entity]),
|
|
99
111
|
getEntity: vi.fn(() => entity),
|
|
112
|
+
getType: vi.fn(),
|
|
100
113
|
},
|
|
101
114
|
}
|
|
102
115
|
const pages = [
|
|
@@ -124,6 +137,7 @@ describe("generatePages", () => {
|
|
|
124
137
|
_api: {
|
|
125
138
|
getEntities: vi.fn(() => [entity]),
|
|
126
139
|
getEntity: vi.fn(() => entity),
|
|
140
|
+
getType: vi.fn(),
|
|
127
141
|
},
|
|
128
142
|
}
|
|
129
143
|
const pages = [
|
|
@@ -156,6 +170,7 @@ describe("generatePages", () => {
|
|
|
156
170
|
_api: {
|
|
157
171
|
getEntities: vi.fn(() => [{}]),
|
|
158
172
|
getEntity: vi.fn(() => ({})),
|
|
173
|
+
getType: vi.fn(),
|
|
159
174
|
},
|
|
160
175
|
}
|
|
161
176
|
const pages = [{ path: "/ssr", filePath: pageFile, moduleName: "ssr" }]
|
package/src/client.js
ADDED
package/src/render/index.js
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { toCamelCase } from "@inglorious/utils/data-structures/string.js"
|
|
2
2
|
|
|
3
|
+
import { getTextDirection, selectLocale } from "../utils/i18n.js"
|
|
3
4
|
import { createGetPageOption } from "../utils/page-options.js"
|
|
4
5
|
import { toHTML } from "./html.js"
|
|
5
6
|
|
|
7
|
+
// Empty, so the site options apply; the layout supplies the final defaults.
|
|
6
8
|
const DEFAULT_OPTIONS = {
|
|
7
|
-
lang: "
|
|
8
|
-
|
|
9
|
+
lang: "",
|
|
10
|
+
dir: "",
|
|
11
|
+
charset: "",
|
|
9
12
|
title: "",
|
|
10
13
|
favicon: "",
|
|
11
14
|
meta: {},
|
|
@@ -28,9 +31,15 @@ export async function renderPage(store, page, entity, options = {}) {
|
|
|
28
31
|
const { moduleName, module } = page
|
|
29
32
|
const entityId = entity?.id ?? toCamelCase(moduleName)
|
|
30
33
|
|
|
34
|
+
// Before anything translates, and with nothing awaited until the templates are built,
|
|
35
|
+
// so that other renders sharing the translations cannot switch them in between.
|
|
36
|
+
selectLocale(store, entity?.locale)
|
|
37
|
+
|
|
31
38
|
const getPageOption = createGetPageOption(store, module, entity)
|
|
32
39
|
|
|
33
|
-
const lang =
|
|
40
|
+
const lang =
|
|
41
|
+
getPageOption("lang", DEFAULT_OPTIONS) || entity?.locale || options.lang
|
|
42
|
+
const dir = getPageOption("dir", DEFAULT_OPTIONS) || getTextDirection(lang)
|
|
34
43
|
const charset = getPageOption("charset", DEFAULT_OPTIONS) || options.charset
|
|
35
44
|
const title = getPageOption("title", DEFAULT_OPTIONS) || options.title
|
|
36
45
|
const favicon = getPageOption("favicon", DEFAULT_OPTIONS) || options.favicon
|
|
@@ -48,6 +57,7 @@ export async function renderPage(store, page, entity, options = {}) {
|
|
|
48
57
|
return toHTML(store, (api) => api.render(entityId), {
|
|
49
58
|
...options,
|
|
50
59
|
lang,
|
|
60
|
+
dir,
|
|
51
61
|
charset,
|
|
52
62
|
title,
|
|
53
63
|
favicon,
|
package/src/render/layout.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* @param {string} body - The body content HTML.
|
|
5
5
|
* @param {Object} options - Layout options.
|
|
6
6
|
* @param {string} [options.lang="en"] - Language attribute.
|
|
7
|
+
* @param {"ltr" | "rtl"} [options.dir="ltr"] - Text direction attribute.
|
|
7
8
|
* @param {string} [options.charset="UTF-8"] - Character set.
|
|
8
9
|
* @param {string} [options.title=""] - Page title.
|
|
9
10
|
* @param {string} [options.favicon=""] - Favicon URL; without one, no icon link is rendered.
|
|
@@ -17,6 +18,7 @@
|
|
|
17
18
|
export function layout(body, options) {
|
|
18
19
|
const {
|
|
19
20
|
lang = "en",
|
|
21
|
+
dir = "ltr",
|
|
20
22
|
head = "",
|
|
21
23
|
prescripts = [],
|
|
22
24
|
charset = "UTF-8",
|
|
@@ -29,7 +31,7 @@ export function layout(body, options) {
|
|
|
29
31
|
} = options
|
|
30
32
|
|
|
31
33
|
return `<!DOCTYPE html>
|
|
32
|
-
<html lang="${lang}">
|
|
34
|
+
<html lang="${lang}" dir="${dir}">
|
|
33
35
|
<head>
|
|
34
36
|
${prescripts
|
|
35
37
|
.map((src) => `<script type="text/javascript" src="${src}"></script>`)
|
|
@@ -6,7 +6,7 @@ describe("layout", () => {
|
|
|
6
6
|
it("should render default layout structure", () => {
|
|
7
7
|
const html = layout("<h1>Hello</h1>", {})
|
|
8
8
|
expect(html).toContain("<!DOCTYPE html>")
|
|
9
|
-
expect(html).toContain('<html lang="en">')
|
|
9
|
+
expect(html).toContain('<html lang="en" dir="ltr">')
|
|
10
10
|
expect(html).toContain('<meta charset="UTF-8" />')
|
|
11
11
|
expect(html).toContain('<div id="root"><h1>Hello</h1></div>')
|
|
12
12
|
expect(html).toContain('<script type="module" src="/main.js"></script>')
|
|
@@ -15,7 +15,7 @@ describe("layout", () => {
|
|
|
15
15
|
it("should render with custom title and language", () => {
|
|
16
16
|
const html = layout("", { title: "My Page", lang: "fr" })
|
|
17
17
|
expect(html).toContain("<title>My Page</title>")
|
|
18
|
-
expect(html).toContain('<html lang="fr">')
|
|
18
|
+
expect(html).toContain('<html lang="fr" dir="ltr">')
|
|
19
19
|
})
|
|
20
20
|
|
|
21
21
|
it("should render meta tags", () => {
|
|
@@ -79,4 +79,9 @@ describe("layout", () => {
|
|
|
79
79
|
const html = layout("", { isDev: false })
|
|
80
80
|
expect(html).not.toContain("/@vite/client")
|
|
81
81
|
})
|
|
82
|
+
|
|
83
|
+
it("should set the text direction", () => {
|
|
84
|
+
const html = layout("", { lang: "he", dir: "rtl" })
|
|
85
|
+
expect(html).toContain('<html lang="he" dir="rtl">')
|
|
86
|
+
})
|
|
82
87
|
})
|
|
@@ -2,6 +2,7 @@ import path from "node:path"
|
|
|
2
2
|
import { pathToFileURL } from "node:url"
|
|
3
3
|
|
|
4
4
|
import { createStore } from "@inglorious/store"
|
|
5
|
+
import { html } from "@inglorious/web"
|
|
5
6
|
import { describe, expect, it } from "vitest"
|
|
6
7
|
|
|
7
8
|
import { renderPage } from "."
|
|
@@ -112,4 +113,112 @@ describe("renderPage", () => {
|
|
|
112
113
|
|
|
113
114
|
expect(html).toMatchSnapshot()
|
|
114
115
|
})
|
|
116
|
+
|
|
117
|
+
it("should set the document language from the page locale", async () => {
|
|
118
|
+
const module = await import(pathToFileURL(path.join(PAGES_DIR, "about.js")))
|
|
119
|
+
const page = { path: "/it/about", moduleName: "about", module }
|
|
120
|
+
const entity = { type: "About", name: "Noi", locale: "it" }
|
|
121
|
+
|
|
122
|
+
const store = createStore({
|
|
123
|
+
types: { About: module.About },
|
|
124
|
+
entities: { about: entity },
|
|
125
|
+
updateMode: "manual",
|
|
126
|
+
})
|
|
127
|
+
store.update()
|
|
128
|
+
|
|
129
|
+
const html = await renderPage(store, page, entity, {
|
|
130
|
+
...DEFAULT_OPTIONS,
|
|
131
|
+
wrap: true,
|
|
132
|
+
lang: "en",
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
expect(html).toContain(`<html lang="it" dir="ltr">`)
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
it("should prefer the language set in the page metadata", async () => {
|
|
139
|
+
const About = { render: () => "" }
|
|
140
|
+
const module = { About, metadata: { lang: "pt" } }
|
|
141
|
+
const page = { path: "/it/about", moduleName: "about", module }
|
|
142
|
+
const entity = { type: "About", locale: "it" }
|
|
143
|
+
|
|
144
|
+
const store = createStore({
|
|
145
|
+
types: { About },
|
|
146
|
+
entities: { about: entity },
|
|
147
|
+
updateMode: "manual",
|
|
148
|
+
})
|
|
149
|
+
store.update()
|
|
150
|
+
|
|
151
|
+
const html = await renderPage(store, page, entity, {
|
|
152
|
+
...DEFAULT_OPTIONS,
|
|
153
|
+
wrap: true,
|
|
154
|
+
lang: "en",
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
expect(html).toContain(`<html lang="pt" dir="ltr">`)
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
it("should fall back to the site language and charset", async () => {
|
|
161
|
+
const About = { render: () => "" }
|
|
162
|
+
const page = { path: "/about", moduleName: "about", module: { About } }
|
|
163
|
+
const entity = { type: "About" }
|
|
164
|
+
|
|
165
|
+
const store = createStore({
|
|
166
|
+
types: { About },
|
|
167
|
+
entities: { about: entity },
|
|
168
|
+
updateMode: "manual",
|
|
169
|
+
})
|
|
170
|
+
store.update()
|
|
171
|
+
|
|
172
|
+
const html = await renderPage(store, page, entity, {
|
|
173
|
+
...DEFAULT_OPTIONS,
|
|
174
|
+
wrap: true,
|
|
175
|
+
lang: "it",
|
|
176
|
+
charset: "ISO-8859-1",
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
expect(html).toContain(`<html lang="it" dir="ltr">`)
|
|
180
|
+
expect(html).toContain(`<meta charset="ISO-8859-1" />`)
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
it("should write right-to-left languages right to left", async () => {
|
|
184
|
+
const About = { render: () => "" }
|
|
185
|
+
const page = { path: "/ar/about", moduleName: "about", module: { About } }
|
|
186
|
+
const entity = { type: "About", locale: "ar" }
|
|
187
|
+
|
|
188
|
+
const store = createStore({
|
|
189
|
+
types: { About },
|
|
190
|
+
entities: { about: entity },
|
|
191
|
+
updateMode: "manual",
|
|
192
|
+
})
|
|
193
|
+
store.update()
|
|
194
|
+
|
|
195
|
+
const html = await renderPage(store, page, entity, {
|
|
196
|
+
...DEFAULT_OPTIONS,
|
|
197
|
+
wrap: true,
|
|
198
|
+
})
|
|
199
|
+
|
|
200
|
+
expect(html).toContain(`<html lang="ar" dir="rtl">`)
|
|
201
|
+
})
|
|
202
|
+
|
|
203
|
+
it("should render in the page's locale", async () => {
|
|
204
|
+
let language = "en"
|
|
205
|
+
const messages = { en: "Hello", it: "Ciao" }
|
|
206
|
+
const I18n = {
|
|
207
|
+
localeChange(entity, locale) {
|
|
208
|
+
entity.locale = language = locale
|
|
209
|
+
},
|
|
210
|
+
}
|
|
211
|
+
const Hello = { render: () => html`<p>${messages[language]}</p>` }
|
|
212
|
+
const page = { path: "/it/hello", moduleName: "hello", module: { Hello } }
|
|
213
|
+
const entity = { type: "Hello", locale: "it" }
|
|
214
|
+
|
|
215
|
+
const store = createStore({
|
|
216
|
+
types: { I18n, Hello },
|
|
217
|
+
entities: { i18n: { type: "I18n", locale: "en" }, hello: entity },
|
|
218
|
+
})
|
|
219
|
+
|
|
220
|
+
const output = await renderPage(store, page, entity, DEFAULT_OPTIONS)
|
|
221
|
+
|
|
222
|
+
expect(output).toContain("Ciao")
|
|
223
|
+
})
|
|
115
224
|
})
|
package/src/scripts/app.js
CHANGED
|
@@ -8,6 +8,9 @@ import { getStoreStuff } from "../store/stuff.js"
|
|
|
8
8
|
* @param {Object} [options] - Runtime options.
|
|
9
9
|
* @param {boolean} [options.hasTypesFile] - Whether src/store/types.js exists.
|
|
10
10
|
* @param {boolean} [options.hasEntitiesFile] - Whether src/store/entities.js exists.
|
|
11
|
+
* @param {string} [options.title] - The site title, used when a page sets none.
|
|
12
|
+
* @param {string} [options.lang] - The site language, used when a page sets none.
|
|
13
|
+
* @param {Object} [options.meta] - Meta tags shared by every page.
|
|
11
14
|
* @returns {string} The generated JavaScript code for the client entry point.
|
|
12
15
|
*/
|
|
13
16
|
export async function generateApp(pages, options = {}, loader) {
|
|
@@ -26,7 +29,7 @@ export async function generateApp(pages, options = {}, loader) {
|
|
|
26
29
|
if (routesByPattern.has(routePattern)) continue
|
|
27
30
|
routesByPattern.set(
|
|
28
31
|
routePattern,
|
|
29
|
-
` "${routePattern}": () => import("@/pages/${page.modulePath}")`,
|
|
32
|
+
` "${routePattern}": loadPage(${JSON.stringify(page.moduleName)}, () => import("@/pages/${page.modulePath}"))`,
|
|
30
33
|
)
|
|
31
34
|
}
|
|
32
35
|
const routes = [...routesByPattern.values()]
|
|
@@ -52,7 +55,7 @@ import { createStore } from "@inglorious/store"
|
|
|
52
55
|
import { createDevtools } from "@inglorious/store/client/devtools"
|
|
53
56
|
import { mount } from "@inglorious/web"
|
|
54
57
|
import { Router, getRoute, setRoutes } from "@inglorious/web/router"
|
|
55
|
-
import { getLocaleFromPath } from "@inglorious/ssx/
|
|
58
|
+
import { getLocaleFromPath, syncPageHead, waitForLocale } from "@inglorious/ssx/client"
|
|
56
59
|
|
|
57
60
|
${typesImport}
|
|
58
61
|
${entitiesImport}
|
|
@@ -108,7 +111,6 @@ const toCamelCase = (str) => {
|
|
|
108
111
|
|
|
109
112
|
const entities = {
|
|
110
113
|
router: { type: "Router", path, route: toCamelCase(page?.moduleName) },
|
|
111
|
-
i18n: { type: "I18n", ...i18n },
|
|
112
114
|
}
|
|
113
115
|
${entitiesAssignment}
|
|
114
116
|
Object.assign(entities, JSON.parse(document.getElementById("__SSX_PAGE__").textContent))
|
|
@@ -122,18 +124,31 @@ if (isDev) {
|
|
|
122
124
|
const systems = []
|
|
123
125
|
if (i18n.defaultLocale && i18n.locales?.length) {
|
|
124
126
|
systems.push({
|
|
125
|
-
routeChange(state, payload) {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
const entity = state[
|
|
130
|
-
if (
|
|
131
|
-
|
|
132
|
-
|
|
127
|
+
routeChange(state, payload, api) {
|
|
128
|
+
if (!payload?.path) return
|
|
129
|
+
const locale = getLocaleFromPath(payload.path, i18n)
|
|
130
|
+
|
|
131
|
+
const entity = state[payload.route]
|
|
132
|
+
if (entity) entity.locale = locale
|
|
133
|
+
|
|
134
|
+
// The URL decides the locale, as it did for the page the server rendered, so
|
|
135
|
+
// an @inglorious/i18n entity follows it rather than the browser's language.
|
|
136
|
+
const translator = state.i18n
|
|
137
|
+
if (translator?.locale !== locale && api.getType(translator?.type)?.localeChange) {
|
|
138
|
+
api.notify("#i18n:localeChange", locale)
|
|
139
|
+
}
|
|
133
140
|
},
|
|
134
141
|
})
|
|
135
142
|
}
|
|
136
143
|
|
|
144
|
+
// Page modules by type name, kept so client navigation can read their metadata.
|
|
145
|
+
const modules = {}
|
|
146
|
+
const loadPage = (moduleName, load) => async () => {
|
|
147
|
+
const module = await load()
|
|
148
|
+
modules[moduleName] = module
|
|
149
|
+
return module
|
|
150
|
+
}
|
|
151
|
+
|
|
137
152
|
setRoutes({
|
|
138
153
|
${routes.join(",\n")}
|
|
139
154
|
})
|
|
@@ -146,10 +161,17 @@ const store = createStore({ types, entities, middlewares, systems, autoCreateEnt
|
|
|
146
161
|
|
|
147
162
|
const root = document.getElementById("root")
|
|
148
163
|
|
|
164
|
+
if (i18n.defaultLocale && i18n.locales?.length) {
|
|
165
|
+
// Hydrates in the language the server rendered, with its translations loaded.
|
|
166
|
+
await waitForLocale(store, getLocaleFromPath(path, i18n))
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const getPageName = syncPageHead(store, modules, ${JSON.stringify({ title: options.title, lang: options.lang, meta: options.meta })})
|
|
170
|
+
|
|
149
171
|
mount(store, (api) => {
|
|
150
172
|
const { route } = api.getEntity("router")
|
|
151
173
|
return api.render(route)
|
|
152
|
-
}, root)
|
|
174
|
+
}, root, { getPageName })
|
|
153
175
|
`
|
|
154
176
|
}
|
|
155
177
|
|
package/src/scripts/app.test.js
CHANGED
|
@@ -13,10 +13,11 @@ describe("generateApp", () => {
|
|
|
13
13
|
pattern: "/",
|
|
14
14
|
path: "/",
|
|
15
15
|
modulePath: "index.js",
|
|
16
|
+
moduleName: "Index",
|
|
16
17
|
filePath: PAGES_DIR,
|
|
17
18
|
}
|
|
18
19
|
|
|
19
|
-
const app = generateApp([page])
|
|
20
|
+
const app = await generateApp([page])
|
|
20
21
|
|
|
21
22
|
expect(app).toMatchSnapshot()
|
|
22
23
|
})
|
|
@@ -26,10 +27,11 @@ describe("generateApp", () => {
|
|
|
26
27
|
pattern: "/about",
|
|
27
28
|
path: "/about",
|
|
28
29
|
modulePath: "about.js",
|
|
30
|
+
moduleName: "About",
|
|
29
31
|
filePath: path.join(PAGES_DIR, "about.js"),
|
|
30
32
|
}
|
|
31
33
|
|
|
32
|
-
const app = generateApp([page])
|
|
34
|
+
const app = await generateApp([page])
|
|
33
35
|
|
|
34
36
|
expect(app).toMatchSnapshot()
|
|
35
37
|
})
|
|
@@ -39,10 +41,11 @@ describe("generateApp", () => {
|
|
|
39
41
|
pattern: "/blog",
|
|
40
42
|
path: "/blog",
|
|
41
43
|
modulePath: "blog.js",
|
|
44
|
+
moduleName: "Blog",
|
|
42
45
|
filePath: path.join(PAGES_DIR, "blog.js"),
|
|
43
46
|
}
|
|
44
47
|
|
|
45
|
-
const app = generateApp([page])
|
|
48
|
+
const app = await generateApp([page])
|
|
46
49
|
|
|
47
50
|
expect(app).toMatchSnapshot()
|
|
48
51
|
})
|
|
@@ -52,10 +55,11 @@ describe("generateApp", () => {
|
|
|
52
55
|
pattern: "/posts/:slug",
|
|
53
56
|
path: "/posts/my-first-post",
|
|
54
57
|
modulePath: "post.js",
|
|
58
|
+
moduleName: "Post",
|
|
55
59
|
filePath: path.join(PAGES_DIR, "posts", "_slug.js"),
|
|
56
60
|
}
|
|
57
61
|
|
|
58
|
-
const app = generateApp([page])
|
|
62
|
+
const app = await generateApp([page])
|
|
59
63
|
|
|
60
64
|
expect(app).toMatchSnapshot()
|
|
61
65
|
})
|
|
@@ -77,18 +81,30 @@ describe("generateApp", () => {
|
|
|
77
81
|
|
|
78
82
|
const app = await generateApp(localizedPages)
|
|
79
83
|
|
|
80
|
-
expect(app).toContain(
|
|
81
|
-
|
|
82
|
-
|
|
84
|
+
expect(app).toContain(
|
|
85
|
+
`"/hello": loadPage("hello", () => import("@/pages/hello.js"))`,
|
|
86
|
+
)
|
|
87
|
+
expect(app).toContain(
|
|
88
|
+
`"/it/hello": loadPage("hello", () => import("@/pages/hello.js"))`,
|
|
89
|
+
)
|
|
90
|
+
expect(app).toContain(
|
|
91
|
+
`"/pt/hello": loadPage("hello", () => import("@/pages/hello.js"))`,
|
|
92
|
+
)
|
|
83
93
|
expect(app).toContain(`const isDev = false`)
|
|
84
94
|
expect(app).toContain(
|
|
85
|
-
`import { getLocaleFromPath } from "@inglorious/ssx/
|
|
95
|
+
`import { getLocaleFromPath, syncPageHead, waitForLocale } from "@inglorious/ssx/client"`,
|
|
96
|
+
)
|
|
97
|
+
expect(app).toContain(
|
|
98
|
+
`await waitForLocale(store, getLocaleFromPath(path, i18n))`,
|
|
86
99
|
)
|
|
87
100
|
expect(app).toContain(`const systems = []`)
|
|
88
|
-
expect(app).toContain(`routeChange(state, payload)`)
|
|
101
|
+
expect(app).toContain(`routeChange(state, payload, api)`)
|
|
89
102
|
expect(app).toContain(
|
|
90
|
-
`
|
|
103
|
+
`const locale = getLocaleFromPath(payload.path, i18n)`,
|
|
91
104
|
)
|
|
105
|
+
expect(app).toContain(`if (entity) entity.locale = locale`)
|
|
106
|
+
expect(app).toContain(`api.notify("#i18n:localeChange", locale)`)
|
|
107
|
+
expect(app).not.toContain(`type: "I18n"`)
|
|
92
108
|
expect(app).toContain(
|
|
93
109
|
`const path = normalizeRoutePath(window.location.pathname)`,
|
|
94
110
|
)
|
|
@@ -100,4 +116,28 @@ describe("generateApp", () => {
|
|
|
100
116
|
`pages.find((page) => matchesPattern(page.path, path))`,
|
|
101
117
|
)
|
|
102
118
|
})
|
|
119
|
+
|
|
120
|
+
it("should sync the page head with the site defaults as fallback", async () => {
|
|
121
|
+
const page = {
|
|
122
|
+
pattern: "/about",
|
|
123
|
+
path: "/about",
|
|
124
|
+
modulePath: "about.js",
|
|
125
|
+
filePath: path.join(PAGES_DIR, "about.js"),
|
|
126
|
+
moduleName: "About",
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const app = await generateApp([page], {
|
|
130
|
+
title: "My Site",
|
|
131
|
+
lang: "en",
|
|
132
|
+
meta: { description: "A site" },
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
expect(app).toContain(
|
|
136
|
+
`"/about": loadPage("About", () => import("@/pages/about.js"))`,
|
|
137
|
+
)
|
|
138
|
+
expect(app).toContain(
|
|
139
|
+
`const getPageName = syncPageHead(store, modules, {"title":"My Site","lang":"en","meta":{"description":"A site"}})`,
|
|
140
|
+
)
|
|
141
|
+
expect(app).toContain(`}, root, { getPageName })`)
|
|
142
|
+
})
|
|
103
143
|
})
|
package/src/ssr/index.js
CHANGED
|
@@ -10,6 +10,7 @@ import { getPages, matchParams, matchRoute } from "../router/index.js"
|
|
|
10
10
|
import { generateApp } from "../scripts/app.js"
|
|
11
11
|
import { generateStore } from "../store/index.js"
|
|
12
12
|
import { loadConfig } from "../utils/config.js"
|
|
13
|
+
import { waitForLocale } from "../utils/i18n.js"
|
|
13
14
|
|
|
14
15
|
export async function ssr(options = {}) {
|
|
15
16
|
const config = await loadConfig(options)
|
|
@@ -139,6 +140,8 @@ export async function renderRequest(
|
|
|
139
140
|
if (page.locale) {
|
|
140
141
|
entity.locale = page.locale
|
|
141
142
|
}
|
|
143
|
+
// Translations in the page's locale, for `load` and the render.
|
|
144
|
+
await waitForLocale(store, page.locale)
|
|
142
145
|
|
|
143
146
|
if (module.load) {
|
|
144
147
|
await module.load(entity, page)
|
package/src/utils/i18n.js
CHANGED
|
@@ -9,3 +9,87 @@ export function getLocaleFromPath(
|
|
|
9
9
|
if (first && locales.includes(first)) return first
|
|
10
10
|
return defaultLocale
|
|
11
11
|
}
|
|
12
|
+
|
|
13
|
+
// Scripts written right to left, by their ISO 15924 code.
|
|
14
|
+
const RTL_SCRIPTS = new Set([
|
|
15
|
+
"Adlm",
|
|
16
|
+
"Arab",
|
|
17
|
+
"Hebr",
|
|
18
|
+
"Mand",
|
|
19
|
+
"Nkoo",
|
|
20
|
+
"Rohg",
|
|
21
|
+
"Samr",
|
|
22
|
+
"Syrc",
|
|
23
|
+
"Thaa",
|
|
24
|
+
"Yezi",
|
|
25
|
+
])
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The direction a language is written in, for the `dir` of `<html>`. The script comes
|
|
29
|
+
* from the locale itself (`az-Arab`) or, when it names none, the likeliest one (`ar` is
|
|
30
|
+
* written in Arabic script).
|
|
31
|
+
*
|
|
32
|
+
* @param {string} [locale] - A BCP 47 language tag, such as `ar` or `en-US`.
|
|
33
|
+
* @returns {"ltr" | "rtl"} The text direction.
|
|
34
|
+
*/
|
|
35
|
+
export function getTextDirection(locale) {
|
|
36
|
+
if (!locale) return "ltr"
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
const { script } = new Intl.Locale(locale).maximize()
|
|
40
|
+
return RTL_SCRIPTS.has(script) ? "rtl" : "ltr"
|
|
41
|
+
} catch {
|
|
42
|
+
// Not a valid language tag.
|
|
43
|
+
return "ltr"
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// The entity of an app that translates with @inglorious/i18n, by that package's convention.
|
|
48
|
+
const TRANSLATOR_ID = "i18n"
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Switches the app's @inglorious/i18n entity, if it has one, to `locale`. Immediate when
|
|
52
|
+
* the locale's catalogue is loaded, as `waitForLocale` makes sure of: call it right before
|
|
53
|
+
* rendering, so that every translation in the render is in that locale even when renders
|
|
54
|
+
* for other locales share the same i18next instance.
|
|
55
|
+
*
|
|
56
|
+
* @param {Object} store - The application store.
|
|
57
|
+
* @param {string} [locale] - The locale of the page.
|
|
58
|
+
*/
|
|
59
|
+
export function selectLocale(store, locale) {
|
|
60
|
+
if (!locale || !hasTranslator(store)) return
|
|
61
|
+
store.notify(`#${TRANSLATOR_ID}:localeChange`, locale)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Switches the app's @inglorious/i18n entity, if it has one, to `locale`, and resolves
|
|
66
|
+
* once its catalogue has loaded, or failed to. Without such an entity it resolves at once.
|
|
67
|
+
*
|
|
68
|
+
* @param {Object} store - The application store.
|
|
69
|
+
* @param {string} [locale] - The locale of the page.
|
|
70
|
+
* @returns {Promise<void>}
|
|
71
|
+
*/
|
|
72
|
+
export function waitForLocale(store, locale) {
|
|
73
|
+
if (!locale || !hasTranslator(store)) return Promise.resolve()
|
|
74
|
+
|
|
75
|
+
store.notify(`#${TRANSLATOR_ID}:localeChange`, locale)
|
|
76
|
+
|
|
77
|
+
return new Promise((resolve) => {
|
|
78
|
+
let unsubscribe = null
|
|
79
|
+
const isLoaded = () => !store._api.getEntity(TRANSLATOR_ID).loadingLocale
|
|
80
|
+
if (isLoaded()) return resolve()
|
|
81
|
+
|
|
82
|
+
unsubscribe = store.subscribe(() => {
|
|
83
|
+
if (!isLoaded()) return
|
|
84
|
+
unsubscribe()
|
|
85
|
+
resolve()
|
|
86
|
+
})
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function hasTranslator(store) {
|
|
91
|
+
const translator = store._api.getEntity(TRANSLATOR_ID)
|
|
92
|
+
return Boolean(
|
|
93
|
+
translator && store._api.getType(translator.type)?.localeChange,
|
|
94
|
+
)
|
|
95
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { createStore } from "@inglorious/store"
|
|
2
|
+
import { describe, expect, it } from "vitest"
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
getLocaleFromPath,
|
|
6
|
+
getTextDirection,
|
|
7
|
+
selectLocale,
|
|
8
|
+
waitForLocale,
|
|
9
|
+
} from "./i18n"
|
|
10
|
+
|
|
11
|
+
// Stands in for @inglorious/i18n: Italian loads later, English is loaded already.
|
|
12
|
+
function createTranslatorStore({ loads = {} } = {}) {
|
|
13
|
+
const loaded = new Set(["en"])
|
|
14
|
+
const I18n = {
|
|
15
|
+
localeChange(entity, locale, api) {
|
|
16
|
+
entity.loadingLocale = null
|
|
17
|
+
if (loaded.has(locale)) {
|
|
18
|
+
entity.locale = locale
|
|
19
|
+
return
|
|
20
|
+
}
|
|
21
|
+
entity.loadingLocale = locale
|
|
22
|
+
new Promise((resolve) => (loads[locale] = resolve)).then(() => {
|
|
23
|
+
loaded.add(locale)
|
|
24
|
+
api.notify("#i18n:localeLoadSuccess", locale)
|
|
25
|
+
})
|
|
26
|
+
},
|
|
27
|
+
localeLoadSuccess(entity, locale) {
|
|
28
|
+
entity.loadingLocale = null
|
|
29
|
+
entity.locale = locale
|
|
30
|
+
},
|
|
31
|
+
}
|
|
32
|
+
return createStore({
|
|
33
|
+
types: { I18n },
|
|
34
|
+
entities: { i18n: { type: "I18n", locale: "en", loadingLocale: null } },
|
|
35
|
+
})
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
describe("getLocaleFromPath", () => {
|
|
39
|
+
const config = { defaultLocale: "en", locales: ["en", "it", "ar"] }
|
|
40
|
+
|
|
41
|
+
it("should read the locale from the first path segment", () => {
|
|
42
|
+
expect(getLocaleFromPath("/it/about?x=1#top", config)).toBe("it")
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it("should fall back to the default locale", () => {
|
|
46
|
+
expect(getLocaleFromPath("/about", config)).toBe("en")
|
|
47
|
+
expect(getLocaleFromPath("/fr/about", config)).toBe("en")
|
|
48
|
+
})
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
describe("getTextDirection", () => {
|
|
52
|
+
it("should be right to left for languages written in a right-to-left script", () => {
|
|
53
|
+
for (const locale of ["ar", "he", "fa", "ur", "yi", "dv", "ar-EG"]) {
|
|
54
|
+
expect(getTextDirection(locale)).toBe("rtl")
|
|
55
|
+
}
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it("should follow a script named in the locale", () => {
|
|
59
|
+
expect(getTextDirection("az-Arab")).toBe("rtl")
|
|
60
|
+
expect(getTextDirection("ks-Deva")).toBe("ltr")
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it("should be left to right otherwise", () => {
|
|
64
|
+
for (const locale of ["en", "it", "zh", "ja", "ru"]) {
|
|
65
|
+
expect(getTextDirection(locale)).toBe("ltr")
|
|
66
|
+
}
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
it("should be left to right without a valid locale", () => {
|
|
70
|
+
expect(getTextDirection(undefined)).toBe("ltr")
|
|
71
|
+
expect(getTextDirection("not a tag")).toBe("ltr")
|
|
72
|
+
})
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
describe("waitForLocale", () => {
|
|
76
|
+
it("should resolve once the locale's translations have loaded", async () => {
|
|
77
|
+
const loads = {}
|
|
78
|
+
const store = createTranslatorStore({ loads })
|
|
79
|
+
let isDone = false
|
|
80
|
+
|
|
81
|
+
const waiting = waitForLocale(store, "it").then(() => (isDone = true))
|
|
82
|
+
await Promise.resolve()
|
|
83
|
+
expect(isDone).toBe(false)
|
|
84
|
+
|
|
85
|
+
loads.it()
|
|
86
|
+
await waiting
|
|
87
|
+
|
|
88
|
+
expect(store.getState().i18n.locale).toBe("it")
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
it("should resolve at once for a loaded locale", async () => {
|
|
92
|
+
const store = createTranslatorStore()
|
|
93
|
+
|
|
94
|
+
await waitForLocale(store, "en")
|
|
95
|
+
|
|
96
|
+
expect(store.getState().i18n.locale).toBe("en")
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
it("should resolve at once for an app that does not translate", async () => {
|
|
100
|
+
const store = createStore({ types: {}, entities: {} })
|
|
101
|
+
|
|
102
|
+
await expect(waitForLocale(store, "it")).resolves.toBeUndefined()
|
|
103
|
+
})
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
describe("selectLocale", () => {
|
|
107
|
+
it("should switch the translations at once", () => {
|
|
108
|
+
const store = createTranslatorStore()
|
|
109
|
+
store.notify("#i18n:localeChange", "fr")
|
|
110
|
+
|
|
111
|
+
selectLocale(store, "en")
|
|
112
|
+
|
|
113
|
+
expect(store.getState().i18n.locale).toBe("en")
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
it("should leave an app that does not translate alone", () => {
|
|
117
|
+
const store = createStore({ types: {}, entities: {} })
|
|
118
|
+
|
|
119
|
+
expect(() => selectLocale(store, "it")).not.toThrow()
|
|
120
|
+
})
|
|
121
|
+
})
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { getTextDirection } from "./i18n.js"
|
|
2
|
+
import { createGetPageOption } from "./page-options.js"
|
|
3
|
+
|
|
4
|
+
const DEFAULT_OPTIONS = { title: "", lang: "", dir: "", meta: {} }
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Keeps the document in step with the current page during client-side navigation.
|
|
8
|
+
* The server renders the head of the page the visitor lands on; after that, the title,
|
|
9
|
+
* the meta tags and the `lang` and `dir` of `<html>` follow the page's `metadata`, merged
|
|
10
|
+
* over the site defaults the same way the server merges them, with the page's locale ahead
|
|
11
|
+
* of the site language and the direction following the language.
|
|
12
|
+
*
|
|
13
|
+
* The metadata is read again whenever the store changes, so values computed from entity
|
|
14
|
+
* data pick up data fetched after the route change.
|
|
15
|
+
*
|
|
16
|
+
* The title it returns a reader for is what `mount` announces after a navigation, so a
|
|
17
|
+
* title that waits for data is announced once that data arrives.
|
|
18
|
+
*
|
|
19
|
+
* @param {Object} store - The application store.
|
|
20
|
+
* @param {Object<string, Object>} modules - Loaded page modules, keyed by page type name.
|
|
21
|
+
* @param {Object} [site] - Site-wide defaults from the site config.
|
|
22
|
+
* @param {string} [site.title=""] - The title used when a page sets none.
|
|
23
|
+
* @param {string} [site.lang="en"] - The language used when a page sets none.
|
|
24
|
+
* @param {Object<string, string>} [site.meta={}] - Meta tags shared by every page.
|
|
25
|
+
* @returns {function(): (string | null)} The current page title, or `null` while it is not
|
|
26
|
+
* known yet: `mount`'s `getPageName`.
|
|
27
|
+
*/
|
|
28
|
+
export function syncPageHead(store, modules, site = {}) {
|
|
29
|
+
const {
|
|
30
|
+
title: siteTitle = "",
|
|
31
|
+
lang: siteLang = "en",
|
|
32
|
+
meta: siteMeta = {},
|
|
33
|
+
} = site
|
|
34
|
+
|
|
35
|
+
const getHead = () => {
|
|
36
|
+
const head = readPageHead(store, modules)
|
|
37
|
+
if (!head) return null
|
|
38
|
+
|
|
39
|
+
const lang = head.lang || siteLang
|
|
40
|
+
return {
|
|
41
|
+
title: head.title || siteTitle,
|
|
42
|
+
lang,
|
|
43
|
+
dir: head.dir || getTextDirection(lang),
|
|
44
|
+
meta: { ...siteMeta, ...head.meta },
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
let head = getHead()
|
|
49
|
+
|
|
50
|
+
store.subscribe(() => {
|
|
51
|
+
const nextHead = getHead()
|
|
52
|
+
if (!nextHead) return
|
|
53
|
+
|
|
54
|
+
applyHead(nextHead, head)
|
|
55
|
+
head = nextHead
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
return () => getHead()?.title ?? null
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function readPageHead(store, modules) {
|
|
62
|
+
const { route } = store._api.getEntity("router")
|
|
63
|
+
const entity = store._api.getEntity(route)
|
|
64
|
+
const module = entity && modules[entity.type]
|
|
65
|
+
if (!module) return null
|
|
66
|
+
|
|
67
|
+
try {
|
|
68
|
+
const getPageOption = createGetPageOption(store, module, entity)
|
|
69
|
+
return {
|
|
70
|
+
title: getPageOption("title", DEFAULT_OPTIONS),
|
|
71
|
+
lang: getPageOption("lang", DEFAULT_OPTIONS) || entity.locale,
|
|
72
|
+
dir: getPageOption("dir", DEFAULT_OPTIONS),
|
|
73
|
+
meta: getPageOption("meta", DEFAULT_OPTIONS),
|
|
74
|
+
}
|
|
75
|
+
} catch {
|
|
76
|
+
// Metadata computed from entity data throws until that data arrives.
|
|
77
|
+
return null
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function applyHead(head, previous) {
|
|
82
|
+
if (document.title !== head.title) {
|
|
83
|
+
document.title = head.title
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const root = document.documentElement
|
|
87
|
+
if (root.lang !== head.lang) {
|
|
88
|
+
root.lang = head.lang
|
|
89
|
+
}
|
|
90
|
+
if (root.dir !== head.dir) {
|
|
91
|
+
root.dir = head.dir
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Only tags named by this page or the previous one are touched, so those the
|
|
95
|
+
// layout writes on its own stay as they are.
|
|
96
|
+
const names = new Set([
|
|
97
|
+
...Object.keys(previous?.meta ?? {}),
|
|
98
|
+
...Object.keys(head.meta),
|
|
99
|
+
])
|
|
100
|
+
for (const name of names) {
|
|
101
|
+
applyMeta(name, head.meta[name])
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function applyMeta(name, content) {
|
|
106
|
+
// The server writes Open Graph style names, such as og:image, as `property`.
|
|
107
|
+
const attribute = name.includes(":") ? "property" : "name"
|
|
108
|
+
let tag = [...document.head.querySelectorAll("meta")].find(
|
|
109
|
+
(meta) => meta.getAttribute(attribute) === name,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
if (content == null) {
|
|
113
|
+
tag?.remove()
|
|
114
|
+
return
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (!tag) {
|
|
118
|
+
tag = document.createElement("meta")
|
|
119
|
+
tag.setAttribute(attribute, name)
|
|
120
|
+
document.head.append(tag)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const value = String(content)
|
|
124
|
+
if (tag.getAttribute("content") !== value) {
|
|
125
|
+
tag.setAttribute("content", value)
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { createStore } from "@inglorious/store"
|
|
2
|
+
import { beforeEach, describe, expect, it } from "vitest"
|
|
3
|
+
|
|
4
|
+
import { syncPageHead } from "./page-head"
|
|
5
|
+
|
|
6
|
+
describe("syncPageHead", () => {
|
|
7
|
+
const Index = { render: () => "" }
|
|
8
|
+
const About = {
|
|
9
|
+
setLocale(entity, locale) {
|
|
10
|
+
entity.locale = locale
|
|
11
|
+
},
|
|
12
|
+
render: () => "",
|
|
13
|
+
}
|
|
14
|
+
const Hello = { render: () => "" }
|
|
15
|
+
const Post = {
|
|
16
|
+
dataFetchSuccess(entity, post) {
|
|
17
|
+
entity.post = post
|
|
18
|
+
},
|
|
19
|
+
render: () => "",
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const modules = {
|
|
23
|
+
Index: { Index },
|
|
24
|
+
About: {
|
|
25
|
+
About,
|
|
26
|
+
metadata: { title: "About", meta: { description: "About us" } },
|
|
27
|
+
},
|
|
28
|
+
Hello: {
|
|
29
|
+
Hello,
|
|
30
|
+
metadata: {
|
|
31
|
+
title: "Ciao",
|
|
32
|
+
lang: "it",
|
|
33
|
+
meta: { "og:title": "Ciao", author: "Me" },
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
Post: { Post, metadata: (entity) => ({ title: entity.post.title }) },
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const Router = {
|
|
40
|
+
navigate(entity, { route, path }) {
|
|
41
|
+
entity.route = route
|
|
42
|
+
entity.path = path
|
|
43
|
+
},
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const site = {
|
|
47
|
+
title: "My Site",
|
|
48
|
+
lang: "en",
|
|
49
|
+
meta: { description: "A site", "og:type": "website" },
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const createTestStore = (route, path) => {
|
|
53
|
+
window.history.replaceState(null, "", path)
|
|
54
|
+
return createStore({
|
|
55
|
+
types: { Router, Index, About, Hello, Post },
|
|
56
|
+
entities: {
|
|
57
|
+
router: { type: "Router", route, path },
|
|
58
|
+
index: { type: "Index" },
|
|
59
|
+
about: { type: "About" },
|
|
60
|
+
hello: { type: "Hello" },
|
|
61
|
+
post: { type: "Post" },
|
|
62
|
+
},
|
|
63
|
+
})
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Navigates the way the router does: the history entry first, then the state change.
|
|
67
|
+
const navigate = (store, route, path) => {
|
|
68
|
+
window.history.pushState(null, "", path)
|
|
69
|
+
store.notify("#router:navigate", { route, path })
|
|
70
|
+
store.update()
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const getMeta = (attribute, name) =>
|
|
74
|
+
[...document.head.querySelectorAll("meta")]
|
|
75
|
+
.find((meta) => meta.getAttribute(attribute) === name)
|
|
76
|
+
?.getAttribute("content")
|
|
77
|
+
|
|
78
|
+
beforeEach(() => {
|
|
79
|
+
document.head.innerHTML = `
|
|
80
|
+
<meta charset="UTF-8">
|
|
81
|
+
<meta name="viewport" content="width=device-width">
|
|
82
|
+
<meta name="description" content="A site">
|
|
83
|
+
<meta property="og:type" content="website">`
|
|
84
|
+
document.title = "Landing"
|
|
85
|
+
document.documentElement.lang = "en"
|
|
86
|
+
document.body.innerHTML = `<a href="/about">About</a>`
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
it("should leave the server-rendered head of the landing page alone", () => {
|
|
90
|
+
const store = createTestStore("about", "/about")
|
|
91
|
+
|
|
92
|
+
syncPageHead(store, modules, site)
|
|
93
|
+
|
|
94
|
+
expect(document.title).toBe("Landing")
|
|
95
|
+
expect(getMeta("name", "description")).toBe("A site")
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
it("should apply the title, lang and meta of the page navigated to", () => {
|
|
99
|
+
const store = createTestStore("index", "/")
|
|
100
|
+
syncPageHead(store, modules, site)
|
|
101
|
+
|
|
102
|
+
navigate(store, "hello", "/hello")
|
|
103
|
+
|
|
104
|
+
expect(document.title).toBe("Ciao")
|
|
105
|
+
expect(document.documentElement.lang).toBe("it")
|
|
106
|
+
expect(getMeta("property", "og:title")).toBe("Ciao")
|
|
107
|
+
expect(getMeta("name", "author")).toBe("Me")
|
|
108
|
+
expect(getMeta("name", "description")).toBe("A site")
|
|
109
|
+
expect(getMeta("property", "og:type")).toBe("website")
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
it("should let page meta override the site meta", () => {
|
|
113
|
+
const store = createTestStore("index", "/")
|
|
114
|
+
syncPageHead(store, modules, site)
|
|
115
|
+
|
|
116
|
+
navigate(store, "about", "/about")
|
|
117
|
+
|
|
118
|
+
expect(getMeta("name", "description")).toBe("About us")
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
it("should fall back to the site defaults and drop the previous page's meta", () => {
|
|
122
|
+
const store = createTestStore("index", "/")
|
|
123
|
+
syncPageHead(store, modules, site)
|
|
124
|
+
navigate(store, "hello", "/hello")
|
|
125
|
+
|
|
126
|
+
navigate(store, "index", "/")
|
|
127
|
+
|
|
128
|
+
expect(document.title).toBe("My Site")
|
|
129
|
+
expect(document.documentElement.lang).toBe("en")
|
|
130
|
+
expect(getMeta("property", "og:title")).toBeUndefined()
|
|
131
|
+
expect(getMeta("name", "author")).toBeUndefined()
|
|
132
|
+
expect(getMeta("name", "description")).toBe("A site")
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
it("should not touch meta tags the layout writes on its own", () => {
|
|
136
|
+
const store = createTestStore("index", "/")
|
|
137
|
+
syncPageHead(store, modules, site)
|
|
138
|
+
|
|
139
|
+
navigate(store, "hello", "/hello")
|
|
140
|
+
|
|
141
|
+
expect(getMeta("name", "viewport")).toBe("width=device-width")
|
|
142
|
+
expect(document.head.querySelector("meta[charset]")).not.toBeNull()
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
it("should return the title of the current page, for mount to announce", () => {
|
|
146
|
+
const store = createTestStore("index", "/")
|
|
147
|
+
const getPageName = syncPageHead(store, modules, site)
|
|
148
|
+
|
|
149
|
+
expect(getPageName()).toBe("My Site")
|
|
150
|
+
|
|
151
|
+
navigate(store, "about", "/about")
|
|
152
|
+
|
|
153
|
+
expect(getPageName()).toBe("About")
|
|
154
|
+
})
|
|
155
|
+
|
|
156
|
+
it("should wait for the data a computed title needs", () => {
|
|
157
|
+
const store = createTestStore("index", "/")
|
|
158
|
+
const getPageName = syncPageHead(store, modules, site)
|
|
159
|
+
|
|
160
|
+
navigate(store, "post", "/posts/hello")
|
|
161
|
+
|
|
162
|
+
expect(document.title).toBe("Landing")
|
|
163
|
+
expect(getPageName()).toBeNull()
|
|
164
|
+
|
|
165
|
+
store.notify("#post:dataFetchSuccess", { title: "Hello" })
|
|
166
|
+
store.update()
|
|
167
|
+
|
|
168
|
+
expect(document.title).toBe("Hello")
|
|
169
|
+
expect(getPageName()).toBe("Hello")
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
it("should set the direction the language is written in", () => {
|
|
173
|
+
const store = createTestStore("index", "/")
|
|
174
|
+
syncPageHead(store, modules, site)
|
|
175
|
+
|
|
176
|
+
store.notify("#about:setLocale", "ar")
|
|
177
|
+
navigate(store, "about", "/ar/about")
|
|
178
|
+
expect(document.documentElement.dir).toBe("rtl")
|
|
179
|
+
|
|
180
|
+
navigate(store, "index", "/")
|
|
181
|
+
expect(document.documentElement.dir).toBe("ltr")
|
|
182
|
+
})
|
|
183
|
+
|
|
184
|
+
it("should take the language from the page locale", () => {
|
|
185
|
+
const store = createTestStore("index", "/")
|
|
186
|
+
syncPageHead(store, modules, site)
|
|
187
|
+
|
|
188
|
+
store.notify("#about:setLocale", "it")
|
|
189
|
+
navigate(store, "about", "/it/about")
|
|
190
|
+
|
|
191
|
+
expect(document.documentElement.lang).toBe("it")
|
|
192
|
+
})
|
|
193
|
+
|
|
194
|
+
it("should leave the head alone for a page that is not loaded yet", () => {
|
|
195
|
+
const store = createTestStore("index", "/")
|
|
196
|
+
syncPageHead(store, {}, site)
|
|
197
|
+
|
|
198
|
+
navigate(store, "about", "/about")
|
|
199
|
+
|
|
200
|
+
expect(document.title).toBe("Landing")
|
|
201
|
+
})
|
|
202
|
+
})
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Store } from "@inglorious/store"
|
|
2
|
+
|
|
3
|
+
export interface I18nConfig {
|
|
4
|
+
defaultLocale: string
|
|
5
|
+
locales: string[]
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface SiteHead {
|
|
9
|
+
title?: string
|
|
10
|
+
lang?: string
|
|
11
|
+
meta?: Record<string, string>
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function getLocaleFromPath(pathname: string, config: I18nConfig): string
|
|
15
|
+
|
|
16
|
+
export function waitForLocale(store: Store, locale?: string): Promise<void>
|
|
17
|
+
|
|
18
|
+
export function syncPageHead(
|
|
19
|
+
store: Store,
|
|
20
|
+
modules: Record<string, Record<string, unknown>>,
|
|
21
|
+
site?: SiteHead,
|
|
22
|
+
): () => string | null
|