@inglorious/ssx 2.1.20 → 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.
@@ -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
package/types/i18n.d.ts DELETED
@@ -1,6 +0,0 @@
1
- export interface I18nConfig {
2
- defaultLocale: string
3
- locales: string[]
4
- }
5
-
6
- export function getLocaleFromPath(pathname: string, config: I18nConfig): string