@phis/ui 0.4.5 → 0.4.7

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.
Files changed (145) hide show
  1. package/components/cms/phi-cms-root-layout.js +1 -1
  2. package/components/controls/phi-button-control.d.ts +3 -1
  3. package/components/controls/phi-button-control.js +2 -2
  4. package/components/controls/phi-collapse-control.d.ts +6 -2
  5. package/components/controls/phi-collapse-control.js +2 -2
  6. package/components/controls/phi-dialog-control.d.ts +11 -5
  7. package/components/controls/phi-dialog-control.js +19 -13
  8. package/components/controls/phi-menu-control-vocabulary.d.ts +7 -0
  9. package/components/controls/phi-menu-control-vocabulary.js +10 -0
  10. package/components/controls/phi-menu-control.d.ts +4 -1
  11. package/components/controls/phi-menu-control.js +6 -1
  12. package/components/controls/phi-text-control.d.ts +6 -1
  13. package/components/controls/phi-text-control.js +2 -1
  14. package/components/layouts/clients/phi-split-card-layout-client.js +13 -5
  15. package/components/layouts/clients/phi-three-column-layout-client.js +9 -3
  16. package/components/layouts/split-card-geometry.js +6 -2
  17. package/components/media/aspect-ratios.d.ts +2 -2
  18. package/components/menus/phi-account-menu.js +3 -1
  19. package/components/navigation/phi-link.js +7 -2
  20. package/components/navigation/use-phi-protected-mail.d.ts +11 -0
  21. package/components/navigation/use-phi-protected-mail.js +29 -0
  22. package/components/regions/clients/cms-region-container-client.js +5 -1
  23. package/components/regions/phi-cms-region-shell.d.ts +1 -0
  24. package/components/regions/phi-cms-region-shell.js +11 -0
  25. package/components/regions/presets/phi-area-shell-preset-nodes.d.ts +5 -0
  26. package/components/regions/presets/phi-area-shell-preset-nodes.js +19 -3
  27. package/components/root/phi-config-provider.js +16 -0
  28. package/components/shell/phi-cms-shell.d.ts +3 -1
  29. package/components/shell/phi-cms-shell.js +7 -3
  30. package/components/shell/phi-nav-link.js +7 -2
  31. package/components/shell/phi-shell-sider-drawer.d.ts +17 -0
  32. package/components/shell/phi-shell-sider-drawer.js +88 -0
  33. package/components/widgets/helpers/internal-reference-resolver.server.d.ts +1 -0
  34. package/components/widgets/helpers/internal-reference-resolver.server.js +4 -1
  35. package/components/widgets/label-sets/inspector.js +2 -0
  36. package/components/widgets/label-sets/search-results.d.ts +4 -0
  37. package/components/widgets/label-sets/search-results.js +35 -0
  38. package/components/widgets/label-types/inspector.d.ts +2 -0
  39. package/components/widgets/label-types/inspector.js +1 -0
  40. package/components/widgets/label-types/search-results.d.ts +15 -0
  41. package/components/widgets/label-types/search-results.js +10 -0
  42. package/components/widgets/server/navigation-request.js +13 -1
  43. package/components/widgets/shared/card-body-client.d.ts +2 -0
  44. package/components/widgets/shared/card-body-client.js +8 -7
  45. package/components/widgets/shared/card-vocabulary.d.ts +36 -0
  46. package/components/widgets/shared/card-vocabulary.js +52 -0
  47. package/components/widgets/shared/markdown-body-client.d.ts +29 -0
  48. package/components/widgets/shared/markdown-body-client.js +60 -5
  49. package/components/widgets/shared/markdown-image-vocabulary.d.ts +31 -0
  50. package/components/widgets/shared/markdown-image-vocabulary.js +68 -0
  51. package/components/widgets/shared/markdown-render.d.ts +5 -0
  52. package/components/widgets/shared/markdown-render.js +123 -8
  53. package/components/widgets/shared/markdown-sections.d.ts +40 -0
  54. package/components/widgets/shared/markdown-sections.js +111 -0
  55. package/constants/cms-widget-types.d.ts +2 -0
  56. package/constants/cms-widget-types.js +4 -0
  57. package/gateway/site-area.d.ts +10 -7
  58. package/gateway/site-area.js +13 -11
  59. package/gateway/site-config.js +7 -1
  60. package/gateway/site-read-marker-listeners.d.ts +24 -0
  61. package/gateway/site-read-marker-listeners.js +22 -0
  62. package/gateway/site-search.d.ts +37 -0
  63. package/gateway/site-search.js +116 -0
  64. package/helpers/external-href.js +1 -1
  65. package/helpers/protected-mail.d.ts +16 -0
  66. package/helpers/protected-mail.js +81 -0
  67. package/next/areas/app.js +5 -1
  68. package/next/areas/public.js +5 -1
  69. package/next/seo-routes.js +2 -2
  70. package/package.json +2 -2
  71. package/plugins/runtime-modules/app/presets.js +23 -0
  72. package/plugins/runtime-modules/app/trees/phi-default-app-area-preset-tree.d.ts +2 -1
  73. package/plugins/runtime-modules/app/trees/phi-default-app-area-preset-tree.js +3 -2
  74. package/plugins/runtime-modules/builder/clients/region-inspector.js +20 -1
  75. package/plugins/runtime-modules/client-manifests/common.js +8 -0
  76. package/plugins/runtime-modules/core/authoring-widgets.js +4 -0
  77. package/plugins/runtime-modules/core/widgets/card/config.d.ts +8 -1
  78. package/plugins/runtime-modules/core/widgets/card/config.js +22 -1
  79. package/plugins/runtime-modules/core/widgets/card/editor.js +9 -1
  80. package/plugins/runtime-modules/core/widgets/card/plugin.js +18 -0
  81. package/plugins/runtime-modules/core/widgets/card/server.js +9 -1
  82. package/plugins/runtime-modules/core/widgets/description/plugin.js +10 -0
  83. package/plugins/runtime-modules/core/widgets/entry-list/view.server.js +2 -1
  84. package/plugins/runtime-modules/core/widgets/gallery/config.d.ts +3 -3
  85. package/plugins/runtime-modules/core/widgets/header-navigation/client.d.ts +6 -1
  86. package/plugins/runtime-modules/core/widgets/header-navigation/client.js +40 -13
  87. package/plugins/runtime-modules/core/widgets/header-navigation/config.d.ts +26 -1
  88. package/plugins/runtime-modules/core/widgets/header-navigation/config.js +27 -0
  89. package/plugins/runtime-modules/core/widgets/header-navigation/plugin.js +1 -1
  90. package/plugins/runtime-modules/core/widgets/header-navigation/server.d.ts +2 -2
  91. package/plugins/runtime-modules/core/widgets/header-navigation/server.js +3 -1
  92. package/plugins/runtime-modules/core/widgets/html/plugin.js +16 -1
  93. package/plugins/runtime-modules/core/widgets/html/server.d.ts +6 -0
  94. package/plugins/runtime-modules/core/widgets/html/server.js +12 -4
  95. package/plugins/runtime-modules/core/widgets/image/client.js +11 -7
  96. package/plugins/runtime-modules/core/widgets/markdown/config.d.ts +16 -0
  97. package/plugins/runtime-modules/core/widgets/markdown/config.js +46 -1
  98. package/plugins/runtime-modules/core/widgets/markdown/plugin.js +16 -0
  99. package/plugins/runtime-modules/core/widgets/markdown/server.js +22 -8
  100. package/plugins/runtime-modules/core/widgets/search-box/authoring.d.ts +6 -0
  101. package/plugins/runtime-modules/core/widgets/search-box/authoring.js +10 -0
  102. package/plugins/runtime-modules/core/widgets/search-box/client.d.ts +21 -0
  103. package/plugins/runtime-modules/core/widgets/search-box/client.js +17 -0
  104. package/plugins/runtime-modules/core/widgets/search-box/config.d.ts +63 -0
  105. package/plugins/runtime-modules/core/widgets/search-box/config.js +48 -0
  106. package/plugins/runtime-modules/core/widgets/search-box/plugin.d.ts +3 -0
  107. package/plugins/runtime-modules/core/widgets/search-box/plugin.js +11 -0
  108. package/plugins/runtime-modules/core/widgets/search-box/server.d.ts +21 -0
  109. package/plugins/runtime-modules/core/widgets/search-box/server.js +48 -0
  110. package/plugins/runtime-modules/core/widgets/search-results/authoring.d.ts +6 -0
  111. package/plugins/runtime-modules/core/widgets/search-results/authoring.js +10 -0
  112. package/plugins/runtime-modules/core/widgets/search-results/client.d.ts +34 -0
  113. package/plugins/runtime-modules/core/widgets/search-results/client.js +32 -0
  114. package/plugins/runtime-modules/core/widgets/search-results/config.d.ts +41 -0
  115. package/plugins/runtime-modules/core/widgets/search-results/config.js +39 -0
  116. package/plugins/runtime-modules/core/widgets/search-results/plugin.d.ts +3 -0
  117. package/plugins/runtime-modules/core/widgets/search-results/plugin.js +10 -0
  118. package/plugins/runtime-modules/core/widgets/search-results/server.d.ts +20 -0
  119. package/plugins/runtime-modules/core/widgets/search-results/server.js +73 -0
  120. package/plugins/runtime-modules/core/widgets/simple-text/plugin.js +11 -0
  121. package/plugins/runtime-modules/core/widgets/simple-text/server.js +11 -1
  122. package/plugins/runtime-modules/core/widgets.js +17 -0
  123. package/plugins/runtime-modules/public/presets.d.ts +16 -0
  124. package/plugins/runtime-modules/public/presets.js +22 -0
  125. package/plugins/runtime-modules/public-base-page-references.d.ts +1 -0
  126. package/plugins/runtime-modules/public-base-page-references.js +1 -0
  127. package/plugins/runtime-modules/search-page-references.d.ts +20 -0
  128. package/plugins/runtime-modules/search-page-references.js +35 -0
  129. package/plugins/runtime-modules/search-page-tree.d.ts +14 -0
  130. package/plugins/runtime-modules/search-page-tree.js +63 -0
  131. package/server-helpers/search-index.d.ts +28 -0
  132. package/server-helpers/search-index.js +299 -0
  133. package/server-helpers/search-text.d.ts +40 -0
  134. package/server-helpers/search-text.js +152 -0
  135. package/server-helpers.d.ts +1 -0
  136. package/server-helpers.js +1 -0
  137. package/styles/controls.css +108 -10
  138. package/styles/layout.css +35 -0
  139. package/styles/shell.css +142 -0
  140. package/theme/phi-tokens.d.ts +6 -0
  141. package/theme/phi-tokens.js +6 -0
  142. package/theme.d.ts +1 -0
  143. package/theme.js +6 -0
  144. package/types/cms-plugins.d.ts +20 -2
  145. package/types/core-widget-placements.d.ts +5 -0
