@blogmcp/render-embed-react 0.1.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.
@@ -0,0 +1,9 @@
1
+ import { type ReactNode } from 'react';
2
+ import type { RenderUnit } from '@blogmcp/render-embed';
3
+ import { type ComponentMap } from './registry-bridge';
4
+ export declare function BlockWrapper({ unit, componentMap, trusted, }: {
5
+ unit: RenderUnit;
6
+ componentMap?: ComponentMap;
7
+ /** Production SSR → skip the redundant re-sanitize; omitted/false → re-sanitize (safe default). */
8
+ trusted?: boolean;
9
+ }): ReactNode;
@@ -0,0 +1,46 @@
1
+ import { jsx } from "react/jsx-runtime";
2
+ import { useContext, Suspense } from "react";
3
+ import { sanitizeHtml } from "@blogmcp/sanitize";
4
+ import { resolveComponent } from "./registry-bridge.js";
5
+ import { BridgeContext } from "./context.js";
6
+ function renderInner(unit, componentMap, trusted) {
7
+ if (unit.type === "html") {
8
+ const html = unit.html ?? "";
9
+ return /* @__PURE__ */ jsx("div", { dangerouslySetInnerHTML: { __html: trusted ? html : sanitizeHtml(html) } });
10
+ }
11
+ const Comp = resolveComponent(unit.name ?? "", componentMap);
12
+ if (!Comp) {
13
+ return /* @__PURE__ */ jsx("div", { className: "render-embed-unknown", children: `Component "${unit.name}" — not available in this renderer.` });
14
+ }
15
+ return /* @__PURE__ */ jsx(Suspense, { fallback: null, children: /* @__PURE__ */ jsx(Comp, { ...unit.props ?? {}, children: unit.children }) });
16
+ }
17
+ function BlockWrapper({
18
+ unit,
19
+ componentMap,
20
+ trusted
21
+ }) {
22
+ const bridge = useContext(BridgeContext);
23
+ const onClick = (e) => {
24
+ if (!bridge) return;
25
+ bridge.reportNodeClick(unit.nodeId, e.currentTarget, { meta: e.metaKey, shift: e.shiftKey });
26
+ };
27
+ const onMouseUp = () => {
28
+ if (!bridge || typeof window === "undefined") return;
29
+ const sel = window.getSelection();
30
+ if (sel) bridge.reportSelection(sel);
31
+ };
32
+ return /* @__PURE__ */ jsx(
33
+ "div",
34
+ {
35
+ "data-mdx-node-id": unit.nodeId,
36
+ "data-mdx-component": unit.type === "component" ? unit.name : void 0,
37
+ className: "render-embed-block",
38
+ onClick,
39
+ onMouseUp,
40
+ children: renderInner(unit, componentMap, trusted === true)
41
+ }
42
+ );
43
+ }
44
+ export {
45
+ BlockWrapper
46
+ };
@@ -0,0 +1,12 @@
1
+ import { type ReactElement } from 'react';
2
+ import type { RenderMode, RenderUnit } from '@blogmcp/render-embed';
3
+ import type { ComponentMap } from './registry-bridge';
4
+ export interface RenderEmbedProps {
5
+ mode: RenderMode;
6
+ /** Server-provided units (production), or the initial set before the host pushes `render`. */
7
+ blocks?: RenderUnit[];
8
+ /** Custom-renderer escape hatch: MDX name → React component, overriding the platform registry. */
9
+ componentMap?: ComponentMap;
10
+ kbOrigin?: string;
11
+ }
12
+ export declare function RenderEmbed({ mode, blocks, componentMap }: RenderEmbedProps): ReactElement;
@@ -0,0 +1,55 @@
1
+ import { jsx } from "react/jsx-runtime";
2
+ import { useState, useRef, useEffect } from "react";
3
+ import { RendererBridge } from "@blogmcp/render-embed";
4
+ import { BlockWrapper } from "./BlockWrapper.js";
5
+ import { BridgeContext } from "./context.js";
6
+ function applyHighlight(root, nodeIds, kind) {
7
+ if (!root) return;
8
+ root.querySelectorAll("[data-mdx-node-id]").forEach((el) => el.classList.remove("re-hl-comment", "re-hl-selection"));
9
+ if (kind === "clear") return;
10
+ const cls = kind === "comment" ? "re-hl-comment" : "re-hl-selection";
11
+ for (const id of nodeIds) root.querySelector(`[data-mdx-node-id="${id}"]`)?.classList.add(cls);
12
+ }
13
+ function RenderEmbed({ mode, blocks = [], componentMap }) {
14
+ const [units, setUnits] = useState(blocks);
15
+ const rootRef = useRef(null);
16
+ const bridgeRef = useRef(null);
17
+ if (mode === "edit" && !bridgeRef.current && typeof window !== "undefined") {
18
+ bridgeRef.current = new RendererBridge({
19
+ mode: "edit",
20
+ capabilities: { canParse: false },
21
+ onRender: (payload) => {
22
+ const next = payload.blocks ?? [];
23
+ setUnits(next);
24
+ requestAnimationFrame(() => {
25
+ bridgeRef.current?.reportRendered(next.map((u) => u.nodeId));
26
+ if (rootRef.current) bridgeRef.current?.reportHeight(rootRef.current.scrollHeight);
27
+ });
28
+ },
29
+ onScrollToNode: (nodeId, behavior) => rootRef.current?.querySelector(`[data-mdx-node-id="${nodeId}"]`)?.scrollIntoView({ behavior, block: "center" }),
30
+ onHighlight: (nodeIds, kind) => applyHighlight(rootRef.current, nodeIds, kind)
31
+ });
32
+ }
33
+ useEffect(() => {
34
+ const bridge = bridgeRef.current;
35
+ bridge?.start();
36
+ let ro;
37
+ if (bridge && rootRef.current && typeof ResizeObserver !== "undefined") {
38
+ ro = new ResizeObserver(() => {
39
+ if (rootRef.current) bridge.reportHeight(rootRef.current.scrollHeight);
40
+ });
41
+ ro.observe(rootRef.current);
42
+ }
43
+ return () => {
44
+ ro?.disconnect();
45
+ bridge?.destroy();
46
+ };
47
+ }, []);
48
+ useEffect(() => {
49
+ if (mode === "production") setUnits(blocks);
50
+ }, [blocks, mode]);
51
+ return /* @__PURE__ */ jsx(BridgeContext.Provider, { value: bridgeRef.current, children: /* @__PURE__ */ jsx("div", { ref: rootRef, className: "render-embed mdx-content", children: units.map((u) => /* @__PURE__ */ jsx(BlockWrapper, { unit: u, componentMap, trusted: mode === "production" }, u.nodeId)) }) });
52
+ }
53
+ export {
54
+ RenderEmbed
55
+ };
@@ -0,0 +1,3 @@
1
+ import type { RendererBridge } from '@blogmcp/render-embed';
2
+ /** The active RendererBridge (edit mode), or `null` in production (inert passthrough). */
3
+ export declare const BridgeContext: import("react").Context<RendererBridge | null>;
@@ -0,0 +1,5 @@
1
+ import { createContext } from "react";
2
+ const BridgeContext = createContext(null);
3
+ export {
4
+ BridgeContext
5
+ };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @blogmcp/render-embed-react
3
+ *
4
+ * React `<RenderEmbed>` wrapper over `@blogmcp/render-embed` (protocol/bridge core) +
5
+ * `@blogmcp/mdx-render-react` (the platform component registry). The React mirror of
6
+ * `@blogmcp/render-embed-vue`: `mode="production"` is inert; `mode="edit"` activates the host
7
+ * protocol; a `componentMap` overrides the platform registry (custom-renderer escape hatch).
8
+ */
9
+ export { RenderEmbed } from './RenderEmbed';
10
+ export type { RenderEmbedProps } from './RenderEmbed';
11
+ export { BlockWrapper } from './BlockWrapper';
12
+ export { resolveComponent } from './registry-bridge';
13
+ export type { ComponentMap } from './registry-bridge';
14
+ export { BridgeContext } from './context';
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ import { RenderEmbed } from "./RenderEmbed.js";
2
+ import { BlockWrapper } from "./BlockWrapper.js";
3
+ import { resolveComponent } from "./registry-bridge.js";
4
+ import { BridgeContext } from "./context.js";
5
+ export {
6
+ BlockWrapper,
7
+ BridgeContext,
8
+ RenderEmbed,
9
+ resolveComponent
10
+ };
@@ -0,0 +1,9 @@
1
+ import { type ComponentType } from 'react';
2
+ /** A consumer-supplied map of MDX component name → React component (the custom-renderer escape hatch). */
3
+ export type ComponentMap = Record<string, ComponentType<Record<string, unknown>>>;
4
+ /**
5
+ * Resolve an MDX component name to a React component: the consumer's `componentMap` first, then the
6
+ * platform `@blogmcp/mdx-render-react` registry (wrapped in `React.lazy` around its async loader —
7
+ * the caller renders it inside a `<Suspense>`). `undefined` → "unknown component" placeholder.
8
+ */
9
+ export declare function resolveComponent(name: string, componentMap?: ComponentMap): ComponentType<Record<string, unknown>> | undefined;
@@ -0,0 +1,16 @@
1
+ import { lazy } from "react";
2
+ import { reactRegistry } from "@blogmcp/mdx-render-react/registry";
3
+ const lazyCache = /* @__PURE__ */ new Map();
4
+ function resolveComponent(name, componentMap) {
5
+ if (componentMap && Object.prototype.hasOwnProperty.call(componentMap, name)) return componentMap[name];
6
+ const cached = lazyCache.get(name);
7
+ if (cached) return cached;
8
+ const loader = reactRegistry[name]?.render?.default;
9
+ if (!loader) return void 0;
10
+ const Lazy = lazy(loader);
11
+ lazyCache.set(name, Lazy);
12
+ return Lazy;
13
+ }
14
+ export {
15
+ resolveComponent
16
+ };
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@blogmcp/render-embed-react",
3
+ "version": "0.1.0",
4
+ "description": "React <RenderEmbed> wrapper over @blogmcp/render-embed + @blogmcp/mdx-render-react, with the production/edit mode switch and a componentMap escape hatch.",
5
+ "type": "module",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "main": "./dist/index.js",
10
+ "module": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./src/index.ts",
15
+ "import": "./dist/index.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "src"
21
+ ],
22
+ "scripts": {
23
+ "build": "vite build && tsc -p tsconfig.build.json --emitDeclarationOnly",
24
+ "dev": "vite build --watch",
25
+ "test": "vitest run",
26
+ "typecheck": "tsc --noEmit"
27
+ },
28
+ "dependencies": {
29
+ "@blogmcp/sanitize": "^0.1.0"
30
+ },
31
+ "peerDependencies": {
32
+ "@blogmcp/mdx-render-react": "^0.1.0",
33
+ "@blogmcp/render-embed": "^0.1.0",
34
+ "react": ">=18",
35
+ "react-dom": ">=18"
36
+ },
37
+ "devDependencies": {
38
+ "@blogmcp/mdx-render-react": "^0.1.0",
39
+ "@blogmcp/render-embed": "^0.1.0",
40
+ "@testing-library/react": "^16.1.0",
41
+ "@types/node": "^20.10.0",
42
+ "@types/react": "^18.3.0",
43
+ "@types/react-dom": "^18.3.0",
44
+ "happy-dom": "^17.4.0",
45
+ "react": "^18.3.0",
46
+ "react-dom": "^18.3.0",
47
+ "typescript": "^5.3.3",
48
+ "vite": "^7.3.0",
49
+ "vitest": "^3.0.0"
50
+ },
51
+ "license": "MIT"
52
+ }
@@ -0,0 +1,61 @@
1
+ import { Suspense, useContext, type MouseEvent, type ReactNode } from 'react'
2
+ import { sanitizeHtml } from '@blogmcp/sanitize'
3
+ import type { RenderUnit } from '@blogmcp/render-embed'
4
+ import { resolveComponent, type ComponentMap } from './registry-bridge'
5
+ import { BridgeContext } from './context'
6
+
7
+ function renderInner(unit: RenderUnit, componentMap: ComponentMap | undefined, trusted: boolean): ReactNode {
8
+ if (unit.type === 'html') {
9
+ // Re-sanitize ONLY in edit/interactive mode (untrusted host-pushed blocks, correction H4).
10
+ // In production SSR (trusted) blocks come from the server parseArticle that already
11
+ // sanitized them — skipping avoids a redundant 2nd jsdom parse per markdown block.
12
+ const html = unit.html ?? ''
13
+ return <div dangerouslySetInnerHTML={{ __html: trusted ? html : sanitizeHtml(html) }} />
14
+ }
15
+ const Comp = resolveComponent(unit.name ?? '', componentMap)
16
+ if (!Comp) {
17
+ return <div className="render-embed-unknown">{`Component "${unit.name}" — not available in this renderer.`}</div>
18
+ }
19
+ return (
20
+ <Suspense fallback={null}>
21
+ <Comp {...(unit.props ?? {})}>{unit.children}</Comp>
22
+ </Suspense>
23
+ )
24
+ }
25
+
26
+ export function BlockWrapper({
27
+ unit,
28
+ componentMap,
29
+ trusted,
30
+ }: {
31
+ unit: RenderUnit
32
+ componentMap?: ComponentMap
33
+ /** Production SSR → skip the redundant re-sanitize; omitted/false → re-sanitize (safe default). */
34
+ trusted?: boolean
35
+ }): ReactNode {
36
+ // `null` in production mode → no reporting (inert). NOTE: bridge gates REPORTING only — it is
37
+ // client-only (null during SSR-edit), so it must NOT gate the security re-sanitize; `trusted` does.
38
+ const bridge = useContext(BridgeContext)
39
+
40
+ const onClick = (e: MouseEvent<HTMLDivElement>): void => {
41
+ if (!bridge) return
42
+ bridge.reportNodeClick(unit.nodeId, e.currentTarget, { meta: e.metaKey, shift: e.shiftKey })
43
+ }
44
+ const onMouseUp = (): void => {
45
+ if (!bridge || typeof window === 'undefined') return
46
+ const sel = window.getSelection()
47
+ if (sel) bridge.reportSelection(sel)
48
+ }
49
+
50
+ return (
51
+ <div
52
+ data-mdx-node-id={unit.nodeId}
53
+ data-mdx-component={unit.type === 'component' ? unit.name : undefined}
54
+ className="render-embed-block"
55
+ onClick={onClick}
56
+ onMouseUp={onMouseUp}
57
+ >
58
+ {renderInner(unit, componentMap, trusted === true)}
59
+ </div>
60
+ )
61
+ }
@@ -0,0 +1,85 @@
1
+ import { useEffect, useRef, useState, type ReactElement } from 'react'
2
+ import { RendererBridge } from '@blogmcp/render-embed'
3
+ import type { RenderMode, RenderPayload, RenderUnit } from '@blogmcp/render-embed'
4
+ import { BlockWrapper } from './BlockWrapper'
5
+ import { BridgeContext } from './context'
6
+ import type { ComponentMap } from './registry-bridge'
7
+
8
+ export interface RenderEmbedProps {
9
+ mode: RenderMode
10
+ /** Server-provided units (production), or the initial set before the host pushes `render`. */
11
+ blocks?: RenderUnit[]
12
+ /** Custom-renderer escape hatch: MDX name → React component, overriding the platform registry. */
13
+ componentMap?: ComponentMap
14
+ kbOrigin?: string
15
+ }
16
+
17
+ function applyHighlight(
18
+ root: HTMLElement | null,
19
+ nodeIds: string[],
20
+ kind: 'comment' | 'selection' | 'clear',
21
+ ): void {
22
+ if (!root) return
23
+ root.querySelectorAll('[data-mdx-node-id]').forEach((el) => el.classList.remove('re-hl-comment', 're-hl-selection'))
24
+ if (kind === 'clear') return
25
+ const cls = kind === 'comment' ? 're-hl-comment' : 're-hl-selection'
26
+ for (const id of nodeIds) root.querySelector(`[data-mdx-node-id="${id}"]`)?.classList.add(cls)
27
+ }
28
+
29
+ export function RenderEmbed({ mode, blocks = [], componentMap }: RenderEmbedProps): ReactElement {
30
+ const [units, setUnits] = useState<RenderUnit[]>(blocks)
31
+ const rootRef = useRef<HTMLDivElement>(null)
32
+ const bridgeRef = useRef<RendererBridge | null>(null)
33
+
34
+ // EDIT mode only: lazily create the bridge once (client-only; SSR keeps the context null so the
35
+ // page renders inert). Production mode = no bridge → inert passthrough.
36
+ if (mode === 'edit' && !bridgeRef.current && typeof window !== 'undefined') {
37
+ bridgeRef.current = new RendererBridge({
38
+ mode: 'edit',
39
+ capabilities: { canParse: false },
40
+ onRender: (payload: RenderPayload) => {
41
+ const next = payload.blocks ?? []
42
+ setUnits(next)
43
+ requestAnimationFrame(() => {
44
+ bridgeRef.current?.reportRendered(next.map((u) => u.nodeId))
45
+ if (rootRef.current) bridgeRef.current?.reportHeight(rootRef.current.scrollHeight)
46
+ })
47
+ },
48
+ onScrollToNode: (nodeId, behavior) =>
49
+ rootRef.current?.querySelector(`[data-mdx-node-id="${nodeId}"]`)?.scrollIntoView({ behavior, block: 'center' }),
50
+ onHighlight: (nodeIds, kind) => applyHighlight(rootRef.current, nodeIds, kind),
51
+ })
52
+ }
53
+
54
+ useEffect(() => {
55
+ const bridge = bridgeRef.current
56
+ // start() installs the message listener; the host waits for the iframe `load` (after mount).
57
+ bridge?.start()
58
+ let ro: ResizeObserver | undefined
59
+ if (bridge && rootRef.current && typeof ResizeObserver !== 'undefined') {
60
+ ro = new ResizeObserver(() => {
61
+ if (rootRef.current) bridge.reportHeight(rootRef.current.scrollHeight)
62
+ })
63
+ ro.observe(rootRef.current)
64
+ }
65
+ return () => {
66
+ ro?.disconnect()
67
+ bridge?.destroy()
68
+ }
69
+ }, [])
70
+
71
+ // Production pages re-render when their server-provided blocks change.
72
+ useEffect(() => {
73
+ if (mode === 'production') setUnits(blocks)
74
+ }, [blocks, mode])
75
+
76
+ return (
77
+ <BridgeContext.Provider value={bridgeRef.current}>
78
+ <div ref={rootRef} className="render-embed mdx-content">
79
+ {units.map((u) => (
80
+ <BlockWrapper key={u.nodeId} unit={u} componentMap={componentMap} trusted={mode === 'production'} />
81
+ ))}
82
+ </div>
83
+ </BridgeContext.Provider>
84
+ )
85
+ }
@@ -0,0 +1,5 @@
1
+ import { createContext } from 'react'
2
+ import type { RendererBridge } from '@blogmcp/render-embed'
3
+
4
+ /** The active RendererBridge (edit mode), or `null` in production (inert passthrough). */
5
+ export const BridgeContext = createContext<RendererBridge | null>(null)
package/src/index.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @blogmcp/render-embed-react
3
+ *
4
+ * React `<RenderEmbed>` wrapper over `@blogmcp/render-embed` (protocol/bridge core) +
5
+ * `@blogmcp/mdx-render-react` (the platform component registry). The React mirror of
6
+ * `@blogmcp/render-embed-vue`: `mode="production"` is inert; `mode="edit"` activates the host
7
+ * protocol; a `componentMap` overrides the platform registry (custom-renderer escape hatch).
8
+ */
9
+
10
+ export { RenderEmbed } from './RenderEmbed'
11
+ export type { RenderEmbedProps } from './RenderEmbed'
12
+ export { BlockWrapper } from './BlockWrapper'
13
+ export { resolveComponent } from './registry-bridge'
14
+ export type { ComponentMap } from './registry-bridge'
15
+ export { BridgeContext } from './context'
@@ -0,0 +1,26 @@
1
+ import { lazy, type ComponentType } from 'react'
2
+ import { reactRegistry } from '@blogmcp/mdx-render-react/registry'
3
+
4
+ /** A consumer-supplied map of MDX component name → React component (the custom-renderer escape hatch). */
5
+ export type ComponentMap = Record<string, ComponentType<Record<string, unknown>>>
6
+
7
+ const lazyCache = new Map<string, ComponentType<Record<string, unknown>>>()
8
+
9
+ /**
10
+ * Resolve an MDX component name to a React component: the consumer's `componentMap` first, then the
11
+ * platform `@blogmcp/mdx-render-react` registry (wrapped in `React.lazy` around its async loader —
12
+ * the caller renders it inside a `<Suspense>`). `undefined` → "unknown component" placeholder.
13
+ */
14
+ export function resolveComponent(
15
+ name: string,
16
+ componentMap?: ComponentMap,
17
+ ): ComponentType<Record<string, unknown>> | undefined {
18
+ if (componentMap && Object.prototype.hasOwnProperty.call(componentMap, name)) return componentMap[name]
19
+ const cached = lazyCache.get(name)
20
+ if (cached) return cached
21
+ const loader = reactRegistry[name]?.render?.default
22
+ if (!loader) return undefined
23
+ const Lazy = lazy(loader as () => Promise<{ default: ComponentType<Record<string, unknown>> }>)
24
+ lazyCache.set(name, Lazy)
25
+ return Lazy
26
+ }