@nibblearn/embed 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +43 -2
- package/dist/index.cjs +190 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +37 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +186 -0
- package/dist/index.js.map +1 -0
- package/dist/nibblearn.global.js +70 -0
- package/dist/styles.css +2 -0
- package/package.json +73 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nibblearn contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,44 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @nibblearn/embed
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Put [Nibblearn](https://github.com/ifgolubev/nibblearn) modules into any HTML page — a CMS, server-rendered templates, lesson HTML stored in a database — without writing React.
|
|
4
|
+
|
|
5
|
+
## With a bundler
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @nibblearn/embed @nibblearn/react @nibblearn/core react react-dom
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import "@nibblearn/embed/styles.css";
|
|
13
|
+
import { hydrate } from "@nibblearn/embed";
|
|
14
|
+
|
|
15
|
+
hydrate(document.querySelector("#lesson")!, {
|
|
16
|
+
onComplete: (result, element) => console.log(result, element),
|
|
17
|
+
});
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Without a bundler
|
|
21
|
+
|
|
22
|
+
`dist/nibblearn.global.js` includes React and registers `<nibblearn-module>` when it loads:
|
|
23
|
+
|
|
24
|
+
```html
|
|
25
|
+
<link rel="stylesheet" href="/vendor/nibblearn/styles.css" />
|
|
26
|
+
<script src="/vendor/nibblearn/nibblearn.global.js" defer></script>
|
|
27
|
+
|
|
28
|
+
<nibblearn-module>
|
|
29
|
+
<p>Fallback text for search engines and readers without JavaScript.</p>
|
|
30
|
+
<script type="application/json">
|
|
31
|
+
{
|
|
32
|
+
"id": "check",
|
|
33
|
+
"type": "true-false",
|
|
34
|
+
"content": { "statements": [{ "text": "CTR is clicks ÷ impressions.", "isTrue": true }] }
|
|
35
|
+
}
|
|
36
|
+
</script>
|
|
37
|
+
</nibblearn-module>
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Copy the two files from `node_modules/@nibblearn/embed/dist/` to your server; the library makes no network requests itself.
|
|
41
|
+
|
|
42
|
+
The element dispatches `nibblearn:event`, `nibblearn:complete` and `nibblearn:statechange` DOM events (they bubble). See the [embedding guide](https://github.com/ifgolubev/nibblearn/blob/main/docs/embedding.md).
|
|
43
|
+
|
|
44
|
+
MIT licensed.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let react_dom_client = require("react-dom/client");
|
|
3
|
+
let _nibblearn_react = require("@nibblearn/react");
|
|
4
|
+
let react_jsx_runtime = require("react/jsx-runtime");
|
|
5
|
+
// src/index.tsx
|
|
6
|
+
/** Elements this library renders into, with their React roots. */
|
|
7
|
+
var roots = /* @__PURE__ */ new WeakMap();
|
|
8
|
+
/** Options given to `hydrate` / `mountElement` for an element; they survive a re-mount. */
|
|
9
|
+
var elementOptions = /* @__PURE__ */ new WeakMap();
|
|
10
|
+
/** Options given to `defineNibblearnElement`, per tag name (the latest call wins). */
|
|
11
|
+
var tagOptions = /* @__PURE__ */ new Map();
|
|
12
|
+
var SELECTOR = "nibblearn-module, [data-nibblearn-module]";
|
|
13
|
+
var ConfigError = class extends Error {
|
|
14
|
+
key;
|
|
15
|
+
constructor(key) {
|
|
16
|
+
super(key);
|
|
17
|
+
this.key = key;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Text of the child config script, remembered per element: React replaces the element's
|
|
22
|
+
* children on the first render, so a later re-mount (the element was moved, `hydrate` ran
|
|
23
|
+
* again) must not depend on the script still being there.
|
|
24
|
+
*/
|
|
25
|
+
var scriptConfigs = /* @__PURE__ */ new WeakMap();
|
|
26
|
+
/** Read the module config from a child `<script type="application/json">` or the `config` attribute. */
|
|
27
|
+
function readConfig(el) {
|
|
28
|
+
const script = [...el.children].find((c) => c.tagName === "SCRIPT" && (c.getAttribute("type") ?? "").toLowerCase() === "application/json");
|
|
29
|
+
if (script?.textContent != null) scriptConfigs.set(el, script.textContent);
|
|
30
|
+
const text = scriptConfigs.get(el) ?? el.getAttribute("config") ?? el.getAttribute("data-config");
|
|
31
|
+
if (text == null || !text.trim()) throw new ConfigError("embed.noConfig");
|
|
32
|
+
try {
|
|
33
|
+
return JSON.parse(text);
|
|
34
|
+
} catch {
|
|
35
|
+
throw new ConfigError("embed.invalidJson");
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** InvalidModule with a translated config problem. */
|
|
39
|
+
function ConfigProblemView({ problem }) {
|
|
40
|
+
const t = (0, _nibblearn_react.useTranslator)();
|
|
41
|
+
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_nibblearn_react.InvalidModule, { issues: [{
|
|
42
|
+
path: "(root)",
|
|
43
|
+
message: t(problem)
|
|
44
|
+
}] });
|
|
45
|
+
}
|
|
46
|
+
var emitDom = (el, name, detail) => el.dispatchEvent(new CustomEvent(name, {
|
|
47
|
+
detail,
|
|
48
|
+
bubbles: true,
|
|
49
|
+
composed: true
|
|
50
|
+
}));
|
|
51
|
+
/** Render (or re-render) one element. `config` overrides what the element contains. */
|
|
52
|
+
function mountElement(el, options = {}, config) {
|
|
53
|
+
elementOptions.set(el, options);
|
|
54
|
+
render(el, options, config);
|
|
55
|
+
}
|
|
56
|
+
/** Options for an element rendered by the custom element: its own, else its tag's. */
|
|
57
|
+
var optionsFor = (el, tagName) => elementOptions.get(el) ?? tagOptions.get(tagName) ?? {};
|
|
58
|
+
function render(el, options, config) {
|
|
59
|
+
let raw = config;
|
|
60
|
+
let problem = null;
|
|
61
|
+
if (raw === void 0) try {
|
|
62
|
+
raw = readConfig(el);
|
|
63
|
+
} catch (e) {
|
|
64
|
+
problem = e instanceof ConfigError ? e.key : "embed.unreadable";
|
|
65
|
+
}
|
|
66
|
+
let root = roots.get(el);
|
|
67
|
+
if (!root) {
|
|
68
|
+
root = (0, react_dom_client.createRoot)(el);
|
|
69
|
+
roots.set(el, root);
|
|
70
|
+
}
|
|
71
|
+
const isObject = typeof raw === "object" && raw !== null && typeof raw.type === "string";
|
|
72
|
+
const renderIssues = (issues, key) => root.render(/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_nibblearn_react.NibblearnProvider, {
|
|
73
|
+
...options.provider,
|
|
74
|
+
wrapper: false,
|
|
75
|
+
children: key ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ConfigProblemView, { problem: key }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_nibblearn_react.InvalidModule, { issues: issues ?? [] })
|
|
76
|
+
}));
|
|
77
|
+
if (problem || !isObject) {
|
|
78
|
+
renderIssues(null, problem ?? "embed.noType");
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
const migrated = (0, _nibblearn_react.migrateModule)(raw, { registry: options.registry?.schemas });
|
|
82
|
+
if (!migrated.success) {
|
|
83
|
+
renderIssues(migrated.issues, null);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const moduleConfig = migrated.data;
|
|
87
|
+
const id = typeof moduleConfig.id === "string" ? moduleConfig.id : "";
|
|
88
|
+
root.render(/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_nibblearn_react.NibblearnProvider, {
|
|
89
|
+
...options.provider,
|
|
90
|
+
wrapper: false,
|
|
91
|
+
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_nibblearn_react.ModuleRenderer, {
|
|
92
|
+
config: moduleConfig,
|
|
93
|
+
registry: options.registry,
|
|
94
|
+
initialState: options.getInitialState?.(id, el) ?? void 0,
|
|
95
|
+
onEvent: (event) => {
|
|
96
|
+
options.onEvent?.(event, el);
|
|
97
|
+
emitDom(el, "nibblearn:event", event);
|
|
98
|
+
},
|
|
99
|
+
onComplete: (result) => {
|
|
100
|
+
options.onComplete?.(result, el);
|
|
101
|
+
emitDom(el, "nibblearn:complete", result);
|
|
102
|
+
},
|
|
103
|
+
onStateChange: (state) => {
|
|
104
|
+
options.onStateChange?.(state, el);
|
|
105
|
+
emitDom(el, "nibblearn:statechange", state);
|
|
106
|
+
}
|
|
107
|
+
})
|
|
108
|
+
}));
|
|
109
|
+
}
|
|
110
|
+
/** Unmount one element rendered by `hydrate`, `mountElement` or the custom element. */
|
|
111
|
+
function unmountElement(el) {
|
|
112
|
+
const root = roots.get(el);
|
|
113
|
+
if (!root) return;
|
|
114
|
+
roots.delete(el);
|
|
115
|
+
root.unmount();
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Find `<nibblearn-module>` and `[data-nibblearn-module]` elements under `root` and render a
|
|
119
|
+
* module into each. Elements that are already mounted are skipped.
|
|
120
|
+
*/
|
|
121
|
+
function hydrate(root = document, options = {}) {
|
|
122
|
+
const elements = [...root.querySelectorAll(SELECTOR)].filter((el) => !roots.has(el) || !elementOptions.has(el));
|
|
123
|
+
for (const el of elements) mountElement(el, options);
|
|
124
|
+
return {
|
|
125
|
+
elements,
|
|
126
|
+
unmount: () => {
|
|
127
|
+
for (const el of elements) unmountElement(el);
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Register the `<nibblearn-module>` custom element (or another tag name). The element reads
|
|
133
|
+
* its config from a child `<script type="application/json">`, the `config` attribute or the
|
|
134
|
+
* `config` property, and dispatches `nibblearn:event`, `nibblearn:complete` and
|
|
135
|
+
* `nibblearn:statechange` DOM events. Safe to call more than once and on the server (no-op).
|
|
136
|
+
*/
|
|
137
|
+
function defineNibblearnElement(tagName = "nibblearn-module", options = {}) {
|
|
138
|
+
if (typeof window === "undefined" || typeof customElements === "undefined") return;
|
|
139
|
+
if (customElements.get(tagName)) {
|
|
140
|
+
if (!tagOptions.has(tagName)) return;
|
|
141
|
+
tagOptions.set(tagName, options);
|
|
142
|
+
for (const el of document.querySelectorAll(tagName)) if (roots.has(el) && !elementOptions.has(el)) render(el, options, el.config);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
tagOptions.set(tagName, options);
|
|
146
|
+
class NibblearnModuleElement extends HTMLElement {
|
|
147
|
+
static observedAttributes = ["config"];
|
|
148
|
+
#config = void 0;
|
|
149
|
+
#connected = false;
|
|
150
|
+
get config() {
|
|
151
|
+
return this.#config;
|
|
152
|
+
}
|
|
153
|
+
set config(value) {
|
|
154
|
+
this.#config = value;
|
|
155
|
+
if (this.#connected) render(this, optionsFor(this, tagName), value);
|
|
156
|
+
}
|
|
157
|
+
connectedCallback() {
|
|
158
|
+
if (Object.prototype.hasOwnProperty.call(this, "config")) {
|
|
159
|
+
const value = this.config;
|
|
160
|
+
delete this.config;
|
|
161
|
+
this.#config = value;
|
|
162
|
+
}
|
|
163
|
+
this.#connected = true;
|
|
164
|
+
const mount = () => {
|
|
165
|
+
if (this.#connected) render(this, optionsFor(this, tagName), this.#config);
|
|
166
|
+
};
|
|
167
|
+
if (this.#config === void 0 && document.readyState === "loading" && !this.hasAttribute("config")) document.addEventListener("DOMContentLoaded", mount, { once: true });
|
|
168
|
+
else mount();
|
|
169
|
+
}
|
|
170
|
+
disconnectedCallback() {
|
|
171
|
+
this.#connected = false;
|
|
172
|
+
queueMicrotask(() => {
|
|
173
|
+
if (!this.#connected) unmountElement(this);
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
attributeChangedCallback(name, old, value) {
|
|
177
|
+
if (name === "config" && this.#connected && old !== value && this.#config === void 0) {
|
|
178
|
+
scriptConfigs.delete(this);
|
|
179
|
+
render(this, optionsFor(this, tagName));
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
customElements.define(tagName, NibblearnModuleElement);
|
|
184
|
+
}
|
|
185
|
+
exports.defineNibblearnElement = defineNibblearnElement;
|
|
186
|
+
exports.hydrate = hydrate;
|
|
187
|
+
exports.mountElement = mountElement;
|
|
188
|
+
exports.unmountElement = unmountElement;
|
|
189
|
+
|
|
190
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["useTranslator","InvalidModule","createRoot","NibblearnProvider","migrateModule","ModuleRenderer"],"sources":["../src/index.tsx"],"sourcesContent":["import { createRoot, type Root } from \"react-dom/client\";\nimport {\n InvalidModule,\n ModuleRenderer,\n NibblearnProvider,\n migrateModule,\n type ModuleRegistry,\n type ModuleResult,\n type ModuleState,\n type NibblearnEvent,\n type NibblearnProviderProps,\n useTranslator,\n type ValidationIssue,\n} from \"@nibblearn/react\";\n\nexport interface HydrateOptions {\n /** Registry used to resolve module types. Defaults to the built-in modules. */\n registry?: ModuleRegistry;\n /** Provider settings (theme, accent, messages, resolveAsset…). The provider renders no wrapper. */\n provider?: Omit<NibblearnProviderProps, \"children\" | \"wrapper\">;\n onEvent?: (event: NibblearnEvent, element: Element) => void;\n onComplete?: (result: ModuleResult, element: Element) => void;\n /** Saved session for a module (see `ModuleState`). */\n getInitialState?: (moduleId: string, element: Element) => ModuleState | null | undefined;\n onStateChange?: (state: ModuleState, element: Element) => void;\n}\n\nexport interface HydrateResult {\n /** The elements that were mounted by this call. */\n elements: Element[];\n /** Unmount every element mounted by this call. */\n unmount: () => void;\n}\n\n/** Elements this library renders into, with their React roots. */\nconst roots = new WeakMap<Element, Root>();\n/** Options given to `hydrate` / `mountElement` for an element; they survive a re-mount. */\nconst elementOptions = new WeakMap<Element, HydrateOptions>();\n/** Options given to `defineNibblearnElement`, per tag name (the latest call wins). */\nconst tagOptions = new Map<string, HydrateOptions>();\n\nconst SELECTOR = \"nibblearn-module, [data-nibblearn-module]\";\n\n/** Message keys (see `embed.*` in the messages) for config problems. */\ntype ConfigProblem = \"embed.noConfig\" | \"embed.invalidJson\" | \"embed.unreadable\" | \"embed.noType\";\n\nclass ConfigError extends Error {\n constructor(readonly key: ConfigProblem) {\n super(key);\n }\n}\n\n/**\n * Text of the child config script, remembered per element: React replaces the element's\n * children on the first render, so a later re-mount (the element was moved, `hydrate` ran\n * again) must not depend on the script still being there.\n */\nconst scriptConfigs = new WeakMap<Element, string>();\n\n/** Read the module config from a child `<script type=\"application/json\">` or the `config` attribute. */\nfunction readConfig(el: Element): unknown {\n const script = [...el.children].find(\n (c) =>\n c.tagName === \"SCRIPT\" && (c.getAttribute(\"type\") ?? \"\").toLowerCase() === \"application/json\",\n );\n if (script?.textContent != null) scriptConfigs.set(el, script.textContent);\n const text = scriptConfigs.get(el) ?? el.getAttribute(\"config\") ?? el.getAttribute(\"data-config\");\n if (text == null || !text.trim()) throw new ConfigError(\"embed.noConfig\");\n try {\n return JSON.parse(text);\n } catch {\n throw new ConfigError(\"embed.invalidJson\");\n }\n}\n\n/** InvalidModule with a translated config problem. */\nfunction ConfigProblemView({ problem }: { problem: ConfigProblem }) {\n const t = useTranslator();\n return <InvalidModule issues={[{ path: \"(root)\", message: t(problem) }]} />;\n}\n\nconst emitDom = (el: Element, name: string, detail: unknown) =>\n el.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true }));\n\n/** Render (or re-render) one element. `config` overrides what the element contains. */\nexport function mountElement(el: Element, options: HydrateOptions = {}, config?: unknown): void {\n elementOptions.set(el, options);\n render(el, options, config);\n}\n\n/** Options for an element rendered by the custom element: its own, else its tag's. */\nconst optionsFor = (el: Element, tagName: string): HydrateOptions =>\n elementOptions.get(el) ?? tagOptions.get(tagName) ?? {};\n\nfunction render(el: Element, options: HydrateOptions, config?: unknown): void {\n let raw: unknown = config;\n let problem: ConfigProblem | null = null;\n if (raw === undefined) {\n try {\n raw = readConfig(el);\n } catch (e) {\n problem = e instanceof ConfigError ? e.key : \"embed.unreadable\";\n }\n }\n let root = roots.get(el);\n if (!root) {\n // React replaces the element's content (the static fallback and the config script).\n root = createRoot(el);\n roots.set(el, root);\n }\n const isObject =\n typeof raw === \"object\" && raw !== null && typeof (raw as { type?: unknown }).type === \"string\";\n const renderIssues = (issues: ValidationIssue[] | null, key: ConfigProblem | null) =>\n root.render(\n <NibblearnProvider {...options.provider} wrapper={false}>\n {key ? <ConfigProblemView problem={key} /> : <InvalidModule issues={issues ?? []} />}\n </NibblearnProvider>,\n );\n if (problem || !isObject) {\n renderIssues(null, problem ?? \"embed.noType\");\n return;\n }\n const migrated = migrateModule(raw, { registry: options.registry?.schemas });\n // A config that cannot be migrated (e.g. saved by a newer version) is not rendered as-is.\n if (!migrated.success) {\n renderIssues(migrated.issues, null);\n return;\n }\n const moduleConfig = migrated.data as { id: string; type: string };\n const id = typeof moduleConfig.id === \"string\" ? moduleConfig.id : \"\";\n root.render(\n <NibblearnProvider {...options.provider} wrapper={false}>\n <ModuleRenderer\n config={moduleConfig}\n registry={options.registry}\n initialState={options.getInitialState?.(id, el) ?? undefined}\n onEvent={(event: NibblearnEvent) => {\n options.onEvent?.(event, el);\n emitDom(el, \"nibblearn:event\", event);\n }}\n onComplete={(result: ModuleResult) => {\n options.onComplete?.(result, el);\n emitDom(el, \"nibblearn:complete\", result);\n }}\n onStateChange={(state: ModuleState) => {\n options.onStateChange?.(state, el);\n emitDom(el, \"nibblearn:statechange\", state);\n }}\n />\n </NibblearnProvider>,\n );\n}\n\n/** Unmount one element rendered by `hydrate`, `mountElement` or the custom element. */\nexport function unmountElement(el: Element): void {\n const root = roots.get(el);\n if (!root) return;\n roots.delete(el);\n root.unmount();\n}\n\n/**\n * Find `<nibblearn-module>` and `[data-nibblearn-module]` elements under `root` and render a\n * module into each. Elements that are already mounted are skipped.\n */\nexport function hydrate(root: ParentNode = document, options: HydrateOptions = {}): HydrateResult {\n // Elements already rendered by `hydrate` / `mountElement` are skipped; ones the custom\n // element rendered on its own are re-rendered with these options.\n const elements = [...root.querySelectorAll(SELECTOR)].filter(\n (el) => !roots.has(el) || !elementOptions.has(el),\n );\n for (const el of elements) mountElement(el, options);\n return {\n elements,\n unmount: () => {\n for (const el of elements) unmountElement(el);\n },\n };\n}\n\n/**\n * Register the `<nibblearn-module>` custom element (or another tag name). The element reads\n * its config from a child `<script type=\"application/json\">`, the `config` attribute or the\n * `config` property, and dispatches `nibblearn:event`, `nibblearn:complete` and\n * `nibblearn:statechange` DOM events. Safe to call more than once and on the server (no-op).\n */\nexport function defineNibblearnElement(\n tagName = \"nibblearn-module\",\n options: HydrateOptions = {},\n): void {\n if (typeof window === \"undefined\" || typeof customElements === \"undefined\") return;\n if (customElements.get(tagName)) {\n // Defined before (e.g. by the standalone script): later options apply to its elements.\n if (!tagOptions.has(tagName)) return;\n tagOptions.set(tagName, options);\n for (const el of document.querySelectorAll(tagName))\n if (roots.has(el) && !elementOptions.has(el))\n render(el, options, (el as { config?: unknown }).config);\n return;\n }\n tagOptions.set(tagName, options);\n\n class NibblearnModuleElement extends HTMLElement {\n static observedAttributes = [\"config\"];\n #config: unknown = undefined;\n #connected = false;\n\n get config(): unknown {\n return this.#config;\n }\n set config(value: unknown) {\n this.#config = value;\n if (this.#connected) render(this, optionsFor(this, tagName), value);\n }\n\n connectedCallback() {\n // A `config` property set before the element was upgraded is an own property that\n // shadows the setter: move it to the private field.\n if (Object.prototype.hasOwnProperty.call(this, \"config\")) {\n const value = (this as unknown as { config: unknown }).config;\n delete (this as unknown as { config?: unknown }).config;\n this.#config = value;\n }\n this.#connected = true;\n const mount = () => {\n if (this.#connected) render(this, optionsFor(this, tagName), this.#config);\n };\n // Children (the config script) may not be parsed yet while the document is loading.\n if (\n this.#config === undefined &&\n document.readyState === \"loading\" &&\n !this.hasAttribute(\"config\")\n )\n document.addEventListener(\"DOMContentLoaded\", mount, { once: true });\n else mount();\n }\n\n disconnectedCallback() {\n this.#connected = false;\n // Unmount after the current task so React is never unmounted while rendering.\n queueMicrotask(() => {\n if (!this.#connected) unmountElement(this);\n });\n }\n\n attributeChangedCallback(name: string, old: string | null, value: string | null) {\n if (name === \"config\" && this.#connected && old !== value && this.#config === undefined) {\n // The attribute was changed explicitly: it now wins over a remembered script config.\n scriptConfigs.delete(this);\n render(this, optionsFor(this, tagName));\n }\n }\n }\n\n customElements.define(tagName, NibblearnModuleElement);\n}\n"],"mappings":";;;;;;AAmCA,IAAM,wBAAQ,IAAI,QAAuB;;AAEzC,IAAM,iCAAiB,IAAI,QAAiC;;AAE5D,IAAM,6BAAa,IAAI,IAA4B;AAEnD,IAAM,WAAW;AAKjB,IAAM,cAAN,cAA0B,MAAM;CACT;CAArB,YAAY,KA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,IAAI,SAAkB;GACpB,OAAO,KAAK;EACd;EACA,IAAI,OAAO,OAAgB;GACzB,KAAK,UAAU;GACf,IAAI,KAAK,YAAY,OAAO,MAAM,WAAW,MAAM,OAAO,GAAG,KAAK;EACpE;EAEA,oBAAoB;GAGlB,IAAI,OAAO,UAAU,eAAe,KAAK,MAAM,QAAQ,GAAG;IACxD,MAAM,QAAS,KAAwC;IACvD,OAAQ,KAAyC;IACjD,KAAK,UAAU;GACjB;GACA,KAAK,aAAa;GAClB,MAAM,cAAc;IAClB,IAAI,KAAK,YAAY,OAAO,MAAM,WAAW,MAAM,OAAO,GAAG,KAAK,OAAO;GAC3E;GAEA,IACE,KAAK,YAAY,KAAA,KACjB,SAAS,eAAe,aACxB,CAAC,KAAK,aAAa,QAAQ,GAE3B,SAAS,iBAAiB,oBAAoB,OAAO,EAAE,MAAM,KAAK,CAAC;QAChE,MAAM;EACb;EAEA,uBAAuB;GACrB,KAAK,aAAa;GAElB,qBAAqB;IACnB,IAAI,CAAC,KAAK,YAAY,eAAe,IAAI;GAC3C,CAAC;EACH;EAEA,yBAAyB,MAAc,KAAoB,OAAsB;GAC/E,IAAI,SAAS,YAAY,KAAK,cAAc,QAAQ,SAAS,KAAK,YAAY,KAAA,GAAW;IAEvF,cAAc,OAAO,IAAI;IACzB,OAAO,MAAM,WAAW,MAAM,OAAO,CAAC;GACxC;EACF;CACF;CAEA,eAAe,OAAO,SAAS,sBAAsB;AACvD"}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { ModuleRegistry, ModuleResult, ModuleState, NibblearnEvent, NibblearnProviderProps } from '@nibblearn/react';
|
|
2
|
+
|
|
3
|
+
export interface HydrateOptions {
|
|
4
|
+
/** Registry used to resolve module types. Defaults to the built-in modules. */
|
|
5
|
+
registry?: ModuleRegistry;
|
|
6
|
+
/** Provider settings (theme, accent, messages, resolveAsset…). The provider renders no wrapper. */
|
|
7
|
+
provider?: Omit<NibblearnProviderProps, "children" | "wrapper">;
|
|
8
|
+
onEvent?: (event: NibblearnEvent, element: Element) => void;
|
|
9
|
+
onComplete?: (result: ModuleResult, element: Element) => void;
|
|
10
|
+
/** Saved session for a module (see `ModuleState`). */
|
|
11
|
+
getInitialState?: (moduleId: string, element: Element) => ModuleState | null | undefined;
|
|
12
|
+
onStateChange?: (state: ModuleState, element: Element) => void;
|
|
13
|
+
}
|
|
14
|
+
export interface HydrateResult {
|
|
15
|
+
/** The elements that were mounted by this call. */
|
|
16
|
+
elements: Element[];
|
|
17
|
+
/** Unmount every element mounted by this call. */
|
|
18
|
+
unmount: () => void;
|
|
19
|
+
}
|
|
20
|
+
/** Render (or re-render) one element. `config` overrides what the element contains. */
|
|
21
|
+
export declare function mountElement(el: Element, options?: HydrateOptions, config?: unknown): void;
|
|
22
|
+
/** Unmount one element rendered by `hydrate`, `mountElement` or the custom element. */
|
|
23
|
+
export declare function unmountElement(el: Element): void;
|
|
24
|
+
/**
|
|
25
|
+
* Find `<nibblearn-module>` and `[data-nibblearn-module]` elements under `root` and render a
|
|
26
|
+
* module into each. Elements that are already mounted are skipped.
|
|
27
|
+
*/
|
|
28
|
+
export declare function hydrate(root?: ParentNode, options?: HydrateOptions): HydrateResult;
|
|
29
|
+
/**
|
|
30
|
+
* Register the `<nibblearn-module>` custom element (or another tag name). The element reads
|
|
31
|
+
* its config from a child `<script type="application/json">`, the `config` attribute or the
|
|
32
|
+
* `config` property, and dispatches `nibblearn:event`, `nibblearn:complete` and
|
|
33
|
+
* `nibblearn:statechange` DOM events. Safe to call more than once and on the server (no-op).
|
|
34
|
+
*/
|
|
35
|
+
export declare function defineNibblearnElement(tagName?: string, options?: HydrateOptions): void;
|
|
36
|
+
|
|
37
|
+
export {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { ModuleRegistry, ModuleResult, ModuleState, NibblearnEvent, NibblearnProviderProps } from '@nibblearn/react';
|
|
2
|
+
|
|
3
|
+
export interface HydrateOptions {
|
|
4
|
+
/** Registry used to resolve module types. Defaults to the built-in modules. */
|
|
5
|
+
registry?: ModuleRegistry;
|
|
6
|
+
/** Provider settings (theme, accent, messages, resolveAsset…). The provider renders no wrapper. */
|
|
7
|
+
provider?: Omit<NibblearnProviderProps, "children" | "wrapper">;
|
|
8
|
+
onEvent?: (event: NibblearnEvent, element: Element) => void;
|
|
9
|
+
onComplete?: (result: ModuleResult, element: Element) => void;
|
|
10
|
+
/** Saved session for a module (see `ModuleState`). */
|
|
11
|
+
getInitialState?: (moduleId: string, element: Element) => ModuleState | null | undefined;
|
|
12
|
+
onStateChange?: (state: ModuleState, element: Element) => void;
|
|
13
|
+
}
|
|
14
|
+
export interface HydrateResult {
|
|
15
|
+
/** The elements that were mounted by this call. */
|
|
16
|
+
elements: Element[];
|
|
17
|
+
/** Unmount every element mounted by this call. */
|
|
18
|
+
unmount: () => void;
|
|
19
|
+
}
|
|
20
|
+
/** Render (or re-render) one element. `config` overrides what the element contains. */
|
|
21
|
+
export declare function mountElement(el: Element, options?: HydrateOptions, config?: unknown): void;
|
|
22
|
+
/** Unmount one element rendered by `hydrate`, `mountElement` or the custom element. */
|
|
23
|
+
export declare function unmountElement(el: Element): void;
|
|
24
|
+
/**
|
|
25
|
+
* Find `<nibblearn-module>` and `[data-nibblearn-module]` elements under `root` and render a
|
|
26
|
+
* module into each. Elements that are already mounted are skipped.
|
|
27
|
+
*/
|
|
28
|
+
export declare function hydrate(root?: ParentNode, options?: HydrateOptions): HydrateResult;
|
|
29
|
+
/**
|
|
30
|
+
* Register the `<nibblearn-module>` custom element (or another tag name). The element reads
|
|
31
|
+
* its config from a child `<script type="application/json">`, the `config` attribute or the
|
|
32
|
+
* `config` property, and dispatches `nibblearn:event`, `nibblearn:complete` and
|
|
33
|
+
* `nibblearn:statechange` DOM events. Safe to call more than once and on the server (no-op).
|
|
34
|
+
*/
|
|
35
|
+
export declare function defineNibblearnElement(tagName?: string, options?: HydrateOptions): void;
|
|
36
|
+
|
|
37
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { createRoot } from "react-dom/client";
|
|
2
|
+
import { InvalidModule, ModuleRenderer, NibblearnProvider, migrateModule, useTranslator } from "@nibblearn/react";
|
|
3
|
+
import { jsx } from "react/jsx-runtime";
|
|
4
|
+
// src/index.tsx
|
|
5
|
+
/** Elements this library renders into, with their React roots. */
|
|
6
|
+
var roots = /* @__PURE__ */ new WeakMap();
|
|
7
|
+
/** Options given to `hydrate` / `mountElement` for an element; they survive a re-mount. */
|
|
8
|
+
var elementOptions = /* @__PURE__ */ new WeakMap();
|
|
9
|
+
/** Options given to `defineNibblearnElement`, per tag name (the latest call wins). */
|
|
10
|
+
var tagOptions = /* @__PURE__ */ new Map();
|
|
11
|
+
var SELECTOR = "nibblearn-module, [data-nibblearn-module]";
|
|
12
|
+
var ConfigError = class extends Error {
|
|
13
|
+
key;
|
|
14
|
+
constructor(key) {
|
|
15
|
+
super(key);
|
|
16
|
+
this.key = key;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Text of the child config script, remembered per element: React replaces the element's
|
|
21
|
+
* children on the first render, so a later re-mount (the element was moved, `hydrate` ran
|
|
22
|
+
* again) must not depend on the script still being there.
|
|
23
|
+
*/
|
|
24
|
+
var scriptConfigs = /* @__PURE__ */ new WeakMap();
|
|
25
|
+
/** Read the module config from a child `<script type="application/json">` or the `config` attribute. */
|
|
26
|
+
function readConfig(el) {
|
|
27
|
+
const script = [...el.children].find((c) => c.tagName === "SCRIPT" && (c.getAttribute("type") ?? "").toLowerCase() === "application/json");
|
|
28
|
+
if (script?.textContent != null) scriptConfigs.set(el, script.textContent);
|
|
29
|
+
const text = scriptConfigs.get(el) ?? el.getAttribute("config") ?? el.getAttribute("data-config");
|
|
30
|
+
if (text == null || !text.trim()) throw new ConfigError("embed.noConfig");
|
|
31
|
+
try {
|
|
32
|
+
return JSON.parse(text);
|
|
33
|
+
} catch {
|
|
34
|
+
throw new ConfigError("embed.invalidJson");
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** InvalidModule with a translated config problem. */
|
|
38
|
+
function ConfigProblemView({ problem }) {
|
|
39
|
+
const t = useTranslator();
|
|
40
|
+
return /* @__PURE__ */ jsx(InvalidModule, { issues: [{
|
|
41
|
+
path: "(root)",
|
|
42
|
+
message: t(problem)
|
|
43
|
+
}] });
|
|
44
|
+
}
|
|
45
|
+
var emitDom = (el, name, detail) => el.dispatchEvent(new CustomEvent(name, {
|
|
46
|
+
detail,
|
|
47
|
+
bubbles: true,
|
|
48
|
+
composed: true
|
|
49
|
+
}));
|
|
50
|
+
/** Render (or re-render) one element. `config` overrides what the element contains. */
|
|
51
|
+
function mountElement(el, options = {}, config) {
|
|
52
|
+
elementOptions.set(el, options);
|
|
53
|
+
render(el, options, config);
|
|
54
|
+
}
|
|
55
|
+
/** Options for an element rendered by the custom element: its own, else its tag's. */
|
|
56
|
+
var optionsFor = (el, tagName) => elementOptions.get(el) ?? tagOptions.get(tagName) ?? {};
|
|
57
|
+
function render(el, options, config) {
|
|
58
|
+
let raw = config;
|
|
59
|
+
let problem = null;
|
|
60
|
+
if (raw === void 0) try {
|
|
61
|
+
raw = readConfig(el);
|
|
62
|
+
} catch (e) {
|
|
63
|
+
problem = e instanceof ConfigError ? e.key : "embed.unreadable";
|
|
64
|
+
}
|
|
65
|
+
let root = roots.get(el);
|
|
66
|
+
if (!root) {
|
|
67
|
+
root = createRoot(el);
|
|
68
|
+
roots.set(el, root);
|
|
69
|
+
}
|
|
70
|
+
const isObject = typeof raw === "object" && raw !== null && typeof raw.type === "string";
|
|
71
|
+
const renderIssues = (issues, key) => root.render(/* @__PURE__ */ jsx(NibblearnProvider, {
|
|
72
|
+
...options.provider,
|
|
73
|
+
wrapper: false,
|
|
74
|
+
children: key ? /* @__PURE__ */ jsx(ConfigProblemView, { problem: key }) : /* @__PURE__ */ jsx(InvalidModule, { issues: issues ?? [] })
|
|
75
|
+
}));
|
|
76
|
+
if (problem || !isObject) {
|
|
77
|
+
renderIssues(null, problem ?? "embed.noType");
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const migrated = migrateModule(raw, { registry: options.registry?.schemas });
|
|
81
|
+
if (!migrated.success) {
|
|
82
|
+
renderIssues(migrated.issues, null);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const moduleConfig = migrated.data;
|
|
86
|
+
const id = typeof moduleConfig.id === "string" ? moduleConfig.id : "";
|
|
87
|
+
root.render(/* @__PURE__ */ jsx(NibblearnProvider, {
|
|
88
|
+
...options.provider,
|
|
89
|
+
wrapper: false,
|
|
90
|
+
children: /* @__PURE__ */ jsx(ModuleRenderer, {
|
|
91
|
+
config: moduleConfig,
|
|
92
|
+
registry: options.registry,
|
|
93
|
+
initialState: options.getInitialState?.(id, el) ?? void 0,
|
|
94
|
+
onEvent: (event) => {
|
|
95
|
+
options.onEvent?.(event, el);
|
|
96
|
+
emitDom(el, "nibblearn:event", event);
|
|
97
|
+
},
|
|
98
|
+
onComplete: (result) => {
|
|
99
|
+
options.onComplete?.(result, el);
|
|
100
|
+
emitDom(el, "nibblearn:complete", result);
|
|
101
|
+
},
|
|
102
|
+
onStateChange: (state) => {
|
|
103
|
+
options.onStateChange?.(state, el);
|
|
104
|
+
emitDom(el, "nibblearn:statechange", state);
|
|
105
|
+
}
|
|
106
|
+
})
|
|
107
|
+
}));
|
|
108
|
+
}
|
|
109
|
+
/** Unmount one element rendered by `hydrate`, `mountElement` or the custom element. */
|
|
110
|
+
function unmountElement(el) {
|
|
111
|
+
const root = roots.get(el);
|
|
112
|
+
if (!root) return;
|
|
113
|
+
roots.delete(el);
|
|
114
|
+
root.unmount();
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Find `<nibblearn-module>` and `[data-nibblearn-module]` elements under `root` and render a
|
|
118
|
+
* module into each. Elements that are already mounted are skipped.
|
|
119
|
+
*/
|
|
120
|
+
function hydrate(root = document, options = {}) {
|
|
121
|
+
const elements = [...root.querySelectorAll(SELECTOR)].filter((el) => !roots.has(el) || !elementOptions.has(el));
|
|
122
|
+
for (const el of elements) mountElement(el, options);
|
|
123
|
+
return {
|
|
124
|
+
elements,
|
|
125
|
+
unmount: () => {
|
|
126
|
+
for (const el of elements) unmountElement(el);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Register the `<nibblearn-module>` custom element (or another tag name). The element reads
|
|
132
|
+
* its config from a child `<script type="application/json">`, the `config` attribute or the
|
|
133
|
+
* `config` property, and dispatches `nibblearn:event`, `nibblearn:complete` and
|
|
134
|
+
* `nibblearn:statechange` DOM events. Safe to call more than once and on the server (no-op).
|
|
135
|
+
*/
|
|
136
|
+
function defineNibblearnElement(tagName = "nibblearn-module", options = {}) {
|
|
137
|
+
if (typeof window === "undefined" || typeof customElements === "undefined") return;
|
|
138
|
+
if (customElements.get(tagName)) {
|
|
139
|
+
if (!tagOptions.has(tagName)) return;
|
|
140
|
+
tagOptions.set(tagName, options);
|
|
141
|
+
for (const el of document.querySelectorAll(tagName)) if (roots.has(el) && !elementOptions.has(el)) render(el, options, el.config);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
tagOptions.set(tagName, options);
|
|
145
|
+
class NibblearnModuleElement extends HTMLElement {
|
|
146
|
+
static observedAttributes = ["config"];
|
|
147
|
+
#config = void 0;
|
|
148
|
+
#connected = false;
|
|
149
|
+
get config() {
|
|
150
|
+
return this.#config;
|
|
151
|
+
}
|
|
152
|
+
set config(value) {
|
|
153
|
+
this.#config = value;
|
|
154
|
+
if (this.#connected) render(this, optionsFor(this, tagName), value);
|
|
155
|
+
}
|
|
156
|
+
connectedCallback() {
|
|
157
|
+
if (Object.prototype.hasOwnProperty.call(this, "config")) {
|
|
158
|
+
const value = this.config;
|
|
159
|
+
delete this.config;
|
|
160
|
+
this.#config = value;
|
|
161
|
+
}
|
|
162
|
+
this.#connected = true;
|
|
163
|
+
const mount = () => {
|
|
164
|
+
if (this.#connected) render(this, optionsFor(this, tagName), this.#config);
|
|
165
|
+
};
|
|
166
|
+
if (this.#config === void 0 && document.readyState === "loading" && !this.hasAttribute("config")) document.addEventListener("DOMContentLoaded", mount, { once: true });
|
|
167
|
+
else mount();
|
|
168
|
+
}
|
|
169
|
+
disconnectedCallback() {
|
|
170
|
+
this.#connected = false;
|
|
171
|
+
queueMicrotask(() => {
|
|
172
|
+
if (!this.#connected) unmountElement(this);
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
attributeChangedCallback(name, old, value) {
|
|
176
|
+
if (name === "config" && this.#connected && old !== value && this.#config === void 0) {
|
|
177
|
+
scriptConfigs.delete(this);
|
|
178
|
+
render(this, optionsFor(this, tagName));
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
customElements.define(tagName, NibblearnModuleElement);
|
|
183
|
+
}
|
|
184
|
+
export { defineNibblearnElement, hydrate, mountElement, unmountElement };
|
|
185
|
+
|
|
186
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.tsx"],"sourcesContent":["import { createRoot, type Root } from \"react-dom/client\";\nimport {\n InvalidModule,\n ModuleRenderer,\n NibblearnProvider,\n migrateModule,\n type ModuleRegistry,\n type ModuleResult,\n type ModuleState,\n type NibblearnEvent,\n type NibblearnProviderProps,\n useTranslator,\n type ValidationIssue,\n} from \"@nibblearn/react\";\n\nexport interface HydrateOptions {\n /** Registry used to resolve module types. Defaults to the built-in modules. */\n registry?: ModuleRegistry;\n /** Provider settings (theme, accent, messages, resolveAsset…). The provider renders no wrapper. */\n provider?: Omit<NibblearnProviderProps, \"children\" | \"wrapper\">;\n onEvent?: (event: NibblearnEvent, element: Element) => void;\n onComplete?: (result: ModuleResult, element: Element) => void;\n /** Saved session for a module (see `ModuleState`). */\n getInitialState?: (moduleId: string, element: Element) => ModuleState | null | undefined;\n onStateChange?: (state: ModuleState, element: Element) => void;\n}\n\nexport interface HydrateResult {\n /** The elements that were mounted by this call. */\n elements: Element[];\n /** Unmount every element mounted by this call. */\n unmount: () => void;\n}\n\n/** Elements this library renders into, with their React roots. */\nconst roots = new WeakMap<Element, Root>();\n/** Options given to `hydrate` / `mountElement` for an element; they survive a re-mount. */\nconst elementOptions = new WeakMap<Element, HydrateOptions>();\n/** Options given to `defineNibblearnElement`, per tag name (the latest call wins). */\nconst tagOptions = new Map<string, HydrateOptions>();\n\nconst SELECTOR = \"nibblearn-module, [data-nibblearn-module]\";\n\n/** Message keys (see `embed.*` in the messages) for config problems. */\ntype ConfigProblem = \"embed.noConfig\" | \"embed.invalidJson\" | \"embed.unreadable\" | \"embed.noType\";\n\nclass ConfigError extends Error {\n constructor(readonly key: ConfigProblem) {\n super(key);\n }\n}\n\n/**\n * Text of the child config script, remembered per element: React replaces the element's\n * children on the first render, so a later re-mount (the element was moved, `hydrate` ran\n * again) must not depend on the script still being there.\n */\nconst scriptConfigs = new WeakMap<Element, string>();\n\n/** Read the module config from a child `<script type=\"application/json\">` or the `config` attribute. */\nfunction readConfig(el: Element): unknown {\n const script = [...el.children].find(\n (c) =>\n c.tagName === \"SCRIPT\" && (c.getAttribute(\"type\") ?? \"\").toLowerCase() === \"application/json\",\n );\n if (script?.textContent != null) scriptConfigs.set(el, script.textContent);\n const text = scriptConfigs.get(el) ?? el.getAttribute(\"config\") ?? el.getAttribute(\"data-config\");\n if (text == null || !text.trim()) throw new ConfigError(\"embed.noConfig\");\n try {\n return JSON.parse(text);\n } catch {\n throw new ConfigError(\"embed.invalidJson\");\n }\n}\n\n/** InvalidModule with a translated config problem. */\nfunction ConfigProblemView({ problem }: { problem: ConfigProblem }) {\n const t = useTranslator();\n return <InvalidModule issues={[{ path: \"(root)\", message: t(problem) }]} />;\n}\n\nconst emitDom = (el: Element, name: string, detail: unknown) =>\n el.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true }));\n\n/** Render (or re-render) one element. `config` overrides what the element contains. */\nexport function mountElement(el: Element, options: HydrateOptions = {}, config?: unknown): void {\n elementOptions.set(el, options);\n render(el, options, config);\n}\n\n/** Options for an element rendered by the custom element: its own, else its tag's. */\nconst optionsFor = (el: Element, tagName: string): HydrateOptions =>\n elementOptions.get(el) ?? tagOptions.get(tagName) ?? {};\n\nfunction render(el: Element, options: HydrateOptions, config?: unknown): void {\n let raw: unknown = config;\n let problem: ConfigProblem | null = null;\n if (raw === undefined) {\n try {\n raw = readConfig(el);\n } catch (e) {\n problem = e instanceof ConfigError ? e.key : \"embed.unreadable\";\n }\n }\n let root = roots.get(el);\n if (!root) {\n // React replaces the element's content (the static fallback and the config script).\n root = createRoot(el);\n roots.set(el, root);\n }\n const isObject =\n typeof raw === \"object\" && raw !== null && typeof (raw as { type?: unknown }).type === \"string\";\n const renderIssues = (issues: ValidationIssue[] | null, key: ConfigProblem | null) =>\n root.render(\n <NibblearnProvider {...options.provider} wrapper={false}>\n {key ? <ConfigProblemView problem={key} /> : <InvalidModule issues={issues ?? []} />}\n </NibblearnProvider>,\n );\n if (problem || !isObject) {\n renderIssues(null, problem ?? \"embed.noType\");\n return;\n }\n const migrated = migrateModule(raw, { registry: options.registry?.schemas });\n // A config that cannot be migrated (e.g. saved by a newer version) is not rendered as-is.\n if (!migrated.success) {\n renderIssues(migrated.issues, null);\n return;\n }\n const moduleConfig = migrated.data as { id: string; type: string };\n const id = typeof moduleConfig.id === \"string\" ? moduleConfig.id : \"\";\n root.render(\n <NibblearnProvider {...options.provider} wrapper={false}>\n <ModuleRenderer\n config={moduleConfig}\n registry={options.registry}\n initialState={options.getInitialState?.(id, el) ?? undefined}\n onEvent={(event: NibblearnEvent) => {\n options.onEvent?.(event, el);\n emitDom(el, \"nibblearn:event\", event);\n }}\n onComplete={(result: ModuleResult) => {\n options.onComplete?.(result, el);\n emitDom(el, \"nibblearn:complete\", result);\n }}\n onStateChange={(state: ModuleState) => {\n options.onStateChange?.(state, el);\n emitDom(el, \"nibblearn:statechange\", state);\n }}\n />\n </NibblearnProvider>,\n );\n}\n\n/** Unmount one element rendered by `hydrate`, `mountElement` or the custom element. */\nexport function unmountElement(el: Element): void {\n const root = roots.get(el);\n if (!root) return;\n roots.delete(el);\n root.unmount();\n}\n\n/**\n * Find `<nibblearn-module>` and `[data-nibblearn-module]` elements under `root` and render a\n * module into each. Elements that are already mounted are skipped.\n */\nexport function hydrate(root: ParentNode = document, options: HydrateOptions = {}): HydrateResult {\n // Elements already rendered by `hydrate` / `mountElement` are skipped; ones the custom\n // element rendered on its own are re-rendered with these options.\n const elements = [...root.querySelectorAll(SELECTOR)].filter(\n (el) => !roots.has(el) || !elementOptions.has(el),\n );\n for (const el of elements) mountElement(el, options);\n return {\n elements,\n unmount: () => {\n for (const el of elements) unmountElement(el);\n },\n };\n}\n\n/**\n * Register the `<nibblearn-module>` custom element (or another tag name). The element reads\n * its config from a child `<script type=\"application/json\">`, the `config` attribute or the\n * `config` property, and dispatches `nibblearn:event`, `nibblearn:complete` and\n * `nibblearn:statechange` DOM events. Safe to call more than once and on the server (no-op).\n */\nexport function defineNibblearnElement(\n tagName = \"nibblearn-module\",\n options: HydrateOptions = {},\n): void {\n if (typeof window === \"undefined\" || typeof customElements === \"undefined\") return;\n if (customElements.get(tagName)) {\n // Defined before (e.g. by the standalone script): later options apply to its elements.\n if (!tagOptions.has(tagName)) return;\n tagOptions.set(tagName, options);\n for (const el of document.querySelectorAll(tagName))\n if (roots.has(el) && !elementOptions.has(el))\n render(el, options, (el as { config?: unknown }).config);\n return;\n }\n tagOptions.set(tagName, options);\n\n class NibblearnModuleElement extends HTMLElement {\n static observedAttributes = [\"config\"];\n #config: unknown = undefined;\n #connected = false;\n\n get config(): unknown {\n return this.#config;\n }\n set config(value: unknown) {\n this.#config = value;\n if (this.#connected) render(this, optionsFor(this, tagName), value);\n }\n\n connectedCallback() {\n // A `config` property set before the element was upgraded is an own property that\n // shadows the setter: move it to the private field.\n if (Object.prototype.hasOwnProperty.call(this, \"config\")) {\n const value = (this as unknown as { config: unknown }).config;\n delete (this as unknown as { config?: unknown }).config;\n this.#config = value;\n }\n this.#connected = true;\n const mount = () => {\n if (this.#connected) render(this, optionsFor(this, tagName), this.#config);\n };\n // Children (the config script) may not be parsed yet while the document is loading.\n if (\n this.#config === undefined &&\n document.readyState === \"loading\" &&\n !this.hasAttribute(\"config\")\n )\n document.addEventListener(\"DOMContentLoaded\", mount, { once: true });\n else mount();\n }\n\n disconnectedCallback() {\n this.#connected = false;\n // Unmount after the current task so React is never unmounted while rendering.\n queueMicrotask(() => {\n if (!this.#connected) unmountElement(this);\n });\n }\n\n attributeChangedCallback(name: string, old: string | null, value: string | null) {\n if (name === \"config\" && this.#connected && old !== value && this.#config === undefined) {\n // The attribute was changed explicitly: it now wins over a remembered script config.\n scriptConfigs.delete(this);\n render(this, optionsFor(this, tagName));\n }\n }\n }\n\n customElements.define(tagName, NibblearnModuleElement);\n}\n"],"mappings":";;;;;AAmCA,IAAM,wBAAQ,IAAI,QAAuB;;AAEzC,IAAM,iCAAiB,IAAI,QAAiC;;AAE5D,IAAM,6BAAa,IAAI,IAA4B;AAEnD,IAAM,WAAW;AAKjB,IAAM,cAAN,cAA0B,MAAM;CACT;CAArB,YAAY,KAA6B;EACvC,MAAM,GAAG;EADU,KAAA,MAAA;CAErB;AACF;;;;;;AAOA,IAAM,gCAAgB,IAAI,QAAyB;;AAGnD,SAAS,WAAW,IAAsB;CACxC,MAAM,SAAS,CAAC,GAAG,GAAG,QAAQ,CAAC,CAAC,MAC7B,MACC,EAAE,YAAY,aAAa,EAAE,aAAa,MAAM,KAAK,GAAA,CAAI,YAAY,MAAM,kBAC/E;CACA,IAAI,QAAQ,eAAe,MAAM,cAAc,IAAI,IAAI,OAAO,WAAW;CACzE,MAAM,OAAO,cAAc,IAAI,EAAE,KAAK,GAAG,aAAa,QAAQ,KAAK,GAAG,aAAa,aAAa;CAChG,IAAI,QAAQ,Q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