@eldrajs/theme-nuxt 0.4.8 → 0.5.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,289 @@
1
+ import { EldraClientError } from "@eldrajs/theme-core";
2
+ import { reactive, watch } from "vue";
3
+ export const PREVIEW_SESSION_META_NAME = "eldra-preview";
4
+ export const PREVIEW_SESSION_META_CONTENT = "session";
5
+ export const PREVIEW_SESSION_PROXY_PATH = "/__eldra/gateway";
6
+ export const PREVIEW_SESSION_EXIT_PATH = "/__eldra/preview/exit";
7
+ export const PREVIEW_SESSION_READY_ATTRIBUTE = "data-eldra-preview-ready";
8
+ const SESSION_HOST = /^p-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.previews(?:-[a-z0-9]+)?\.eldra\.dev$/;
9
+ export function isPreviewSessionHost(hostname) {
10
+ return SESSION_HOST.test(hostname.toLowerCase());
11
+ }
12
+ export function isLocalDevelopmentHost(hostname) {
13
+ const host = hostname.toLowerCase().replace(/\.$/, "");
14
+ return host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1" || host.endsWith(".localhost") || host.endsWith(".test");
15
+ }
16
+ export function hasPreviewSessionMarker(doc) {
17
+ const head = doc.head;
18
+ if (head === null || head === void 0) return false;
19
+ for (const meta of head.querySelectorAll(`meta[name="${PREVIEW_SESSION_META_NAME}"]`)) {
20
+ if (meta.getAttribute("content")?.trim().toLowerCase() === PREVIEW_SESSION_META_CONTENT) {
21
+ return true;
22
+ }
23
+ }
24
+ return false;
25
+ }
26
+ export function detectPreviewSession(win) {
27
+ if (win === void 0) return false;
28
+ const { hostname } = win.location;
29
+ if (isPreviewSessionHost(hostname)) return true;
30
+ return isLocalDevelopmentHost(hostname) && hasPreviewSessionMarker(win.document);
31
+ }
32
+ const state = reactive({
33
+ active: false,
34
+ status: "off",
35
+ errorId: null,
36
+ hydrated: false
37
+ });
38
+ export function usePreviewSession() {
39
+ return state;
40
+ }
41
+ export function isPreviewSessionRefused(status) {
42
+ return status === "expired" || status === "unavailable";
43
+ }
44
+ export function markPreviewSessionDraftShown() {
45
+ if (state.status === "pending") state.status = "ready";
46
+ }
47
+ export function markPreviewSessionHydrated() {
48
+ if (state.active) state.hydrated = true;
49
+ }
50
+ export function previewSessionRefusal(error) {
51
+ if (!(error instanceof EldraClientError) || !error.sessionPreview) return null;
52
+ if (error.status === 401) return { status: "expired", errorId: error.errorId };
53
+ if (error.status === 403 || error.status === 502 || error.status === 503) {
54
+ return { status: "unavailable", errorId: error.errorId };
55
+ }
56
+ return null;
57
+ }
58
+ function refuse(refusal) {
59
+ if (state.status === "expired") return;
60
+ state.status = refusal.status;
61
+ state.errorId = refusal.errorId;
62
+ }
63
+ export function reportPreviewSessionSiteSettingError(error) {
64
+ const refusal = previewSessionRefusal(error);
65
+ if (refusal?.status === "expired") refuse(refusal);
66
+ }
67
+ function trackAppRoot(doc) {
68
+ watch(
69
+ () => state.status,
70
+ (status) => {
71
+ const app = doc.getElementById("__nuxt");
72
+ if (app === null) return;
73
+ const pending = status === "pending";
74
+ if (pending) app.setAttribute("aria-busy", "true");
75
+ else app.removeAttribute("aria-busy");
76
+ app.toggleAttribute("inert", pending || isPreviewSessionRefused(status));
77
+ },
78
+ { immediate: true, flush: "sync" }
79
+ );
80
+ }
81
+ function liftEarlyHide(doc) {
82
+ doc.documentElement.setAttribute(PREVIEW_SESSION_READY_ATTRIBUTE, "");
83
+ }
84
+ function liftEarlyHideOnLeavingVeil(doc) {
85
+ const stop = watch(
86
+ () => state.status,
87
+ (status) => {
88
+ if (status !== "ready" && !isPreviewSessionRefused(status)) return;
89
+ liftEarlyHide(doc);
90
+ queueMicrotask(() => stop());
91
+ },
92
+ { immediate: true, flush: "sync" }
93
+ );
94
+ }
95
+ function replayCoveredFocus(doc) {
96
+ const win = doc.defaultView;
97
+ if (win === null) return;
98
+ const protos = [win.HTMLElement?.prototype, win.SVGElement?.prototype].filter(
99
+ (proto) => proto !== void 0
100
+ );
101
+ let requested = null;
102
+ const inApp = (element) => doc.getElementById("__nuxt")?.contains(element) ?? false;
103
+ const patches = protos.map((proto) => {
104
+ const original = { focus: proto.focus, blur: proto.blur };
105
+ const focus = function focus2(options) {
106
+ if (state.status === "pending" && inApp(this)) requested = { element: this, options };
107
+ original.focus.call(this, options);
108
+ };
109
+ const blur = function blur2() {
110
+ if (state.status === "pending" && requested?.element === this) requested = null;
111
+ original.blur.call(this);
112
+ };
113
+ proto.focus = focus;
114
+ proto.blur = blur;
115
+ return { proto, original, focus, blur };
116
+ });
117
+ const stop = watch(
118
+ () => state.status,
119
+ (status) => {
120
+ if (status === "pending") return;
121
+ stop();
122
+ for (const { proto, original, focus, blur } of patches) {
123
+ if (proto.focus === focus) proto.focus = original.focus;
124
+ if (proto.blur === blur) proto.blur = original.blur;
125
+ }
126
+ const target = requested;
127
+ requested = null;
128
+ if (status !== "ready" || target === null || !target.element.isConnected) return;
129
+ if (doc.activeElement !== null && doc.activeElement !== doc.body) return;
130
+ target.element.focus(target.options);
131
+ },
132
+ { flush: "sync" }
133
+ );
134
+ }
135
+ function loadUi(doc) {
136
+ const fallBack = (cause) => {
137
+ console.warn("[eldra] the draft preview UI could not be loaded", cause);
138
+ mountFallbackNotice(doc);
139
+ liftEarlyHide(doc);
140
+ return void 0;
141
+ };
142
+ return import("./previewSessionUi.js").then(({ mountPreviewSessionUi }) => {
143
+ let ui;
144
+ try {
145
+ ui = mountPreviewSessionUi(doc, state);
146
+ } catch (cause) {
147
+ return fallBack(cause);
148
+ }
149
+ liftEarlyHide(doc);
150
+ return ui;
151
+ }, fallBack);
152
+ }
153
+ const FALLBACK_TEXT = {
154
+ is: {
155
+ pending: "S\xE6ki dr\xF6g\u2026",
156
+ expired: "Forsko\xF0uninni er loki\xF0. Opna\xF0u n\xFDja forsko\xF0un \xFAr Studio.",
157
+ unavailable: "Forsko\xF0un er ekki tilt\xE6k. Reyndu aftur eftir sm\xE1stund.",
158
+ exit: "H\xE6tta \xED forsko\xF0un"
159
+ },
160
+ en: {
161
+ pending: "Loading draft\u2026",
162
+ expired: "This preview has ended. Open a new preview from Studio.",
163
+ unavailable: "The preview is unavailable. Try again in a moment.",
164
+ exit: "Exit preview"
165
+ }
166
+ };
167
+ export function mountFallbackNotice(doc) {
168
+ const lang = doc.documentElement.lang?.trim().toLowerCase().startsWith("is") ? "is" : "en";
169
+ const text = FALLBACK_TEXT[lang];
170
+ const host = doc.createElement("div");
171
+ host.setAttribute("data-eldra-preview-session", "");
172
+ const root = host.attachShadow({ mode: "open" });
173
+ const box = doc.createElement("div");
174
+ box.setAttribute("role", "alert");
175
+ box.setAttribute("lang", lang);
176
+ box.setAttribute("tabindex", "-1");
177
+ box.setAttribute(
178
+ "style",
179
+ // `visibility:visible`: the router's early hide keeps the body hidden while the veil is up.
180
+ "position:fixed;inset:0;z-index:2147483647;display:flex;flex-direction:column;gap:12px;visibility:visible;align-items:center;justify-content:center;padding:16px;background:#fff;color:#1f2328;font:16px/1.5 system-ui,sans-serif;text-align:center"
181
+ );
182
+ const line = doc.createElement("p");
183
+ const exit = doc.createElement("a");
184
+ exit.href = PREVIEW_SESSION_EXIT_PATH;
185
+ exit.textContent = text.exit;
186
+ box.append(line, exit);
187
+ root.append(box);
188
+ doc.body.append(host);
189
+ watch(
190
+ () => state.status,
191
+ (status) => {
192
+ const shown = status === "pending" || isPreviewSessionRefused(status);
193
+ box.hidden = !shown;
194
+ if (status === "pending" || status === "expired" || status === "unavailable") {
195
+ line.textContent = text[status];
196
+ }
197
+ if (isPreviewSessionRefused(status)) box.focus();
198
+ },
199
+ { immediate: true, flush: "sync" }
200
+ );
201
+ return host;
202
+ }
203
+ export const PREVIEW_SESSION_DRAFT_TIMEOUT_MS = 15e3;
204
+ export async function settlePreviewSessionDrafts(reads, afterRender, timeoutMs = PREVIEW_SESSION_DRAFT_TIMEOUT_MS) {
205
+ let timer;
206
+ const timedOut = new Promise((resolve) => {
207
+ timer = setTimeout(() => resolve("timeout"), timeoutMs);
208
+ });
209
+ const settled = Promise.resolve().then(reads).then(
210
+ () => "settled",
211
+ () => "settled"
212
+ );
213
+ const outcome = await Promise.race([settled, timedOut]);
214
+ clearTimeout(timer);
215
+ if (outcome === "timeout") {
216
+ refuse({ status: "unavailable", errorId: null });
217
+ return;
218
+ }
219
+ try {
220
+ await afterRender();
221
+ } catch (cause) {
222
+ console.warn("[eldra] the draft preview could not be rendered", cause);
223
+ refuse({ status: "unavailable", errorId: null });
224
+ return;
225
+ }
226
+ markPreviewSessionDraftShown();
227
+ }
228
+ export const PREVIEW_SESSION_SITE_SETTINGS_TIMEOUT_MS = 1e4;
229
+ export async function settlePreviewSessionSiteSettings(read, timeoutMs = PREVIEW_SESSION_SITE_SETTINGS_TIMEOUT_MS) {
230
+ let open = true;
231
+ let timer;
232
+ const bound = new Promise((resolve) => {
233
+ timer = setTimeout(() => {
234
+ console.warn(
235
+ "[eldra] the saved design tokens and theme texts took too long; showing the build\u2019s"
236
+ );
237
+ resolve();
238
+ }, timeoutMs);
239
+ });
240
+ const reading = Promise.resolve().then(() => read(() => open)).then(
241
+ () => void 0,
242
+ (cause) => {
243
+ console.warn("[eldra] the saved design tokens and theme texts could not be read", cause);
244
+ }
245
+ );
246
+ try {
247
+ await Promise.race([reading, bound]);
248
+ } finally {
249
+ open = false;
250
+ clearTimeout(timer);
251
+ }
252
+ }
253
+ function startDraftDeadline() {
254
+ const timer = setTimeout(() => {
255
+ if (state.status === "pending") refuse({ status: "unavailable", errorId: null });
256
+ }, PREVIEW_SESSION_DRAFT_TIMEOUT_MS);
257
+ const stop = watch(
258
+ () => state.status,
259
+ (status) => {
260
+ if (status === "pending") return;
261
+ clearTimeout(timer);
262
+ stop();
263
+ },
264
+ { flush: "sync" }
265
+ );
266
+ }
267
+ export function startPreviewSession(client, options) {
268
+ const win = options.win ?? (typeof window === "undefined" ? void 0 : window);
269
+ if (win === void 0 || !detectPreviewSession(win)) return false;
270
+ state.active = true;
271
+ trackAppRoot(win.document);
272
+ liftEarlyHideOnLeavingVeil(win.document);
273
+ if (typeof client.enableSessionPreview !== "function") {
274
+ state.status = "unavailable";
275
+ void loadUi(win.document);
276
+ return true;
277
+ }
278
+ client.enableSessionPreview({ proxyBase: `${win.location.origin}${PREVIEW_SESSION_PROXY_PATH}` });
279
+ state.status = "pending";
280
+ startDraftDeadline();
281
+ replayCoveredFocus(win.document);
282
+ client.onRequestError?.((error) => {
283
+ const refusal = previewSessionRefusal(error);
284
+ if (refusal !== null) refuse(refusal);
285
+ });
286
+ options.onHydrated(markPreviewSessionHydrated);
287
+ void loadUi(win.document);
288
+ return true;
289
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The veil of a draft preview session drops only once the head shows the draft too (WS-1358).
3
+ *
4
+ * `@unhead/vue`'s client writes the document head in a `setTimeout(0)` after an entry changes
5
+ * (`createHead`'s debounced renderer, `dist/client.mjs`), not in Vue's render. Dropped right after
6
+ * `nextTick()`, the veil could uncover a frame whose `<title>`, description and Open Graph tags
7
+ * are still the pinned build's. This waits for Vue's render, then for the head's: unhead's
8
+ * `dom:rendered` when a render is queued, and in any case a timer queued after it — a timer of the
9
+ * same delay runs after the one unhead queued first, and when no head change is pending there is
10
+ * no render to wait for.
11
+ */
12
+ /** The part of an unhead instance this uses. */
13
+ export interface HeadRenderHooks {
14
+ hooks?: {
15
+ hook(name: 'dom:rendered', fn: () => void): (() => void) | void;
16
+ };
17
+ }
18
+ export declare function afterHeadRendered(head: HeadRenderHooks | undefined, tick: () => Promise<unknown>, later?: (fn: () => void) => void): Promise<void>;
@@ -0,0 +1,18 @@
1
+ export async function afterHeadRendered(head, tick, later = (fn) => {
2
+ setTimeout(fn, 0);
3
+ }) {
4
+ await tick();
5
+ await new Promise((resolve) => {
6
+ let done = false;
7
+ const unhook = [];
8
+ const finish = () => {
9
+ if (done) return;
10
+ done = true;
11
+ for (const off2 of unhook) off2();
12
+ resolve();
13
+ };
14
+ const off = head?.hooks?.hook("dom:rendered", finish);
15
+ if (typeof off === "function") unhook.push(off);
16
+ later(finish);
17
+ });
18
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Which async data entries a draft preview session reads again once the published prerender is
3
+ * hydrated (WS-1303, WS-1358). `plugin.ts` runs them; this decides them, so it can be tested
4
+ * without a Nuxt app.
5
+ */
6
+ /** The prefix of the async data key `useEldraPage` stores one route's resolution under. */
7
+ export declare const PAGE_KEY_PREFIX = "eldra-page:";
8
+ /** The parts of a Nuxt async data entry this reads (`nuxtApp._asyncData[key]`). */
9
+ export interface SessionAsyncDataEntry {
10
+ data?: {
11
+ value?: unknown;
12
+ };
13
+ status?: {
14
+ value?: string;
15
+ };
16
+ _default?: () => unknown;
17
+ }
18
+ export interface SessionReadsInput {
19
+ /** The keys the payload carried a value for, captured before anything ran in the browser. */
20
+ hydratedKeys: readonly string[];
21
+ /** `nuxtApp._asyncData`. */
22
+ asyncData: Record<string, SessionAsyncDataEntry | undefined>;
23
+ /** `nuxtApp._asyncDataPromises`. */
24
+ promises: Record<string, Promise<unknown> | undefined>;
25
+ }
26
+ export interface SessionReads {
27
+ /** Keys to refresh through the session. */
28
+ reread: string[];
29
+ /** Reads the browser itself started on load: waited for, never run again. */
30
+ inFlight: Promise<unknown>[];
31
+ }
32
+ /**
33
+ * The session's reads:
34
+ *
35
+ * - **every key the payload carried a value for** — hydrated from the published build, and would
36
+ * stay published beside the drafts;
37
+ * - **a route read Nuxt marked hydrated with nothing from the payload** (`unread`): during
38
+ * hydration Nuxt counts an entry whose `default` gives a value as hydrated (`success`) and never
39
+ * fetches it. That is a route the document was not rendered for — a page only the draft has,
40
+ * opened directly, hydrates the build's not-found document — so its own data was never read.
41
+ * Only an entry whose data is still its `default` (anything else ran and has its own answer),
42
+ * and only `useEldraPage`'s (`eldra-page:` keys), which always runs on load: Nuxt marks an
43
+ * `immediate: false` entry with a `default` the same way, and nothing on the entry says which it
44
+ * was, so a theme's own entry is never run by the session on that guess — a cart create, a form
45
+ * submit, runs only when the page runs it.
46
+ *
47
+ * Reads still in flight are waited for, not run again.
48
+ */
49
+ export declare function sessionReads({ hydratedKeys, asyncData, promises, }: SessionReadsInput): SessionReads;
@@ -0,0 +1,23 @@
1
+ export const PAGE_KEY_PREFIX = "eldra-page:";
2
+ export function sessionReads({
3
+ hydratedKeys,
4
+ asyncData,
5
+ promises
6
+ }) {
7
+ const inFlight = Object.entries(promises).filter(([key, promise]) => promise !== void 0 && !hydratedKeys.includes(key)).map(([, promise]) => promise);
8
+ const unread = Object.entries(asyncData).filter(
9
+ ([key, entry]) => key.startsWith(PAGE_KEY_PREFIX) && !hydratedKeys.includes(key) && promises[key] === void 0 && entry?.status?.value === "success" && isStillDefault(entry)
10
+ ).map(([key]) => key);
11
+ return { reread: [...hydratedKeys, ...unread], inFlight };
12
+ }
13
+ function isStillDefault(entry) {
14
+ if (typeof entry._default !== "function") return false;
15
+ const value = entry.data?.value;
16
+ const fallback = entry._default();
17
+ if (Object.is(value, fallback)) return true;
18
+ try {
19
+ return JSON.stringify(value) === JSON.stringify(fallback);
20
+ } catch {
21
+ return false;
22
+ }
23
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * In a draft preview session, a page only the draft has resolves the address bar's path, never
3
+ * the not-found document's (WS-1358).
4
+ *
5
+ * A page that exists only as a draft is not in the pinned build, so the host answers its path with
6
+ * the build's not-found document. When that document is a prerendered page (the starter copies its
7
+ * styled `/404` over `404.html`, so a static host shows it), Nuxt's router starts at the path the
8
+ * document was **rendered** for (`payload.path`, here `/404`) rather than the one in the address
9
+ * bar, and the session then resolves `/404`: it shows "Page not found" for a draft that exists,
10
+ * where Publish puts the page live. So in a session, and only then, the payload's path is set to
11
+ * the address bar's before the router reads it, and the route resolves the draft.
12
+ *
13
+ * Only the not-found document is rewritten (`/404`, the path Nuxt prerenders for a static host's
14
+ * `404.html`): any other document served under another address (an alias, a host's rewrite) keeps
15
+ * the path it was rendered for, as Nuxt would start it. The paths are compared the way Nuxt's
16
+ * router compares them (`createCurrentLocation`): the address bar's without the app's `baseURL`,
17
+ * a trailing slash and percent-encoding aside.
18
+ *
19
+ * Ordered between Nuxt's payload revival (`order: -30`) and its router (`enforce: 'pre'`, -20).
20
+ * Outside a session nothing changes.
21
+ */
22
+ declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
23
+ export default _default;
24
+ /**
25
+ * The path a session's router should start at, when it is not the one the document was rendered
26
+ * for: the address bar's (`pathname`, without `baseURL`) when the document is the not-found page
27
+ * rendered for another path. `undefined` leaves the payload as it is.
28
+ */
29
+ export declare function sessionStartPath(rendered: unknown, pathname: string, baseURL?: string): string | undefined;
@@ -0,0 +1,46 @@
1
+ import { defineNuxtPlugin } from "nuxt/app";
2
+ import { detectPreviewSession } from "./previewSession.js";
3
+ export default defineNuxtPlugin({
4
+ name: "eldra-preview-session-route",
5
+ order: -25,
6
+ setup(nuxtApp) {
7
+ if (import.meta.server || typeof window === "undefined") return;
8
+ if (!detectPreviewSession(window)) return;
9
+ const path = sessionStartPath(
10
+ nuxtApp.payload.path,
11
+ window.location.pathname,
12
+ nuxtApp.$config.app.baseURL
13
+ );
14
+ if (path !== void 0) nuxtApp.payload.path = path;
15
+ }
16
+ });
17
+ const NOT_FOUND_PATH = "/404";
18
+ export function sessionStartPath(rendered, pathname, baseURL = "/") {
19
+ if (typeof rendered !== "string" || rendered === "") return void 0;
20
+ if (baseURL.includes("#")) return void 0;
21
+ const renderedPath = rendered.split("?")[0] ?? rendered;
22
+ if (!isSamePath(renderedPath, NOT_FOUND_PATH)) return void 0;
23
+ const displayed = withoutBase(pathname, baseURL);
24
+ if (isSamePath(displayed, renderedPath)) return void 0;
25
+ return displayed;
26
+ }
27
+ function withoutBase(input, base) {
28
+ if (base === "" || base === "/") return input;
29
+ const prefix = base.replace(/\/+$/, "");
30
+ if (!input.startsWith(prefix)) return input;
31
+ const next = input[prefix.length];
32
+ if (next !== void 0 && next !== "/" && next !== "?") return input;
33
+ const trimmed = input.slice(prefix.length);
34
+ return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
35
+ }
36
+ function isSamePath(a, b) {
37
+ const bare = (path) => {
38
+ let decoded = path;
39
+ try {
40
+ decoded = decodeURI(path);
41
+ } catch {
42
+ }
43
+ return decoded.replace(/\/+$/, "") || "/";
44
+ };
45
+ return bare(a) === bare(b);
46
+ }
@@ -0,0 +1,54 @@
1
+ import type { EldraClient } from '@eldrajs/theme-core';
2
+ import { type ThemeMessages } from '@eldrajs/theme-core/i18n';
3
+ import type { EldraContext } from '@eldrajs/theme-vue';
4
+ import { type ThemeDesignTokens } from './designTokens.js';
5
+ import type { StoreLocales } from './locales.js';
6
+ /**
7
+ * A draft preview session shows the site's **saved** design tokens and theme texts (WS-1394; the
8
+ * owner's decision, 2026-11-23: a preview shows them as soon as they are saved). A build reads both
9
+ * once and bakes them in (`readDesignTokens`, `readThemeMessages`), so a session's pinned build
10
+ * carries whatever was saved when it was built. Once the published prerender is hydrated the session
11
+ * reads both again, through the router like its CMS reads (`getSiteSetting`), and puts them where
12
+ * the build put its own: the tokens into `context.designTokens` (which `EldraLayout`'s
13
+ * `<style data-eldra-design-token-styles>` renders), the texts, resolved exactly as the build
14
+ * resolves them, into `context.messages` (which the theme's i18n reads). Before the veil comes
15
+ * down, inside the same bounded settle.
16
+ *
17
+ * Its own module, loaded only by a session, so a storefront's JavaScript carries none of it. Never
18
+ * fatal: a read that fails or answers something unusable leaves the build's values as they are.
19
+ * The bound is the caller's, around this chunk's load and these reads together
20
+ * (`settlePreviewSessionSiteSettings`): past it, `isOpen` answers `false` and a late answer is
21
+ * dropped, so nothing changes after the veil.
22
+ */
23
+ export interface SessionSiteSettingsOptions {
24
+ /** The theme's own catalogue (`virtual:eldra/manifest`'s `messages`), as the build merged over. */
25
+ themeMessages: ThemeMessages | undefined;
26
+ /** The organisation's locales the build resolved the texts over (`null`: unknown). */
27
+ locales: StoreLocales | null;
28
+ /**
29
+ * Whether an answer may still be applied: `false` once the session's bound around this read has
30
+ * passed (`settlePreviewSessionSiteSettings`), so a late answer changes nothing after the veil.
31
+ */
32
+ isOpen?: () => boolean;
33
+ /**
34
+ * Answers are applied only once this has settled: the reads start with the session, before the
35
+ * published prerender is hydrated, and the context must not change under Vue's hydration.
36
+ */
37
+ applyAfter?: Promise<unknown>;
38
+ /** Told of each read that failed (`reportPreviewSessionSiteSettingError`). */
39
+ onError?: (error: unknown) => void;
40
+ warn?: (message: string, cause?: unknown) => void;
41
+ }
42
+ export declare function readSessionSiteSettings(client: Pick<EldraClient, 'getSiteSetting'>, context: Pick<EldraContext, 'designTokens' | 'messages'>, options: SessionSiteSettingsOptions): Promise<void>;
43
+ /**
44
+ * The saved catalog into the reactive one, in place (the context's object is the one `EldraLayout`
45
+ * renders), in the answer's own key order, which is the order a build made from it would render.
46
+ * An equal catalog is left alone, so a session whose tokens did not change renders nothing new.
47
+ */
48
+ export declare function assignDesignTokens(target: ThemeDesignTokens, source: ThemeDesignTokens): boolean;
49
+ /**
50
+ * The resolved texts into the reactive catalogue, a locale's whole record at a time (as Studio's
51
+ * live `editor:theme-messages` push replaces one), only where it changed. A locale the answer does
52
+ * not resolve is left as the build had it.
53
+ */
54
+ export declare function assignMessages(target: ThemeMessages, source: ThemeMessages): boolean;
@@ -0,0 +1,62 @@
1
+ import { EMPTY_THEME_MESSAGES } from "@eldrajs/theme-core/i18n";
2
+ import { toResolvedDesignTokens } from "./designTokens.js";
3
+ import { resolveSiteMessages, toThemeMessages } from "./messages.js";
4
+ export async function readSessionSiteSettings(client, context, options) {
5
+ if (typeof client.getSiteSetting !== "function") return;
6
+ const read = (path) => client.getSiteSetting(path);
7
+ const isOpen = options.isOpen ?? (() => true);
8
+ const applyAfter = options.applyAfter ?? Promise.resolve();
9
+ const warn = options.warn ?? ((message, cause) => console.warn(`[eldra] ${message}`, cause ?? ""));
10
+ const failed = (what) => (cause) => {
11
+ try {
12
+ options.onError?.(cause);
13
+ } catch {
14
+ }
15
+ warn(`the saved ${what} could not be read; showing the build\u2019s`, cause);
16
+ };
17
+ await Promise.all([
18
+ read("/site/v1/design-tokens").then(async (answer) => {
19
+ await applyAfter;
20
+ const resolved = toResolvedDesignTokens(answer);
21
+ if (resolved === null) throw new Error("the platform published an unusable response");
22
+ if (isOpen()) assignDesignTokens(context.designTokens, resolved);
23
+ }).catch(failed("design tokens")),
24
+ read("/site/v1/theme-messages").then(async (answer) => {
25
+ await applyAfter;
26
+ const platform = toThemeMessages(answer);
27
+ if (platform === null) throw new Error("the platform published an unusable response");
28
+ const resolved = resolveSiteMessages(
29
+ options.themeMessages ?? EMPTY_THEME_MESSAGES,
30
+ platform,
31
+ options.locales
32
+ );
33
+ if (isOpen()) assignMessages(context.messages, resolved);
34
+ }).catch(failed("theme texts"))
35
+ ]);
36
+ }
37
+ export function assignDesignTokens(target, source) {
38
+ if (JSON.stringify(target) === JSON.stringify(source)) return false;
39
+ replaceRecord(target.colors, source.colors);
40
+ replaceRecord(target.containers, source.containers);
41
+ if (source.allowCustomColors === void 0) delete target.allowCustomColors;
42
+ else target.allowCustomColors = source.allowCustomColors;
43
+ return true;
44
+ }
45
+ export function assignMessages(target, source) {
46
+ let changed = false;
47
+ if (target.defaultLocale !== source.defaultLocale) {
48
+ target.defaultLocale = source.defaultLocale;
49
+ changed = true;
50
+ }
51
+ for (const tag of Object.keys(source.locales)) {
52
+ const record = source.locales[tag];
53
+ if (JSON.stringify(target.locales[tag]) === JSON.stringify(record)) continue;
54
+ target.locales[tag] = record;
55
+ changed = true;
56
+ }
57
+ return changed;
58
+ }
59
+ function replaceRecord(target, source) {
60
+ for (const key of Object.keys(target)) delete target[key];
61
+ for (const key of Object.keys(source)) target[key] = source[key];
62
+ }
@@ -0,0 +1,30 @@
1
+ import { type PreviewSessionState } from './previewSession.js';
2
+ /**
3
+ * The draft preview session's veil, exit banner and notices (`./previewSession.ts`). Its own module
4
+ * so that only a session loads it: `startPreviewSession` imports it dynamically, and an ordinary
5
+ * storefront's JavaScript carries the detection alone.
6
+ */
7
+ export type PreviewSessionLocale = 'is' | 'en';
8
+ export interface PreviewSessionMessages {
9
+ banner: string;
10
+ exit: string;
11
+ loading: string;
12
+ expiredTitle: string;
13
+ expiredInvalid: string;
14
+ expiredRevoked: string;
15
+ expiredExpired: string;
16
+ expiredHint: string;
17
+ unavailableTitle: string;
18
+ unavailableBody: string;
19
+ retry: string;
20
+ }
21
+ export declare const PREVIEW_SESSION_MESSAGES: Record<PreviewSessionLocale, PreviewSessionMessages>;
22
+ /** The page's own language when it is Icelandic, else the browser's, else English. */
23
+ export declare function previewSessionLocale(doc: Pick<Document, 'documentElement'>, languages?: readonly string[]): PreviewSessionLocale;
24
+ /** How long the veil stays silent before it says it is loading. */
25
+ export declare const PREVIEW_SESSION_LOADING_DELAY_MS = 500;
26
+ export interface PreviewSessionUi {
27
+ host: HTMLElement;
28
+ destroy(): void;
29
+ }
30
+ export declare function mountPreviewSessionUi(doc: Document, session: Readonly<PreviewSessionState>, locale?: PreviewSessionLocale): PreviewSessionUi;