`):
+*
+* ```javascript
+* var hljs = require('highlight.js') // https://highlightjs.org/
+*
+* // Actual default values
+* var md = require('markdown-it')({
+* highlight: function (str, lang) {
+* if (lang && hljs.getLanguage(lang)) {
+* try {
+* return '' +
+* hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
+* '
';
+* } catch (__) {}
+* }
+*
+* return '' + md.utils.escapeHtml(str) + '
';
+* }
+* });
+* ```
+*
+**/
function MarkdownIt(presetName, options) {
- if (!(this instanceof MarkdownIt)) {
- return new MarkdownIt(presetName, options);
- }
- if (!options) {
- if (!isString$1(presetName)) {
- options = presetName || {};
- presetName = "default";
- }
- }
- /**
- * MarkdownIt#inline -> ParserInline
- *
- * Instance of [[ParserInline]]. You may need it to add new rules when
- * writing plugins. For simple rules control use [[MarkdownIt.disable]] and
- * [[MarkdownIt.enable]].
- **/
- this.inline = new parser_inline_default();
- /**
- * MarkdownIt#block -> ParserBlock
- *
- * Instance of [[ParserBlock]]. You may need it to add new rules when
- * writing plugins. For simple rules control use [[MarkdownIt.disable]] and
- * [[MarkdownIt.enable]].
- **/
- this.block = new parser_block_default();
- /**
- * MarkdownIt#core -> Core
- *
- * Instance of [[Core]] chain executor. You may need it to add new rules when
- * writing plugins. For simple rules control use [[MarkdownIt.disable]] and
- * [[MarkdownIt.enable]].
- **/
- this.core = new parser_core_default();
- /**
- * MarkdownIt#renderer -> Renderer
- *
- * Instance of [[Renderer]]. Use it to modify output look. Or to add rendering
- * rules for new token types, generated by plugins.
- *
- * ##### Example
- *
- * ```javascript
- * var md = require('markdown-it')();
- *
- * function myToken(tokens, idx, options, env, self) {
- * //...
- * return result;
- * };
- *
- * md.renderer.rules['my_token'] = myToken
- * ```
- *
- * See [[Renderer]] docs and [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.mjs).
- **/
- this.renderer = new renderer_default();
- /**
- * MarkdownIt#linkify -> LinkifyIt
- *
- * [linkify-it](https://github.com/markdown-it/linkify-it) instance.
- * Used by [linkify](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/linkify.mjs)
- * rule.
- **/
- this.linkify = new linkify_it_default();
- /**
- * MarkdownIt#validateLink(url) -> Boolean
- *
- * Link validation function. CommonMark allows too much in links. By default
- * we disable `javascript:`, `vbscript:`, `file:` schemas, and almost all `data:...` schemas
- * except some embedded image types.
- *
- * You can change this behaviour:
- *
- * ```javascript
- * var md = require('markdown-it')();
- * // enable everything
- * md.validateLink = function () { return true; }
- * ```
- **/
- this.validateLink = validateLink;
- /**
- * MarkdownIt#normalizeLink(url) -> String
- *
- * Function used to encode link url to a machine-readable format,
- * which includes url-encoding, punycode, etc.
- **/
- this.normalizeLink = normalizeLink;
- /**
- * MarkdownIt#normalizeLinkText(url) -> String
- *
- * Function used to decode link url to a human-readable format`
- **/
- this.normalizeLinkText = normalizeLinkText;
- /**
- * MarkdownIt#utils -> utils
- *
- * Assorted utility functions, useful to write plugins. See details
- * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/common/utils.mjs).
- **/
- this.utils = utils_exports;
- /**
- * MarkdownIt#helpers -> helpers
- *
- * Link components parser functions, useful to write plugins. See details
- * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/helpers).
- **/
- this.helpers = assign$1({}, helpers_exports);
- this.options = {};
- this.configure(presetName);
- if (options) {
- this.set(options);
- }
+ if (!(this instanceof MarkdownIt)) {
+ return new MarkdownIt(presetName, options);
+ }
+ if (!options) {
+ if (!isString$1(presetName)) {
+ options = presetName || {};
+ presetName = "default";
+ }
+ }
+ /**
+ * MarkdownIt#inline -> ParserInline
+ *
+ * Instance of [[ParserInline]]. You may need it to add new rules when
+ * writing plugins. For simple rules control use [[MarkdownIt.disable]] and
+ * [[MarkdownIt.enable]].
+ **/
+ this.inline = new parser_inline_default();
+ /**
+ * MarkdownIt#block -> ParserBlock
+ *
+ * Instance of [[ParserBlock]]. You may need it to add new rules when
+ * writing plugins. For simple rules control use [[MarkdownIt.disable]] and
+ * [[MarkdownIt.enable]].
+ **/
+ this.block = new parser_block_default();
+ /**
+ * MarkdownIt#core -> Core
+ *
+ * Instance of [[Core]] chain executor. You may need it to add new rules when
+ * writing plugins. For simple rules control use [[MarkdownIt.disable]] and
+ * [[MarkdownIt.enable]].
+ **/
+ this.core = new parser_core_default();
+ /**
+ * MarkdownIt#renderer -> Renderer
+ *
+ * Instance of [[Renderer]]. Use it to modify output look. Or to add rendering
+ * rules for new token types, generated by plugins.
+ *
+ * ##### Example
+ *
+ * ```javascript
+ * var md = require('markdown-it')();
+ *
+ * function myToken(tokens, idx, options, env, self) {
+ * //...
+ * return result;
+ * };
+ *
+ * md.renderer.rules['my_token'] = myToken
+ * ```
+ *
+ * See [[Renderer]] docs and [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.mjs).
+ **/
+ this.renderer = new renderer_default();
+ /**
+ * MarkdownIt#linkify -> LinkifyIt
+ *
+ * [linkify-it](https://github.com/markdown-it/linkify-it) instance.
+ * Used by [linkify](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/linkify.mjs)
+ * rule.
+ **/
+ this.linkify = new linkify_it_default();
+ /**
+ * MarkdownIt#validateLink(url) -> Boolean
+ *
+ * Link validation function. CommonMark allows too much in links. By default
+ * we disable `javascript:`, `vbscript:`, `file:` schemas, and almost all `data:...` schemas
+ * except some embedded image types.
+ *
+ * You can change this behaviour:
+ *
+ * ```javascript
+ * var md = require('markdown-it')();
+ * // enable everything
+ * md.validateLink = function () { return true; }
+ * ```
+ **/
+ this.validateLink = validateLink;
+ /**
+ * MarkdownIt#normalizeLink(url) -> String
+ *
+ * Function used to encode link url to a machine-readable format,
+ * which includes url-encoding, punycode, etc.
+ **/
+ this.normalizeLink = normalizeLink;
+ /**
+ * MarkdownIt#normalizeLinkText(url) -> String
+ *
+ * Function used to decode link url to a human-readable format`
+ **/
+ this.normalizeLinkText = normalizeLinkText;
+ /**
+ * MarkdownIt#utils -> utils
+ *
+ * Assorted utility functions, useful to write plugins. See details
+ * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/common/utils.mjs).
+ **/
+ this.utils = utils_exports;
+ /**
+ * MarkdownIt#helpers -> helpers
+ *
+ * Link components parser functions, useful to write plugins. See details
+ * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/helpers).
+ **/
+ this.helpers = assign$1({}, helpers_exports);
+ this.options = {};
+ this.configure(presetName);
+ if (options) {
+ this.set(options);
+ }
}
/** chainable
- * MarkdownIt.set(options)
- *
- * Set parser options (in the same format as in constructor). Probably, you
- * will never need it, but you can change options after constructor call.
- *
- * ##### Example
- *
- * ```javascript
- * var md = require('markdown-it')()
- * .set({ html: true, breaks: true })
- * .set({ typographer, true });
- * ```
- *
- * __Note:__ To achieve the best possible performance, don't modify a
- * `markdown-it` instance options on the fly. If you need multiple configurations
- * it's best to create multiple instances and initialize each with separate
- * config.
- **/
-MarkdownIt.prototype.set = function (options) {
- assign$1(this.options, options);
- return this;
+* MarkdownIt.set(options)
+*
+* Set parser options (in the same format as in constructor). Probably, you
+* will never need it, but you can change options after constructor call.
+*
+* ##### Example
+*
+* ```javascript
+* var md = require('markdown-it')()
+* .set({ html: true, breaks: true })
+* .set({ typographer, true });
+* ```
+*
+* __Note:__ To achieve the best possible performance, don't modify a
+* `markdown-it` instance options on the fly. If you need multiple configurations
+* it's best to create multiple instances and initialize each with separate
+* config.
+**/
+MarkdownIt.prototype.set = function(options) {
+ assign$1(this.options, options);
+ return this;
};
/** chainable, internal
- * MarkdownIt.configure(presets)
- *
- * Batch load of all options and compenent settings. This is internal method,
- * and you probably will not need it. But if you will - see available presets
- * and data structure [here](https://github.com/markdown-it/markdown-it/tree/master/lib/presets)
- *
- * We strongly recommend to use presets instead of direct config loads. That
- * will give better compatibility with next versions.
- **/
-MarkdownIt.prototype.configure = function (presets) {
- const self = this;
- if (isString$1(presets)) {
- const presetName = presets;
- presets = config[presetName];
- if (!presets) {
- throw new Error('Wrong `markdown-it` preset "' + presetName + '", check name');
- }
- }
- if (!presets) {
- throw new Error("Wrong `markdown-it` preset, can't be empty");
- }
- if (presets.options) {
- self.set(presets.options);
- }
- if (presets.components) {
- Object.keys(presets.components).forEach(function (name) {
- if (presets.components[name].rules) {
- self[name].ruler.enableOnly(presets.components[name].rules);
- }
- if (presets.components[name].rules2) {
- self[name].ruler2.enableOnly(presets.components[name].rules2);
- }
- });
- }
- return this;
+* MarkdownIt.configure(presets)
+*
+* Batch load of all options and compenent settings. This is internal method,
+* and you probably will not need it. But if you will - see available presets
+* and data structure [here](https://github.com/markdown-it/markdown-it/tree/master/lib/presets)
+*
+* We strongly recommend to use presets instead of direct config loads. That
+* will give better compatibility with next versions.
+**/
+MarkdownIt.prototype.configure = function(presets) {
+ const self = this;
+ if (isString$1(presets)) {
+ const presetName = presets;
+ presets = config[presetName];
+ if (!presets) {
+ throw new Error("Wrong `markdown-it` preset \"" + presetName + "\", check name");
+ }
+ }
+ if (!presets) {
+ throw new Error("Wrong `markdown-it` preset, can't be empty");
+ }
+ if (presets.options) {
+ self.set(presets.options);
+ }
+ if (presets.components) {
+ Object.keys(presets.components).forEach(function(name) {
+ if (presets.components[name].rules) {
+ self[name].ruler.enableOnly(presets.components[name].rules);
+ }
+ if (presets.components[name].rules2) {
+ self[name].ruler2.enableOnly(presets.components[name].rules2);
+ }
+ });
+ }
+ return this;
};
/** chainable
- * MarkdownIt.enable(list, ignoreInvalid)
- * - list (String|Array): rule name or list of rule names to enable
- * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found.
- *
- * Enable list or rules. It will automatically find appropriate components,
- * containing rules with given names. If rule not found, and `ignoreInvalid`
- * not set - throws exception.
- *
- * ##### Example
- *
- * ```javascript
- * var md = require('markdown-it')()
- * .enable(['sub', 'sup'])
- * .disable('smartquotes');
- * ```
- **/
-MarkdownIt.prototype.enable = function (list$1, ignoreInvalid) {
- let result = [];
- if (!Array.isArray(list$1)) {
- list$1 = [list$1];
- }
- ["core", "block", "inline"].forEach(function (chain) {
- result = result.concat(this[chain].ruler.enable(list$1, true));
- }, this);
- result = result.concat(this.inline.ruler2.enable(list$1, true));
- const missed = list$1.filter(function (name) {
- return result.indexOf(name) < 0;
- });
- if (missed.length && !ignoreInvalid) {
- throw new Error("MarkdownIt. Failed to enable unknown rule(s): " + missed);
- }
- return this;
+* MarkdownIt.enable(list, ignoreInvalid)
+* - list (String|Array): rule name or list of rule names to enable
+* - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found.
+*
+* Enable list or rules. It will automatically find appropriate components,
+* containing rules with given names. If rule not found, and `ignoreInvalid`
+* not set - throws exception.
+*
+* ##### Example
+*
+* ```javascript
+* var md = require('markdown-it')()
+* .enable(['sub', 'sup'])
+* .disable('smartquotes');
+* ```
+**/
+MarkdownIt.prototype.enable = function(list$1, ignoreInvalid) {
+ let result = [];
+ if (!Array.isArray(list$1)) {
+ list$1 = [list$1];
+ }
+ [
+ "core",
+ "block",
+ "inline"
+ ].forEach(function(chain) {
+ result = result.concat(this[chain].ruler.enable(list$1, true));
+ }, this);
+ result = result.concat(this.inline.ruler2.enable(list$1, true));
+ const missed = list$1.filter(function(name) {
+ return result.indexOf(name) < 0;
+ });
+ if (missed.length && !ignoreInvalid) {
+ throw new Error("MarkdownIt. Failed to enable unknown rule(s): " + missed);
+ }
+ return this;
};
/** chainable
- * MarkdownIt.disable(list, ignoreInvalid)
- * - list (String|Array): rule name or list of rule names to disable.
- * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found.
- *
- * The same as [[MarkdownIt.enable]], but turn specified rules off.
- **/
-MarkdownIt.prototype.disable = function (list$1, ignoreInvalid) {
- let result = [];
- if (!Array.isArray(list$1)) {
- list$1 = [list$1];
- }
- ["core", "block", "inline"].forEach(function (chain) {
- result = result.concat(this[chain].ruler.disable(list$1, true));
- }, this);
- result = result.concat(this.inline.ruler2.disable(list$1, true));
- const missed = list$1.filter(function (name) {
- return result.indexOf(name) < 0;
- });
- if (missed.length && !ignoreInvalid) {
- throw new Error("MarkdownIt. Failed to disable unknown rule(s): " + missed);
- }
- return this;
+* MarkdownIt.disable(list, ignoreInvalid)
+* - list (String|Array): rule name or list of rule names to disable.
+* - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found.
+*
+* The same as [[MarkdownIt.enable]], but turn specified rules off.
+**/
+MarkdownIt.prototype.disable = function(list$1, ignoreInvalid) {
+ let result = [];
+ if (!Array.isArray(list$1)) {
+ list$1 = [list$1];
+ }
+ [
+ "core",
+ "block",
+ "inline"
+ ].forEach(function(chain) {
+ result = result.concat(this[chain].ruler.disable(list$1, true));
+ }, this);
+ result = result.concat(this.inline.ruler2.disable(list$1, true));
+ const missed = list$1.filter(function(name) {
+ return result.indexOf(name) < 0;
+ });
+ if (missed.length && !ignoreInvalid) {
+ throw new Error("MarkdownIt. Failed to disable unknown rule(s): " + missed);
+ }
+ return this;
};
/** chainable
- * MarkdownIt.use(plugin, params)
- *
- * Load specified plugin with given params into current parser instance.
- * It's just a sugar to call `plugin(md, params)` with curring.
- *
- * ##### Example
- *
- * ```javascript
- * var iterator = require('markdown-it-for-inline');
- * var md = require('markdown-it')()
- * .use(iterator, 'foo_replace', 'text', function (tokens, idx) {
- * tokens[idx].content = tokens[idx].content.replace(/foo/g, 'bar');
- * });
- * ```
- **/
-MarkdownIt.prototype.use = function (plugin) {
- const args = [this].concat(Array.prototype.slice.call(arguments, 1));
- plugin.apply(plugin, args);
- return this;
+* MarkdownIt.use(plugin, params)
+*
+* Load specified plugin with given params into current parser instance.
+* It's just a sugar to call `plugin(md, params)` with curring.
+*
+* ##### Example
+*
+* ```javascript
+* var iterator = require('markdown-it-for-inline');
+* var md = require('markdown-it')()
+* .use(iterator, 'foo_replace', 'text', function (tokens, idx) {
+* tokens[idx].content = tokens[idx].content.replace(/foo/g, 'bar');
+* });
+* ```
+**/
+MarkdownIt.prototype.use = function(plugin) {
+ const args = [this].concat(Array.prototype.slice.call(arguments, 1));
+ plugin.apply(plugin, args);
+ return this;
};
/** internal
- * MarkdownIt.parse(src, env) -> Array
- * - src (String): source string
- * - env (Object): environment sandbox
- *
- * Parse input string and return list of block tokens (special token type
- * "inline" will contain list of inline tokens). You should not call this
- * method directly, until you write custom renderer (for example, to produce
- * AST).
- *
- * `env` is used to pass data between "distributed" rules and return additional
- * metadata like reference info, needed for the renderer. It also can be used to
- * inject data in specific cases. Usually, you will be ok to pass `{}`,
- * and then pass updated object to renderer.
- **/
-MarkdownIt.prototype.parse = function (src, env) {
- if (typeof src !== "string") {
- throw new Error("Input data should be a String");
- }
- const state = new this.core.State(src, this, env);
- this.core.process(state);
- return state.tokens;
+* MarkdownIt.parse(src, env) -> Array
+* - src (String): source string
+* - env (Object): environment sandbox
+*
+* Parse input string and return list of block tokens (special token type
+* "inline" will contain list of inline tokens). You should not call this
+* method directly, until you write custom renderer (for example, to produce
+* AST).
+*
+* `env` is used to pass data between "distributed" rules and return additional
+* metadata like reference info, needed for the renderer. It also can be used to
+* inject data in specific cases. Usually, you will be ok to pass `{}`,
+* and then pass updated object to renderer.
+**/
+MarkdownIt.prototype.parse = function(src, env) {
+ if (typeof src !== "string") {
+ throw new Error("Input data should be a String");
+ }
+ const state = new this.core.State(src, this, env);
+ this.core.process(state);
+ return state.tokens;
};
/**
- * MarkdownIt.render(src [, env]) -> String
- * - src (String): source string
- * - env (Object): environment sandbox
- *
- * Render markdown string into html. It does all magic for you :).
- *
- * `env` can be used to inject additional metadata (`{}` by default).
- * But you will not need it with high probability. See also comment
- * in [[MarkdownIt.parse]].
- **/
-MarkdownIt.prototype.render = function (src, env) {
- env = env || {};
- return this.renderer.render(this.parse(src, env), this.options, env);
+* MarkdownIt.render(src [, env]) -> String
+* - src (String): source string
+* - env (Object): environment sandbox
+*
+* Render markdown string into html. It does all magic for you :).
+*
+* `env` can be used to inject additional metadata (`{}` by default).
+* But you will not need it with high probability. See also comment
+* in [[MarkdownIt.parse]].
+**/
+MarkdownIt.prototype.render = function(src, env) {
+ env = env || {};
+ return this.renderer.render(this.parse(src, env), this.options, env);
};
/** internal
- * MarkdownIt.parseInline(src, env) -> Array
- * - src (String): source string
- * - env (Object): environment sandbox
- *
- * The same as [[MarkdownIt.parse]] but skip all block rules. It returns the
- * block tokens list with the single `inline` element, containing parsed inline
- * tokens in `children` property. Also updates `env` object.
- **/
-MarkdownIt.prototype.parseInline = function (src, env) {
- const state = new this.core.State(src, this, env);
- state.inlineMode = true;
- this.core.process(state);
- return state.tokens;
+* MarkdownIt.parseInline(src, env) -> Array
+* - src (String): source string
+* - env (Object): environment sandbox
+*
+* The same as [[MarkdownIt.parse]] but skip all block rules. It returns the
+* block tokens list with the single `inline` element, containing parsed inline
+* tokens in `children` property. Also updates `env` object.
+**/
+MarkdownIt.prototype.parseInline = function(src, env) {
+ const state = new this.core.State(src, this, env);
+ state.inlineMode = true;
+ this.core.process(state);
+ return state.tokens;
};
/**
- * MarkdownIt.renderInline(src [, env]) -> String
- * - src (String): source string
- * - env (Object): environment sandbox
- *
- * Similar to [[MarkdownIt.render]] but for single paragraph content. Result
- * will NOT be wrapped into `` tags.
- **/
-MarkdownIt.prototype.renderInline = function (src, env) {
- env = env || {};
- return this.renderer.render(this.parseInline(src, env), this.options, env);
+* MarkdownIt.renderInline(src [, env]) -> String
+* - src (String): source string
+* - env (Object): environment sandbox
+*
+* Similar to [[MarkdownIt.render]] but for single paragraph content. Result
+* will NOT be wrapped into `
` tags.
+**/
+MarkdownIt.prototype.renderInline = function(src, env) {
+ env = env || {};
+ return this.renderer.render(this.parseInline(src, env), this.options, env);
};
var lib_default = MarkdownIt;
/**
- * This is only safe for (and intended to be used for) text node positions. If
- * you are using attribute position, then this is only safe if the attribute
- * value is surrounded by double-quotes, and is unsafe otherwise (because the
- * value could break out of the attribute value and e.g. add another attribute).
- */
+* This is only safe for (and intended to be used for) text node positions. If
+* you are using attribute position, then this is only safe if the attribute
+* value is surrounded by double-quotes, and is unsafe otherwise (because the
+* value could break out of the attribute value and e.g. add another attribute).
+*/
function escapeNodeText(str) {
- const frag = document.createElement("div");
- D(b`${str}`, frag);
- return frag.innerHTML.replaceAll(//gim, "");
+ const frag = document.createElement("div");
+ D(b`${str}`, frag);
+ return frag.innerHTML.replaceAll(//gim, "");
}
function unescapeNodeText(str) {
- if (!str) {
- return "";
- }
- const frag = document.createElement("textarea");
- frag.innerHTML = str;
- return frag.value;
+ if (!str) {
+ return "";
+ }
+ const frag = document.createElement("textarea");
+ frag.innerHTML = str;
+ return frag.value;
}
var MarkdownDirective = class extends i$5 {
- #markdownIt = lib_default({
- highlight: (str, lang) => {
- switch (lang) {
- case "html": {
- const iframe = document.createElement("iframe");
- iframe.classList.add("html-view");
- iframe.srcdoc = str;
- iframe.sandbox = "";
- return iframe.innerHTML;
- }
- default:
- return escapeNodeText(str);
- }
- },
- });
- #lastValue = null;
- #lastTagClassMap = null;
- update(_part, [value, tagClassMap]) {
- if (this.#lastValue === value && JSON.stringify(tagClassMap) === this.#lastTagClassMap) {
- return E;
- }
- this.#lastValue = value;
- this.#lastTagClassMap = JSON.stringify(tagClassMap);
- return this.render(value, tagClassMap);
- }
- #originalClassMap = new Map();
- #applyTagClassMap(tagClassMap) {
- Object.entries(tagClassMap).forEach(([tag]) => {
- let tokenName;
- switch (tag) {
- case "p":
- tokenName = "paragraph";
- break;
- case "h1":
- case "h2":
- case "h3":
- case "h4":
- case "h5":
- case "h6":
- tokenName = "heading";
- break;
- case "ul":
- tokenName = "bullet_list";
- break;
- case "ol":
- tokenName = "ordered_list";
- break;
- case "li":
- tokenName = "list_item";
- break;
- case "a":
- tokenName = "link";
- break;
- case "strong":
- tokenName = "strong";
- break;
- case "em":
- tokenName = "em";
- break;
- }
- if (!tokenName) {
- return;
- }
- const key = `${tokenName}_open`;
- this.#markdownIt.renderer.rules[key] = (tokens, idx, options, _env, self) => {
- const token = tokens[idx];
- const tokenClasses = tagClassMap[token.tag] ?? [];
- for (const clazz of tokenClasses) {
- token.attrJoin("class", clazz);
- }
- return self.renderToken(tokens, idx, options);
- };
- });
- }
- #unapplyTagClassMap() {
- for (const [key] of this.#originalClassMap) {
- delete this.#markdownIt.renderer.rules[key];
- }
- this.#originalClassMap.clear();
- }
- /**
- * Renders the markdown string to HTML using MarkdownIt.
- *
- * Note: MarkdownIt doesn't enable HTML in its output, so we render the
- * value directly without further sanitization.
- * @see https://github.com/markdown-it/markdown-it/blob/master/docs/security.md
- */
- render(value, tagClassMap) {
- if (tagClassMap) {
- this.#applyTagClassMap(tagClassMap);
- }
- const htmlString = this.#markdownIt.render(value);
- this.#unapplyTagClassMap();
- return o(htmlString);
- }
+ #markdownIt = lib_default({ highlight: (str, lang) => {
+ switch (lang) {
+ case "html": {
+ const iframe = document.createElement("iframe");
+ iframe.classList.add("html-view");
+ iframe.srcdoc = str;
+ iframe.sandbox = "";
+ return iframe.innerHTML;
+ }
+ default: return escapeNodeText(str);
+ }
+ } });
+ #lastValue = null;
+ #lastTagClassMap = null;
+ update(_part, [value, tagClassMap]) {
+ if (this.#lastValue === value && JSON.stringify(tagClassMap) === this.#lastTagClassMap) {
+ return E;
+ }
+ this.#lastValue = value;
+ this.#lastTagClassMap = JSON.stringify(tagClassMap);
+ return this.render(value, tagClassMap);
+ }
+ #originalClassMap = new Map();
+ #applyTagClassMap(tagClassMap) {
+ Object.entries(tagClassMap).forEach(([tag]) => {
+ let tokenName;
+ switch (tag) {
+ case "p":
+ tokenName = "paragraph";
+ break;
+ case "h1":
+ case "h2":
+ case "h3":
+ case "h4":
+ case "h5":
+ case "h6":
+ tokenName = "heading";
+ break;
+ case "ul":
+ tokenName = "bullet_list";
+ break;
+ case "ol":
+ tokenName = "ordered_list";
+ break;
+ case "li":
+ tokenName = "list_item";
+ break;
+ case "a":
+ tokenName = "link";
+ break;
+ case "strong":
+ tokenName = "strong";
+ break;
+ case "em":
+ tokenName = "em";
+ break;
+ }
+ if (!tokenName) {
+ return;
+ }
+ const key = `${tokenName}_open`;
+ this.#markdownIt.renderer.rules[key] = (tokens, idx, options, _env, self) => {
+ const token = tokens[idx];
+ const tokenClasses = tagClassMap[token.tag] ?? [];
+ for (const clazz of tokenClasses) {
+ token.attrJoin("class", clazz);
+ }
+ return self.renderToken(tokens, idx, options);
+ };
+ });
+ }
+ #unapplyTagClassMap() {
+ for (const [key] of this.#originalClassMap) {
+ delete this.#markdownIt.renderer.rules[key];
+ }
+ this.#originalClassMap.clear();
+ }
+ /**
+ * Renders the markdown string to HTML using MarkdownIt.
+ *
+ * Note: MarkdownIt doesn't enable HTML in its output, so we render the
+ * value directly without further sanitization.
+ * @see https://github.com/markdown-it/markdown-it/blob/master/docs/security.md
+ */
+ render(value, tagClassMap) {
+ if (tagClassMap) {
+ this.#applyTagClassMap(tagClassMap);
+ }
+ const htmlString = this.#markdownIt.render(value);
+ this.#unapplyTagClassMap();
+ return o(htmlString);
+ }
};
const markdown = e$10(MarkdownDirective);
const markdownItStandalone = lib_default();
function renderMarkdownToHtmlString(value) {
- return markdownItStandalone.render(value);
+ return markdownItStandalone.render(value);
}
-var __esDecorate$1 =
- (void 0 && (void 0).__esDecorate) ||
- function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
- function accept(f$4) {
- if (f$4 !== void 0 && typeof f$4 !== "function") throw new TypeError("Function expected");
- return f$4;
- }
- var kind = contextIn.kind,
- key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
- var target = !descriptorIn && ctor ? (contextIn["static"] ? ctor : ctor.prototype) : null;
- var descriptor =
- descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
- var _$1,
- done = false;
- for (var i$10 = decorators.length - 1; i$10 >= 0; i$10--) {
- var context = {};
- for (var p$3 in contextIn) context[p$3] = p$3 === "access" ? {} : contextIn[p$3];
- for (var p$3 in contextIn.access) context.access[p$3] = contextIn.access[p$3];
- context.addInitializer = function (f$4) {
- if (done) throw new TypeError("Cannot add initializers after decoration has completed");
- extraInitializers.push(accept(f$4 || null));
- };
- var result = (0, decorators[i$10])(
- kind === "accessor"
- ? {
- get: descriptor.get,
- set: descriptor.set,
- }
- : descriptor[key],
- context,
- );
- if (kind === "accessor") {
- if (result === void 0) continue;
- if (result === null || typeof result !== "object") throw new TypeError("Object expected");
- if ((_$1 = accept(result.get))) descriptor.get = _$1;
- if ((_$1 = accept(result.set))) descriptor.set = _$1;
- if ((_$1 = accept(result.init))) initializers.unshift(_$1);
- } else if ((_$1 = accept(result))) {
- if (kind === "field") initializers.unshift(_$1);
- else descriptor[key] = _$1;
- }
- }
- if (target) Object.defineProperty(target, contextIn.name, descriptor);
- done = true;
- };
-var __runInitializers$1 =
- (void 0 && (void 0).__runInitializers) ||
- function (thisArg, initializers, value) {
- var useValue = arguments.length > 2;
- for (var i$10 = 0; i$10 < initializers.length; i$10++) {
- value = useValue ? initializers[i$10].call(thisArg, value) : initializers[i$10].call(thisArg);
- }
- return useValue ? value : void 0;
- };
+var __esDecorate$1 = void 0 && (void 0).__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
+ function accept(f$4) {
+ if (f$4 !== void 0 && typeof f$4 !== "function") throw new TypeError("Function expected");
+ return f$4;
+ }
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
+ var _$1, done = false;
+ for (var i$10 = decorators.length - 1; i$10 >= 0; i$10--) {
+ var context = {};
+ for (var p$3 in contextIn) context[p$3] = p$3 === "access" ? {} : contextIn[p$3];
+ for (var p$3 in contextIn.access) context.access[p$3] = contextIn.access[p$3];
+ context.addInitializer = function(f$4) {
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
+ extraInitializers.push(accept(f$4 || null));
+ };
+ var result = (0, decorators[i$10])(kind === "accessor" ? {
+ get: descriptor.get,
+ set: descriptor.set
+ } : descriptor[key], context);
+ if (kind === "accessor") {
+ if (result === void 0) continue;
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
+ if (_$1 = accept(result.get)) descriptor.get = _$1;
+ if (_$1 = accept(result.set)) descriptor.set = _$1;
+ if (_$1 = accept(result.init)) initializers.unshift(_$1);
+ } else if (_$1 = accept(result)) {
+ if (kind === "field") initializers.unshift(_$1);
+ else descriptor[key] = _$1;
+ }
+ }
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
+ done = true;
+};
+var __runInitializers$1 = void 0 && (void 0).__runInitializers || function(thisArg, initializers, value) {
+ var useValue = arguments.length > 2;
+ for (var i$10 = 0; i$10 < initializers.length; i$10++) {
+ value = useValue ? initializers[i$10].call(thisArg, value) : initializers[i$10].call(thisArg);
+ }
+ return useValue ? value : void 0;
+};
let Text = (() => {
- let _classDecorators = [t$1("a2ui-text")];
- let _classDescriptor;
- let _classExtraInitializers = [];
- let _classThis;
- let _classSuper = Root;
- let _text_decorators;
- let _text_initializers = [];
- let _text_extraInitializers = [];
- let _usageHint_decorators;
- let _usageHint_initializers = [];
- let _usageHint_extraInitializers = [];
- var Text = class extends _classSuper {
- static {
- _classThis = this;
- }
- static {
- const _metadata =
- typeof Symbol === "function" && Symbol.metadata
- ? Object.create(_classSuper[Symbol.metadata] ?? null)
- : void 0;
- _text_decorators = [n$6()];
- _usageHint_decorators = [
- n$6({
- reflect: true,
- attribute: "usage-hint",
- }),
- ];
- __esDecorate$1(
- this,
- null,
- _text_decorators,
- {
- kind: "accessor",
- name: "text",
- static: false,
- private: false,
- access: {
- has: (obj) => "text" in obj,
- get: (obj) => obj.text,
- set: (obj, value) => {
- obj.text = value;
- },
- },
- metadata: _metadata,
- },
- _text_initializers,
- _text_extraInitializers,
- );
- __esDecorate$1(
- this,
- null,
- _usageHint_decorators,
- {
- kind: "accessor",
- name: "usageHint",
- static: false,
- private: false,
- access: {
- has: (obj) => "usageHint" in obj,
- get: (obj) => obj.usageHint,
- set: (obj, value) => {
- obj.usageHint = value;
- },
- },
- metadata: _metadata,
- },
- _usageHint_initializers,
- _usageHint_extraInitializers,
- );
- __esDecorate$1(
- null,
- (_classDescriptor = { value: _classThis }),
- _classDecorators,
- {
- kind: "class",
- name: _classThis.name,
- metadata: _metadata,
- },
- null,
- _classExtraInitializers,
- );
- Text = _classThis = _classDescriptor.value;
- if (_metadata)
- Object.defineProperty(_classThis, Symbol.metadata, {
- enumerable: true,
- configurable: true,
- writable: true,
- value: _metadata,
- });
- }
- #text_accessor_storage = __runInitializers$1(this, _text_initializers, null);
- get text() {
- return this.#text_accessor_storage;
- }
- set text(value) {
- this.#text_accessor_storage = value;
- }
- #usageHint_accessor_storage =
- (__runInitializers$1(this, _text_extraInitializers),
- __runInitializers$1(this, _usageHint_initializers, null));
- get usageHint() {
- return this.#usageHint_accessor_storage;
- }
- set usageHint(value) {
- this.#usageHint_accessor_storage = value;
- }
- static {
- this.styles = [
- structuralStyles,
- i$9`
+ let _classDecorators = [t$1("a2ui-text")];
+ let _classDescriptor;
+ let _classExtraInitializers = [];
+ let _classThis;
+ let _classSuper = Root;
+ let _text_decorators;
+ let _text_initializers = [];
+ let _text_extraInitializers = [];
+ let _usageHint_decorators;
+ let _usageHint_initializers = [];
+ let _usageHint_extraInitializers = [];
+ var Text = class extends _classSuper {
+ static {
+ _classThis = this;
+ }
+ static {
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
+ _text_decorators = [n$6()];
+ _usageHint_decorators = [n$6({
+ reflect: true,
+ attribute: "usage-hint"
+ })];
+ __esDecorate$1(this, null, _text_decorators, {
+ kind: "accessor",
+ name: "text",
+ static: false,
+ private: false,
+ access: {
+ has: (obj) => "text" in obj,
+ get: (obj) => obj.text,
+ set: (obj, value) => {
+ obj.text = value;
+ }
+ },
+ metadata: _metadata
+ }, _text_initializers, _text_extraInitializers);
+ __esDecorate$1(this, null, _usageHint_decorators, {
+ kind: "accessor",
+ name: "usageHint",
+ static: false,
+ private: false,
+ access: {
+ has: (obj) => "usageHint" in obj,
+ get: (obj) => obj.usageHint,
+ set: (obj, value) => {
+ obj.usageHint = value;
+ }
+ },
+ metadata: _metadata
+ }, _usageHint_initializers, _usageHint_extraInitializers);
+ __esDecorate$1(null, _classDescriptor = { value: _classThis }, _classDecorators, {
+ kind: "class",
+ name: _classThis.name,
+ metadata: _metadata
+ }, null, _classExtraInitializers);
+ Text = _classThis = _classDescriptor.value;
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, {
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ value: _metadata
+ });
+ }
+ #text_accessor_storage = __runInitializers$1(this, _text_initializers, null);
+ get text() {
+ return this.#text_accessor_storage;
+ }
+ set text(value) {
+ this.#text_accessor_storage = value;
+ }
+ #usageHint_accessor_storage = (__runInitializers$1(this, _text_extraInitializers), __runInitializers$1(this, _usageHint_initializers, null));
+ get usageHint() {
+ return this.#usageHint_accessor_storage;
+ }
+ set usageHint(value) {
+ this.#usageHint_accessor_storage = value;
+ }
+ static {
+ this.styles = [structuralStyles, i$9`
:host {
display: block;
flex: var(--weight);
@@ -19123,226 +16985,198 @@ let Text = (() => {
line-height: inherit;
font: inherit;
}
- `,
- ];
- }
- #renderText() {
- let textValue = null;
- if (this.text && typeof this.text === "object") {
- if ("literalString" in this.text && this.text.literalString) {
- textValue = this.text.literalString;
- } else if ("literal" in this.text && this.text.literal !== undefined) {
- textValue = this.text.literal;
- } else if (this.text && "path" in this.text && this.text.path) {
- if (!this.processor || !this.component) {
- return b`(no model)`;
- }
- const value = this.processor.getData(
- this.component,
- this.text.path,
- this.surfaceId ?? A2uiMessageProcessor.DEFAULT_SURFACE_ID,
- );
- if (value !== null && value !== undefined) {
- textValue = value.toString();
- }
- }
- }
- if (textValue === null || textValue === undefined) {
- return b`(empty)`;
- }
- let markdownText = textValue;
- switch (this.usageHint) {
- case "h1":
- markdownText = `# ${markdownText}`;
- break;
- case "h2":
- markdownText = `## ${markdownText}`;
- break;
- case "h3":
- markdownText = `### ${markdownText}`;
- break;
- case "h4":
- markdownText = `#### ${markdownText}`;
- break;
- case "h5":
- markdownText = `##### ${markdownText}`;
- break;
- case "caption":
- markdownText = `*${markdownText}*`;
- break;
- default:
- break;
- }
- return b`${markdown(markdownText, appendToAll(this.theme.markdown, ["ol", "ul", "li"], {}))}`;
- }
- #areHintedStyles(styles) {
- if (typeof styles !== "object") return false;
- if (Array.isArray(styles)) return false;
- if (!styles) return false;
- const expected = ["h1", "h2", "h3", "h4", "h5", "h6", "caption", "body"];
- return expected.every((v$2) => v$2 in styles);
- }
- #getAdditionalStyles() {
- let additionalStyles = {};
- const styles = this.theme.additionalStyles?.Text;
- if (!styles) return additionalStyles;
- if (this.#areHintedStyles(styles)) {
- const hint = this.usageHint ?? "body";
- additionalStyles = styles[hint];
- } else {
- additionalStyles = styles;
- }
- return additionalStyles;
- }
- render() {
- const classes = merge(
- this.theme.components.Text.all,
- this.usageHint ? this.theme.components.Text[this.usageHint] : {},
- );
- return b` v$2 in styles);
+ }
+ #getAdditionalStyles() {
+ let additionalStyles = {};
+ const styles = this.theme.additionalStyles?.Text;
+ if (!styles) return additionalStyles;
+ if (this.#areHintedStyles(styles)) {
+ const hint = this.usageHint ?? "body";
+ additionalStyles = styles[hint];
+ } else {
+ additionalStyles = styles;
+ }
+ return additionalStyles;
+ }
+ render() {
+ const classes = merge(this.theme.components.Text.all, this.usageHint ? this.theme.components.Text[this.usageHint] : {});
+ return b``;
- }
- constructor() {
- super(...arguments);
- __runInitializers$1(this, _usageHint_extraInitializers);
- }
- static {
- __runInitializers$1(_classThis, _classExtraInitializers);
- }
- };
- return (Text = _classThis);
+ }
+ constructor() {
+ super(...arguments);
+ __runInitializers$1(this, _usageHint_extraInitializers);
+ }
+ static {
+ __runInitializers$1(_classThis, _classExtraInitializers);
+ }
+ };
+ return Text = _classThis;
})();
-var __esDecorate =
- (void 0 && (void 0).__esDecorate) ||
- function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
- function accept(f$4) {
- if (f$4 !== void 0 && typeof f$4 !== "function") throw new TypeError("Function expected");
- return f$4;
- }
- var kind = contextIn.kind,
- key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
- var target = !descriptorIn && ctor ? (contextIn["static"] ? ctor : ctor.prototype) : null;
- var descriptor =
- descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
- var _$1,
- done = false;
- for (var i$10 = decorators.length - 1; i$10 >= 0; i$10--) {
- var context = {};
- for (var p$3 in contextIn) context[p$3] = p$3 === "access" ? {} : contextIn[p$3];
- for (var p$3 in contextIn.access) context.access[p$3] = contextIn.access[p$3];
- context.addInitializer = function (f$4) {
- if (done) throw new TypeError("Cannot add initializers after decoration has completed");
- extraInitializers.push(accept(f$4 || null));
- };
- var result = (0, decorators[i$10])(
- kind === "accessor"
- ? {
- get: descriptor.get,
- set: descriptor.set,
- }
- : descriptor[key],
- context,
- );
- if (kind === "accessor") {
- if (result === void 0) continue;
- if (result === null || typeof result !== "object") throw new TypeError("Object expected");
- if ((_$1 = accept(result.get))) descriptor.get = _$1;
- if ((_$1 = accept(result.set))) descriptor.set = _$1;
- if ((_$1 = accept(result.init))) initializers.unshift(_$1);
- } else if ((_$1 = accept(result))) {
- if (kind === "field") initializers.unshift(_$1);
- else descriptor[key] = _$1;
- }
- }
- if (target) Object.defineProperty(target, contextIn.name, descriptor);
- done = true;
- };
-var __runInitializers =
- (void 0 && (void 0).__runInitializers) ||
- function (thisArg, initializers, value) {
- var useValue = arguments.length > 2;
- for (var i$10 = 0; i$10 < initializers.length; i$10++) {
- value = useValue ? initializers[i$10].call(thisArg, value) : initializers[i$10].call(thisArg);
- }
- return useValue ? value : void 0;
- };
+var __esDecorate = void 0 && (void 0).__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
+ function accept(f$4) {
+ if (f$4 !== void 0 && typeof f$4 !== "function") throw new TypeError("Function expected");
+ return f$4;
+ }
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
+ var _$1, done = false;
+ for (var i$10 = decorators.length - 1; i$10 >= 0; i$10--) {
+ var context = {};
+ for (var p$3 in contextIn) context[p$3] = p$3 === "access" ? {} : contextIn[p$3];
+ for (var p$3 in contextIn.access) context.access[p$3] = contextIn.access[p$3];
+ context.addInitializer = function(f$4) {
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
+ extraInitializers.push(accept(f$4 || null));
+ };
+ var result = (0, decorators[i$10])(kind === "accessor" ? {
+ get: descriptor.get,
+ set: descriptor.set
+ } : descriptor[key], context);
+ if (kind === "accessor") {
+ if (result === void 0) continue;
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
+ if (_$1 = accept(result.get)) descriptor.get = _$1;
+ if (_$1 = accept(result.set)) descriptor.set = _$1;
+ if (_$1 = accept(result.init)) initializers.unshift(_$1);
+ } else if (_$1 = accept(result)) {
+ if (kind === "field") initializers.unshift(_$1);
+ else descriptor[key] = _$1;
+ }
+ }
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
+ done = true;
+};
+var __runInitializers = void 0 && (void 0).__runInitializers || function(thisArg, initializers, value) {
+ var useValue = arguments.length > 2;
+ for (var i$10 = 0; i$10 < initializers.length; i$10++) {
+ value = useValue ? initializers[i$10].call(thisArg, value) : initializers[i$10].call(thisArg);
+ }
+ return useValue ? value : void 0;
+};
let Video = (() => {
- let _classDecorators = [t$1("a2ui-video")];
- let _classDescriptor;
- let _classExtraInitializers = [];
- let _classThis;
- let _classSuper = Root;
- let _url_decorators;
- let _url_initializers = [];
- let _url_extraInitializers = [];
- var Video = class extends _classSuper {
- static {
- _classThis = this;
- }
- static {
- const _metadata =
- typeof Symbol === "function" && Symbol.metadata
- ? Object.create(_classSuper[Symbol.metadata] ?? null)
- : void 0;
- _url_decorators = [n$6()];
- __esDecorate(
- this,
- null,
- _url_decorators,
- {
- kind: "accessor",
- name: "url",
- static: false,
- private: false,
- access: {
- has: (obj) => "url" in obj,
- get: (obj) => obj.url,
- set: (obj, value) => {
- obj.url = value;
- },
- },
- metadata: _metadata,
- },
- _url_initializers,
- _url_extraInitializers,
- );
- __esDecorate(
- null,
- (_classDescriptor = { value: _classThis }),
- _classDecorators,
- {
- kind: "class",
- name: _classThis.name,
- metadata: _metadata,
- },
- null,
- _classExtraInitializers,
- );
- Video = _classThis = _classDescriptor.value;
- if (_metadata)
- Object.defineProperty(_classThis, Symbol.metadata, {
- enumerable: true,
- configurable: true,
- writable: true,
- value: _metadata,
- });
- }
- #url_accessor_storage = __runInitializers(this, _url_initializers, null);
- get url() {
- return this.#url_accessor_storage;
- }
- set url(value) {
- this.#url_accessor_storage = value;
- }
- static {
- this.styles = [
- structuralStyles,
- i$9`
+ let _classDecorators = [t$1("a2ui-video")];
+ let _classDescriptor;
+ let _classExtraInitializers = [];
+ let _classThis;
+ let _classSuper = Root;
+ let _url_decorators;
+ let _url_initializers = [];
+ let _url_extraInitializers = [];
+ var Video = class extends _classSuper {
+ static {
+ _classThis = this;
+ }
+ static {
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
+ _url_decorators = [n$6()];
+ __esDecorate(this, null, _url_decorators, {
+ kind: "accessor",
+ name: "url",
+ static: false,
+ private: false,
+ access: {
+ has: (obj) => "url" in obj,
+ get: (obj) => obj.url,
+ set: (obj, value) => {
+ obj.url = value;
+ }
+ },
+ metadata: _metadata
+ }, _url_initializers, _url_extraInitializers);
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, {
+ kind: "class",
+ name: _classThis.name,
+ metadata: _metadata
+ }, null, _classExtraInitializers);
+ Video = _classThis = _classDescriptor.value;
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, {
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ value: _metadata
+ });
+ }
+ #url_accessor_storage = __runInitializers(this, _url_initializers, null);
+ get url() {
+ return this.#url_accessor_storage;
+ }
+ set url(value) {
+ this.#url_accessor_storage = value;
+ }
+ static {
+ this.styles = [structuralStyles, i$9`
* {
box-sizing: border-box;
}
@@ -19358,71 +17192,66 @@ let Video = (() => {
display: block;
width: 100%;
}
- `,
- ];
- }
- #renderVideo() {
- if (!this.url) {
- return A;
- }
- if (this.url && typeof this.url === "object") {
- if ("literalString" in this.url) {
- return b``;
- } else if ("literal" in this.url) {
- return b``;
- } else if (this.url && "path" in this.url && this.url.path) {
- if (!this.processor || !this.component) {
- return b`(no processor)`;
- }
- const videoUrl = this.processor.getData(
- this.component,
- this.url.path,
- this.surfaceId ?? A2uiMessageProcessor.DEFAULT_SURFACE_ID,
- );
- if (!videoUrl) {
- return b`Invalid video URL`;
- }
- if (typeof videoUrl !== "string") {
- return b`Invalid video URL`;
- }
- return b``;
- }
- }
- return b`(empty)`;
- }
- render() {
- return b``;
+ } else if ("literal" in this.url) {
+ return b``;
+ } else if (this.url && "path" in this.url && this.url.path) {
+ if (!this.processor || !this.component) {
+ return b`(no processor)`;
+ }
+ const videoUrl = this.processor.getData(this.component, this.url.path, this.surfaceId ?? A2uiMessageProcessor.DEFAULT_SURFACE_ID);
+ if (!videoUrl) {
+ return b`Invalid video URL`;
+ }
+ if (typeof videoUrl !== "string") {
+ return b`Invalid video URL`;
+ }
+ return b``;
+ }
+ }
+ return b`(empty)`;
+ }
+ render() {
+ return b``;
- }
- constructor() {
- super(...arguments);
- __runInitializers(this, _url_extraInitializers);
- }
- static {
- __runInitializers(_classThis, _classExtraInitializers);
- }
- };
- return (Video = _classThis);
+ }
+ constructor() {
+ super(...arguments);
+ __runInitializers(this, _url_extraInitializers);
+ }
+ static {
+ __runInitializers(_classThis, _classExtraInitializers);
+ }
+ };
+ return Video = _classThis;
})();
function registerCustomComponents() {}
/**
- * Type-safely retrieves a custom element constructor using the tagName map.
- * @param tagName The tag name to look up (must exist in HTMLElementTagNameMap).
- * @returns The specific constructor type or undefined.
- */
+* Type-safely retrieves a custom element constructor using the tagName map.
+* @param tagName The tag name to look up (must exist in HTMLElementTagNameMap).
+* @returns The specific constructor type or undefined.
+*/
function instanceOf(tagName) {
- const ctor = customElements.get(tagName);
- if (!ctor) {
- console.warn("No element definition for", tagName);
- return;
- }
- return new ctor();
+ const ctor = customElements.get(tagName);
+ if (!ctor) {
+ console.warn("No element definition for", tagName);
+ return;
+ }
+ return new ctor();
}
const modalStyles = i$9`
@@ -19447,200 +17276,196 @@ const modalStyles = i$9`
`;
const modalElement = customElements.get("a2ui-modal");
if (modalElement && Array.isArray(modalElement.styles)) {
- modalElement.styles = [...modalElement.styles, modalStyles];
+ modalElement.styles = [...modalElement.styles, modalStyles];
}
const empty = Object.freeze({});
const emptyClasses = () => ({});
const textHintStyles = () => ({
- h1: {},
- h2: {},
- h3: {},
- h4: {},
- h5: {},
- body: {},
- caption: {},
+ h1: {},
+ h2: {},
+ h3: {},
+ h4: {},
+ h5: {},
+ body: {},
+ caption: {}
});
const isAndroid = /Android/i.test(globalThis.navigator?.userAgent ?? "");
const cardShadow = isAndroid ? "0 2px 10px rgba(0,0,0,.18)" : "0 10px 30px rgba(0,0,0,.35)";
-const buttonShadow = isAndroid
- ? "0 2px 10px rgba(6, 182, 212, 0.14)"
- : "0 10px 25px rgba(6, 182, 212, 0.18)";
-const statusShadow = isAndroid
- ? "0 2px 10px rgba(0, 0, 0, 0.18)"
- : "0 10px 24px rgba(0, 0, 0, 0.25)";
+const buttonShadow = isAndroid ? "0 2px 10px rgba(6, 182, 212, 0.14)" : "0 10px 25px rgba(6, 182, 212, 0.18)";
+const statusShadow = isAndroid ? "0 2px 10px rgba(0, 0, 0, 0.18)" : "0 10px 24px rgba(0, 0, 0, 0.25)";
const statusBlur = isAndroid ? "10px" : "14px";
const clawdbotTheme = {
- components: {
- AudioPlayer: emptyClasses(),
- Button: emptyClasses(),
- Card: emptyClasses(),
- Column: emptyClasses(),
- CheckBox: {
- container: emptyClasses(),
- element: emptyClasses(),
- label: emptyClasses(),
- },
- DateTimeInput: {
- container: emptyClasses(),
- element: emptyClasses(),
- label: emptyClasses(),
- },
- Divider: emptyClasses(),
- Image: {
- all: emptyClasses(),
- icon: emptyClasses(),
- avatar: emptyClasses(),
- smallFeature: emptyClasses(),
- mediumFeature: emptyClasses(),
- largeFeature: emptyClasses(),
- header: emptyClasses(),
- },
- Icon: emptyClasses(),
- List: emptyClasses(),
- Modal: {
- backdrop: emptyClasses(),
- element: emptyClasses(),
- },
- MultipleChoice: {
- container: emptyClasses(),
- element: emptyClasses(),
- label: emptyClasses(),
- },
- Row: emptyClasses(),
- Slider: {
- container: emptyClasses(),
- element: emptyClasses(),
- label: emptyClasses(),
- },
- Tabs: {
- container: emptyClasses(),
- element: emptyClasses(),
- controls: {
- all: emptyClasses(),
- selected: emptyClasses(),
- },
- },
- Text: {
- all: emptyClasses(),
- h1: emptyClasses(),
- h2: emptyClasses(),
- h3: emptyClasses(),
- h4: emptyClasses(),
- h5: emptyClasses(),
- caption: emptyClasses(),
- body: emptyClasses(),
- },
- TextField: {
- container: emptyClasses(),
- element: emptyClasses(),
- label: emptyClasses(),
- },
- Video: emptyClasses(),
- },
- elements: {
- a: emptyClasses(),
- audio: emptyClasses(),
- body: emptyClasses(),
- button: emptyClasses(),
- h1: emptyClasses(),
- h2: emptyClasses(),
- h3: emptyClasses(),
- h4: emptyClasses(),
- h5: emptyClasses(),
- iframe: emptyClasses(),
- input: emptyClasses(),
- p: emptyClasses(),
- pre: emptyClasses(),
- textarea: emptyClasses(),
- video: emptyClasses(),
- },
- markdown: {
- p: [],
- h1: [],
- h2: [],
- h3: [],
- h4: [],
- h5: [],
- ul: [],
- ol: [],
- li: [],
- a: [],
- strong: [],
- em: [],
- },
- additionalStyles: {
- Card: {
- background: "linear-gradient(180deg, rgba(255,255,255,.06), rgba(255,255,255,.03))",
- border: "1px solid rgba(255,255,255,.09)",
- borderRadius: "14px",
- padding: "14px",
- boxShadow: cardShadow,
- },
- Modal: {
- background: "rgba(12, 16, 24, 0.92)",
- border: "1px solid rgba(255,255,255,.12)",
- borderRadius: "16px",
- padding: "16px",
- boxShadow: "0 30px 80px rgba(0,0,0,.6)",
- width: "min(520px, calc(100vw - 48px))",
- },
- Column: { gap: "10px" },
- Row: {
- gap: "10px",
- alignItems: "center",
- },
- Divider: { opacity: "0.25" },
- Button: {
- background: "linear-gradient(135deg, #22c55e 0%, #06b6d4 100%)",
- border: "0",
- borderRadius: "12px",
- padding: "10px 14px",
- color: "#071016",
- fontWeight: "650",
- cursor: "pointer",
- boxShadow: buttonShadow,
- },
- Text: {
- ...textHintStyles(),
- h1: {
- fontSize: "20px",
- fontWeight: "750",
- margin: "0 0 6px 0",
- },
- h2: {
- fontSize: "16px",
- fontWeight: "700",
- margin: "0 0 6px 0",
- },
- body: {
- fontSize: "13px",
- lineHeight: "1.4",
- },
- caption: { opacity: "0.8" },
- },
- TextField: {
- display: "grid",
- gap: "6px",
- },
- Image: { borderRadius: "12px" },
- },
+ components: {
+ AudioPlayer: emptyClasses(),
+ Button: emptyClasses(),
+ Card: emptyClasses(),
+ Column: emptyClasses(),
+ CheckBox: {
+ container: emptyClasses(),
+ element: emptyClasses(),
+ label: emptyClasses()
+ },
+ DateTimeInput: {
+ container: emptyClasses(),
+ element: emptyClasses(),
+ label: emptyClasses()
+ },
+ Divider: emptyClasses(),
+ Image: {
+ all: emptyClasses(),
+ icon: emptyClasses(),
+ avatar: emptyClasses(),
+ smallFeature: emptyClasses(),
+ mediumFeature: emptyClasses(),
+ largeFeature: emptyClasses(),
+ header: emptyClasses()
+ },
+ Icon: emptyClasses(),
+ List: emptyClasses(),
+ Modal: {
+ backdrop: emptyClasses(),
+ element: emptyClasses()
+ },
+ MultipleChoice: {
+ container: emptyClasses(),
+ element: emptyClasses(),
+ label: emptyClasses()
+ },
+ Row: emptyClasses(),
+ Slider: {
+ container: emptyClasses(),
+ element: emptyClasses(),
+ label: emptyClasses()
+ },
+ Tabs: {
+ container: emptyClasses(),
+ element: emptyClasses(),
+ controls: {
+ all: emptyClasses(),
+ selected: emptyClasses()
+ }
+ },
+ Text: {
+ all: emptyClasses(),
+ h1: emptyClasses(),
+ h2: emptyClasses(),
+ h3: emptyClasses(),
+ h4: emptyClasses(),
+ h5: emptyClasses(),
+ caption: emptyClasses(),
+ body: emptyClasses()
+ },
+ TextField: {
+ container: emptyClasses(),
+ element: emptyClasses(),
+ label: emptyClasses()
+ },
+ Video: emptyClasses()
+ },
+ elements: {
+ a: emptyClasses(),
+ audio: emptyClasses(),
+ body: emptyClasses(),
+ button: emptyClasses(),
+ h1: emptyClasses(),
+ h2: emptyClasses(),
+ h3: emptyClasses(),
+ h4: emptyClasses(),
+ h5: emptyClasses(),
+ iframe: emptyClasses(),
+ input: emptyClasses(),
+ p: emptyClasses(),
+ pre: emptyClasses(),
+ textarea: emptyClasses(),
+ video: emptyClasses()
+ },
+ markdown: {
+ p: [],
+ h1: [],
+ h2: [],
+ h3: [],
+ h4: [],
+ h5: [],
+ ul: [],
+ ol: [],
+ li: [],
+ a: [],
+ strong: [],
+ em: []
+ },
+ additionalStyles: {
+ Card: {
+ background: "linear-gradient(180deg, rgba(255,255,255,.06), rgba(255,255,255,.03))",
+ border: "1px solid rgba(255,255,255,.09)",
+ borderRadius: "14px",
+ padding: "14px",
+ boxShadow: cardShadow
+ },
+ Modal: {
+ background: "rgba(12, 16, 24, 0.92)",
+ border: "1px solid rgba(255,255,255,.12)",
+ borderRadius: "16px",
+ padding: "16px",
+ boxShadow: "0 30px 80px rgba(0,0,0,.6)",
+ width: "min(520px, calc(100vw - 48px))"
+ },
+ Column: { gap: "10px" },
+ Row: {
+ gap: "10px",
+ alignItems: "center"
+ },
+ Divider: { opacity: "0.25" },
+ Button: {
+ background: "linear-gradient(135deg, #22c55e 0%, #06b6d4 100%)",
+ border: "0",
+ borderRadius: "12px",
+ padding: "10px 14px",
+ color: "#071016",
+ fontWeight: "650",
+ cursor: "pointer",
+ boxShadow: buttonShadow
+ },
+ Text: {
+ ...textHintStyles(),
+ h1: {
+ fontSize: "20px",
+ fontWeight: "750",
+ margin: "0 0 6px 0"
+ },
+ h2: {
+ fontSize: "16px",
+ fontWeight: "700",
+ margin: "0 0 6px 0"
+ },
+ body: {
+ fontSize: "13px",
+ lineHeight: "1.4"
+ },
+ caption: { opacity: "0.8" }
+ },
+ TextField: {
+ display: "grid",
+ gap: "6px"
+ },
+ Image: { borderRadius: "12px" }
+ }
};
var ClawdbotA2UIHost = class extends i$6 {
- static properties = {
- surfaces: { state: true },
- pendingAction: { state: true },
- toast: { state: true },
- };
- #processor = Data.createSignalA2uiMessageProcessor();
- #themeProvider = new i$3(this, {
- context: themeContext,
- initialValue: clawdbotTheme,
- });
- surfaces = [];
- pendingAction = null;
- toast = null;
- #statusListener = null;
- static styles = i$9`
+ static properties = {
+ surfaces: { state: true },
+ pendingAction: { state: true },
+ toast: { state: true }
+ };
+ #processor = Data.createSignalA2uiMessageProcessor();
+ #themeProvider = new i$3(this, {
+ context: themeContext,
+ initialValue: clawdbotTheme
+ });
+ surfaces = [];
+ pendingAction = null;
+ toast = null;
+ #statusListener = null;
+ static styles = i$9`
:host {
display: block;
height: 100%;
@@ -19743,219 +17568,201 @@ var ClawdbotA2UIHost = class extends i$6 {
}
}
`;
- connectedCallback() {
- super.connectedCallback();
- globalThis.clawdbotA2UI = {
- applyMessages: (messages) => this.applyMessages(messages),
- reset: () => this.reset(),
- getSurfaces: () => Array.from(this.#processor.getSurfaces().keys()),
- };
- this.addEventListener("a2uiaction", (evt) => this.#handleA2UIAction(evt));
- this.#statusListener = (evt) => this.#handleActionStatus(evt);
- globalThis.addEventListener("clawdbot:a2ui-action-status", this.#statusListener);
- this.#syncSurfaces();
- }
- disconnectedCallback() {
- super.disconnectedCallback();
- if (this.#statusListener) {
- globalThis.removeEventListener("clawdbot:a2ui-action-status", this.#statusListener);
- this.#statusListener = null;
- }
- }
- #makeActionId() {
- return (
- globalThis.crypto?.randomUUID?.() ??
- `a2ui_${Date.now()}_${Math.random().toString(16).slice(2)}`
- );
- }
- #setToast(text$1, kind = "ok", timeoutMs = 1400) {
- const toast = {
- text: text$1,
- kind,
- expiresAt: Date.now() + timeoutMs,
- };
- this.toast = toast;
- this.requestUpdate();
- setTimeout(() => {
- if (this.toast === toast) {
- this.toast = null;
- this.requestUpdate();
- }
- }, timeoutMs + 30);
- }
- #handleActionStatus(evt) {
- const detail = evt?.detail ?? null;
- if (!detail || typeof detail.id !== "string") return;
- if (!this.pendingAction || this.pendingAction.id !== detail.id) return;
- if (detail.ok) {
- this.pendingAction = {
- ...this.pendingAction,
- phase: "sent",
- sentAt: Date.now(),
- };
- } else {
- const msg = typeof detail.error === "string" && detail.error ? detail.error : "send failed";
- this.pendingAction = {
- ...this.pendingAction,
- phase: "error",
- error: msg,
- };
- this.#setToast(`Failed: ${msg}`, "error", 4500);
- }
- this.requestUpdate();
- }
- #handleA2UIAction(evt) {
- const payload = evt?.detail ?? evt?.payload ?? null;
- if (!payload || payload.eventType !== "a2ui.action") {
- return;
- }
- const action = payload.action;
- const name = action?.name;
- if (!name) {
- return;
- }
- const sourceComponentId = payload.sourceComponentId ?? "";
- const surfaces = this.#processor.getSurfaces();
- let surfaceId = null;
- let sourceNode = null;
- for (const [sid, surface] of surfaces.entries()) {
- const node = surface?.components?.get?.(sourceComponentId) ?? null;
- if (node) {
- surfaceId = sid;
- sourceNode = node;
- break;
- }
- }
- const context = {};
- const ctxItems = Array.isArray(action?.context) ? action.context : [];
- for (const item of ctxItems) {
- const key = item?.key;
- const value = item?.value ?? null;
- if (!key || !value) continue;
- if (typeof value.path === "string") {
- const resolved = sourceNode
- ? this.#processor.getData(sourceNode, value.path, surfaceId ?? undefined)
- : null;
- context[key] = resolved;
- continue;
- }
- if (Object.prototype.hasOwnProperty.call(value, "literalString")) {
- context[key] = value.literalString ?? "";
- continue;
- }
- if (Object.prototype.hasOwnProperty.call(value, "literalNumber")) {
- context[key] = value.literalNumber ?? 0;
- continue;
- }
- if (Object.prototype.hasOwnProperty.call(value, "literalBoolean")) {
- context[key] = value.literalBoolean ?? false;
- continue;
- }
- }
- const actionId = this.#makeActionId();
- this.pendingAction = {
- id: actionId,
- name,
- phase: "sending",
- startedAt: Date.now(),
- };
- this.requestUpdate();
- const userAction = {
- id: actionId,
- name,
- surfaceId: surfaceId ?? "main",
- sourceComponentId,
- timestamp: new Date().toISOString(),
- ...(Object.keys(context).length ? { context } : {}),
- };
- globalThis.__clawdbotLastA2UIAction = userAction;
- const handler =
- globalThis.webkit?.messageHandlers?.clawdbotCanvasA2UIAction ??
- globalThis.clawdbotCanvasA2UIAction;
- if (handler?.postMessage) {
- try {
- if (handler === globalThis.clawdbotCanvasA2UIAction) {
- handler.postMessage(JSON.stringify({ userAction }));
- } else {
- handler.postMessage({ userAction });
- }
- } catch (e$14) {
- const msg = String(e$14?.message ?? e$14);
- this.pendingAction = {
- id: actionId,
- name,
- phase: "error",
- startedAt: Date.now(),
- error: msg,
- };
- this.#setToast(`Failed: ${msg}`, "error", 4500);
- }
- } else {
- this.pendingAction = {
- id: actionId,
- name,
- phase: "error",
- startedAt: Date.now(),
- error: "missing native bridge",
- };
- this.#setToast("Failed: missing native bridge", "error", 4500);
- }
- }
- applyMessages(messages) {
- if (!Array.isArray(messages)) {
- throw new Error("A2UI: expected messages array");
- }
- this.#processor.processMessages(messages);
- this.#syncSurfaces();
- if (this.pendingAction?.phase === "sent") {
- this.#setToast(`Updated: ${this.pendingAction.name}`, "ok", 1100);
- this.pendingAction = null;
- }
- this.requestUpdate();
- return {
- ok: true,
- surfaces: this.surfaces.map(([id]) => id),
- };
- }
- reset() {
- this.#processor.clearSurfaces();
- this.#syncSurfaces();
- this.pendingAction = null;
- this.requestUpdate();
- return { ok: true };
- }
- #syncSurfaces() {
- this.surfaces = Array.from(this.#processor.getSurfaces().entries());
- }
- render() {
- if (this.surfaces.length === 0) {
- return b`
+ connectedCallback() {
+ super.connectedCallback();
+ globalThis.clawdbotA2UI = {
+ applyMessages: (messages) => this.applyMessages(messages),
+ reset: () => this.reset(),
+ getSurfaces: () => Array.from(this.#processor.getSurfaces().keys())
+ };
+ this.addEventListener("a2uiaction", (evt) => this.#handleA2UIAction(evt));
+ this.#statusListener = (evt) => this.#handleActionStatus(evt);
+ globalThis.addEventListener("clawdbot:a2ui-action-status", this.#statusListener);
+ this.#syncSurfaces();
+ }
+ disconnectedCallback() {
+ super.disconnectedCallback();
+ if (this.#statusListener) {
+ globalThis.removeEventListener("clawdbot:a2ui-action-status", this.#statusListener);
+ this.#statusListener = null;
+ }
+ }
+ #makeActionId() {
+ return globalThis.crypto?.randomUUID?.() ?? `a2ui_${Date.now()}_${Math.random().toString(16).slice(2)}`;
+ }
+ #setToast(text$1, kind = "ok", timeoutMs = 1400) {
+ const toast = {
+ text: text$1,
+ kind,
+ expiresAt: Date.now() + timeoutMs
+ };
+ this.toast = toast;
+ this.requestUpdate();
+ setTimeout(() => {
+ if (this.toast === toast) {
+ this.toast = null;
+ this.requestUpdate();
+ }
+ }, timeoutMs + 30);
+ }
+ #handleActionStatus(evt) {
+ const detail = evt?.detail ?? null;
+ if (!detail || typeof detail.id !== "string") return;
+ if (!this.pendingAction || this.pendingAction.id !== detail.id) return;
+ if (detail.ok) {
+ this.pendingAction = {
+ ...this.pendingAction,
+ phase: "sent",
+ sentAt: Date.now()
+ };
+ } else {
+ const msg = typeof detail.error === "string" && detail.error ? detail.error : "send failed";
+ this.pendingAction = {
+ ...this.pendingAction,
+ phase: "error",
+ error: msg
+ };
+ this.#setToast(`Failed: ${msg}`, "error", 4500);
+ }
+ this.requestUpdate();
+ }
+ #handleA2UIAction(evt) {
+ const payload = evt?.detail ?? evt?.payload ?? null;
+ if (!payload || payload.eventType !== "a2ui.action") {
+ return;
+ }
+ const action = payload.action;
+ const name = action?.name;
+ if (!name) {
+ return;
+ }
+ const sourceComponentId = payload.sourceComponentId ?? "";
+ const surfaces = this.#processor.getSurfaces();
+ let surfaceId = null;
+ let sourceNode = null;
+ for (const [sid, surface] of surfaces.entries()) {
+ const node = surface?.components?.get?.(sourceComponentId) ?? null;
+ if (node) {
+ surfaceId = sid;
+ sourceNode = node;
+ break;
+ }
+ }
+ const context = {};
+ const ctxItems = Array.isArray(action?.context) ? action.context : [];
+ for (const item of ctxItems) {
+ const key = item?.key;
+ const value = item?.value ?? null;
+ if (!key || !value) continue;
+ if (typeof value.path === "string") {
+ const resolved = sourceNode ? this.#processor.getData(sourceNode, value.path, surfaceId ?? undefined) : null;
+ context[key] = resolved;
+ continue;
+ }
+ if (Object.prototype.hasOwnProperty.call(value, "literalString")) {
+ context[key] = value.literalString ?? "";
+ continue;
+ }
+ if (Object.prototype.hasOwnProperty.call(value, "literalNumber")) {
+ context[key] = value.literalNumber ?? 0;
+ continue;
+ }
+ if (Object.prototype.hasOwnProperty.call(value, "literalBoolean")) {
+ context[key] = value.literalBoolean ?? false;
+ continue;
+ }
+ }
+ const actionId = this.#makeActionId();
+ this.pendingAction = {
+ id: actionId,
+ name,
+ phase: "sending",
+ startedAt: Date.now()
+ };
+ this.requestUpdate();
+ const userAction = {
+ id: actionId,
+ name,
+ surfaceId: surfaceId ?? "main",
+ sourceComponentId,
+ timestamp: new Date().toISOString(),
+ ...Object.keys(context).length ? { context } : {}
+ };
+ globalThis.__clawdbotLastA2UIAction = userAction;
+ const handler = globalThis.webkit?.messageHandlers?.clawdbotCanvasA2UIAction ?? globalThis.clawdbotCanvasA2UIAction;
+ if (handler?.postMessage) {
+ try {
+ if (handler === globalThis.clawdbotCanvasA2UIAction) {
+ handler.postMessage(JSON.stringify({ userAction }));
+ } else {
+ handler.postMessage({ userAction });
+ }
+ } catch (e$14) {
+ const msg = String(e$14?.message ?? e$14);
+ this.pendingAction = {
+ id: actionId,
+ name,
+ phase: "error",
+ startedAt: Date.now(),
+ error: msg
+ };
+ this.#setToast(`Failed: ${msg}`, "error", 4500);
+ }
+ } else {
+ this.pendingAction = {
+ id: actionId,
+ name,
+ phase: "error",
+ startedAt: Date.now(),
+ error: "missing native bridge"
+ };
+ this.#setToast("Failed: missing native bridge", "error", 4500);
+ }
+ }
+ applyMessages(messages) {
+ if (!Array.isArray(messages)) {
+ throw new Error("A2UI: expected messages array");
+ }
+ this.#processor.processMessages(messages);
+ this.#syncSurfaces();
+ if (this.pendingAction?.phase === "sent") {
+ this.#setToast(`Updated: ${this.pendingAction.name}`, "ok", 1100);
+ this.pendingAction = null;
+ }
+ this.requestUpdate();
+ return {
+ ok: true,
+ surfaces: this.surfaces.map(([id]) => id)
+ };
+ }
+ reset() {
+ this.#processor.clearSurfaces();
+ this.#syncSurfaces();
+ this.pendingAction = null;
+ this.requestUpdate();
+ return { ok: true };
+ }
+ #syncSurfaces() {
+ this.surfaces = Array.from(this.#processor.getSurfaces().entries());
+ }
+ render() {
+ if (this.surfaces.length === 0) {
+ return b`
Canvas (A2UI)
Waiting for A2UI messages…
`;
- }
- const statusText =
- this.pendingAction?.phase === "sent"
- ? `Working: ${this.pendingAction.name}`
- : this.pendingAction?.phase === "sending"
- ? `Sending: ${this.pendingAction.name}`
- : this.pendingAction?.phase === "error"
- ? `Failed: ${this.pendingAction.name}`
- : "";
- return b`
+ }
+ const statusText = this.pendingAction?.phase === "sent" ? `Working: ${this.pendingAction.name}` : this.pendingAction?.phase === "sending" ? `Sending: ${this.pendingAction.name}` : this.pendingAction?.phase === "error" ? `Failed: ${this.pendingAction.name}` : "";
+ return b`
${this.pendingAction && this.pendingAction.phase !== "error" ? b`
` : ""}
${this.toast ? b`
${this.toast.text}
` : ""}
- ${c$2(
- this.surfaces,
- ([surfaceId]) => surfaceId,
- ([surfaceId, surface]) => b` surfaceId, ([surfaceId, surface]) => b``,
- )}
+ >`)}
`;
- }
+ }
};
customElements.define("clawdbot-a2ui-host", ClawdbotA2UIHost);