@phis/ui 0.5.5 → 0.5.6

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 (42) hide show
  1. package/components/controls/phi-anchor-nav-control.js +18 -1
  2. package/components/widgets/shared/card-body-client.d.ts +6 -2
  3. package/components/widgets/shared/card-body-client.js +27 -20
  4. package/components/widgets/shared/card-vocabulary.d.ts +7 -0
  5. package/components/widgets/shared/card-vocabulary.js +6 -0
  6. package/components/widgets/shared/markdown-body-client.js +7 -2
  7. package/constants/module-identity.d.ts +8 -0
  8. package/constants/module-identity.js +13 -0
  9. package/gateway/server-module-media.d.ts +12 -0
  10. package/gateway/server-module-media.js +83 -0
  11. package/helpers/cms-navigation-catalog.js +4 -1
  12. package/helpers/cms-page-catalog.d.ts +7 -0
  13. package/helpers/cms-preset-page-tree.js +16 -1
  14. package/helpers/module-media-check.d.ts +23 -0
  15. package/helpers/module-media-check.js +32 -0
  16. package/helpers/module-media.d.ts +7 -0
  17. package/helpers/module-media.js +15 -0
  18. package/helpers/route-address-check.d.ts +35 -0
  19. package/helpers/route-address-check.js +28 -0
  20. package/module-page-check.d.ts +2 -0
  21. package/module-page-check.js +2 -0
  22. package/package.json +1 -1
  23. package/plugins/runtime-modules/builder/area-shell-presets.server.js +2 -0
  24. package/plugins/runtime-modules/builder/navigation-folder-drop.js +2 -1
  25. package/plugins/runtime-modules/builder/options-providers.js +7 -1
  26. package/plugins/runtime-modules/builder/page-presets.server.js +2 -0
  27. package/plugins/runtime-modules/core/widgets/breadcrumb/server.js +9 -2
  28. package/plugins/runtime-modules/core/widgets/card/config.d.ts +7 -1
  29. package/plugins/runtime-modules/core/widgets/card/config.js +19 -2
  30. package/plugins/runtime-modules/core/widgets/card/editor.js +2 -0
  31. package/plugins/runtime-modules/core/widgets/card/server.js +2 -0
  32. package/plugins/runtime-modules/descriptor-compiler.d.ts +23 -3
  33. package/plugins/runtime-modules/descriptor-compiler.js +107 -12
  34. package/server-helpers/cms-area.js +9 -1
  35. package/server-helpers/cms-request.js +15 -2
  36. package/server-helpers/cms-root.js +2 -0
  37. package/server-helpers/module-folder-targets.d.ts +7 -0
  38. package/server-helpers/module-folder-targets.js +15 -0
  39. package/types/cms-module-descriptors.d.ts +24 -0
  40. package/types/module-media.d.ts +31 -0
  41. package/types/module-media.js +11 -0
  42. package/types.d.ts +1 -0
@@ -1,6 +1,23 @@
1
1
  "use client";
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { Anchor } from "antd";
4
+ /**
5
+ * Tells the page about a jump the way a link to `#id` would.
6
+ *
7
+ * Ant Design scrolls to the place itself and writes the address with `history.pushState`, which fires no
8
+ * `hashchange` -- so whatever opens on its fragment (a folded section, `markdown-body-client.tsx`) never
9
+ * heard of the jump and the reader landed on a closed question. Sent once the address is written, after
10
+ * the click. It is not the browser's event (`isTrusted` is false): a listener reads that the scroll is
11
+ * this Control's and leaves it alone.
12
+ */
13
+ function announcePhiInPageJump(oldURL) {
14
+ queueMicrotask(() => {
15
+ const newURL = window.location.href;
16
+ if (newURL !== oldURL) {
17
+ window.dispatchEvent(new HashChangeEvent("hashchange", { oldURL, newURL }));
18
+ }
19
+ });
20
+ }
4
21
  /**
5
22
  * Links to places on the same page, with the one currently in view marked.
6
23
  *
@@ -8,7 +25,7 @@ import { Anchor } from "antd";
8
25
  * page, the shape a table of contents takes. It stays where it is drawn and never pins itself.
9
26
  */
