drupal-canvas 0.7.0 → 0.8.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.
@@ -1,6 +1,6 @@
1
1
  import { jsx } from "react/jsx-runtime";
2
2
  import NextImage from "next-image-standalone";
3
- //#region src/next-image-standalone.tsx
3
+ // src/next-image-standalone.tsx
4
4
  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;
@@ -37,5 +37,4 @@ function Image(props) {
37
37
  sizes: props.sizes || "auto 100vw"
38
38
  });
39
39
  }
40
- //#endregion
41
40
  export { Image as default };
package/dist/react.d.ts CHANGED
@@ -1,7 +1,54 @@
1
- import { a as useSiteContext, i as usePageContext, n as CanvasContextProviderProps, r as useHasCanvasContext, t as CanvasContextProvider } from "./context-Cb4HbPbR.js";
2
- import { a as LegacyJsonApiClient } from "./jsonapi-client-BAQ3V5CC.js";
1
+ import { a as useHasCanvasContext, c as useTranslation, d as TranslationArgs, f as TranslationOptions, i as TranslationsProviderProps, l as FormatPluralFunction, n as CanvasContextProviderProps, o as usePageContext, r as TranslationsProvider, s as useSiteContext, t as CanvasContextProvider, u as TranslateFunction } from "./context-DMp0nsTU.js";
2
+ import { a as LegacyJsonApiClient } from "./jsonapi-client-CKzxh1on.js";
3
3
  import { ReactNode } from "react";
