@draftbase/renderer 0.5.1 → 0.5.2

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 CHANGED
@@ -126,6 +126,8 @@ createReactNativeRenderer({ Text, View, Image }, { unstyled: true });
126
126
 
127
127
  This package never imports the `react-native` package itself — you pass its `Text`/`View`/`Image` in, so nothing RN-specific ends up in a web or Vue bundle.
128
128
 
129
+ RN has no DOM to silently fall back on the way web does — a JSX component the source references but you didn't map (a typo'd custom component, a raw HTML tag RN has no native view for) would otherwise crash the whole screen. `Content` catches that automatically: it's logged via `console.error` and the raw source renders as plain text in place of the broken content, instead of taking down the app. No setup needed — this is on by default, unlike the web/Vue entry points where you wrap `Content` in `MDXErrorBoundary` yourself.
130
+
129
131
  ## Astro
130
132
 
131
133
  Astro components aren't React, so render through a React island. Compile server-side in the `.astro` frontmatter (Astro's runtime does allow `await` there), then hand the compiled `Content` to a small client React wrapper component:
@@ -290,6 +292,25 @@ function EntryLink({ id, children }: { id: string; children: React.ReactNode })
290
292
  <MDXContent source={entry.fields.body} components={{ EntryLink }} />;
291
293
  ```
292
294
 
295
+ ## Images
296
+
297
+ A markdown image (`![alt](url)`) renders as a plain `<img loading="lazy" decoding="async">` by default — no framework-specific optimizer, so this works identically across every web/RSC/Vue target and `toHtml`. Swap in your own (e.g. Next.js's `<Image>`) by overriding `img` like any other standard element:
298
+
299
+ ```tsx
300
+ import NextImage from "next/image";
301
+
302
+ <MDXContent
303
+ source={entry.fields.body}
304
+ components={{
305
+ img: ({ src, alt }) => <NextImage src={src} alt={alt ?? ""} width={800} height={450} />,
306
+ }}
307
+ />;
308
+ ```
309
+
310
+ An explicit `loading`/`decoding` written into the source (rare, but possible via raw `<img>` JSX in MDX) still wins over the default — only the no-attributes case gets the lazy default filled in.
311
+
312
+ Every Draftbase asset URL — the one in an `![]()` src, or `asset.url` from `@draftbase/sdk` used outside MDX entirely — also supports on-demand resizing via query params: append `?w=800` (and/or `&h=450`) to shrink it server-side, capped to the size it was originally uploaded at (never upscales). Sizes are snapped to a fixed breakpoint set at the CDN edge, so requesting arbitrary values (`?w=803`) still hits a shared cache entry instead of minting a new one per pixel.
313
+
293
314
  ## Styling
294
315
 
295
316
  `@draftbase/renderer/styles.css` wraps output in a `.db-content` class with slim, sensible defaults (typography, tables, code blocks). Web-only, opt-in:
@@ -310,7 +331,7 @@ If you're an agent wiring this into a project, follow this checklist:
310
331
  2. **Pick the right entry point first** — check the target framework in the table at the top of this file, then import only that one (`@draftbase/renderer` vs `@draftbase/renderer/vue`). Importing the wrong one pulls in a peer dependency (React or Vue) the project may not have installed, and will fail to resolve.
311
332
  3. **Detect RSC support before choosing a pattern**: Next.js App Router (or another RSC framework) → use `<MDXContent source={...} />` directly, it's an async Server Component. Everything else (client-side React, React Native, Remix, Vite SPA, Vue) → use the `compileMDX(source)` + state/ref pattern shown above; do not try to `await` it inside a plain client component render.
312
333
  4. **Every `compileMDX`/`MDXContent` result is a discriminated union** — always branch on `.ok` before touching `.Content`; treat `!ok` as a real render path (show `.error` or fallback text), don't just assume success.
313
- 5. **Non-DOM renderers (React Native, custom email/RSS pipelines) have no intrinsic HTML tags** — you must pass a `components` map covering every markdown element actually used in the source (`p`, `h1`-`h6`, `a`, `img`, `table`, ...), or those elements will fail to render. For plain HTML output (email, RSS, non-React embeds) use `toHtml` instead of a component tree.
334
+ 5. **Non-DOM renderers (React Native, custom email/RSS pipelines) have no intrinsic HTML tags** — you must pass a `components` map covering every markdown element actually used in the source (`p`, `h1`-`h6`, `a`, `img`, `table`, ...), or those elements render as an unstyled RN default (React Native's `createReactNativeRenderer` already ships styled defaults, so this mainly matters for a fully custom RN setup). React Native specifically never crashes the screen over this — an unmapped/missing component logs to `console.error` and falls back to plain text instead. For plain HTML output (email, RSS, non-React embeds) use `toHtml` instead of a component tree.
314
335
  6. **Don't hand-roll styling** — import `@draftbase/renderer/styles.css` for sensible defaults, or pass `unstyled`/`className` on `MDXContent`, rather than writing new prose/typography CSS from scratch.
315
336
  7. **This package ships zero bundled React/Vue** — both are optional peer dependencies. If the target project doesn't already have the matching framework installed, install it too or the build will fail.
316
337
 
@@ -1,10 +1,13 @@
1
1
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import * as runtime from "react/jsx-runtime";
3
- import { compileMDXCore, makeDefaultEntryLink } from "./core.js";
3
+ import { compileMDXCore, makeDefaultEntryLink, makeDefaultImage } from "./core.js";
4
4
  import { wrapperClassName } from "./wrapperClassName.js";
5
5
  import { MDXErrorBoundary } from "./MDXErrorBoundary.js";
6
6
  import { CSS_TEXT } from "./cssText.js";
7
- const defaultComponents = { EntryLink: makeDefaultEntryLink(runtime) };
7
+ const defaultComponents = {
8
+ EntryLink: makeDefaultEntryLink(runtime),
9
+ img: makeDefaultImage(runtime),
10
+ };
8
11
  /**
9
12
  * Compiles raw MDX/markdown into a renderable React component — no DOM assumptions, safe for client effects or RSC.
10
13
  * Standard markdown elements render via real DOM tags with zero setup; only a JSX component with no built-in default needs `components`.
@@ -44,6 +44,35 @@ test("vue EntryLink renders as a link to /entries/{id} with no components map su
44
44
  assert.equal(link.type, "a");
45
45
  assert.equal(link.props.href, "/entries/abc123");
46
46
  });
47
+ // A standalone `![]()` compiles to a <p><img/></p> — resolve the paragraph, then its one child.
48
+ function imgFrom(paragraph) {
49
+ const child = paragraph.props.children;
50
+ return resolve(Array.isArray(child) ? child[0] : child);
51
+ }
52
+ test("react img gets lazy-loading defaults with no components map supplied", async () => {
53
+ const result = await compileReactMDX("![alt text](https://example.com/a.png)");
54
+ assert.equal(result.ok, true);
55
+ if (!result.ok)
56
+ return;
57
+ const paragraph = resolve(result.Content({}));
58
+ const img = imgFrom(paragraph);
59
+ assert.equal(img.type, "img");
60
+ assert.equal(img.props.loading, "lazy");
61
+ assert.equal(img.props.decoding, "async");
62
+ assert.equal(img.props.src, "https://example.com/a.png");
63
+ });
64
+ test("a supplied img override still wins over the default", async () => {
65
+ const result = await compileReactMDX("![alt text](https://example.com/a.png)");
66
+ assert.equal(result.ok, true);
67
+ if (!result.ok)
68
+ return;
69
+ const CustomImage = () => ({ type: "custom-image", props: {} });
70
+ const paragraph = resolve(result.Content({
71
+ components: { img: CustomImage },
72
+ }));
73
+ const img = imgFrom(paragraph);
74
+ assert.equal(img.type, "custom-image");
75
+ });
47
76
  test("a supplied EntryLink override still wins over the default", async () => {
48
77
  const result = await compileReactMDX('<EntryLink id="abc123">Read more</EntryLink>');
49
78
  assert.equal(result.ok, true);
package/dist/core.d.ts CHANGED
@@ -19,3 +19,7 @@ export declare function makeDefaultEntryLink(jsxRuntime: JsxRuntime): ({ id, chi
19
19
  id?: string;
20
20
  children?: unknown;
21
21
  }) => JSX.Element;
22
+ /** Default `img` for a given JSX runtime — defers offscreen image loads instead of the browser's
23
+ * eager default. Apps that want `next/image` (or another optimizer) override it via `components.img`;
24
+ * an explicit `loading`/`decoding` on the element itself (rare, but author-settable) still wins. */
25
+ export declare function makeDefaultImage(jsxRuntime: JsxRuntime): (props: Record<string, unknown>) => JSX.Element;
package/dist/core.js CHANGED
@@ -38,3 +38,11 @@ export function makeDefaultEntryLink(jsxRuntime) {
38
38
  return jsxRuntime.jsx("a", { href: id ? `/entries/${id}` : undefined, children });
39
39
  };
40
40
  }
41
+ /** Default `img` for a given JSX runtime — defers offscreen image loads instead of the browser's
42
+ * eager default. Apps that want `next/image` (or another optimizer) override it via `components.img`;
43
+ * an explicit `loading`/`decoding` on the element itself (rare, but author-settable) still wins. */
44
+ export function makeDefaultImage(jsxRuntime) {
45
+ return function Img(props) {
46
+ return jsxRuntime.jsx("img", { loading: "lazy", decoding: "async", ...props });
47
+ };
48
+ }
@@ -12,6 +12,9 @@ export type { FailedMDX };
12
12
  /**
13
13
  * Wires up a React Native `compileMDX` with default Text/View/Image mappings for every standard markdown element
14
14
  * (and `EntryLink`), so a project sets up its RN primitives once instead of mapping every tag on every call.
15
+ * A tag/component the source references but nothing maps (a typo'd custom component, a raw HTML tag RN has no
16
+ * native view for) is caught at render — logged via `console.error` and replaced with the raw source as
17
+ * plain text, instead of crashing the screen.
15
18
  */
16
19
  export declare function createReactNativeRenderer(primitives: ReactNativePrimitives, styleOptions?: ReactNativeStyleOptions): {
17
20
  compileMDX: (source: string) => Promise<CompiledMDX | FailedMDX>;
@@ -1,9 +1,13 @@
1
1
  import * as runtime from "react/jsx-runtime";
2
2
  import { compileMDXCore } from "./core.js";
3
+ import { MDXErrorBoundary } from "./MDXErrorBoundary.js";
3
4
  import { buildReactNativeComponents, } from "./reactNativeComponents.js";
4
5
  /**
5
6
  * Wires up a React Native `compileMDX` with default Text/View/Image mappings for every standard markdown element
6
7
  * (and `EntryLink`), so a project sets up its RN primitives once instead of mapping every tag on every call.
8
+ * A tag/component the source references but nothing maps (a typo'd custom component, a raw HTML tag RN has no
9
+ * native view for) is caught at render — logged via `console.error` and replaced with the raw source as
10
+ * plain text, instead of crashing the screen.
7
11
  */
8
12
  export function createReactNativeRenderer(primitives, styleOptions) {
9
13
  const defaultComponents = buildReactNativeComponents(primitives, styleOptions);
@@ -27,9 +31,17 @@ export function createReactNativeRenderer(primitives, styleOptions) {
27
31
  : wrapped;
28
32
  return stripWhitespaceRootChildren(rootElement);
29
33
  };
34
+ // A JSX component referenced in `source` but missing from `components`, or a raw HTML tag RN has
35
+ // no native view for, throws mid-render — RN has no DOM to silently fall back on the way web
36
+ // does, so catch it here instead of taking down the whole screen, and log it loudly so the
37
+ // content author (or whoever wired up `components`) notices and fixes it.
38
+ const SafeContent = (props) => runtime.jsx(MDXErrorBoundary, {
39
+ fallback: runtime.jsx(primitives.Text, { children: source }),
40
+ children: runtime.jsx(RootWithoutWhitespace, props),
41
+ });
30
42
  return {
31
43
  ok: true,
32
- Content: RootWithoutWhitespace,
44
+ Content: SafeContent,
33
45
  };
34
46
  }
35
47
  return { compileMDX };
@@ -1,17 +1,23 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
  import { createReactNativeRenderer } from "./reactNative.js";
4
+ import { MDXErrorBoundary } from "./MDXErrorBoundary.js";
4
5
  // Fakes standing in for react-native's Text/View/Image — see reactNativeComponents.test.ts.
5
6
  const Text = () => null;
6
7
  const View = () => null;
7
8
  const Image = () => null;
8
9
  const LEAVES = [Text, View, Image];
9
10
  /** Unwraps nested function-component elements down to the RN primitive actually used,
10
- * without calling into it (Text/View/Image are opaque leaves here, not JSX). */
11
+ * without calling into it (Text/View/Image are opaque leaves here, not JSX). Class components
12
+ * (MDXErrorBoundary) can't be invoked directly like a function — unwrap via `children`,
13
+ * matching its non-error render path. */
11
14
  function resolve(element) {
12
- return typeof element.type === "function" && !LEAVES.includes(element.type)
13
- ? resolve(element.type(element.props))
14
- : element;
15
+ if (typeof element.type !== "function" || LEAVES.includes(element.type))
16
+ return element;
17
+ const type = element.type;
18
+ return type.prototype?.isReactComponent
19
+ ? resolve(element.props.children)
20
+ : resolve(element.type(element.props));
15
21
  }
16
22
  test("React Native smoke test: renders standard markdown through Text/View with zero setup beyond the three primitives", async () => {
17
23
  const { compileMDX } = createReactNativeRenderer({ Text, View, Image });
@@ -24,6 +30,38 @@ test("React Native smoke test: renders standard markdown through Text/View with
24
30
  assert.equal(heading.type, Text);
25
31
  assert.equal(heading.props.style.fontSize, 28);
26
32
  });
33
+ test("React Native falls back to the raw source and logs to console instead of crashing on an unknown tag", async () => {
34
+ const { compileMDX } = createReactNativeRenderer({ Text, View, Image });
35
+ const result = await compileMDX("<Callout>hi</Callout>");
36
+ assert.equal(result.ok, true);
37
+ if (!result.ok)
38
+ return;
39
+ const originalConsoleError = console.error;
40
+ const logged = [];
41
+ console.error = (...args) => logged.push(args);
42
+ try {
43
+ // No react-dom/test-renderer in this package — drive the real MDXErrorBoundary class by
44
+ // hand the way React would: render children, and on throw, catch + re-render the fallback.
45
+ const boundaryElement = result.Content({});
46
+ assert.equal(boundaryElement.type, MDXErrorBoundary);
47
+ const boundary = new MDXErrorBoundary(boundaryElement.props);
48
+ try {
49
+ resolve(boundaryElement.props.children);
50
+ assert.fail("expected the missing <Callout> component to throw");
51
+ }
52
+ catch (error) {
53
+ boundary.componentDidCatch(error);
54
+ Object.assign(boundary.state, MDXErrorBoundary.getDerivedStateFromError());
55
+ }
56
+ const fallback = resolve(boundary.render());
57
+ assert.equal(fallback.type, Text);
58
+ assert.equal(fallback.props.children, "<Callout>hi</Callout>");
59
+ }
60
+ finally {
61
+ console.error = originalConsoleError;
62
+ }
63
+ assert.equal(logged.length, 1);
64
+ });
27
65
  test("React Native EntryLink renders out of the box (no components map)", async () => {
28
66
  const { compileMDX } = createReactNativeRenderer({ Text, View, Image });
29
67
  const result = await compileMDX('<EntryLink id="abc123">Read more</EntryLink>');
package/dist/toHtml.js CHANGED
@@ -48,6 +48,10 @@ function rehypeDraftbase(options) {
48
48
  }
49
49
  return;
50
50
  }
51
+ if (node.tagName === "img") {
52
+ node.properties = { loading: "lazy", decoding: "async", ...node.properties };
53
+ return;
54
+ }
51
55
  if (node.tagName === "a" && options.externalLinks) {
52
56
  const href = node.properties?.href;
53
57
  if (typeof href !== "string" || !SCHEME_HREF.test(href))
@@ -19,6 +19,10 @@ test("className merges onto the wrapper div, styles still inlined", async () =>
19
19
  const html = await toHtml("hi", { className: "prose" });
20
20
  assert.equal(html, `<style>${CSS_TEXT}</style><div class="db-content prose"><p>hi</p></div>`);
21
21
  });
22
+ test("img gets lazy-loading defaults with no components option supplied", async () => {
23
+ const html = await toHtml("![alt text](https://example.com/a.png)", { unstyled: true });
24
+ assert.equal(html, '<p><img loading="lazy" decoding="async" src="https://example.com/a.png" alt="alt text"></p>');
25
+ });
22
26
  test("supports gfm tables", async () => {
23
27
  const html = await toHtml("| a | b |\n| - | - |\n| 1 | 2 |");
24
28
  assert.match(html, /<table>/);
package/dist/vue.js CHANGED
@@ -1,6 +1,9 @@
1
- import { compileMDXCore, makeDefaultEntryLink } from "./core.js";
1
+ import { compileMDXCore, makeDefaultEntryLink, makeDefaultImage } from "./core.js";
2
2
  import { vueJsxRuntime } from "./vueRuntime.js";
3
- const defaultComponents = { EntryLink: makeDefaultEntryLink(vueJsxRuntime) };
3
+ const defaultComponents = {
4
+ EntryLink: makeDefaultEntryLink(vueJsxRuntime),
5
+ img: makeDefaultImage(vueJsxRuntime),
6
+ };
4
7
  /**
5
8
  * Compiles raw MDX/markdown into a renderable Vue component. Vue has no RSC-style async component, so call this
6
9
  * from `setup()`/a composable and render the result yourself: `h(Content, props)`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@draftbase/renderer",
3
- "version": "0.5.1",
3
+ "version": "0.5.2",
4
4
  "description": "Framework-agnostic MDX renderer for Draftbase content (React, Next.js RSC, React Native, Astro, Vite, Vue)",
5
5
  "keywords": [
6
6
  "draftbase",