drupal-canvas 0.5.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/dist/index.d.ts +97 -1
- package/dist/index.js +143 -1
- package/dist/json-render-utils.js +11 -1
- package/dist/next-image-standalone.js +16 -17
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -379,6 +379,11 @@ export default function MyComponent({ photo }) {
|
|
|
379
379
|
}
|
|
380
380
|
```
|
|
381
381
|
|
|
382
|
+
Drupal generates no derivative images for an image its image toolkit cannot
|
|
383
|
+
process, an SVG image for example. Such an image is rendered as-is, without a
|
|
384
|
+
`srcset`. An SVG image that specifies neither its dimensions nor a `viewBox` is
|
|
385
|
+
rendered without `width` and `height` too, and is then sized by the browser.
|
|
386
|
+
|
|
382
387
|
### Region / RegionsProvider
|
|
383
388
|
|
|
384
389
|
Render Drupal Canvas global regions inside a layout component.
|
package/dist/index.d.ts
CHANGED
|
@@ -5,6 +5,102 @@ import { getNodePath, sortMenu as sortMenu$1 } from "./jsonapi-utils.js";
|
|
|
5
5
|
import Image from "./next-image-standalone.js";
|
|
6
6
|
import { cn } from "./utils.js";
|
|
7
7
|
import { ReactNode } from "react";
|
|
8
|
+
//#region src/date-utils.d.ts
|
|
9
|
+
/**
|
|
10
|
+
* Locale-aware date formatting utilities for Canvas Code Components.
|
|
11
|
+
*
|
|
12
|
+
* These functions format ISO date/time strings using the Drupal-selected
|
|
13
|
+
* langcode from `drupalSettings.canvasData.v0.langcode`. They are opt-in: Canvas passes date
|
|
14
|
+
* props to templates as raw ISO strings by default. Use these utilities when
|
|
15
|
+
* you want to display a date in the user's locale.
|
|
16
|
+
*
|
|
17
|
+
* All functions accept an optional `options` object so callers can override
|
|
18
|
+
* default format styles without losing the Drupal langcode or the UTC timezone
|
|
19
|
+
* guard that prevents stored dates from shifting by the viewer's UTC offset.
|
|
20
|
+
*
|
|
21
|
+
* @example Twig: `{{ my_date_prop|canvasFormatDate }}`
|
|
22
|
+
* @example JSX: `canvasFormatDate(myDateProp)`
|
|
23
|
+
* @example JSX with options: `canvasFormatDate(myDateProp, { dateStyle: 'long' })`
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* Options accepted by the Canvas date formatting utilities.
|
|
27
|
+
*
|
|
28
|
+
* All fields are optional and default to `'short'`. Pass an options object to
|
|
29
|
+
* override the format style without losing the Drupal langcode or UTC timezone
|
|
30
|
+
* guard.
|
|
31
|
+
*/
|
|
32
|
+
interface CanvasDateFormatOptions {
|
|
33
|
+
/** Controls the date portion style. Defaults to `'short'`. */
|
|
34
|
+
dateStyle?: Intl.DateTimeFormatOptions['dateStyle'];
|
|
35
|
+
/** Controls the time portion style. Defaults to `'short'`. */
|
|
36
|
+
timeStyle?: Intl.DateTimeFormatOptions['timeStyle'];
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Formats an ISO date string using the active Drupal locale's date format.
|
|
40
|
+
*
|
|
41
|
+
* Returns the original `iso` string unchanged if it cannot be parsed, and an
|
|
42
|
+
* empty string for `null` or `undefined` (an optional prop without a value).
|
|
43
|
+
*
|
|
44
|
+
* @param iso
|
|
45
|
+
* ISO date string, e.g. '2026-01-15'.
|
|
46
|
+
* @param options
|
|
47
|
+
* Optional format overrides. Defaults to `{ dateStyle: 'short' }`.
|
|
48
|
+
*
|
|
49
|
+
* @return
|
|
50
|
+
* Locale-formatted date string, e.g. '1/15/26' (en) or '15/01/2026' (fr).
|
|
51
|
+
*/
|
|
52
|
+
declare function canvasFormatDate(iso: string | null | undefined, options?: Pick<CanvasDateFormatOptions, 'dateStyle'>): string;
|
|
53
|
+
/**
|
|
54
|
+
* Formats an ISO datetime string using the active Drupal locale's format.
|
|
55
|
+
*
|
|
56
|
+
* Returns the original `iso` string unchanged if it cannot be parsed, and an
|
|
57
|
+
* empty string for `null` or `undefined` (an optional prop without a value).
|
|
58
|
+
*
|
|
59
|
+
* @param iso
|
|
60
|
+
* ISO datetime string, e.g. '2026-01-15T14:30:00Z'.
|
|
61
|
+
* @param options
|
|
62
|
+
* Optional format overrides. Defaults to
|
|
63
|
+
* `{ dateStyle: 'short', timeStyle: 'short' }`.
|
|
64
|
+
*
|
|
65
|
+
* @return
|
|
66
|
+
* Locale-formatted datetime string.
|
|
67
|
+
*/
|
|
68
|
+
declare function canvasFormatDateTime(iso: string | null | undefined, options?: CanvasDateFormatOptions): string;
|
|
69
|
+
/**
|
|
70
|
+
* Formats an ISO time/datetime string using the active Drupal locale's time format.
|
|
71
|
+
*
|
|
72
|
+
* Returns the original `iso` string unchanged if it cannot be parsed, and an
|
|
73
|
+
* empty string for `null` or `undefined` (an optional prop without a value).
|
|
74
|
+
*
|
|
75
|
+
* @param iso
|
|
76
|
+
* ISO time or datetime string, e.g. '14:30:00' or '2026-01-15T14:30:00Z'.
|
|
77
|
+
* @param options
|
|
78
|
+
* Optional format overrides. Defaults to `{ timeStyle: 'short' }`.
|
|
79
|
+
*
|
|
80
|
+
* @return
|
|
81
|
+
* Locale-formatted time string.
|
|
82
|
+
*/
|
|
83
|
+
declare function canvasFormatTime(iso: string | null | undefined, options?: Pick<CanvasDateFormatOptions, 'timeStyle'>): string;
|
|
84
|
+
/**
|
|
85
|
+
* Formats the `from` and `to` fields of a Canvas date-range prop.
|
|
86
|
+
*
|
|
87
|
+
* Returns `null` or `undefined` unchanged (an optional prop without a value).
|
|
88
|
+
*
|
|
89
|
+
* @param range
|
|
90
|
+
* Canvas date-range object, e.g. `{ from: '2026-01-15', to: '2026-03-20' }`.
|
|
91
|
+
* @param options
|
|
92
|
+
* Optional format overrides passed to each field. Defaults to
|
|
93
|
+
* `{ dateStyle: 'short' }`.
|
|
94
|
+
*
|
|
95
|
+
* @return
|
|
96
|
+
* A new object with the same keys; each string date value is replaced with a
|
|
97
|
+
* formatted string.
|
|
98
|
+
*/
|
|
99
|
+
declare function canvasFormatDateRange<T extends {
|
|
100
|
+
from?: string | null;
|
|
101
|
+
to?: string | null;
|
|
102
|
+
} | null | undefined>(range: T, options?: Pick<CanvasDateFormatOptions, 'dateStyle'>): T;
|
|
103
|
+
//#endregion
|
|
8
104
|
//#region src/Region.d.ts
|
|
9
105
|
type RegionsMap = Record<string, ReactNode>;
|
|
10
106
|
type RegionsProviderProps = {
|
|
@@ -18,4 +114,4 @@ type RegionProps = {
|
|
|
18
114
|
};
|
|
19
115
|
declare function Region({ name, fallback }: RegionProps): import("react/jsx-runtime").JSX.Element;
|
|
20
116
|
//#endregion
|
|
21
|
-
export { FormattedText, Image, CanvasJsonApiClient as JsonApiClient, Region, RegionsProvider, cn, getNodePath, getPageData, getSiteData, sortMenu as sortLinksetMenu, sortMenu$1 as sortMenu };
|
|
117
|
+
export { type CanvasDateFormatOptions, FormattedText, Image, CanvasJsonApiClient as JsonApiClient, Region, RegionsProvider, canvasFormatDate, canvasFormatDateRange, canvasFormatDateTime, canvasFormatTime, cn, getNodePath, getPageData, getSiteData, sortMenu as sortLinksetMenu, sortMenu$1 as sortMenu };
|
package/dist/index.js
CHANGED
|
@@ -6,6 +6,148 @@ import Image from "./next-image-standalone.js";
|
|
|
6
6
|
import { cn } from "./utils.js";
|
|
7
7
|
import { Fragment, jsx } from "react/jsx-runtime";
|
|
8
8
|
import { createContext, useContext } from "react";
|
|
9
|
+
//#region src/date-utils.ts
|
|
10
|
+
/**
|
|
11
|
+
* Reads the Drupal-selected langcode from Canvas runtime settings when present,
|
|
12
|
+
* falling back to `drupalSettings.langcode` and then 'en'.
|
|
13
|
+
*
|
|
14
|
+
* Canvas attaches `canvasData.v0.langcode` for every code component that imports
|
|
15
|
+
* one of these utilities: the import adds `v0.langcode` to the component's
|
|
16
|
+
* `dataDependencies.drupalSettings`. Drupal core only sets
|
|
17
|
+
* `drupalSettings.langcode` on pages with a machine name form element, so that
|
|
18
|
+
* fallback is not a langcode source on rendered pages.
|
|
19
|
+
*
|
|
20
|
+
* @see ui/src/features/code-editor/utils/ast-utils.ts
|
|
21
|
+
*/
|
|
22
|
+
const getDrupalLangcode = () => globalThis.drupalSettings?.canvasData?.v0?.langcode ?? globalThis.drupalSettings?.langcode ?? "en";
|
|
23
|
+
/**
|
|
24
|
+
* Creates an `Intl.DateTimeFormat` instance, falling back to 'en' locale if
|
|
25
|
+
* the Drupal langcode string is not a valid BCP 47 tag.
|
|
26
|
+
*
|
|
27
|
+
* Drupal langcodes like `zh-hans` or `pt-br` use lowercase language tag
|
|
28
|
+
* components which may throw `RangeError` in strict BCP 47 environments.
|
|
29
|
+
* The try/catch ensures graceful degradation.
|
|
30
|
+
*
|
|
31
|
+
* All formatters use `timeZone: 'UTC'` because Canvas date/datetime props are
|
|
32
|
+
* stored without timezone offset. Formatting in the local browser timezone
|
|
33
|
+
* would silently shift dates — e.g. a UTC midnight date would appear as the
|
|
34
|
+
* previous day in negative-UTC-offset timezones (Americas).
|
|
35
|
+
*/
|
|
36
|
+
const createFormatter = (locale, options) => {
|
|
37
|
+
const utcOptions = {
|
|
38
|
+
timeZone: "UTC",
|
|
39
|
+
...options
|
|
40
|
+
};
|
|
41
|
+
try {
|
|
42
|
+
return new Intl.DateTimeFormat(locale, utcOptions);
|
|
43
|
+
} catch {
|
|
44
|
+
return new Intl.DateTimeFormat("en", utcOptions);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Parses an ISO string to a Date object, returning null on failure.
|
|
49
|
+
*
|
|
50
|
+
* ECMAScript parses a date-time string without a UTC offset as local time,
|
|
51
|
+
* whereas date-only strings are parsed as UTC. Canvas treats every stored
|
|
52
|
+
* value as UTC (the PHP side appends `Z` before formatting), so a `Z` is
|
|
53
|
+
* appended to date-time strings that carry no offset. Without it, the UTC
|
|
54
|
+
* formatter would shift the value by the viewer's UTC offset.
|
|
55
|
+
*/
|
|
56
|
+
const parseIso = (iso) => {
|
|
57
|
+
if (!iso) return null;
|
|
58
|
+
const hasTimePart = /[T ]\d{2}:\d{2}/.test(iso);
|
|
59
|
+
const hasOffset = /(Z|[+-]\d{2}(:?\d{2})?)$/i.test(iso);
|
|
60
|
+
const d = new Date(hasTimePart && !hasOffset ? `${iso}Z` : iso);
|
|
61
|
+
return isNaN(d.getTime()) ? null : d;
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Formats an ISO date string using the active Drupal locale's date format.
|
|
65
|
+
*
|
|
66
|
+
* Returns the original `iso` string unchanged if it cannot be parsed, and an
|
|
67
|
+
* empty string for `null` or `undefined` (an optional prop without a value).
|
|
68
|
+
*
|
|
69
|
+
* @param iso
|
|
70
|
+
* ISO date string, e.g. '2026-01-15'.
|
|
71
|
+
* @param options
|
|
72
|
+
* Optional format overrides. Defaults to `{ dateStyle: 'short' }`.
|
|
73
|
+
*
|
|
74
|
+
* @return
|
|
75
|
+
* Locale-formatted date string, e.g. '1/15/26' (en) or '15/01/2026' (fr).
|
|
76
|
+
*/
|
|
77
|
+
function canvasFormatDate(iso, options) {
|
|
78
|
+
if (iso == null) return "";
|
|
79
|
+
const date = parseIso(iso);
|
|
80
|
+
if (!date) return iso;
|
|
81
|
+
return createFormatter(getDrupalLangcode(), { dateStyle: options?.dateStyle ?? "short" }).format(date);
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Formats an ISO datetime string using the active Drupal locale's format.
|
|
85
|
+
*
|
|
86
|
+
* Returns the original `iso` string unchanged if it cannot be parsed, and an
|
|
87
|
+
* empty string for `null` or `undefined` (an optional prop without a value).
|
|
88
|
+
*
|
|
89
|
+
* @param iso
|
|
90
|
+
* ISO datetime string, e.g. '2026-01-15T14:30:00Z'.
|
|
91
|
+
* @param options
|
|
92
|
+
* Optional format overrides. Defaults to
|
|
93
|
+
* `{ dateStyle: 'short', timeStyle: 'short' }`.
|
|
94
|
+
*
|
|
95
|
+
* @return
|
|
96
|
+
* Locale-formatted datetime string.
|
|
97
|
+
*/
|
|
98
|
+
function canvasFormatDateTime(iso, options) {
|
|
99
|
+
if (iso == null) return "";
|
|
100
|
+
const date = parseIso(iso);
|
|
101
|
+
if (!date) return iso;
|
|
102
|
+
return createFormatter(getDrupalLangcode(), {
|
|
103
|
+
dateStyle: options?.dateStyle ?? "short",
|
|
104
|
+
timeStyle: options?.timeStyle ?? "short"
|
|
105
|
+
}).format(date);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Formats an ISO time/datetime string using the active Drupal locale's time format.
|
|
109
|
+
*
|
|
110
|
+
* Returns the original `iso` string unchanged if it cannot be parsed, and an
|
|
111
|
+
* empty string for `null` or `undefined` (an optional prop without a value).
|
|
112
|
+
*
|
|
113
|
+
* @param iso
|
|
114
|
+
* ISO time or datetime string, e.g. '14:30:00' or '2026-01-15T14:30:00Z'.
|
|
115
|
+
* @param options
|
|
116
|
+
* Optional format overrides. Defaults to `{ timeStyle: 'short' }`.
|
|
117
|
+
*
|
|
118
|
+
* @return
|
|
119
|
+
* Locale-formatted time string.
|
|
120
|
+
*/
|
|
121
|
+
function canvasFormatTime(iso, options) {
|
|
122
|
+
if (iso == null) return "";
|
|
123
|
+
const normalized = /^\d{2}:\d{2}/.test(iso) ? `1970-01-01T${iso}` : iso;
|
|
124
|
+
const date = parseIso(normalized);
|
|
125
|
+
if (!date) return iso;
|
|
126
|
+
return createFormatter(getDrupalLangcode(), { timeStyle: options?.timeStyle ?? "short" }).format(date);
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Formats the `from` and `to` fields of a Canvas date-range prop.
|
|
130
|
+
*
|
|
131
|
+
* Returns `null` or `undefined` unchanged (an optional prop without a value).
|
|
132
|
+
*
|
|
133
|
+
* @param range
|
|
134
|
+
* Canvas date-range object, e.g. `{ from: '2026-01-15', to: '2026-03-20' }`.
|
|
135
|
+
* @param options
|
|
136
|
+
* Optional format overrides passed to each field. Defaults to
|
|
137
|
+
* `{ dateStyle: 'short' }`.
|
|
138
|
+
*
|
|
139
|
+
* @return
|
|
140
|
+
* A new object with the same keys; each string date value is replaced with a
|
|
141
|
+
* formatted string.
|
|
142
|
+
*/
|
|
143
|
+
function canvasFormatDateRange(range, options) {
|
|
144
|
+
if (range == null) return range;
|
|
145
|
+
const result = { ...range };
|
|
146
|
+
if (typeof result.from === "string") result.from = canvasFormatDate(result.from, options);
|
|
147
|
+
if (typeof result.to === "string") result.to = canvasFormatDate(result.to, options);
|
|
148
|
+
return result;
|
|
149
|
+
}
|
|
150
|
+
//#endregion
|
|
9
151
|
//#region src/Region.tsx
|
|
10
152
|
const RegionsContext = createContext({});
|
|
11
153
|
function RegionsProvider({ regions, children }) {
|
|
@@ -19,4 +161,4 @@ function Region({ name, fallback = null }) {
|
|
|
19
161
|
return /* @__PURE__ */ jsx(Fragment, { children: node ?? fallback });
|
|
20
162
|
}
|
|
21
163
|
//#endregion
|
|
22
|
-
export { FormattedText, Image, CanvasJsonApiClient as JsonApiClient, Region, RegionsProvider, cn, getNodePath, getPageData, getSiteData, sortMenu as sortLinksetMenu, sortMenu$1 as sortMenu };
|
|
164
|
+
export { FormattedText, Image, CanvasJsonApiClient as JsonApiClient, Region, RegionsProvider, canvasFormatDate, canvasFormatDateRange, canvasFormatDateTime, canvasFormatTime, cn, getNodePath, getPageData, getSiteData, sortMenu as sortLinksetMenu, sortMenu$1 as sortMenu };
|
|
@@ -588,6 +588,8 @@ function renderCanvasTree(components, registry) {
|
|
|
588
588
|
* Canvas JSON Schema `$ref` prefix used in component metadata.
|
|
589
589
|
*/
|
|
590
590
|
const CANVAS_REF_PREFIX = "json-schema-definitions://canvas.module/";
|
|
591
|
+
const COLOR_DEF_KEY = "color";
|
|
592
|
+
const COLOR_DEF_LOCAL_REF = "#/$defs/color";
|
|
591
593
|
/**
|
|
592
594
|
* Rewrites Canvas-specific `$ref` URIs to local JSON Pointer refs (`#/$defs/...`)
|
|
593
595
|
* that Zod's `fromJSONSchema` can resolve natively.
|
|
@@ -600,10 +602,18 @@ function rewriteCanvasRefs(node) {
|
|
|
600
602
|
else result[key] = rewriteCanvasRefs(value);
|
|
601
603
|
return result;
|
|
602
604
|
}
|
|
605
|
+
function normalizeCanvasDefsForValidation(defs) {
|
|
606
|
+
const result = { ...defs };
|
|
607
|
+
const colorDef = result[COLOR_DEF_KEY];
|
|
608
|
+
if (!colorDef || typeof colorDef !== "object" || Array.isArray(colorDef)) return result;
|
|
609
|
+
const colorDefRecord = colorDef;
|
|
610
|
+
if (colorDefRecord.$ref === COLOR_DEF_LOCAL_REF) delete colorDefRecord.$ref;
|
|
611
|
+
return result;
|
|
612
|
+
}
|
|
603
613
|
/**
|
|
604
614
|
* Pre-rewritten Canvas $defs with local refs.
|
|
605
615
|
*/
|
|
606
|
-
const canvasDefs = rewriteCanvasRefs($defs);
|
|
616
|
+
const canvasDefs = normalizeCanvasDefsForValidation(rewriteCanvasRefs($defs));
|
|
607
617
|
/**
|
|
608
618
|
* Recursively walks a JSON schema object, stripping `uri-reference` and
|
|
609
619
|
* `iri-reference` format keywords and collecting the property paths where
|
|
@@ -5,26 +5,25 @@ function Image(props) {
|
|
|
5
5
|
const { src, loader } = props;
|
|
6
6
|
const srcString = typeof src === "string" ? src : "default" in src ? src.default.src : src.src;
|
|
7
7
|
if (!loader) {
|
|
8
|
+
const alternateWidths = new URLSearchParams(srcString.split("?")[1]?.split("#")[0]).get("alternateWidths");
|
|
9
|
+
if (!alternateWidths) return /* @__PURE__ */ jsx(NextImage, {
|
|
10
|
+
...props,
|
|
11
|
+
loader: () => srcString,
|
|
12
|
+
unoptimized: true
|
|
13
|
+
});
|
|
8
14
|
const defaultLoader = ({ width, imageProps }) => {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
if (
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
if (!intrinsicWidth || !intrinsicHeight) throw new Error("Height calculation requires intrinsic image dimensions.");
|
|
17
|
-
const height = Math.round(width / (intrinsicWidth / intrinsicHeight));
|
|
18
|
-
result = result.replace("{height}", height.toString());
|
|
15
|
+
let result = alternateWidths.replace("{width}", width.toString());
|
|
16
|
+
if (result.includes("{height}")) {
|
|
17
|
+
const intrinsicWidth = Number(imageProps.width);
|
|
18
|
+
const intrinsicHeight = Number(imageProps.height);
|
|
19
|
+
if (!intrinsicWidth || !intrinsicHeight) {
|
|
20
|
+
console.error("Height calculation requires intrinsic image dimensions.", { src });
|
|
21
|
+
return srcString;
|
|
19
22
|
}
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
console.error("Responsive image generation failed. To fix this:\n1. Provide a custom `loader` function, or\n2. Ensure your image `src` includes an `alternateWidths` query parameter\n Example: ?alternateWidths=/path/to/responsive/{width}/image.jpg", {
|
|
23
|
-
src,
|
|
24
|
-
error
|
|
25
|
-
});
|
|
26
|
-
return srcString;
|
|
23
|
+
const height = Math.round(width / (intrinsicWidth / intrinsicHeight));
|
|
24
|
+
result = result.replace("{height}", height.toString());
|
|
27
25
|
}
|
|
26
|
+
return result;
|
|
28
27
|
};
|
|
29
28
|
return /* @__PURE__ */ jsx(NextImage, {
|
|
30
29
|
...props,
|