@@ -0,0 +1,299 @@
1
+ import "server-only";
2
+ import { createHash } from "node:crypto";
3
+ import { PHI_SEARCH_MAX_DOCUMENTS } from "@phis/contracts/search";
4
+ import { resolvePhiCmsPageRedirect } from "../components/cms/phi-cms-page-redirect";
5
+ import { getSiteAreaWithPublishedPages } from "../gateway/site-area";
6
+ import { onPhiSiteReadMarker } from "../gateway/site-read-marker-listeners";
7
+ import { fetchPhiSiteSearchIndexStates, putPhiSiteSearchIndexSet } from "../gateway/site-search";
8
+ import { readPhiAreaLandingSelection, readPhiAreaPublicRoutePaths } from "../helpers/cms-area-config";
9
+ import { collectPhiSitemapCandidates } from "../helpers/phi-seo";
10
+ import { compilePhiCmsActiveRouteTable, resolvePhiCmsAreaShellPresetBinding, resolvePhiCmsDescriptorCatalog, } from "../plugins/runtime-modules/descriptor-compiler";
11
+ import { resolvePhiCmsAreaRuntimeModuleScope } from "../components/cms/phi-cms-runtime-registry";
12
+ import { canPhiViewerAccess } from "../types/access";
13
+ import { resolvePhiCmsLookup } from "./cms-lookup";
14
+ import { resolveActivePresetModuleKeys } from "./cms-request";
15
+ import { loadPhiSiteRequestContext } from "./runtime";
16
+ import { joinPhiSearchText } from "./search-text";
17
+ /**
18
+ * The Site's half of its search (SEARCH.md): the documents phis indexes, built from the published Pages.
19
+ *
20
+ * A Page's words are not in one place phis could read -- Widget configs, content bound to an instance in
21
+ * a tree, documents fetched while the Page is drawn -- so the Site reads each Page the way a visitor's
22
+ * request does and writes what it saw. The enumeration is the sitemap's: the Area's published Pages and
23
+ * the active Module routes are the candidates, and resolving each one as a lookup decides whether a
24
+ * visitor would get a document. The text is each Widget's own answer (`searchText` on its plugin),
25
+ * translated for the language being indexed; the title and description are the Page's own.
26
+ *
27
+ * Two Areas, read as the reader who may search them: Public anonymously, App as a signed-in member with
28
+ * no further roles. A Page with a narrower access policy than that is not written.
29
+ *
30
+ * It runs when the Site's read marker is first seen by this process and whenever it moves -- which a
31
+ * publish does -- and writes only the sets whose fingerprint phis does not hold yet, so several
32
+ * processes noticing one publish produce one write. One run at a time per process; a marker that moves
33
+ * during a run queues one more.
34
+ */
35
+ const PHI_SEARCH_INDEX_AREAS = ["public", "app"];
36
+ /** How many Pages are resolved at once; each is a page lookup against the server. */
37
+ const PHI_SEARCH_INDEX_RESOLVE_CONCURRENCY = 4;
38
+ /** How long after the marker moved the run starts, so a burst of publishes is one run. */
39
+ const PHI_SEARCH_INDEX_DEBOUNCE_MS = 2_000;
40
+ /**
41
+ * What the extraction is, named in the fingerprint: a change in how documents are built reindexes every
42
+ * Site on its next start, which the published revisions alone would not do.
43
+ */
44
+ const PHI_SEARCH_INDEX_FORMAT = 1;
45
+ const REGISTRY_KEY = Symbol.for("phis-ui.search-index");
46
+ function readRegistry() {
47
+ const holder = globalThis;
48
+ holder[REGISTRY_KEY] ??= { bridges: new Map(), listening: false, running: null, queued: false, timer: null };
49
+ return holder[REGISTRY_KEY];
50
+ }
51
+ /**
52
+ * Names the Bridge an Area's Pages are read through. The Area host registers itself when it is created
53
+ * (next/areas/*.ts); an Area this process never served is not indexed by it, and another process will.
54
+ */
55
+ export function registerPhiSearchIndexArea(area, bridge) {
56
+ const registry = readRegistry();
57
+ registry.bridges.set(area, bridge);
58
+ if (!registry.listening) {
59
+ registry.listening = true;
60
+ onPhiSiteReadMarker(() => schedulePhiSearchIndexRun());
61
+ }
62
+ /*
63
+ * And once now: the Site's marker may have been seen before this Area was registered -- the proxy reads
64
+ * the config before the first page is served -- and a set phis already holds costs one read of its states.
65
+ */
66
+ schedulePhiSearchIndexRun();
67
+ }
68
+ /** Runs the indexer soon, once, however often it is asked meanwhile. */
69
+ function schedulePhiSearchIndexRun() {
70
+ const registry = readRegistry();
71
+ if (registry.timer)
72
+ return;
73
+ registry.timer = setTimeout(() => {
74
+ registry.timer = null;
75
+ void runPhiSearchIndex();
76
+ }, PHI_SEARCH_INDEX_DEBOUNCE_MS);
77
+ // A timer must not keep a process alive that is otherwise done.
78
+ registry.timer.unref?.();
79
+ }
80
+ /**
81
+ * Indexes every registered Area now, or queues one more run when one is under way. The promise settles
82
+ * when this run is done; it never rejects -- a failed Area is logged and the others are still written.
83
+ */
84
+ function runPhiSearchIndex() {
85
+ const registry = readRegistry();
86
+ if (registry.running) {
87
+ registry.queued = true;
88
+ return registry.running;
89
+ }
90
+ registry.running = (async () => {
91
+ try {
92
+ await indexRegisteredAreas(registry);
93
+ }
94
+ catch (error) {
95
+ console.error("[phis-ui] The search index run failed.", error);
96
+ }
97
+ finally {
98
+ registry.running = null;
99
+ if (registry.queued) {
100
+ registry.queued = false;
101
+ schedulePhiSearchIndexRun();
102
+ }
103
+ }
104
+ })();
105
+ return registry.running;
106
+ }
107
+ async function indexRegisteredAreas(registry) {
108
+ const first = registry.bridges.values().next().value;
109
+ const bridgeRuntime = first?.runtime;
110
+ if (!first || !bridgeRuntime)
111
+ return;
112
+ const credentials = {
113
+ apiBaseUrl: bridgeRuntime.apiBaseUrl,
114
+ internalToken: bridgeRuntime.internalToken,
115
+ siteKey: bridgeRuntime.siteKey,
116
+ };
117
+ const held = await fetchPhiSiteSearchIndexStates(credentials);
118
+ const heldFingerprint = (areaMask, locale) => held.find((state) => state.areaMask === areaMask && state.locale === locale)?.fingerprint ?? null;
119
+ for (const area of PHI_SEARCH_INDEX_AREAS) {
120
+ const bridge = registry.bridges.get(area);
121
+ if (!bridge)
122
+ continue;
123
+ try {
124
+ await indexArea({ area, bridge, credentials, heldFingerprint });
125
+ }
126
+ catch (error) {
127
+ console.error(`[phis-ui] Indexing the ${area} Area for search failed.`, error);
128
+ }
129
+ }
130
+ }
131
+ /**
132
+ * The reader an Area is indexed as: the Public Area's anonymous visitor, the App's signed-in member who
133
+ * holds no role -- the least any member holds, so what they may read every member may read.
134
+ */
135
+ function asIndexingReader(context, area) {
136
+ if (area === "public")
137
+ return context;
138
+ return {
139
+ ...context,
140
+ viewer: {
141
+ ...context.viewer,
142
+ access: "authenticated",
143
+ roleClaims: [],
144
+ groupClaims: [],
145
+ addonRoleClaims: [],
146
+ },
147
+ };
148
+ }
149
+ async function indexArea({ area, bridge, credentials, heldFingerprint, }) {
150
+ const { apiBaseUrl, internalToken, siteKey } = credentials;
151
+ const catalog = resolvePhiCmsDescriptorCatalog(bridge.runtimeModuleCatalog);
152
+ const shellBinding = resolvePhiCmsAreaShellPresetBinding(catalog, area);
153
+ if (!shellBinding) {
154
+ console.warn(`[phis-ui] The ${area} Area has no shell preset; nothing to index.`);
155
+ return;
156
+ }
157
+ const sourcePreset = {
158
+ ownerModuleId: shellBinding.descriptor.ownerModuleId,
159
+ presetKey: shellBinding.descriptor.presetKey,
160
+ };
161
+ const areaMask = area === "public" ? 1 : 2;
162
+ // The Site's languages and its server, read once as the anonymous reader; the locale is per set.
163
+ const anonymous = await loadPhiSiteRequestContext(siteKey, "", "", apiBaseUrl, internalToken);
164
+ const locales = anonymous.site.availableLocales.map((option) => option.code);
165
+ const { area: areaPreset, publishedPages } = await getSiteAreaWithPublishedPages({
166
+ apiBaseUrl,
167
+ internalToken,
168
+ siteKey,
169
+ locale: anonymous.site.defaultLocale,
170
+ sourcePreset,
171
+ area,
172
+ });
173
+ const activeModuleIds = resolveActivePresetModuleKeys(bridge.runtimeModuleCatalog, area, areaPreset ? { preset: areaPreset.preset } : null, anonymous.serverCapabilities);
174
+ const routeTable = compilePhiCmsActiveRouteTable({
175
+ catalog,
176
+ area,
177
+ activeModuleIds,
178
+ publicRoutePaths: readPhiAreaPublicRoutePaths(areaPreset?.preset.preset.config),
179
+ landingSelection: readPhiAreaLandingSelection(areaPreset?.preset.preset.config),
180
+ });
181
+ const candidates = collectPhiSitemapCandidates({
182
+ moduleRoutes: [...routeTable.exactByPath].map(([path, descriptor]) => [path, descriptor]),
183
+ publishedPages,
184
+ });
185
+ const fingerprint = createHash("sha256").update(JSON.stringify({
186
+ format: PHI_SEARCH_INDEX_FORMAT,
187
+ area,
188
+ publishedPages,
189
+ areaPreset: areaPreset?.preset ?? null,
190
+ activeModuleIds: [...activeModuleIds].sort(),
191
+ locales,
192
+ })).digest("hex");
193
+ // The Area's Module scope as the live render resolves it: the preset's selection, the locked ones implied.
194
+ const { moduleSet } = await resolvePhiCmsAreaRuntimeModuleScope({
195
+ cmsBridge: bridge,
196
+ area,
197
+ areaPreset: areaPreset?.preset ?? null,
198
+ serverCapabilities: anonymous.serverCapabilities,
199
+ });
200
+ const plugins = new Map();
201
+ const loadPlugin = (type) => {
202
+ let pending = plugins.get(type);
203
+ if (!pending) {
204
+ pending = (moduleSet.widgetDefinitionsByType.get(type)?.loadRuntime() ?? Promise.resolve(null))
205
+ .catch((error) => {
206
+ console.error(`[phis-ui] The search index could not load the Widget "${type}".`, error);
207
+ return null;
208
+ });
209
+ plugins.set(type, pending);
210
+ }
211
+ return pending;
212
+ };
213
+ if (locales.length === 0) {
214
+ console.warn(`[phis-ui] The Site names no locales; the ${area} Area is not indexed.`);
215
+ return;
216
+ }
217
+ for (const locale of locales) {
218
+ if (heldFingerprint(areaMask, locale) === fingerprint)
219
+ continue;
220
+ const context = asIndexingReader(await loadPhiSiteRequestContext(siteKey, locale, "", apiBaseUrl, internalToken), area);
221
+ const documents = await readDocuments({ bridge, area, locale, context, candidates, loadPlugin });
222
+ const answer = await putPhiSiteSearchIndexSet({
223
+ ...credentials,
224
+ area,
225
+ locale,
226
+ fingerprint,
227
+ documents,
228
+ });
229
+ if (answer.dropped > 0) {
230
+ console.warn(`[phis-ui] The search index dropped ${answer.dropped} document(s) of the ${area} Area (${locale}).`);
231
+ }
232
+ // One line per set, so an operator's log says when a Site became searchable and how large it is.
233
+ console.info(`[phis-ui] Search index ${area}/${locale}: ${answer.accepted ? `${answer.state.documentCount} documents written` : "already held"}.`);
234
+ }
235
+ }
236
+ async function readDocuments({ bridge, area, locale, context, candidates, loadPlugin, }) {
237
+ const documents = new Array(candidates.length).fill(null);
238
+ let next = 0;
239
+ async function work() {
240
+ while (next < candidates.length) {
241
+ const index = next++;
242
+ const path = candidates[index].path;
243
+ try {
244
+ documents[index] = await readDocument({ bridge, area, locale, context, path, loadPlugin });
245
+ }
246
+ catch (error) {
247
+ console.error(`[phis-ui] The search index could not read ${area}:${path} (${locale}).`, error);
248
+ }
249
+ }
250
+ }
251
+ await Promise.all(Array.from({ length: PHI_SEARCH_INDEX_RESOLVE_CONCURRENCY }, work));
252
+ return documents
253
+ .filter((document) => document !== null)
254
+ .slice(0, PHI_SEARCH_MAX_DOCUMENTS);
255
+ }
256
+ /**
257
+ * One Page as a document, or `null` where a reader of this Area would not get one: nothing resolves
258
+ * there, it forwards, it asked to stay out of the index, or its access policy is narrower than the
259
+ * reader's. The words are the Page's title and description and every Widget's own answer, in tree order.
260
+ */
261
+ async function readDocument({ bridge, area, locale, context, path, loadPlugin, }) {
262
+ const resolved = await resolvePhiCmsLookup({
263
+ bridge,
264
+ area,
265
+ locale,
266
+ path,
267
+ cookieHeader: "",
268
+ requestContext: context,
269
+ });
270
+ if (!resolved)
271
+ return null;
272
+ const page = resolved.page.page;
273
+ if (resolvePhiCmsPageRedirect(page, locale) != null)
274
+ return null;
275
+ if (resolved.runtime.page?.noindex === true)
276
+ return null;
277
+ if (!canPhiViewerAccess(resolved.runtime.viewer, page.accessPolicy))
278
+ return null;
279
+ const lines = [];
280
+ for (const widget of resolved.page.contentWidgets) {
281
+ const plugin = await loadPlugin(widget.widgetType);
282
+ if (!plugin?.searchText)
283
+ continue;
284
+ try {
285
+ const config = plugin.parseConfig(widget.config);
286
+ lines.push(...await plugin.searchText({ widget, config, runtime: resolved.runtime }));
287
+ }
288
+ catch (error) {
289
+ // One Widget that cannot say its words costs the Page those words, not the Page.
290
+ console.error(`[phis-ui] The search index could not read the Widget "${widget.widgetType}" on ${area}:${path}.`, error);
291
+ }
292
+ }
293
+ return {
294
+ path: page.path,
295
+ title: resolved.runtime.page?.title ?? "",
296
+ description: resolved.runtime.page?.description ?? "",
297
+ text: joinPhiSearchText(lines),
298
+ };
299
+ }
@@ -0,0 +1,40 @@
1
+ import "server-only";
2
+ import type { PhiMarkdownBlock } from "../components/widgets/shared/markdown-body-client";
3
+ import { type PhiTextSource } from "../helpers/text-source";
4
+ import type { PhiBlockRuntime } from "../types";
5
+ /**
6
+ * What a Widget's `searchText` is made of (SEARCH.md): the words as a reader sees them, one line per
7
+ * block of text, with nothing a reader does not see.
8
+ *
9
+ * Three answers every text Widget needs: its own words translated the way its render translates them,
10
+ * a rendered Markdown document read back as lines, and an HTML fragment read without its tags. They
11
+ * stand here rather than in each Widget so that the index reads every Widget the same way.
12
+ */
13
+ /**
14
+ * The Widget's own words in the reader's language, the way the Widget's render translates them: a
15
+ * Preset's sentence through the platform's store, an author's through the Site's. Empty entries stay
16
+ * in place so the caller can line answers up with what it asked.
17
+ */
18
+ export declare function translatePhiSearchTexts(locale: string, texts: readonly (string | undefined | null)[], options: {
19
+ translate: boolean;
20
+ textSource?: PhiTextSource;
21
+ }): Promise<string[]>;
22
+ /**
23
+ * A Widget's own sentences the way its render shows them: masked, translated, filled -- the order
24
+ * `helpers/text-placeholders.ts` sets out, so `{site.name}` reads as the Site's name in the index as it
25
+ * does on the Page, and never reaches the translator. Empty entries are dropped.
26
+ */
27
+ export declare function translatePhiSearchWidgetTexts(runtime: PhiBlockRuntime, texts: readonly (string | undefined | null)[], options: {
28
+ translate: boolean;
29
+ textSource?: PhiTextSource;
30
+ }): Promise<string[]>;
31
+ /** A rendered Markdown document as lines of text, headings and paragraphs alike, code included. */
32
+ export declare function readPhiMarkdownSearchText(blocks: readonly PhiMarkdownBlock[]): string[];
33
+ /**
34
+ * An HTML fragment as lines of text: block elements end a line, every other tag is dropped, entities
35
+ * are read. Scripts and styles are gone before this is called -- the fragment is the sanitised one the
36
+ * Widget draws -- so only words remain.
37
+ */
38
+ export declare function readPhiHtmlSearchText(html: string): string[];
39
+ /** The lines a Widget answered, as one text: trimmed, empties dropped, one per line. */
40
+ export declare function joinPhiSearchText(lines: readonly (string | undefined | null)[]): string;
@@ -0,0 +1,152 @@
1
+ import "server-only";
2
+ import { maskPhiTextPlaceholders, resolvePhiTextPlaceholders } from "../helpers/text-placeholders";
3
+ import { PHI_TEXT_SOURCE_PRESET } from "../helpers/text-source";
4
+ import { trBulkForLocale, trGlobalBulkForLocale } from "./translate";
5
+ /**
6
+ * What a Widget's `searchText` is made of (SEARCH.md): the words as a reader sees them, one line per
7
+ * block of text, with nothing a reader does not see.
8
+ *
9
+ * Three answers every text Widget needs: its own words translated the way its render translates them,
10
+ * a rendered Markdown document read back as lines, and an HTML fragment read without its tags. They
11
+ * stand here rather than in each Widget so that the index reads every Widget the same way.
12
+ */
13
+ /**
14
+ * The Widget's own words in the reader's language, the way the Widget's render translates them: a
15
+ * Preset's sentence through the platform's store, an author's through the Site's. Empty entries stay
16
+ * in place so the caller can line answers up with what it asked.
17
+ */
18
+ export async function translatePhiSearchTexts(locale, texts, options) {
19
+ const source = texts.map((text) => (typeof text === "string" ? text.trim() : ""));
20
+ if (!options.translate || !source.some(Boolean)) {
21
+ return source;
22
+ }
23
+ const translated = options.textSource === PHI_TEXT_SOURCE_PRESET
24
+ ? await trGlobalBulkForLocale(locale, source)
25
+ : await trBulkForLocale(locale, source);
26
+ return translated.map((text, index) => text || source[index] || "");
27
+ }
28
+ /**
29
+ * A Widget's own sentences the way its render shows them: masked, translated, filled -- the order
30
+ * `helpers/text-placeholders.ts` sets out, so `{site.name}` reads as the Site's name in the index as it
31
+ * does on the Page, and never reaches the translator. Empty entries are dropped.
32
+ */
33
+ export async function translatePhiSearchWidgetTexts(runtime, texts, options) {
34
+ const present = texts.filter((text) => typeof text === "string" && text.trim().length > 0);
35
+ if (present.length === 0)
36
+ return [];
37
+ const masked = present.map((text) => maskPhiTextPlaceholders(text, 0));
38
+ const translated = await translatePhiSearchTexts(runtime.locale.current, masked.map((entry) => entry.text), options);
39
+ return translated
40
+ .map((text, index) => resolvePhiTextPlaceholders(text, masked[index].names, runtime, []))
41
+ .filter(Boolean);
42
+ }
43
+ function readInlineText(inlines) {
44
+ let text = "";
45
+ for (const inline of inlines) {
46
+ switch (inline.kind) {
47
+ case "text":
48
+ case "inline_code":
49
+ text += inline.text;
50
+ break;
51
+ case "strong":
52
+ case "emphasis":
53
+ case "delete":
54
+ case "link":
55
+ text += readInlineText(inline.children);
56
+ break;
57
+ case "image":
58
+ text += inline.alt;
59
+ break;
60
+ case "break":
61
+ text += " ";
62
+ break;
63
+ // A protected address is not written into the index: that is the point of protecting it.
64
+ case "mail_text":
65
+ break;
66
+ }
67
+ }
68
+ return text;
69
+ }
70
+ /** A rendered Markdown document as lines of text, headings and paragraphs alike, code included. */
71
+ export function readPhiMarkdownSearchText(blocks) {
72
+ const lines = [];
73
+ const push = (text) => {
74
+ const collapsed = text.replace(/\s+/gu, " ").trim();
75
+ if (collapsed)
76
+ lines.push(collapsed);
77
+ };
78
+ const walk = (block) => {
79
+ switch (block.kind) {
80
+ case "heading":
81
+ case "paragraph":
82
+ push(readInlineText(block.inlines));
83
+ break;
84
+ case "blockquote":
85
+ block.children.forEach(walk);
86
+ break;
87
+ case "list":
88
+ for (const item of block.items)
89
+ item.forEach(walk);
90
+ break;
91
+ case "code":
92
+ push(block.tokens.map((token) => token.text).join(""));
93
+ break;
94
+ case "table":
95
+ push(block.header.map(readInlineText).join(" "));
96
+ for (const row of block.rows)
97
+ push(row.map(readInlineText).join(" "));
98
+ break;
99
+ case "image":
100
+ push(block.image.alt);
101
+ break;
102
+ case "divider":
103
+ break;
104
+ }
105
+ };
106
+ blocks.forEach(walk);
107
+ return lines;
108
+ }
109
+ const HTML_BLOCK_TAGS = /<\/?(?:p|div|br|li|ul|ol|h[1-6]|tr|td|th|blockquote|pre|section|article|header|footer|figcaption|dd|dt)\b[^>]*>/giu;
110
+ const HTML_ENTITIES = {
111
+ amp: "&",
112
+ lt: "<",
113
+ gt: ">",
114
+ quot: "\"",
115
+ apos: "'",
116
+ nbsp: " ",
117
+ };
118
+ function decodeHtmlEntities(text) {
119
+ return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/giu, (whole, entity) => {
120
+ if (entity.startsWith("#x") || entity.startsWith("#X")) {
121
+ const code = Number.parseInt(entity.slice(2), 16);
122
+ return Number.isFinite(code) ? String.fromCodePoint(code) : whole;
123
+ }
124
+ if (entity.startsWith("#")) {
125
+ const code = Number.parseInt(entity.slice(1), 10);
126
+ return Number.isFinite(code) ? String.fromCodePoint(code) : whole;
127
+ }
128
+ return HTML_ENTITIES[entity.toLowerCase()] ?? whole;
129
+ });
130
+ }
131
+ /**
132
+ * An HTML fragment as lines of text: block elements end a line, every other tag is dropped, entities
133
+ * are read. Scripts and styles are gone before this is called -- the fragment is the sanitised one the
134
+ * Widget draws -- so only words remain.
135
+ */
136
+ export function readPhiHtmlSearchText(html) {
137
+ const withBreaks = html
138
+ .replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1>/giu, " ")
139
+ .replace(HTML_BLOCK_TAGS, "\n")
140
+ .replace(/<[^>]+>/gu, " ");
141
+ return withBreaks
142
+ .split("\n")
143
+ .map((line) => decodeHtmlEntities(line).replace(/\s+/gu, " ").trim())
144
+ .filter(Boolean);
145
+ }
146
+ /** The lines a Widget answered, as one text: trimmed, empties dropped, one per line. */
147
+ export function joinPhiSearchText(lines) {
148
+ return lines
149
+ .map((line) => (typeof line === "string" ? line.replace(/\s+/gu, " ").trim() : ""))
150
+ .filter(Boolean)
151
+ .join("\n");
152
+ }
@@ -11,3 +11,4 @@ export { loadPhiCmsRootRequest } from "./server-helpers/cms-root";
11
11
  export { isPhiCmsGatewayAuthError } from "./gateway/errors";