4
- //#region src/jsonapi-client-context.d.ts
4
+ /**
5
+ * Locale-aware date formatting for Canvas Code Components.
6
+ *
7
+ * `useDateFormatter()` (see `date-formatter.ts`) returns a function that
8
+ * formats ISO date/time strings in the interface language the rendering
9
+ * integration supplies through the site context. This module holds the
10
+ * React-free formatting itself. Formatting is opt-in: Canvas passes date props
11
+ * to components as raw ISO strings by default.
12
+ *
13
+ * It accepts an optional `options` object so callers can override
14
+ * default format styles without losing the site locale or the UTC timezone
15
+ * guard that prevents stored dates from shifting by the viewer's UTC offset.
16
+ */
17
+ /**
18
+ * Options accepted by the function `useDateFormatter()` returns.
19
+ *
20
+ * Pass an options object to override the format style without losing the
21
+ * site locale or UTC timezone guard. When neither style is set, each part
22
+ * the value has is shown in the `'short'` style. When at least one is set,
23
+ * only the parts set are shown. A part the value does not have is ignored.
24
+ */
25
+ interface CanvasDateFormatOptions {
26
+ /** Style of the date part. Defaults to `'short'` when no option is set. */
27
+ dateStyle?: Intl.DateTimeFormatOptions['dateStyle'];
28
+ /** Style of the time part. Defaults to `'short'` when no option is set. */
29
+ timeStyle?: Intl.DateTimeFormatOptions['timeStyle'];
30
+ }
31
+ /** Formats ISO date, date-time, and time strings in the site's locale. */
32
+ type DateFormatter = (value: string | null | undefined, options?: CanvasDateFormatOptions) => string;
33
+ /**
34
+ * Returns a function that formats ISO date, date-time, and time strings in the
35
+ * interface language of the site.
36
+ *
37
+ * The locale comes from the site context, which every rendering integration
38
+ * (Drupal-rendered pages, Workbench, Headless) supplies, so it needs no
39
+ * runtime-specific setup. Without a site language it falls back to `en`.
40
+ *
41
+ * The parts shown depend on the value: a date, a time, or both. Each part uses
42
+ * the `'short'` style unless options are passed; see `CanvasDateFormatOptions`.
43
+ * Values are always formatted in UTC, because Canvas stores them without a
44
+ * time zone. To format a date range prop, call the function on its `from` and
45
+ * `to` values.
46
+ *
47
+ * @example
48
+ * const formatDate = useDateFormatter();
49
+ * return <time>{formatDate(date, { dateStyle: 'long' })}</time>;
50
+ */
51
+ export declare function useDateFormatter(): DateFormatter;
5
52
  interface JsonApiClientProviderProps {
6
53
  client: LegacyJsonApiClient;
7
54
  children?: ReactNode;
@@ -10,16 +57,15 @@ interface JsonApiClientProviderProps {
10
57
  * Makes a configured JSON:API client available to every React descendant.
11
58
  * It does not construct the client or manage authentication.
12
59
  */
13
- declare function JsonApiClientProvider({ client, children }: JsonApiClientProviderProps): import("react/jsx-runtime").JSX.Element;
60
+ export declare function JsonApiClientProvider({ client, children }: JsonApiClientProviderProps): import("react/jsx-runtime").JSX.Element;
14
61
  /**
15
62
  * Returns the nearest provider's client, or `null` with a deduplicated
16
63
  * warning when no provider exists. The hook never fetches data or creates a
17
64
  * client on render.
18
65
  */
19
- declare function useJsonApiClient(): LegacyJsonApiClient | null;
66
+ export declare function useJsonApiClient(): LegacyJsonApiClient | null;
20
67
  /**
21
68
  * Whether a `JsonApiClientProvider` is mounted above the calling component.
22
69
  */
23
- declare function useHasJsonApiClient(): boolean;
24
- //#endregion
25
- export { CanvasContextProvider, type CanvasContextProviderProps, JsonApiClientProvider, type JsonApiClientProviderProps, useHasCanvasContext, useHasJsonApiClient, useJsonApiClient, usePageContext, useSiteContext };
70
+ export declare function useHasJsonApiClient(): boolean;
71
+ export { CanvasContextProvider, type CanvasContextProviderProps, type CanvasDateFormatOptions, type DateFormatter, type FormatPluralFunction, type JsonApiClientProviderProps, type TranslateFunction, type TranslationArgs, type TranslationOptions, TranslationsProvider, type TranslationsProviderProps, useHasCanvasContext, usePageContext, useSiteContext, useTranslation };
package/dist/react.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { jsx } from "react/jsx-runtime";
2
- import { createContext, useContext, useEffect } from "react";
3
- //#region src/data-inspection.ts
2
+ import { createContext, useContext, useEffect, useMemo } from "react";
3
+ // src/data-inspection.ts
4
4
  /**
5
5
  * @file
6
6
  * Editor data inspection: reports the values a Code Component reads through
@@ -35,8 +35,31 @@ function reportCanvasData(id, data) {
35
35
  });
36
36
  } catch {}
37
37
  }
38
- //#endregion
39
- //#region src/warnings.ts
38
+ // src/translation.ts
39
+ /** Joins plural forms, like Drupal's `PoItem::DELIMITER`. */
40
+ const PLURAL_DELIMITER = "";
41
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
42
+ const lookUp = (translations, str, options) => translations?.strings?.[options?.context ?? ""]?.[str] || void 0;
43
+ function translate(translations, str, args, options) {
44
+ return replacePlaceholders(lookUp(translations, str, options) ?? str, args);
45
+ }
46
+ function formatPlural(translations, count, singular, plural, args, options) {
47
+ const source = singular + PLURAL_DELIMITER + plural;
48
+ const translated = lookUp(translations, source, options);
49
+ const forms = replacePlaceholders(translated ?? source, {
50
+ ...args,
51
+ "@count": count
52
+ }).split(PLURAL_DELIMITER);
53
+ const formula = translated ? translations?.pluralFormula : null;
54
+ return forms[formula ? formula[count > 199 ? 100 + count % 100 : count] ?? formula.default ?? 0 : count === 1 ? 0 : 1] ?? forms[forms.length - 1];
55
+ }
56
+ function replacePlaceholders(translated, args) {
57
+ const keys = Object.keys(args ?? {}).filter((key) => key.startsWith("@"));
58
+ if (!args || keys.length === 0) return translated;
59
+ const pattern = new RegExp(keys.sort((a, b) => b.length - a.length).map(escapeRegExp).join("|"), "g");
60
+ return translated.replace(pattern, (key) => String(args[key]));
61
+ }
62
+ // src/warnings.ts
40
63
  /**
41
64
  * @file
42
65
  * Deduplicated developer warnings for the context hooks. Each distinct
@@ -50,8 +73,7 @@ function warnOnce(message) {
50
73
  emitted.add(message);
51
74
  console.warn(`[drupal-canvas] ${message}`);
52
75
  }
53
- //#endregion
54
- //#region src/context.tsx
76
+ // src/context.tsx
55
77
  /**
56
78
  * @file
57
79
  * The shared page and site context for React Code Components. Rendering
@@ -77,6 +99,22 @@ function CanvasContextProvider({ context, children }) {
77
99
  children
78
100
  });
79
101
  }
102
+ /** `undefined` means no `TranslationsProvider` is mounted. */
103
+ const TranslationsContext = createContext(void 0);
104
+ TranslationsContext.displayName = "CanvasTranslations";
105
+ /**
106
+ * Replaces the translations `useTranslation()` uses below it. The nearest
107
+ * provider takes precedence over the Canvas context's translations, also over
108
+ * a context that a rendering integration provides further down, such as the
109
+ * `context` of `CanvasComponentTree`. Without it, components use the
110
+ * translations of the Canvas context. Adds no DOM wrapper.
111
+ */
112
+ function TranslationsProvider({ translations, children }) {
113
+ return /* @__PURE__ */ jsx(TranslationsContext.Provider, {
114
+ value: translations,
115
+ children
116
+ });
117
+ }
80
118
  const MISSING_PROVIDER_WARNING = "No CanvasContextProvider is mounted above this component. In headless React applications pass `context={page.context}` to CanvasComponentTree or wrap the tree in CanvasContextProvider; in Drupal and Workbench the rendering integration provides it.";
81
119
  /**
82
120
  * Returns the current page context, or `null` when no provider supplies one.
@@ -108,6 +146,33 @@ function useSiteContext() {
108
146
  return site;
109
147
  }
110
148
  /**
149
+ * Returns `t()` and `formatPlural()`, which translate strings into the page's
150
+ * interface language. They take the arguments of `Drupal.t()` and
151
+ * `Drupal.formatPlural()`, with `@` placeholders only, but return text, not
152
+ * HTML, which React escapes when it renders it. The code editor, the Canvas
153
+ * CLI, and the Headless SDK find the strings to translate in the component
154
+ * source: pass string literals.
155
+ *
156
+ * The translations come from the nearest `TranslationsProvider`, otherwise
157
+ * from the Canvas context. Without a translation for a string, they return the
158
+ * source string. Without either provider they also warn once.
159
+ *
160
+ * @example
161
+ * const { t, formatPlural } = useTranslation();
162
+ * t('Hello @name', { '@name': name });
163
+ * formatPlural(count, '1 item', '@count items');
164
+ */
165
+ function useTranslation() {
166
+ const context = useContext(Context$1);
167
+ const override = useContext(TranslationsContext);
168
+ if (context === void 0 && override === void 0) warnOnce(`useTranslation(): ${MISSING_PROVIDER_WARNING}`);
169
+ const translations = override === void 0 ? context?.translations : override;
170
+ return useMemo(() => ({
171
+ t: (str, args, options) => translate(translations, str, args, options),
172
+ formatPlural: (count, singular, plural, args, options) => formatPlural(translations, count, singular, plural, args, options)
173
+ }), [translations]);
174
+ }
175
+ /**
111
176
  * Whether a `CanvasContextProvider` is mounted above the calling component.
112
177
  * Rendering integrations use it to decide whether to inherit an outer
113
178
  * provider instead of adding their own.
@@ -115,8 +180,122 @@ function useSiteContext() {
115
180
  function useHasCanvasContext() {
116
181
  return useContext(Context$1) !== void 0;
117
182
  }
118
- //#endregion
119
- //#region src/jsonapi-client-context.tsx
183
+ // src/date-utils.ts
184
+ /**
185
+ * Creates an `Intl.DateTimeFormat` instance, falling back to 'en' locale if
186
+ * the langcode string is not a valid BCP 47 tag.
187
+ *
188
+ * Drupal langcodes like `zh-hans` or `pt-br` use lowercase language tag
189
+ * components which may throw `RangeError` in strict BCP 47 environments.
190
+ * The try/catch ensures graceful degradation.
191
+ *
192
+ * All formatters use `timeZone: 'UTC'` because Canvas date/datetime props are
193
+ * stored without timezone offset. Formatting in the local browser timezone
194
+ * would silently shift dates — e.g. a UTC midnight date would appear as the
195
+ * previous day in negative-UTC-offset timezones (Americas).
196
+ */
197
+ const createFormatter = (locale, options) => {
198
+ const utcOptions = {
199
+ timeZone: "UTC",
200
+ ...options
201
+ };
202
+ try {
203
+ return new Intl.DateTimeFormat(locale, utcOptions);
204
+ } catch {
205
+ return new Intl.DateTimeFormat("en", utcOptions);
206
+ }
207
+ };
208
+ /**
209
+ * Parses an ISO string to a Date object, returning null on failure.
210
+ *
211
+ * ECMAScript parses a date-time string without a UTC offset as local time,
212
+ * whereas date-only strings are parsed as UTC. Canvas treats every value as
213
+ * UTC, but values can arrive without an offset (e.g. static prop values, which
214
+ * never pass through the PHP evaluator). So a `Z` is appended to date-time
215
+ * strings that carry no offset, regardless of what the server did. Without it,
216
+ * the UTC formatter would shift the value by the viewer's UTC offset.
217
+ */
218
+ const parseIso = (iso) => {
219
+ if (!iso) return null;
220
+ const normalized = iso.replace(/^(\d{4}-\d{2}-\d{2}) (?=\d{2}:\d{2})/, "$1T");
221
+ const hasTimePart = /[T ]\d{2}:\d{2}/.test(normalized);
222
+ const hasOffset = /(?:Z|[+-]\d{2}(?::?\d{2})?)$/i.test(normalized);
223
+ const d = new Date(hasTimePart && !hasOffset ? `${normalized}Z` : normalized);
224
+ return isNaN(d.getTime()) ? null : d;
225
+ };
226
+ /**
227
+ * Formats an ISO date, date-time, or time string in a locale.
228
+ *
229
+ * The parts shown depend on the value:
230
+ * - date only (`2026-01-15`): the date.
231
+ * - time only (`14:30:00`): the time.
232
+ * - date and time (`2026-01-15T14:30:00Z`): the date and the time.
233
+ *
234
+ * Each part uses the `'short'` style unless `options` is passed. When
235
+ * `options` is passed, only the parts it sets are shown, so
236
+ * `{ timeStyle: 'short' }` shows only the time of a date-time value. A part the
237
+ * value does not have is ignored, e.g. `timeStyle` for a date-only value. If
238
+ * no part remains, the defaults for the value apply.
239
+ *
240
+ * Returns the original `value` string unchanged if it cannot be parsed, and an
241
+ * empty string for `null` or `undefined` (an optional prop without a value).
242
+ *
243
+ * To format a date range prop, call this function on its `from` and `to`
244
+ * values.
245
+ *
246
+ * @param value
247
+ * ISO date, date-time, or time string.
248
+ * @param locale
249
+ * The Drupal langcode of the locale, e.g. `fr`.
250
+ * @param options
251
+ * Optional format styles for the date and time parts.
252
+ *
253
+ * @return
254
+ * Locale-formatted string, e.g. '1/15/26' (en) or '15/01/2026' (fr) for
255
+ * '2026-01-15'.
256
+ */
257
+ function formatDateInLocale(value, locale, options) {
258
+ if (value == null) return "";
259
+ const isTimeOnly = /^\d{2}:\d{2}/.test(value);
260
+ const hasDate = !isTimeOnly;
261
+ const hasTime = isTimeOnly || /[T ]\d{2}:\d{2}/.test(value);
262
+ const date = parseIso(isTimeOnly ? `1970-01-01T${value}` : value);
263
+ if (!date) return value;
264
+ const dateStyle = hasDate ? options?.dateStyle : void 0;
265
+ const timeStyle = hasTime ? options?.timeStyle : void 0;
266
+ return createFormatter(locale, dateStyle || timeStyle ? {
267
+ dateStyle,
268
+ timeStyle
269
+ } : {
270
+ dateStyle: hasDate ? "short" : void 0,
271
+ timeStyle: hasTime ? "short" : void 0
272
+ }).format(date);
273
+ }
274
+ // src/date-formatter.ts
275
+ const FALLBACK_LOCALE = "en";
276
+ /**
277
+ * Returns a function that formats ISO date, date-time, and time strings in the
278
+ * interface language of the site.
279
+ *
280
+ * The locale comes from the site context, which every rendering integration
281
+ * (Drupal-rendered pages, Workbench, Headless) supplies, so it needs no
282
+ * runtime-specific setup. Without a site language it falls back to `en`.
283
+ *
284
+ * The parts shown depend on the value: a date, a time, or both. Each part uses
285
+ * the `'short'` style unless options are passed; see `CanvasDateFormatOptions`.
286
+ * Values are always formatted in UTC, because Canvas stores them without a
287
+ * time zone. To format a date range prop, call the function on its `from` and
288
+ * `to` values.
289
+ *
290
+ * @example
291
+ * const formatDate = useDateFormatter();
292
+ * return <time>{formatDate(date, { dateStyle: 'long' })}</time>;
293
+ */
294
+ function useDateFormatter() {
295
+ const langcode = useSiteContext()?.langcode || FALLBACK_LOCALE;
296
+ return useMemo(() => (value, options) => formatDateInLocale(value, langcode, options), [langcode]);
297
+ }
298
+ // src/jsonapi-client-context.tsx
120
299
  /**
121
300
  * @file
122
301
  * The JSON:API client context for React Code Components. Rendering
@@ -154,5 +333,4 @@ function useJsonApiClient() {
154
333
  function useHasJsonApiClient() {
155
334
  return useContext(Context) !== void 0;
156
335
  }
157
- //#endregion
158
- export { CanvasContextProvider, JsonApiClientProvider, useHasCanvasContext, useHasJsonApiClient, useJsonApiClient, usePageContext, useSiteContext };
336
+ export { CanvasContextProvider, JsonApiClientProvider, TranslationsProvider, useDateFormatter, useHasCanvasContext, useHasJsonApiClient, useJsonApiClient, usePageContext, useSiteContext, useTranslation };
package/dist/utils.d.ts CHANGED
@@ -1,5 +1,2 @@
1
1
  import { ClassValue } from "clsx";
2
- //#region src/utils.d.ts
3
- declare function cn(...inputs: ClassValue[]): string;
4
- //#endregion
5
- export { cn };
2
+ export declare function cn(...inputs: ClassValue[]): string;
package/dist/utils.js CHANGED
@@ -1,8 +1,7 @@
1
1
  import { clsx } from "clsx";
2
2
  import { twMerge } from "tailwind-merge";
3
- //#region src/utils.ts
3
+ // src/utils.ts
4
4
  function cn(...inputs) {
5
5
  return twMerge(clsx(inputs));
6
6
  }
7
- //#endregion
8
7
  export { cn };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drupal-canvas",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "engines": {
5
5
  "node": ">=22.19.0 <23 || >=24.5.0"
6
6
  },
@@ -82,7 +82,7 @@
82
82
  "devDependencies": {
83
83
  "jsdom": "^26.1.0",
84
84
  "react-dom": "^18.3.1",
85
- "tsdown": "^0.22.12",
85
+ "tsdown": "^0.23.0",
86
86
  "typescript": "^5.9.3",
87
87
  "vitest": "^4.1.8"
88
88
  },
@@ -1,32 +0,0 @@
1
- import { d as PageContext, f as SiteContext, u as CanvasContext } from "./drupal-utils-CUaK4jOk.js";
2
- import { ReactNode } from "react";
3
- //#region src/context.d.ts
4
- interface CanvasContextProviderProps {
5
- context: CanvasContext;
6
- children?: ReactNode;
7
- }
8
- /**
9
- * Makes page and site context available to every React descendant. Adds no
10
- * DOM wrapper. Rendering integrations use it internally; applications can use
11
- * it to reach components outside the Canvas tree, such as a site header.
12
- */
13
- declare function CanvasContextProvider({ context, children }: CanvasContextProviderProps): import("react/jsx-runtime").JSX.Element;
14
- /**
15
- * Returns the current page context, or `null` when no provider supplies one.
16
- * Emits a deduplicated developer warning in that case; a provider that
17
- * carries valid empty page data is not a missing-context condition.
18
- */
19
- declare function usePageContext(): PageContext | null;
20
- /**
21
- * Returns the current site context, or `null` when no provider supplies one.
22
- * Emits a deduplicated developer warning in that case.
23
- */
24
- declare function useSiteContext(): SiteContext | null;
25
- /**
26
- * Whether a `CanvasContextProvider` is mounted above the calling component.
27
- * Rendering integrations use it to decide whether to inherit an outer
28
- * provider instead of adding their own.
29
- */
30
- declare function useHasCanvasContext(): boolean;
31
- //#endregion
32
- export { useSiteContext as a, usePageContext as i, CanvasContextProviderProps as n, useHasCanvasContext as r, CanvasContextProvider as t };