line-flex-message-preview 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 line-flex-message-preview 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,255 @@
1
- # Temporary Holding Version
1
+ # line-flex-message-preview
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Renders [LINE Flex Message](https://developers.line.biz/en/docs/messaging-api/using-flex-messages/)
4
+ JSON in a web page, the way a phone shows it, so that a message can be
5
+ previewed before it is sent.
6
+
7
+ - **No framework, no runtime dependencies.** A `<flex-message>` custom element,
8
+ plus functions that return an HTML string or a DOM element.
9
+ - **Isolated in both directions.** The preview lives in a shadow root: the
10
+ page's CSS cannot restyle it and its CSS cannot leak out. This is tested
11
+ against a deliberately hostile stylesheet.
12
+ - **Measured, not guessed.** LINE does not publish how Flex Messages are drawn.
13
+ Every metric here is a recorded measurement ([docs/measurements.md](docs/measurements.md)),
14
+ and the layout is compared box by box with LINE's Flex Message Simulator.
15
+ - **Safe with untrusted messages.** No value from the JSON is ever written into
16
+ markup or CSS as-is, and actions are reported as events, never followed.
17
+ - **A validator** that mirrors LINE's published schema and says which
18
+ properties the preview cannot show faithfully.
19
+
20
+ > **Status: 0.1.** Early: the API may still change before 1.0. See
21
+ > [What is not done](#what-is-not-done).
22
+
23
+ ## Install
24
+
25
+ ```sh
26
+ npm install line-flex-message-preview
27
+ ```
28
+
29
+ ES modules only, with type declarations, and no dependencies of its own.
30
+
31
+ ## Use
32
+
33
+ ### The element
34
+
35
+ ```html
36
+ <flex-message>
37
+ <script type="application/json">
38
+ { "type": "bubble", "body": { "type": "box", "layout": "vertical",
39
+ "contents": [{ "type": "text", "text": "Hello" }] } }
40
+ </script>
41
+ </flex-message>
42
+
43
+ <script type="module">
44
+ import 'line-flex-message-preview/define';
45
+ </script>
46
+ ```
47
+
48
+ The message can be a whole Flex message (`{ "type": "flex", "altText": …, "contents": … }`)
49
+ or just its bubble or carousel. For a live preview, set the property; it
50
+ re-renders on every change:
51
+
52
+ ```js
53
+ const preview = document.querySelector('flex-message');
54
+ preview.message = message; // an object, or a JSON string
55
+
56
+ preview.addEventListener('flex-message-render', (event) => {
57
+ // Problems in the message; see "Validation" below.
58
+ console.log(event.detail.issues);
59
+ });
60
+ preview.addEventListener('flex-message-action', (event) => {
61
+ // The user tapped something with an action. Nothing was opened or sent.
62
+ console.log(event.detail.path, event.detail.action);
63
+ });
64
+ ```
65
+
66
+ | | |
67
+ |---|---|
68
+ | `message` property | The message to show. `null` goes back to the child `<script type="application/json">`, which is re-read whenever it changes. |
69
+ | `profile` attribute | `ios` (default) or `simulator`. See [Fidelity](#fidelity). The `profile` property takes a custom `Profile` object. |
70
+ | `annotate` attribute | Adds `data-path` (a JSON Pointer into the bubble or carousel) to every component in the shadow root. |
71
+ | `issues` property | The problems found at the last render. |
72
+ | `render()` | Renders immediately instead of at the next microtask. |
73
+ | `flex-message-render` event | After each render; `detail.issues`. |
74
+ | `flex-message-action` event | On a tap on a component with an `action`; `detail.action`, `detail.path`. Bubbles and crosses shadow boundaries. |
75
+ | `::part(error)` | The notice shown in place of a message that is not Flex JSON at all. |
76
+
77
+ Importing `…/define` registers the element. To choose the tag name or the
78
+ moment, import `defineFlexMessageElement` from `…/element` instead; that module
79
+ and the main entry have no side effects and are safe to import on a server.
80
+ For a page without a bundler, `dist/flex-message.bundle.js` is the same thing
81
+ in one file (about 29 kB minified).
82
+
83
+ To reserve space before the element is defined:
84
+
85
+ ```css
86
+ flex-message:not(:defined) { display: block; min-height: 200px; }
87
+ ```
88
+
89
+ ### Static HTML
90
+
91
+ ```js
92
+ import { renderToString } from 'line-flex-message-preview';
93
+
94
+ const html = renderToString(message, { nonce });
95
+ // <flex-message profile="ios"><template shadowrootmode="open"><style nonce="…">…
96
+ ```
97
+
98
+ The result uses a [declarative shadow root](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/template#shadowrootmode),
99
+ so it displays with no JavaScript and is isolated just the same. It contains no
100
+ `style` attributes, so a Content-Security-Policy that allows styles by nonce is
101
+ enough. If the element is defined later, it adopts this markup as it is.
102
+ `renderDocument()` wraps the same output in a complete page, which is what the
103
+ screenshot script uses:
104
+
105
+ ```sh
106
+ node scripts/screenshot.ts message.json out.png --profile ios --width 375
107
+ ```
108
+
109
+ `renderToElement(message, options)` returns a detached element for those who
110
+ want to place it in their own shadow root together with `stylesheetFor(profile)`.
111
+
112
+ ### Validation
113
+
114
+ ```js
115
+ import { validate } from 'line-flex-message-preview';
116
+
117
+ validate(message);
118
+ // [{ path: '/contents/body/contents/0/colour', severity: 'error',
119
+ // code: 'unknown-property', message: 'text has no property "colour".' }]
120
+ ```
121
+
122
+ - **`error`**: LINE rejects the message (unknown or missing properties, wrong
123
+ value shapes, misplaced components), or it cannot be rendered.
124
+ - **`warning`**: LINE accepts it, but the preview will not match the phone
125
+ (`not-rendered`), or the component is deprecated.
126
+
127
+ It is held to LINE's own answers: `spec/line-verdicts.json` records what LINE
128
+ said about 172 single-rule messages (`tests/line-cases.ts`), and the test suite
129
+ requires `validate()` to agree with every one of them. It is still a fast
130
+ offline check rather than LINE's verdict on *your* message. For that, LINE has
131
+ an endpoint that validates without delivering anything:
132
+
133
+ ```sh
134
+ node scripts/validate-with-line.ts --env-file .env tests/fixtures/*.json
135
+ ```
136
+
137
+ It needs the credentials of a **test** channel with no real friends, and it
138
+ fails when LINE and `validate()` disagree.
139
+
140
+ ### Theming
141
+
142
+ Nothing outside can style the inside, by design. Two custom properties are the
143
+ exceptions:
144
+
145
+ | property | default |
146
+ |---|---|
147
+ | `--flex-message-font-family` | the system font stack (`-apple-system, …, sans-serif`) |
148
+ | `--flex-message-bubble-background` | `#ffffff` |
149
+
150
+ The font matters for fidelity: line breaks depend on glyph widths, so a preview
151
+ on Windows or Linux will wrap long text differently from an iPhone. Heights of
152
+ single lines do not depend on it.
153
+
154
+ ## Fidelity
155
+
156
+ There are two references one could aim for, and they disagree:
157
+
158
+ | | `ios` profile (default) | `simulator` profile |
159
+ |---|---|---|
160
+ | target | LINE on an iPhone | LINE's Flex Message Simulator |
161
+ | line height | `max(1.2em, 16px)` | `1.4` (about 15% taller) |
162
+ | `maxLines`, `lineSpacing` | applied | ignored, as the Simulator ignores them |
163
+ | how it is checked | 18 boxes of a calibration card within 1 px of published iPhone measurements (`pnpm test:device`) | 311 cases, 3 488 boxes and computed styles within 0.02 px of a reconstruction of the Simulator (`pnpm test:parity`) |
164
+
165
+ The `simulator` profile exists so that everything the two have in common
166
+ (spacing, sizes, flex behaviour, paddings, colours) can be regression-tested
167
+ exhaustively and automatically. The `ios` profile is that, plus what a phone
168
+ was measured to do differently. Where every number comes from, and what has
169
+ not been measured yet, is in [docs/measurements.md](docs/measurements.md).
170
+
171
+ ### What is not done
172
+
173
+ - **Our own device calibration.** The iPhone measurements behind the `ios`
174
+ profile are third-party so far; the messages and procedure for repeating
175
+ them are in [calibration/](calibration/README.md). Android has not been
176
+ measured at all.
177
+ - **`adjustMode: shrink-to-fit`, `scaling`, animated images.** Accepted by
178
+ `validate()` with a `not-rendered` warning, drawn as if absent.
179
+ - **Video.** The `altContent` is shown in its place.
180
+ - **A chat frame** (header, avatar, bubble tail) around the message.
181
+ - **Browsers.** Tested in Chrome 158. The features used need Chrome 111,
182
+ Safari 16.4 or Firefox 123 for the static output; the element falls back to a
183
+ `<style>` element where constructable stylesheets are missing. Safari and
184
+ Firefox have not been run yet.
185
+ - **A broken image in static output** shows the browser's broken-image icon;
186
+ the element hides it.
187
+
188
+ ## Security
189
+
190
+ A message is treated as untrusted input.
191
+
192
+ - Text goes in as text nodes (or escaped, in string output).
193
+ - Lengths, colours, angles and ratios are parsed and re-serialised from the
194
+ parsed value; anything that does not parse is dropped.
195
+ - Images load only from `https:` URLs without credentials, with
196
+ `referrerpolicy="no-referrer"`. Note that showing a message does fetch its
197
+ images from wherever the message says.
198
+ - Actions are never executed. No link is ever emitted.
199
+ - `tests/security.test.ts` puts hostile values into every property of every
200
+ component (over a thousand renderings) and checks the tags, the fetched URLs
201
+ and the generated CSS separately.
202
+
203
+ ## Tracking LINE
204
+
205
+ - **Schema.** `spec/flex-schemas.json` is a digest of the `Flex*` schemas in
206
+ [LINE's OpenAPI document](https://github.com/line/line-openapi) (Apache-2.0).
207
+ `pnpm spec:check` fails when upstream has changed; after `pnpm spec:update`,
208
+ `tests/spec.test.ts` fails until `validate()` knows every new property and
209
+ the profile has a value for every new keyword.
210
+ - **Acceptance.** `node scripts/line-verdicts.ts --env-file .env` asks LINE again about
211
+ every case in `tests/line-cases.ts` and rewrites `spec/line-verdicts.json`;
212
+ a changed verdict then fails `tests/line-verdicts.test.ts`.
213
+ - **Rendering.** The parity test pins the Simulator's stylesheet by sha256 and
214
+ stops when it changes.
215
+ - A scheduled workflow (`.github/workflows/upstream.yml`) runs both weekly.
216
+
217
+ ## Develop
218
+
219
+ Needs Node 22.18 or later, pnpm, and Chrome for the browser tests (set
220
+ `CHROME_PATH` if it is not in a usual place). Sources run as they are; there is
221
+ no build step for tests.
222
+
223
+ ```sh
224
+ pnpm install
225
+ pnpm test # unit tests: rendering, validation, security, schema, LINE's recorded verdicts
226
+ pnpm build # dist/ (ES modules, types, single-file bundle)
227
+ pnpm test:browser # the element in Chrome: isolation and behaviour
228
+ pnpm test:parity # layout against the Simulator reconstruction (downloads into .cache/)
229
+ pnpm test:device # the ios profile against iPhone measurements (macOS only)
230
+ pnpm demo # playground at http://127.0.0.1:4173/examples/
231
+ ```
232
+
233
+ The browser tests drive a local Chrome directly and add no dependency. The only
234
+ development dependencies are TypeScript, esbuild and Node's type definitions.
235
+
236
+ ```
237
+ src/tree.ts Flex JSON → element tree (the one place layout is decided)
238
+ src/profile.ts metrics per target
239
+ src/styles.ts the stylesheet inside the shadow root
240
+ src/html.ts tree → HTML string src/dom.ts tree → DOM
241
+ src/element.ts <flex-message> src/validate.ts structural validation
242
+ src/values.ts parsers for every value shape
243
+ ```
244
+
245
+ ## Origins and licence
246
+
247
+ [MIT](LICENSE). This is an independent implementation written from LINE's
248
+ public documentation and from measurements; it contains no code or stylesheet
249
+ from LINE or from other renderers. The test suite compares against
250
+ [lis186/line-flex-message-skill](https://github.com/lis186/line-flex-message-skill)
251
+ (MIT), whose probe corpus and iPhone measurements made that comparison
252
+ possible; it is fetched at test time and not redistributed here.
253
+
254
+ Not affiliated with or endorsed by LY Corporation. LINE is a trademark of
255
+ LY Corporation.
@@ -0,0 +1 @@
1
+ export * from './element.js';
package/dist/define.js ADDED
@@ -0,0 +1,4 @@
1
+ // Side-effect entry: importing it registers <flex-message>.
2
+ import { defineFlexMessageElement } from './element.js';
3
+ defineFlexMessageElement();
4
+ export * from './element.js';
package/dist/dom.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import type { RenderOptions } from './html.js';
2
+ import type { FlexAction } from './types.js';
3
+ export interface ActionTarget {
4
+ action: FlexAction;
5
+ /** JSON Pointer of the component within the container. */
6
+ path: string;
7
+ }
8
+ /** The action of the nearest component at or above `element`, if any. */
9
+ export declare function actionAt(element: Element | null, within: Node): ActionTarget | undefined;
10
+ /**
11
+ * Renders a Flex message (or a bare bubble / carousel) to a detached element.
12
+ * It carries no styles of its own: put it in a shadow root next to
13
+ * `stylesheetFor(profile)`, which is what `<flex-message>` does.
14
+ */
15
+ export declare function renderToElement(input: unknown, options?: RenderOptions, doc?: Document): HTMLElement;
package/dist/dom.js ADDED
@@ -0,0 +1,38 @@
1
+ // Element tree → live DOM.
2
+ import { resolveProfile } from './profile.js';
3
+ import { buildTree } from './tree.js';
4
+ const actions = new WeakMap();
5
+ /** The action of the nearest component at or above `element`, if any. */
6
+ export function actionAt(element, within) {
7
+ for (let el = element; el && el !== within; el = el.parentElement) {
8
+ const target = actions.get(el);
9
+ if (target)
10
+ return target;
11
+ }
12
+ return undefined;
13
+ }
14
+ function create(node, doc) {
15
+ const el = doc.createElement(node.tag);
16
+ if (node.classes.length > 0)
17
+ el.className = node.classes.join(' ');
18
+ // Set through the CSSOM, which a Content-Security-Policy does not restrict.
19
+ for (const [property, value] of node.style)
20
+ el.style.setProperty(property, value);
21
+ for (const [name, value] of Object.entries(node.attrs))
22
+ el.setAttribute(name, value);
23
+ for (const child of node.children) {
24
+ el.appendChild(typeof child === 'string' ? doc.createTextNode(child) : create(child, doc));
25
+ }
26
+ if (node.action)
27
+ actions.set(el, node.action);
28
+ return el;
29
+ }
30
+ /**
31
+ * Renders a Flex message (or a bare bubble / carousel) to a detached element.
32
+ * It carries no styles of its own: put it in a shadow root next to
33
+ * `stylesheetFor(profile)`, which is what `<flex-message>` does.
34
+ */
35
+ export function renderToElement(input, options = {}, doc = document) {
36
+ const profile = resolveProfile(options.profile);
37
+ return create(buildTree(input, { profile, annotate: options.annotate }), doc);
38
+ }
@@ -0,0 +1,44 @@
1
+ import { type ActionTarget } from './dom.js';
2
+ import { type Profile } from './profile.js';
3
+ import { type Issue } from './validate.js';
4
+ export interface FlexMessageRenderDetail {
5
+ /** Problems found in the message; see validate(). */
6
+ issues: readonly Issue[];
7
+ }
8
+ export type FlexMessageActionDetail = ActionTarget;
9
+ declare global {
10
+ interface HTMLElementEventMap {
11
+ 'flex-message-render': CustomEvent<FlexMessageRenderDetail>;
12
+ 'flex-message-action': CustomEvent<FlexMessageActionDetail>;
13
+ }
14
+ }
15
+ declare const Base: typeof HTMLElement;
16
+ export declare class FlexMessageElement extends Base {
17
+ #private;
18
+ static readonly observedAttributes: string[];
19
+ /**
20
+ * The message to show: a Flex message, a bare bubble or carousel, or any of
21
+ * those as a JSON string. Setting it re-renders. `null` or `undefined` goes
22
+ * back to the JSON in a child `<script type="application/json">`, if any.
23
+ */
24
+ get message(): unknown;
25
+ set message(value: unknown);
26
+ /** A custom metrics profile; overrides the `profile` attribute. */
27
+ get profile(): Profile | undefined;
28
+ set profile(value: Profile | undefined);
29
+ /** Problems found in the message at the last render. */
30
+ get issues(): readonly Issue[];
31
+ connectedCallback(): void;
32
+ disconnectedCallback(): void;
33
+ attributeChangedCallback(_name: string, before: string | null, after: string | null): void;
34
+ /** Renders now instead of at the next microtask. */
35
+ render(): void;
36
+ }
37
+ /** Registers the element. Safe to call more than once and on a server. */
38
+ export declare function defineFlexMessageElement(tagName?: string): void;
39
+ declare global {
40
+ interface HTMLElementTagNameMap {
41
+ 'flex-message': FlexMessageElement;
42
+ }
43
+ }
44
+ export {};
@@ -0,0 +1,174 @@
1
+ // <flex-message>: a preview of one Flex message, isolated in a shadow root.
2
+ //
3
+ // <flex-message>
4
+ // <script type="application/json">{ "type": "bubble", ... }</script>
5
+ // </flex-message>
6
+ //
7
+ // element.message = { type: 'flex', altText: '...', contents: { ... } };
8
+ //
9
+ // Importing this module defines nothing; call defineFlexMessageElement(), or
10
+ // import the `define` entry, which does it for you.
11
+ import { actionAt, renderToElement } from './dom.js';
12
+ import { resolveProfile } from './profile.js';
13
+ import { stylesheetFor } from './styles.js';
14
+ import { containerOf } from './tree.js';
15
+ import { validate } from './validate.js';
16
+ // So that importing this module on a server (where there is no DOM) is harmless.
17
+ const Base = globalThis.HTMLElement ?? class {
18
+ };
19
+ const sheets = new WeakMap();
20
+ function applyStyles(root, profile) {
21
+ const css = stylesheetFor(profile);
22
+ if ('adoptedStyleSheets' in root && typeof CSSStyleSheet === 'function' && 'replaceSync' in CSSStyleSheet.prototype) {
23
+ // One stylesheet object shared by every instance using this profile.
24
+ let sheet = sheets.get(profile);
25
+ if (!sheet) {
26
+ sheet = new CSSStyleSheet();
27
+ sheet.replaceSync(css);
28
+ sheets.set(profile, sheet);
29
+ }
30
+ root.adoptedStyleSheets = [sheet];
31
+ return;
32
+ }
33
+ const style = document.createElement('style');
34
+ style.textContent = css;
35
+ root.append(style);
36
+ }
37
+ export class FlexMessageElement extends Base {
38
+ static observedAttributes = ['profile', 'annotate'];
39
+ #message = undefined;
40
+ #hasMessage = false;
41
+ #issues = [];
42
+ #root;
43
+ #observer;
44
+ #scheduled = false;
45
+ #profile;
46
+ /**
47
+ * The message to show: a Flex message, a bare bubble or carousel, or any of
48
+ * those as a JSON string. Setting it re-renders. `null` or `undefined` goes
49
+ * back to the JSON in a child `<script type="application/json">`, if any.
50
+ */
51
+ get message() {
52
+ return this.#message;
53
+ }
54
+ set message(value) {
55
+ this.#message = value ?? undefined;
56
+ this.#hasMessage = value !== null && value !== undefined;
57
+ this.#schedule();
58
+ }
59
+ /** A custom metrics profile; overrides the `profile` attribute. */
60
+ get profile() {
61
+ return this.#profile;
62
+ }
63
+ set profile(value) {
64
+ this.#profile = value ?? undefined;
65
+ this.#schedule();
66
+ }
67
+ /** Problems found in the message at the last render. */
68
+ get issues() {
69
+ return this.#issues;
70
+ }
71
+ connectedCallback() {
72
+ // A property set before the element was defined would otherwise shadow the accessor.
73
+ for (const name of ['message', 'profile']) {
74
+ if (Object.hasOwn(this, name)) {
75
+ const value = this[name];
76
+ delete this[name];
77
+ this[name] = value;
78
+ }
79
+ }
80
+ if (!this.#root) {
81
+ // Reuse a declarative shadow root left by renderToString(), if there is one.
82
+ this.#root = this.shadowRoot ?? this.attachShadow({ mode: 'open' });
83
+ this.#root.addEventListener('click', this.#onClick);
84
+ // `error` does not bubble, hence the capture. A URL that fails to load
85
+ // (common while it is being typed) leaves its space, not a broken-image icon.
86
+ this.#root.addEventListener('error', this.#onError, true);
87
+ }
88
+ this.#observer ??= new MutationObserver(() => {
89
+ if (!this.#hasMessage)
90
+ this.#schedule();
91
+ });
92
+ this.#observer.observe(this, { childList: true, characterData: true, subtree: true });
93
+ this.#schedule();
94
+ }
95
+ disconnectedCallback() {
96
+ this.#observer?.disconnect();
97
+ }
98
+ attributeChangedCallback(_name, before, after) {
99
+ if (before !== after)
100
+ this.#schedule();
101
+ }
102
+ /** Renders now instead of at the next microtask. */
103
+ render() {
104
+ this.#scheduled = false;
105
+ const root = this.#root;
106
+ if (!root)
107
+ return;
108
+ let source = this.#message;
109
+ if (!this.#hasMessage) {
110
+ const script = this.querySelector(':scope > script[type="application/json"]');
111
+ source = script?.textContent?.trim() || undefined;
112
+ // Server-rendered content and nothing to replace it with: leave it alone.
113
+ if (source === undefined && root.childElementCount > 0 && !root.querySelector('.root[data-rendered]'))
114
+ return;
115
+ }
116
+ let parsed = source;
117
+ let issues = [];
118
+ if (typeof source === 'string') {
119
+ try {
120
+ parsed = JSON.parse(source);
121
+ }
122
+ catch {
123
+ parsed = undefined;
124
+ }
125
+ }
126
+ if (source !== undefined)
127
+ issues = validate(source);
128
+ const profile = this.#profile ?? resolveProfile(this.getAttribute('profile'));
129
+ const content = renderToElement(parsed, { profile, annotate: this.hasAttribute('annotate') }, this.ownerDocument);
130
+ content.setAttribute('data-rendered', '');
131
+ if (source !== undefined && !containerOf(parsed)?.type) {
132
+ const error = this.ownerDocument.createElement('div');
133
+ error.className = 'error';
134
+ error.setAttribute('part', 'error');
135
+ error.textContent = issues[0]?.message ?? 'Not a Flex message.';
136
+ content.append(error);
137
+ }
138
+ root.replaceChildren();
139
+ applyStyles(root, profile);
140
+ root.append(content);
141
+ this.#issues = Object.freeze(issues);
142
+ this.dispatchEvent(new CustomEvent('flex-message-render', { detail: { issues: this.#issues } }));
143
+ }
144
+ #schedule() {
145
+ if (this.#scheduled || !this.#root)
146
+ return;
147
+ this.#scheduled = true;
148
+ queueMicrotask(() => {
149
+ if (this.#scheduled)
150
+ this.render();
151
+ });
152
+ }
153
+ #onError = (event) => {
154
+ if (event.target instanceof HTMLImageElement)
155
+ event.target.style.visibility = 'hidden';
156
+ };
157
+ // A preview never navigates or sends anything: taps are only reported.
158
+ #onClick = (event) => {
159
+ const root = this.#root;
160
+ if (!root || !(event.target instanceof Element))
161
+ return;
162
+ const target = actionAt(event.target, root);
163
+ if (!target)
164
+ return;
165
+ this.dispatchEvent(new CustomEvent('flex-message-action', { detail: target, bubbles: true, composed: true }));
166
+ };
167
+ }
168
+ /** Registers the element. Safe to call more than once and on a server. */
169
+ export function defineFlexMessageElement(tagName = 'flex-message') {
170
+ if (typeof customElements === 'undefined')
171
+ return;
172
+ if (!customElements.get(tagName))
173
+ customElements.define(tagName, FlexMessageElement);
174
+ }