12
12
  export { loadPhiSiteRequestContext } from "./server-helpers/runtime";
13
13
  export { loadPhiRootLayoutContext, type LoadPhiRootLayoutContextOptions, type PhiRootLayoutContext, } from "./server-helpers/root-layout";
14
+ export { translatePhiSearchWidgetTexts } from "./server-helpers/search-text";
package/server-helpers.js CHANGED
@@ -17,3 +17,4 @@ export { loadPhiCmsRootRequest } from "./server-helpers/cms-root";
17
17
  export { isPhiCmsGatewayAuthError } from "./gateway/errors";
18
18
  export { loadPhiSiteRequestContext } from "./server-helpers/runtime";
19
19
  export { loadPhiRootLayoutContext, } from "./server-helpers/root-layout";
20
+ export { translatePhiSearchWidgetTexts } from "./server-helpers/search-text";
@@ -293,6 +293,59 @@ h5.phi-typography, .phi-typography h5 {
293
293
  --ant-menu-icon-margin-inline-end: calc(var(--ant-control-height-sm) - var(--phi-menu-font-size));
294
294
  }
295
295
 
296
+ /*
297
+ * A horizontal menu's mark for the current entry (`PhiMenuControl` `selectionStyle`).
298
+ *
299
+ * The pill: the entry stands at the control height in the middle of its bar, on a ground in the Theme's
300
+ * Control shape -- a light primary tint in light mode, the primary mixed into the dark ground in dark
301
+ * mode -- and no bar under it. Ant Design writes the bar's width under a dark menu as a number rather than
302
+ * its variable, so it is set to nothing on the entry itself.
303
+ */
304
+ .phi-menu-control--selection-pill.ant-menu.ant-menu-root.ant-menu-horizontal,
305
+ .phi-menu-control--selection-auto.ant-menu-dark.ant-menu-root.ant-menu-horizontal {
306
+ --ant-menu-active-bar-height: 0px;
307
+ /*
308
+ * The Theme's Control shape at the default size: one Control line tall, so the radius a grown Control
309
+ * holds is exactly this entry's -- the shape's number, or the capsule under `pill`.
310
+ */
311
+ --ant-menu-horizontal-item-border-radius: var(--phi-control-radius-grown-md, var(--ant-border-radius));
312
+ --ant-menu-horizontal-item-selected-bg: var(--ant-color-primary-bg);
313
+ --ant-menu-dark-item-selected-bg: color-mix(in srgb, var(--ant-color-primary) 30%, transparent);
314
+ }
315
+
316
+ .phi-menu-control--selection-pill.ant-menu-horizontal > :is(.ant-menu-item, .ant-menu-submenu),
317
+ .phi-menu-control--selection-auto.ant-menu-dark.ant-menu-horizontal > :is(.ant-menu-item, .ant-menu-submenu) {
318
+ align-self: center;
319
+ height: var(--ant-control-height);
320
+ line-height: var(--ant-control-height);
321
+ }
322
+
323
+ .phi-menu-control--selection-pill.ant-menu-horizontal > :is(.ant-menu-item, .ant-menu-submenu)::after,
324
+ .phi-menu-control--selection-auto.ant-menu-dark.ant-menu-horizontal > :is(.ant-menu-item, .ant-menu-submenu)::after {
325
+ border-bottom-width: 0;
326
+ }
327
+
328
+ /* The bar in dark mode as well: no ground, and the bar Ant Design leaves out under a dark menu. */
329
+ .phi-menu-control--selection-underline.ant-menu-dark.ant-menu-root.ant-menu-horizontal {
330
+ --ant-menu-dark-item-selected-bg: transparent;
331
+ --ant-menu-dark-item-selected-color: var(--ant-color-primary);
332
+ }
333
+
334
+ .phi-menu-control--selection-underline.ant-menu-dark.ant-menu-horizontal
335
+ > :is(.ant-menu-item-selected, .ant-menu-submenu-selected)::after {
336
+ /* Ant Design's own `lineWidthBold`, which it derives as `lineWidth + 1`. */
337
+ border-bottom-width: calc(var(--ant-line-width) + 1px);
338
+ border-bottom-color: var(--ant-color-primary);
339
+ }
340
+
341
+ /*
342
+ * A Markdown text's sections that fold (`foldSections`): a fine rule of the Theme's between the questions,
343
+ * so a list of them reads as a list while every one is closed.
344
+ */
345
+ .phi-markdown-folds :where(.ant-collapse-item + .ant-collapse-item) {
346
+ border-block-start: var(--ant-line-width, 1px) solid var(--ant-color-split);
347
+ }
348
+
296
349
  /* --- Labeled control ---------------------------------------------------------------------------- */