10
27
  export function PhiAnchorNavControl({ items, offsetTop = 0, style }) {
11
- return (_jsx(Anchor, { affix: false, offsetTop: offsetTop, items: [...items], className: "phi-anchor-nav-control",
28
+ return (_jsx(Anchor, { affix: false, offsetTop: offsetTop, items: [...items], onClick: () => announcePhiInPageJump(window.location.href), className: "phi-anchor-nav-control",
12
29
  // As wide as its slot and no wider: Ant Design sizes the list to its longest title, which in a
13
30
  // narrow sider ran past the edge. Within the slot a long title ends in an ellipsis, Ant Design's own.
14
31
  style: { maxWidth: "100%", minWidth: 0, ...style } }));
@@ -7,8 +7,8 @@ import type { PhiImagePresentation } from "../../media/image-presentation";
7
7
  import type { PhiClientBlockBaseProps } from "../../../types";
8
8
  import type { PhiSurface } from "../../../types/surface";
9
9
  import type { PhiSignalRouteSet } from "../../../types/signals";
10
- import type { PhiCardBadgeStyle, PhiCardBillingPeriod, PhiCardHeadingLevel, PhiCardHoverEffect, PhiCardIconPlacement, PhiCardTextAlign, PhiCardTextSlot, PhiCardVariant, PhiCardWidgetBody } from "./card-vocabulary";
11
- export type { PhiCardBadgeStyle, PhiCardBillingPeriod, PhiCardHeadingLevel, PhiCardHoverEffect, PhiCardIconPlacement, PhiCardTextAlign, PhiCardTextSlot, PhiCardVariant, PhiCardWidgetBody, } from "./card-vocabulary";
10
+ import type { PhiCardBadgeStyle, PhiCardBillingPeriod, PhiCardHeadingLevel, PhiCardHoverEffect, PhiCardIconPlacement, PhiCardIconSize, PhiCardTextAlign, PhiCardTextSlot, PhiCardVariant, PhiCardWidgetBody } from "./card-vocabulary";
11
+ export type { PhiCardBadgeStyle, PhiCardBillingPeriod, PhiCardHeadingLevel, PhiCardHoverEffect, PhiCardIconPlacement, PhiCardIconSize, PhiCardTextAlign, PhiCardTextSlot, PhiCardVariant, PhiCardWidgetBody, } from "./card-vocabulary";
12
12
  export type PhiCardWidgetClientLabels = {
13
13
  eyebrow?: string;
14
14
  /**
@@ -62,6 +62,10 @@ export type PhiCardWidgetClientConfig = {
62
62
  /** The icon's colour and its ground; absent, the Theme's. */
63
63
  iconColor?: string;
64
64
  iconBackground?: string;
65
+ /** How large the icon is drawn; absent is `default`. */
66
+ iconSize?: PhiCardIconSize;
67
+ /** `false` draws the icon without its ground; absent is framed, as a card always drew it. */
68
+ iconFramed?: boolean;
65
69
  textAlign?: PhiCardTextAlign;
66
70
  headingLevel?: PhiCardHeadingLevel;
67
71
  /** Where the whole card leads, already resolved to an address. */
@@ -56,8 +56,7 @@ const PHI_CARD_VARIANT_METRICS = {
56
56
  h4: { fontSize: token.fontSizeHeading4, lineHeight: token.lineHeightHeading4 },
57
57
  },
58
58
  descriptionSize: token.fontSizeLG,
59
- iconSize: 24,
60
- topIconSize: 40,
59
+ iconSizes: { default: { inline: 24, top: 40 }, large: { inline: 40, top: 64 }, xlarge: { inline: 64, top: 96 } },
61
60
  buttonSize: "medium",
62
61
  }),
63
62
  compact: (token) => ({
@@ -69,8 +68,7 @@ const PHI_CARD_VARIANT_METRICS = {
69
68
  h4: { fontSize: token.fontSizeHeading5, lineHeight: token.lineHeightHeading5 },
70
69
  },
71
70
  descriptionSize: token.fontSize,
72
- iconSize: 20,
73
- topIconSize: 32,
71
+ iconSizes: { default: { inline: 20, top: 32 }, large: { inline: 24, top: 40 }, xlarge: { inline: 40, top: 64 } },
74
72
  buttonSize: "small",
75
73
  // A strip rather than a poster, so the words stay the larger part of a compact card.
76
74
  mediaAspectRatio: "2 / 1",
@@ -145,9 +143,11 @@ export function PhiCardWidgetClient({ labels: placedLabels, config, binding, lis
145
143
  const variant = config?.variant ?? "default";
146
144
  const body = config?.body ?? "text";
147
145
  const metrics = (PHI_CARD_VARIANT_METRICS[variant] ?? PHI_CARD_VARIANT_METRICS.default)(token);
148
- const { inset, gap, headingType, descriptionSize, iconSize, topIconSize, buttonSize } = metrics;
146
+ const { inset, gap, headingType, descriptionSize, buttonSize } = metrics;
149
147
  const textAlign = metrics.arrangement?.textAlign ?? config?.textAlign ?? "start";
150
148
  const headingLevel = config?.headingLevel ?? "h3";
149
+ const { inline: iconSize, top: topIconSize } = metrics.iconSizes[config?.iconSize ?? "default"];
150
+ const iconFramed = config?.iconFramed !== false;
151
151
  const iconPlacement = metrics.arrangement?.iconPlacement ?? config?.iconPlacement ?? "inline";
152
152
  const highlight = overrides.highlight ?? config?.highlight === true;
153
153
  const href = config?.href;
@@ -202,13 +202,17 @@ export function PhiCardWidgetClient({ labels: placedLabels, config, binding, lis
202
202
  /*
203
203
  * The icon's colours as custom properties, which `.phi-card__icon` paints (`styles/layout.css`): the
204
204
  * `icon` hover effect turns them round, and a colour stated inline could not be turned by a rule.
205
+ * An icon without its ground takes no part in that: it has no ground to turn the colours onto, so it
206
+ * carries no `phi-card__icon` class and states its colour directly, which no hover rule reaches.
205
207
  */
206
- const iconColours = (color, background) => ({
207
- "--phi-card-icon-color": color,
208
- "--phi-card-icon-background": background,
209
- /* The mark's colour once the `icon` effect turns them round: a ground it can be read on. */
210
- "--phi-card-icon-hover-color": config?.iconBackground ?? PHI_COLOR.bgContainer,
211
- });
208
+ const iconColours = (color, background) => (iconFramed
209
+ ? {
210
+ "--phi-card-icon-color": color,
211
+ "--phi-card-icon-background": background,
212
+ /* The mark's colour once the `icon` effect turns them round: a ground it can be read on. */
213
+ "--phi-card-icon-hover-color": config?.iconBackground ?? PHI_COLOR.bgContainer,
214
+ }
215
+ : { color });
212
216
  /*
213
217
  * The corner of the icon's ground: the Theme's Control shape at the large size, scaled from a large
214
218
  * Control's height to the ground's side. So `square` draws a square, `pill` a circle -- half the large
@@ -217,15 +221,16 @@ export function PhiCardWidgetClient({ labels: placedLabels, config, binding, lis
217
221
  */
218
222
  const iconCorner = (side) => `calc(var(--phi-control-radius-lg, ${token.borderRadiusLG}px) * ${side / token.controlHeightLG})`;
219
223
  /* The framed box an icon before the title stands in. */
220
- const inlineIconFrame = iconSize + 16;
221
- const iconMark = (size, framed) => iconName ? (_jsx("span", { "aria-hidden": "true", className: "phi-card__icon", style: {
224
+ const inlineIconFrame = iconFramed ? iconSize + 16 : iconSize;
225
+ const topIconFrame = iconFramed ? topIconSize + 24 : topIconSize;
226
+ const iconMark = (size, framed) => iconName ? (_jsx("span", { "aria-hidden": "true", className: iconFramed ? "phi-card__icon" : undefined, style: {
222
227
  display: "inline-flex",
223
228
  flex: "none",
224
229
  alignItems: "center",
225
230
  justifyContent: "center",
226
231
  width: framed,
227
232
  height: framed,
228
- borderRadius: iconCorner(framed),
233
+ ...(iconFramed ? { borderRadius: iconCorner(framed) } : {}),
229
234
  ...iconColours(config?.iconColor ?? (highlight ? PHI_COLOR.primary : PHI_COLOR.textSecondary), config?.iconBackground ?? PHI_COLOR.fillQuaternary),
230
235
  }, children: _jsx(PhiIcon, { name: iconName, size: size }) })) : null;
231
236
  /*
@@ -285,6 +290,8 @@ export function PhiCardWidgetClient({ labels: placedLabels, config, binding, lis
285
290
  position: "relative",
286
291
  aspectRatio: config?.mediaAspectRatio ?? metrics.mediaAspectRatio ?? resolveMediaAspectRatio(image.presentation),
287
292
  overflow: "hidden",
293
+ // The icon stands in the picture's middle: a picture shorter than its box would clip it.
294
+ ...(iconAtTop && iconName ? { minHeight: topIconFrame } : {}),
288
295
  }, children: [_jsx(PhiImageControl, { presentation: image.presentation, source: image.source, alt: image.alt, blurDataUrl: image.blurDataUrl, optimizable: image.optimizable, sizes: PHI_CARD_IMAGE_SIZES, style: { width: "100%", height: "100%" }, imageStyle: {
289
296
  width: "100%",
290
297
  height: "100%",
@@ -294,7 +301,7 @@ export function PhiCardWidgetClient({ labels: placedLabels, config, binding, lis
294
301
  position: "absolute",
295
302
  inset: 0,
296
303
  pointerEvents: "none",
297
- } })) : null, iconAtTop && iconName ? (_jsx("span", { "aria-hidden": "true", className: "phi-card__icon", style: {
304
+ } })) : null, iconAtTop && iconName ? (_jsx("span", { "aria-hidden": "true", className: iconFramed ? "phi-card__icon" : undefined, style: {
298
305
  position: "absolute",
299
306
  insetInlineStart: markSide === "start" ? inset : markSide === "end" ? undefined : "50%",
300
307
  insetInlineEnd: markSide === "end" ? inset : undefined,
@@ -303,12 +310,12 @@ export function PhiCardWidgetClient({ labels: placedLabels, config, binding, lis
303
310
  display: "inline-flex",
304
311
  alignItems: "center",
305
312
  justifyContent: "center",
306
- width: topIconSize + 24,
307
- height: topIconSize + 24,
308
- borderRadius: iconCorner(topIconSize + 24),
313
+ width: topIconFrame,
314
+ height: topIconFrame,
315
+ ...(iconFramed ? { borderRadius: iconCorner(topIconFrame) } : {}),
309
316
  // A ground of its own, so the mark reads on a bright picture and on a dark one alike.
310
317
  ...iconColours(config?.iconColor ?? (highlight ? PHI_COLOR.primary : PHI_COLOR.text), config?.iconBackground ?? `color-mix(in srgb, ${PHI_COLOR.bgContainer} 88%, transparent)`),
311
- boxShadow: token.boxShadowTertiary,
318
+ ...(iconFramed ? { boxShadow: token.boxShadowTertiary } : {}),
312
319
  }, children: _jsx(PhiIcon, { name: iconName, size: topIconSize }) })) : null, eyebrowOnMedia && eyebrow != null ? (_jsx(PhiTypographyControl, { type: "secondary", style: {
313
320
  ...eyebrowType,
314
321
  position: "absolute",
@@ -363,7 +370,7 @@ export function PhiCardWidgetClient({ labels: placedLabels, config, binding, lis
363
370
  : {}),
364
371
  }
365
372
  : {}), ...(renderText ? { style: { pointerEvents: "auto", minWidth: "6em" } } : {}), children: badge })) : null;
366
- const words = (_jsxs("div", { style: { display: "grid", gap, padding: footAction ? 0 : inset, justifyItems }, children: [iconAtTop && iconName && !image ? (_jsx("div", { style: { justifySelf: markSide === "center" ? "center" : markSide === "end" ? "end" : "start" }, children: iconMark(topIconSize, topIconSize + 24) })) : null, eyebrow != null && !eyebrowOnMedia && !labels.eyebrowEnd ? (_jsx(PhiTypographyControl, { type: "secondary", style: { ...eyebrowType, color: highlight ? PHI_COLOR.primary : PHI_COLOR.textTertiary, ...slotWidth }, children: eyebrow })) : null, labels.eyebrowEnd && !eyebrowOnMedia ? (_jsxs(PhiFlexControl, { justify: "space-between", align: "baseline", wrap: true, gap: PHI_SPACE.xs, style: { justifySelf: "stretch", minWidth: 0 }, children: [_jsx(PhiTypographyControl, { type: "secondary", style: { ...eyebrowType, color: highlight ? PHI_COLOR.primary : PHI_COLOR.textTertiary }, children: eyebrow ?? "" }), _jsx(PhiTypographyControl, { type: "secondary", style: { ...eyebrowType, color: PHI_COLOR.textTertiary }, children: labels.eyebrowEnd })] })) : null, headingRow, body === "stat" ? figure : null, body === "series" ? (_jsxs(_Fragment, { children: [labels.value || binding?.error || binding?.loading === true || overrides.loading === true ? figure : null, list != null && !binding?.error && binding?.loading !== true && overrides.loading !== true ? (_jsx("div", { style: { justifySelf: "stretch", minWidth: 0 }, children: list })) : null] })) : null, body === "list" && list != null ? (_jsx("div", { style: { justifySelf: "stretch", minWidth: 0 }, children: list })) : null, description != null ? (_jsx(PhiTypographyControl, { presentation: "paragraph", style: {
373
+ const words = (_jsxs("div", { style: { display: "grid", gap, padding: footAction ? 0 : inset, justifyItems }, children: [iconAtTop && iconName && !image ? (_jsx("div", { style: { justifySelf: markSide === "center" ? "center" : markSide === "end" ? "end" : "start" }, children: iconMark(topIconSize, topIconFrame) })) : null, eyebrow != null && !eyebrowOnMedia && !labels.eyebrowEnd ? (_jsx(PhiTypographyControl, { type: "secondary", style: { ...eyebrowType, color: highlight ? PHI_COLOR.primary : PHI_COLOR.textTertiary, ...slotWidth }, children: eyebrow })) : null, labels.eyebrowEnd && !eyebrowOnMedia ? (_jsxs(PhiFlexControl, { justify: "space-between", align: "baseline", wrap: true, gap: PHI_SPACE.xs, style: { justifySelf: "stretch", minWidth: 0 }, children: [_jsx(PhiTypographyControl, { type: "secondary", style: { ...eyebrowType, color: highlight ? PHI_COLOR.primary : PHI_COLOR.textTertiary }, children: eyebrow ?? "" }), _jsx(PhiTypographyControl, { type: "secondary", style: { ...eyebrowType, color: PHI_COLOR.textTertiary }, children: labels.eyebrowEnd })] })) : null, headingRow, body === "stat" ? figure : null, body === "series" ? (_jsxs(_Fragment, { children: [labels.value || binding?.error || binding?.loading === true || overrides.loading === true ? figure : null, list != null && !binding?.error && binding?.loading !== true && overrides.loading !== true ? (_jsx("div", { style: { justifySelf: "stretch", minWidth: 0 }, children: list })) : null] })) : null, body === "list" && list != null ? (_jsx("div", { style: { justifySelf: "stretch", minWidth: 0 }, children: list })) : null, description != null ? (_jsx(PhiTypographyControl, { presentation: "paragraph", style: {
367
374
  marginBottom: 0,
368
375
  color: PHI_COLOR.textSecondary,
369
376
  fontSize: descriptionSize,
@@ -53,6 +53,13 @@ export type PhiCardBadgeStyle = (typeof PHI_CARD_BADGE_STYLES)[number];
53
53
  */
54
54
  export declare const PHI_CARD_ICON_PLACEMENTS: readonly ["inline", "top", "top-center", "top-end"];
55
55
  export type PhiCardIconPlacement = (typeof PHI_CARD_ICON_PLACEMENTS)[number];
56
+ /**
57
+ * How large the icon is drawn: fixed steps, no pixel entry, so every card of a Site stands on the same few
58
+ * sizes and the variant's table (`PHI_CARD_VARIANT_METRICS`) decides what each step is for its placement.
59
+ * Absent is `default`, which is what a card drew before the steps existed.
60
+ */
61
+ export declare const PHI_CARD_ICON_SIZES: readonly ["default", "large", "xlarge"];
62
+ export type PhiCardIconSize = (typeof PHI_CARD_ICON_SIZES)[number];
56
63
  /**
57
64
  * How a card that leads somewhere answers the pointer; a card without a link has none. A list, so a
58
65
  * further effect is an entry and a rule in `styles/layout.css`, not another flag. `lift` raises the card, `zoom` enlarges its picture, `icon`
@@ -39,6 +39,12 @@ export const PHI_CARD_BADGE_STYLES = ["none", "corner", "tag", "ribbon"];
39
39
  * picture. Logical like the text alignment: `top` is the left in a left-to-right page.
40
40
  */
41
41
  export const PHI_CARD_ICON_PLACEMENTS = ["inline", "top", "top-center", "top-end"];
42
+ /**
43
+ * How large the icon is drawn: fixed steps, no pixel entry, so every card of a Site stands on the same few
44
+ * sizes and the variant's table (`PHI_CARD_VARIANT_METRICS`) decides what each step is for its placement.
45
+ * Absent is `default`, which is what a card drew before the steps existed.
46
+ */
47
+ export const PHI_CARD_ICON_SIZES = ["default", "large", "xlarge"];
42
48
  /**
43
49
  * How a card that leads somewhere answers the pointer; a card without a link has none. A list, so a
44
50
  * further effect is an entry and a rule in `styles/layout.css`, not another flag. `lift` raises the card, `zoom` enlarges its picture, `icon`
@@ -230,12 +230,14 @@ export function PhiMarkdownWidgetClient({ config, labels }) {
230
230
  * The sections that fold: each heading is a header, what follows it the body. Every answer is drawn even
231
231
  * while folded, so a search engine and the browser's own find read the whole text. A heading keeps its id,
232
232
  * so the table of contents and a link to `#that-question` reach it -- and a link to it opens it, on arrival
233
- * and whenever the address's fragment changes.
233
+ * and whenever the address's fragment changes. The table of contents announces its jumps as a fragment
234
+ * change of its own (`phi-anchor-nav-control.tsx`) and scrolls there itself, with the Header's offset;
235
+ * only on arrival and on the browser's own change is the heading scrolled to here.
234
236
  */
235
237
  function PhiMarkdownFoldedSections({ sections, accordion, renderBody, }) {
236
238
  const [openKeys, setOpenKeys] = useState([]);
237
239
  useEffect(() => {
238
- const openFromAddress = () => {
240
+ const openFromAddress = (event) => {
239
241
  const id = decodeURIComponent(window.location.hash.slice(1));
240
242
  if (!id)
241
243
  return;
@@ -243,6 +245,9 @@ function PhiMarkdownFoldedSections({ sections, accordion, renderBody, }) {
243
245
  if (!section)
244
246
  return;
245
247
  setOpenKeys((current) => accordion ? [section.heading.id] : [...new Set([...current, section.heading.id])]);
248
+ // A change the page sent itself comes with its own scroll (the table of contents').
249
+ if (event && !event.isTrusted)
250
+ return;
246
251
  window.requestAnimationFrame(() => document.getElementById(id)?.scrollIntoView({ block: "start" }));
247
252
  };
248
253
  openFromAddress();
@@ -65,3 +65,11 @@ export declare function parsePhiModuleIconName(value: unknown): {
65
65
  moduleId: `${string}/${string}`;
66
66
  name: string;
67
67
  } | null;
68
+ /**
69
+ * The npm package a runtime module id belongs to: its first two path segments
70
+ * (`@phis/phisys/modules/site` -> `@phis/phisys`).
71
+ *
72
+ * What is declared per package -- the pictures of `phis.media` -- is looked up by this name, so a Module
73
+ * reaches its own package's names and nobody else's. Throws on an id that is not a runtime module id.
74
+ */
75
+ export declare function readPhiRuntimeModulePackageName(moduleId: string): string;
@@ -127,3 +127,16 @@ export function parsePhiModuleIconName(value) {
127
127
  const name = reference.slice(cut + 1);
128
128
  return isPhiRuntimeModuleId(moduleId) && isPhiModuleIconName(name) ? { moduleId, name } : null;
129
129
  }
130
+ /**
131
+ * The npm package a runtime module id belongs to: its first two path segments
132
+ * (`@phis/phisys/modules/site` -> `@phis/phisys`).
133
+ *
134
+ * What is declared per package -- the pictures of `phis.media` -- is looked up by this name, so a Module
135
+ * reaches its own package's names and nobody else's. Throws on an id that is not a runtime module id.
136
+ */
137
+ export function readPhiRuntimeModulePackageName(moduleId) {
138
+ if (!isPhiRuntimeModuleId(moduleId)) {
139
+ throw new Error(`Invalid Phi runtime module id: ${moduleId}.`);
140
+ }
141
+ return moduleId.split("/", 2).join("/");
142
+ }
@@ -0,0 +1,12 @@
1
+ import "server-only";
2
+ import { type PhiModuleMediaLoader, type PhiModuleMediaMapping } from "../types/module-media";
3
+ export declare function parsePhiModuleMediaMapping(value: unknown): PhiModuleMediaMapping;
4
+ /** Re-arms the once-per-process log; for tests. */
5
+ export declare function resetPhiModuleMediaUnavailableLog(): void;
6
+ export declare function getPhiModuleMediaMapping(options: {
7
+ apiBaseUrl: string;
8
+ internalToken: string;
9
+ siteKey: string;
10
+ }): Promise<PhiModuleMediaMapping>;
11
+ /** The loader a server caller hands to the descriptor compiler for this Site. */
12
+ export declare function createPhiModuleMediaLoader(siteKey: string): PhiModuleMediaLoader;
@@ -0,0 +1,83 @@
1
+ import "server-only";
2
+ import { isPhiRecord } from "../helpers/is-record";
3
+ import { readPhiServerApiCredentials } from "../helpers/phis-server-credentials";
4
+ import { PHI_EMPTY_MODULE_MEDIA_MAPPING, } from "../types/module-media";
5
+ import { fetchPhiSiteApi } from "./site-api-request";
6
+ import { readPhiSiteReadCache } from "./site-read-cache";
7
+ const PACKAGE_NAME_PATTERN = /^@[^/]+\/[^/]+$/;
8
+ const KEY_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
9
+ function parseIds(value, what) {
10
+ if (!isPhiRecord(value)) {
11
+ throw new Error(`Invalid module media ${what}.`);
12
+ }
13
+ const result = {};
14
+ for (const [packageName, keys] of Object.entries(value)) {
15
+ if (!PACKAGE_NAME_PATTERN.test(packageName) || !isPhiRecord(keys)) {
16
+ throw new Error(`Invalid module media ${what}.`);
17
+ }
18
+ const ids = {};
19
+ for (const [key, id] of Object.entries(keys)) {
20
+ if (!KEY_PATTERN.test(key) || typeof id !== "number" || !Number.isSafeInteger(id) || id <= 0) {
21
+ throw new Error(`Invalid module media ${what}.`);
22
+ }
23
+ ids[key] = id;
24
+ }
25
+ result[packageName] = ids;
26
+ }
27
+ return result;
28
+ }
29
+ export function parsePhiModuleMediaMapping(value) {
30
+ if (!isPhiRecord(value)) {
31
+ throw new Error("Invalid module media mapping.");
32
+ }
33
+ return { assets: parseIds(value.assets, "assets"), folders: parseIds(value.folders, "folders") };
34
+ }
35
+ let unavailableLogged = false;
36
+ /** Re-arms the once-per-process log; for tests. */
37
+ export function resetPhiModuleMediaUnavailableLog() {
38
+ unavailableLogged = false;
39
+ }
40
+ export async function getPhiModuleMediaMapping(options) {
41
+ /*
42
+ * Kept in the read cache outside development, with the capability snapshot's reasoning and lifetime
43
+ * (60 s): the mapping is the same for every viewer and changes only on `phis module media sync` or a
44
+ * rebind, which no read marker sees, so the TTL is what lets a hand binding reach a running Site.
45
+ */
46
+ if (process.env.NODE_ENV === "development") {
47
+ return loadPhiModuleMediaMapping(options);
48
+ }
49
+ return readPhiSiteReadCache(`module-media:${options.siteKey.trim().toLowerCase()}`, () => loadPhiModuleMediaMapping(options));
50
+ }
51
+ /**
52
+ * Unlike the capability snapshot, a Core that cannot answer is not an error here: a missing route (`404`,
53
+ * a Core older than the route), a refusal or an unreachable Core give the empty mapping, and the first
54
+ * time per process is logged. A missing picture must not take a page down, and `@phis/ui` may be rolled
55
+ * out before the Core that knows the route. An answer that arrives but is malformed still throws.
56
+ */
57
+ async function loadPhiModuleMediaMapping({ apiBaseUrl, internalToken, siteKey, }) {
58
+ let answer;
59
+ try {
60
+ answer = await fetchPhiSiteApi({
61
+ context: "getPhiModuleMediaMapping",
62
+ apiBaseUrl,
63
+ internalToken,
64
+ siteKey,
65
+ path: "/api/v1/site/module-media",
66
+ failure: "Failed to read module media",
67
+ });
68
+ }
69
+ catch (error) {
70
+ if (!unavailableLogged) {
71
+ unavailableLogged = true;
72
+ console.warn("[phi-module-media] The Site's module media could not be read; presets leave their pictures out.", {
73
+ error,
74
+ });
75
+ }
76
+ return PHI_EMPTY_MODULE_MEDIA_MAPPING;
77
+ }
78
+ return parsePhiModuleMediaMapping(answer);
79
+ }
80
+ /** The loader a server caller hands to the descriptor compiler for this Site. */
81
+ export function createPhiModuleMediaLoader(siteKey) {
82
+ return () => getPhiModuleMediaMapping({ ...readPhiServerApiCredentials(), siteKey });
83
+ }
@@ -51,7 +51,10 @@ function materializeNavigationItem(item, tombstones, customItems, overrides) {
51
51
  const customTarget = customItem?.target;
52
52
  // A Site's stored external link and a Module's external entry resolve to the same target.
53
53
  const externalTarget = item.target?.kind === "custom" && item.target.external === true ? item.target : null;
54
- const folder = item.kind === "container" ? customItem?.folder ?? overrides.get(item.id)?.folder : undefined;
54
+ // A Site's own choice first; a Module container's descriptor names its default (`folderTarget`).
55
+ const folder = item.kind === "container"
56
+ ? customItem?.folder ?? overrides.get(item.id)?.folder ?? item.folder
57
+ : undefined;
55
58
  return {
56
59
  id: item.id,
57
60
  source: item.ownerModuleId === null ? "custom" : "module",
@@ -43,6 +43,13 @@ export type PhiPresetPageNode = {
43
43
  pendingPath?: string | null;
44
44
  pathLocked?: boolean;
45
45
  pathOwnershipReason?: string;
46
+ /**
47
+ * A route that answers a family of Pages, by its parameter's name: `slug` for `/blog/:slug`. Every
48
+ * entry of a list answers on it, so it is shown as their kind ("Slug") rather than as one Page, and
49
+ * nothing links to it -- a link names one entry. It stands beneath its list's Page where there is one
50
+ * (`helpers/cms-preset-page-tree.ts`).
51
+ */
52
+ routeParameter?: string;
46
53
  children?: PhiPresetPageNode[];
47
54
  };
48
55
  /** A Page's address as the Builder shows it: the current one, and where a pending rename moves it. */
@@ -47,9 +47,19 @@ export function insertPhiPresetPageTarget(roots, target) {
47
47
  });
48
48
  return;
49
49
  }
50
+ /*
51
+ * A segment is one node, whether a Page answers on it or it only holds what lies beneath: a folder
52
+ * and a Page of the same address side by side read as two entries for one place. The one nesting
53
+ * routes may have is a list's entries beneath the list (`/blog/:slug` under `/blog`,
54
+ * `helpers/route-address-check.ts`), so they hang beneath the list's Page; whichever route comes
55
+ * first, the Page takes the folder's place and keeps what it held.
56
+ */
50
57
  let siblings = roots;
58
+ let folderPath = "";
51
59
  for (const segment of segments.slice(0, -1)) {
52
- let group = siblings.find((node) => node.key === segment);
60
+ folderPath = `${folderPath}/${segment}`;
61
+ let group = siblings.find((node) => node.catalogPath === folderPath)
62
+ ?? siblings.find((node) => node.key === segment && !node.storagePath);
53
63
  if (!group) {
54
64
  group = { key: segment, title: humanizePageKey(segment), children: [] };
55
65
  siblings.push(group);
@@ -57,6 +67,9 @@ export function insertPhiPresetPageTarget(roots, target) {
57
67
  group.children ??= [];
58
68
  siblings = group.children;
59
69
  }
70
+ const last = segments[segments.length - 1];
71
+ const folderIndex = siblings.findIndex((node) => node.key === last && !node.storagePath);
72
+ const held = folderIndex >= 0 ? siblings.splice(folderIndex, 1)[0].children ?? [] : [];
60
73
  siblings.push({
61
74
  key: pageId,
62
75
  title: target.title,
@@ -66,6 +79,8 @@ export function insertPhiPresetPageTarget(roots, target) {
66
79
  ...(target.defaultPageFlags ? { defaultPageFlags: target.defaultPageFlags } : {}),
67
80
  ...(target.landingPage ? { landingPage: true } : {}),
68
81
  ...(target.pageRecord ? { pageRecord: { providerKey: target.pageRecord.providerKey } } : {}),
82
+ ...(last.startsWith(":") ? { routeParameter: last.slice(1) } : {}),
83
+ ...(held.length > 0 ? { children: held } : {}),
69
84
  });
70
85
  }
71
86
  /**
@@ -0,0 +1,23 @@
1
+ import type { PhiModuleMediaResolver } from "../types/module-media";
2
+ /** A name a preset asked for that the package does not declare in `phis.media`. */
3
+ export type PhiModuleMediaFinding = {
4
+ kind: "asset" | "folder";
5
+ key: string;
6
+ message: string;
7
+ };
8
+ /**
9
+ * The resolver a Module package hands its own `loadTree` in its verify step, where there is no Core
10
+ * (THIRD_PARTY_MODULES.md, "Checking a Page preset").
11
+ *
12
+ * `assets` and `folders` are the keys the package declares in `phis.media`. A declared key answers a
13
+ * placeholder id -- a stable positive integer, distinct from every other key's -- so the tree is built
14
+ * as on a Site that has imported everything. An undeclared key answers `null` and is recorded: on a
15
+ * real Site it would never resolve. Verify-time only, from `@phis/ui/module/page-check`.
16
+ */
17
+ export declare function createPhiDeclaredMediaResolver(declared?: {
18
+ assets?: readonly string[];
19
+ folders?: readonly string[];
20
+ }): {
21
+ media: PhiModuleMediaResolver;
22
+ findings(): PhiModuleMediaFinding[];
23
+ };
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The resolver a Module package hands its own `loadTree` in its verify step, where there is no Core
3
+ * (THIRD_PARTY_MODULES.md, "Checking a Page preset").
4
+ *
5
+ * `assets` and `folders` are the keys the package declares in `phis.media`. A declared key answers a
6
+ * placeholder id -- a stable positive integer, distinct from every other key's -- so the tree is built
7
+ * as on a Site that has imported everything. An undeclared key answers `null` and is recorded: on a
8
+ * real Site it would never resolve. Verify-time only, from `@phis/ui/module/page-check`.
9
+ */
10
+ export function createPhiDeclaredMediaResolver(declared = {}) {
11
+ const ids = new Map();
12
+ const found = [];
13
+ const answer = (kind, declaredKeys, key) => {
14
+ if (!declaredKeys?.includes(key)) {
15
+ if (!found.some((finding) => finding.kind === kind && finding.key === key)) {
16
+ found.push({ kind, key, message: `${kind} \`${key}\` is not declared in the package's \`phis.media\`.` });
17
+ }
18
+ return null;
19
+ }
20
+ const id = `${kind}:${key}`;
21
+ if (!ids.has(id))
22
+ ids.set(id, ids.size + 1);
23
+ return ids.get(id);
24
+ };
25
+ return {
26
+ media: {
27
+ asset: async (key) => answer("asset", declared.assets, key),
28
+ folder: async (key) => answer("folder", declared.folders, key),
29
+ },
30
+ findings: () => [...found],
31
+ };
32
+ }
@@ -0,0 +1,7 @@
1
+ import type { PhiModuleMediaLoader, PhiModuleMediaResolver } from "../types/module-media";
2
+ /**
3
+ * The resolver a preset of `ownerModuleId` is handed: the names of that Module's own package, answered
4
+ * from `load`. `load` runs on the first question only and its promise is kept, so one instantiation asks
5
+ * Core at most once and a preset that asks nothing costs nothing.
6
+ */
7
+ export declare function createPhiModuleMediaResolver(ownerModuleId: string, load: PhiModuleMediaLoader): PhiModuleMediaResolver;
@@ -0,0 +1,15 @@
1
+ import { readPhiRuntimeModulePackageName } from "../constants/module-identity";
2
+ /**
3
+ * The resolver a preset of `ownerModuleId` is handed: the names of that Module's own package, answered
4
+ * from `load`. `load` runs on the first question only and its promise is kept, so one instantiation asks
5
+ * Core at most once and a preset that asks nothing costs nothing.
6
+ */
7
+ export function createPhiModuleMediaResolver(ownerModuleId, load) {
8
+ const packageName = readPhiRuntimeModulePackageName(ownerModuleId);
9
+ let mapping = null;
10
+ const read = () => (mapping ??= load());
11
+ return {
12
+ asset: async (key) => (await read()).assets[packageName]?.[key] ?? null,
13
+ folder: async (key) => (await read()).folders[packageName]?.[key] ?? null,
14
+ };
15
+ }
@@ -0,0 +1,35 @@
1
+ import type { PhiCmsAreaKey } from "../constants/cms-areas";
2
+ /**
3
+ * Whether a Module's routes keep the rule that a Page is never a folder (THIRD_PARTY_MODULES.md,
4
+ * "Addresses and folders"; phis-server REFERENCES.md, "A Page is never a folder").
5
+ *
6
+ * A route whose path lies beneath another route's path in the same Area makes the upper one a Page and
7
+ * a folder at once: the Builder lists it twice -- the Page, and a folder of the same name beside it --
8
+ * and a Navigation container of the lower Pages gets a folder address that the upper Page shadows. An
9
+ * overview belongs beside the Pages it leads to (`/faq/overview` next to `/faq/hosting`), and the
10
+ * container's `folderTarget` sends `/faq` to it.
11
+ *
12
+ * One nesting is allowed: a list's entries directly beneath the list, `/blog` and `/blog/:slug`. The
13
+ * entries are not Pages of their own in a Navigation -- one route answers every entry -- so no
14
+ * container is built of them and no folder address is shadowed. Anything further down is a Page beneath
15
+ * a Page again: `/blog/:slug/edit` beneath `/blog`, `/blog/archive` beside `/blog/:slug`.
16
+ *
17
+ * Compared by segment, a parameter by its name like any other segment: `/shop/:slug` and `/shop/cart`
18
+ * are siblings. `/` is the Area's root slot and no folder.
19
+ *
20
+ * Verify-time only, from `@phis/ui/module/page-check`: a package runs it over its own routes, and
21
+ * phis-ui over the first-party ones. The Site's own Pages are refused by phis-server when written.
22
+ */
23
+ export type PhiRouteAddressSubject = {
24
+ area: PhiCmsAreaKey;
25
+ path: string;
26
+ presetKey: string;
27
+ };
28
+ export type PhiRouteAddressFinding = {
29
+ /** The route beneath, by its preset key. */
30
+ route: string;
31
+ /** The route above it, which would be a Page and a folder at once. */
32
+ above: string;
33
+ message: string;
34
+ };
35
+ export declare function checkPhiRouteAddresses(routes: readonly PhiRouteAddressSubject[]): PhiRouteAddressFinding[];
@@ -0,0 +1,28 @@
1
+ function segments(path) {
2
+ return path.split("/").filter(Boolean);
3
+ }
4
+ export function checkPhiRouteAddresses(routes) {
5
+ const findings = [];
6
+ for (const route of routes) {
7
+ const own = segments(route.path);
8
+ for (const other of routes) {
9
+ if (other === route || other.area !== route.area)
10
+ continue;
11
+ const upper = segments(other.path);
12
+ if (upper.length === 0 || upper.length >= own.length)
13
+ continue;
14
+ if (!upper.every((segment, index) => segment === own[index]))
15
+ continue;
16
+ // A list's entries, one parameter directly beneath it.
17
+ if (own.length === upper.length + 1 && own[own.length - 1].startsWith(":"))
18
+ continue;
19
+ findings.push({
20
+ route: route.presetKey,
21
+ above: other.presetKey,
22
+ message: `"${route.path}" lies beneath "${other.path}" (${other.presetKey}) in Area "${route.area}": `
23
+ + "a Page is never a folder. Put the upper Page beside the others and name it the container's folderTarget.",
24
+ });
25
+ }
26
+ }
27
+ return findings;
28
+ }
@@ -9,5 +9,7 @@
9
9
  *
10
10
  * No `server-only` here, on purpose: a test in a package loads this door without a mock.
11
11
  */
12
+ export { createPhiDeclaredMediaResolver, type PhiModuleMediaFinding } from "./helpers/module-media-check";
12
13
  export { checkPhiPagePresetLayout, type PhiPageLayoutFinding } from "./helpers/page-layout-check";
13
14
  export { checkPhiPresetTextSources, type PhiPresetTextSourceFinding } from "./helpers/preset-text-source-check";
15
+ export { checkPhiRouteAddresses, type PhiRouteAddressFinding, type PhiRouteAddressSubject } from "./helpers/route-address-check";
@@ -9,5 +9,7 @@
9
9
  *
10
10
  * No `server-only` here, on purpose: a test in a package loads this door without a mock.
11
11
  */
12
+ export { createPhiDeclaredMediaResolver } from "./helpers/module-media-check";
12
13
  export { checkPhiPagePresetLayout } from "./helpers/page-layout-check";
13
14
  export { checkPhiPresetTextSources } from "./helpers/preset-text-source-check";
15
+ export { checkPhiRouteAddresses } from "./helpers/route-address-check";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phis/ui",
3
- "version": "0.5.5",
3
+ "version": "0.5.6",
4
4
  "license": "Apache-2.0",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -12,6 +12,7 @@ import { resolvePhiBuilderAreaAsCmsArea } from "../../../constants/cms-areas";
12
12
  import { instantiatePhiCmsAreaShellPreset, resolvePhiCmsAreaShellPresetBinding, resolvePhiCmsDescriptorCatalog, } from "../../../plugins/runtime-modules/descriptor-compiler";
13
13
  import { PHI_BUILDER_AREA_SEARCH_PARAM, normalizePhiBuilderAreaSearchParam, } from "../../../helpers/cms-scope-search-params";
14
14
  import { readPhiServerApiCredentials } from "../../../helpers/phis-server-credentials";
15
+ import { createPhiModuleMediaLoader } from "../../../gateway/server-module-media";
15
16
  /**
16
17
  * Every Area's installed Shell as the Builder edits it: with the current content of every node somebody
17
18
  * wrote content for. All Areas together and once per request, because the Builder holds the preset
@@ -31,6 +32,7 @@ const loadInstalledAreaShellPresetTrees = cache(async function loadInstalledArea
31
32
  siteId: runtime.site.id,
32
33
  path: resolveStructureAreaPath(area),
33
34
  runtime,
35
+ loadModuleMedia: createPhiModuleMediaLoader(runtime.site.key),
34
36
  });
35
37
  return [area, tree];
36
38
  }))).filter((entry) => entry != null);