297
350
 
298
351
  /*
@@ -670,24 +723,69 @@ h5.phi-typography, .phi-typography h5 {
670
723
  * Markdown pictures the text flows past (`imageFloat` on the Markdown Widget).
671
724
  *
672
725
  * Only where there is room for both: below 560px a picture beside the words leaves each of them a column
673
- * nobody reads, so there the picture stands on its own line at full width, as an unfloated one does. The
674
- * width is a share of the text with a ceiling, so a wide column does not grow the picture past a glance.
726
+ * nobody reads, so there the picture stands on its own line at full width, as an unfloated one does.
727
+ *
728
+ * Beside the words the line is shared in the golden ratio: what is left after the gap between them goes
729
+ * 1 : φ to picture and text (`PHI_GOLDEN_RATIO`, 1 + φ = 2.618), so the text is 1.618 times as wide as the
730
+ * picture at any column width -- 415 px of picture beside 671 px of text in a 1120 px column, with the
731
+ * Phi scale's `md` (34 px) between them. Every distance here is the Phi scale's, never `--ant-margin-*`.
675
732
  */
676
- .phi-markdown-body :is(img) {
733
+ .phi-markdown-body {
734
+ /* The gap between picture and text, on the Phi scale (`PHI_SPACE.md`), not Ant Design's margins. */
735
+ --phi-markdown-float-gap: var(--ant-padding-md, 34px);
736
+ --phi-markdown-float-width: calc((100% - var(--phi-markdown-float-gap)) / 2.618034);
737
+ }
738
+
739
+ .phi-markdown-body :is(img):not(:where(.phi-markdown-figure *)) {
677
740
  display: block;
678
- margin-block-end: var(--ant-margin, 16px);
741
+ margin-block-end: var(--ant-padding, 21px);
742
+ /*
743
+ * A picture is a surface, so its corners are the Theme's surface step (`--phi-surface-radius`, THEME.md
744
+ * "Control shape"): square under `square`, the widest step of the scale under `pill`.
745
+ */
746
+ border-radius: var(--phi-surface-radius, 0);
747
+ }
748
+
749
+ @container (min-width: 560px) {
750
+ .phi-markdown-body--float-start :is(img):not(:where(.phi-markdown-figure *)) {
751
+ float: inline-start;
752
+ width: var(--phi-markdown-float-width);
753
+ margin-inline-end: var(--phi-markdown-float-gap);
754
+ }
755
+
756
+ .phi-markdown-body--float-end :is(img):not(:where(.phi-markdown-figure *)) {
757
+ float: inline-end;
758
+ width: var(--phi-markdown-float-width);
759
+ margin-inline-start: var(--phi-markdown-float-gap);
760
+ }
761
+ }
762
+
763
+ /*
764
+ * A Media picture standing on its own (`PhiMarkdownFigure`): a figure whose frame holds the picture at its
765
+ * proportion, cropped into it, on the Theme's surface corner. It floats as the Widget says or as its own
766
+ * address says (`float=start|end|none`), in the same golden share and from the same container width as above.
767
+ */
768
+ .phi-markdown-figure {
769
+ margin: 0 0 var(--ant-padding, 21px);
770
+ }
771
+
772
+ .phi-markdown-figure__frame {
773
+ position: relative;
774
+ width: 100%;
775
+ overflow: hidden;
776
+ border-radius: var(--phi-surface-radius, 0);
679
777
  }
680
778
 
681
779
  @container (min-width: 560px) {
682
- .phi-markdown-body--float-start :is(img) {
780
+ .phi-markdown-figure--float-start {
683
781
  float: inline-start;
684
- width: min(45%, 440px);
685
- margin-inline-end: var(--ant-margin-lg, 24px);
782
+ width: var(--phi-markdown-float-width);
783
+ margin-inline-end: var(--phi-markdown-float-gap);
686
784
  }
687
785
 
688
- .phi-markdown-body--float-end :is(img) {
786
+ .phi-markdown-figure--float-end {
689
787
  float: inline-end;
690
- width: min(45%, 440px);
691
- margin-inline-start: var(--ant-margin-lg, 24px);
788
+ width: var(--phi-markdown-float-width);
789
+ margin-inline-start: var(--phi-markdown-float-gap);
692
790
  }
693
791
  }