@symbiotejs/symbiote 3.9.0 → 3.10.1

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.
Files changed (131) hide show
  1. package/README.md +12 -0
  2. package/core/AppRouter.js +97 -58
  3. package/core/PubSub.js +42 -11
  4. package/core/Symbiote.js +70 -46
  5. package/core/itemizeProcessor-keyed.js +88 -188
  6. package/core/itemizeProcessor.js +1 -12
  7. package/core/itemizeSetup.js +26 -3
  8. package/core/ownElements.js +1 -4
  9. package/core/resolveTemplate.js +12 -0
  10. package/core/tpl-processors.js +1 -2
  11. package/docs/README.md +2 -0
  12. package/docs/html-app-vs-htmx.md +55 -0
  13. package/docs/lifecycle.md +2 -0
  14. package/docs/list-rendering.md +10 -2
  15. package/docs/pubsub.md +3 -0
  16. package/docs/routing.md +15 -4
  17. package/html-app/BaseClass.js +203 -0
  18. package/html-app/README.md +369 -0
  19. package/html-app/action-data.js +168 -0
  20. package/html-app/actions.js +366 -0
  21. package/html-app/collection-actions.js +104 -0
  22. package/html-app/collection-data.js +234 -0
  23. package/html-app/collection-items.js +45 -0
  24. package/html-app/conditions.js +42 -0
  25. package/html-app/context-data.js +185 -0
  26. package/html-app/context-requests.js +374 -0
  27. package/html-app/context-storage.js +376 -0
  28. package/html-app/declarations.js +55 -0
  29. package/html-app/examples/assets/actions.html +56 -0
  30. package/html-app/examples/assets/collections.html +72 -0
  31. package/html-app/examples/assets/components.html +25 -0
  32. package/html-app/examples/assets/conditional.html +29 -0
  33. package/html-app/examples/assets/data.html +31 -0
  34. package/html-app/examples/assets/guide.html +4 -0
  35. package/html-app/examples/assets/imports.html +11 -0
  36. package/html-app/examples/assets/not-found.html +4 -0
  37. package/html-app/examples/assets/routes.json +58 -0
  38. package/html-app/examples/assets/routing.html +27 -0
  39. package/html-app/examples/assets/state.html +32 -0
  40. package/html-app/examples/assets/storage.html +28 -0
  41. package/html-app/examples/assets/tasks.json +25 -0
  42. package/html-app/examples/full-app.html +147 -0
  43. package/html-app/examples/todo-ref.html +37 -0
  44. package/html-app/fetch-source.js +147 -0
  45. package/html-app/fragment-content.js +29 -0
  46. package/html-app/fragment-source.js +169 -0
  47. package/html-app/index.js +34 -0
  48. package/html-app/initial-data.js +88 -0
  49. package/html-app/pub-map.js +93 -0
  50. package/html-app/router-data.js +50 -0
  51. package/html-app/router-navigation.js +70 -0
  52. package/html-app/storage-revisions.js +130 -0
  53. package/html-app/sym-collection.js +142 -0
  54. package/html-app/sym-component.js +20 -0
  55. package/html-app/sym-conditional.js +141 -0
  56. package/html-app/sym-context.js +176 -0
  57. package/html-app/sym-import.js +218 -0
  58. package/html-app/sym-router.js +107 -0
  59. package/package.json +18 -6
  60. package/scripts/check-html-app-package.js +117 -0
  61. package/scripts/check-html-app-size.js +91 -0
  62. package/scripts/update-exports.js +4 -0
  63. package/skills/symbiote/SKILL.md +64 -15
  64. package/skills/symbiote/agents/openai.yaml +1 -1
  65. package/types/core/AppRouter.d.ts +13 -4
  66. package/types/core/AppRouter.d.ts.map +1 -1
  67. package/types/core/PubSub.d.ts +1 -1
  68. package/types/core/PubSub.d.ts.map +1 -1
  69. package/types/core/Symbiote.d.ts +4 -1
  70. package/types/core/Symbiote.d.ts.map +1 -1
  71. package/types/core/itemizeProcessor-keyed.d.ts.map +1 -1
  72. package/types/core/itemizeProcessor.d.ts.map +1 -1
  73. package/types/core/itemizeSetup.d.ts +1 -0
  74. package/types/core/itemizeSetup.d.ts.map +1 -1
  75. package/types/core/ownElements.d.ts +1 -1
  76. package/types/core/ownElements.d.ts.map +1 -1
  77. package/types/core/resolveTemplate.d.ts +2 -0
  78. package/types/core/resolveTemplate.d.ts.map +1 -0
  79. package/types/core/tpl-processors.d.ts.map +1 -1
  80. package/types/html-app/BaseClass.d.ts +24 -0
  81. package/types/html-app/BaseClass.d.ts.map +1 -0
  82. package/types/html-app/action-data.d.ts +15 -0
  83. package/types/html-app/action-data.d.ts.map +1 -0
  84. package/types/html-app/actions.d.ts +104 -0
  85. package/types/html-app/actions.d.ts.map +1 -0
  86. package/types/html-app/collection-actions.d.ts +12 -0
  87. package/types/html-app/collection-actions.d.ts.map +1 -0
  88. package/types/html-app/collection-data.d.ts +13 -0
  89. package/types/html-app/collection-data.d.ts.map +1 -0
  90. package/types/html-app/collection-items.d.ts +7 -0
  91. package/types/html-app/collection-items.d.ts.map +1 -0
  92. package/types/html-app/conditions.d.ts +5 -0
  93. package/types/html-app/conditions.d.ts.map +1 -0
  94. package/types/html-app/context-data.d.ts +31 -0
  95. package/types/html-app/context-data.d.ts.map +1 -0
  96. package/types/html-app/context-requests.d.ts +97 -0
  97. package/types/html-app/context-requests.d.ts.map +1 -0
  98. package/types/html-app/context-storage.d.ts +102 -0
  99. package/types/html-app/context-storage.d.ts.map +1 -0
  100. package/types/html-app/declarations.d.ts +3 -0
  101. package/types/html-app/declarations.d.ts.map +1 -0
  102. package/types/html-app/fetch-source.d.ts +23 -0
  103. package/types/html-app/fetch-source.d.ts.map +1 -0
  104. package/types/html-app/fragment-content.d.ts +6 -0
  105. package/types/html-app/fragment-content.d.ts.map +1 -0
  106. package/types/html-app/fragment-source.d.ts +14 -0
  107. package/types/html-app/fragment-source.d.ts.map +1 -0
  108. package/types/html-app/index.d.ts +9 -0
  109. package/types/html-app/index.d.ts.map +1 -0
  110. package/types/html-app/initial-data.d.ts +8 -0
  111. package/types/html-app/initial-data.d.ts.map +1 -0
  112. package/types/html-app/pub-map.d.ts +19 -0
  113. package/types/html-app/pub-map.d.ts.map +1 -0
  114. package/types/html-app/router-data.d.ts +4 -0
  115. package/types/html-app/router-data.d.ts.map +1 -0
  116. package/types/html-app/router-navigation.d.ts +3 -0
  117. package/types/html-app/router-navigation.d.ts.map +1 -0
  118. package/types/html-app/storage-revisions.d.ts +11 -0
  119. package/types/html-app/storage-revisions.d.ts.map +1 -0
  120. package/types/html-app/sym-collection.d.ts +16 -0
  121. package/types/html-app/sym-collection.d.ts.map +1 -0
  122. package/types/html-app/sym-component.d.ts +5 -0
  123. package/types/html-app/sym-component.d.ts.map +1 -0
  124. package/types/html-app/sym-conditional.d.ts +10 -0
  125. package/types/html-app/sym-conditional.d.ts.map +1 -0
  126. package/types/html-app/sym-context.d.ts +16 -0
  127. package/types/html-app/sym-context.d.ts.map +1 -0
  128. package/types/html-app/sym-import.d.ts +19 -0
  129. package/types/html-app/sym-import.d.ts.map +1 -0
  130. package/types/html-app/sym-router.d.ts +12 -0
  131. package/types/html-app/sym-router.d.ts.map +1 -0
@@ -0,0 +1,203 @@
1
+ import Symbiote, { css } from '../core/Symbiote.js';
2
+ import { DICT } from '../core/dictionary.js';
3
+ import { ActionBindings, actionProcessor } from './actions.js';
4
+ import { PubMap } from './pub-map.js';
5
+ import { declarationProcessor } from './declarations.js';
6
+ import { initialDataProcessor, isDataKey, readInitialData, readTemplateData, rememberDefaults } from './initial-data.js';
7
+
8
+ export class BaseClass extends Symbiote {
9
+ static observedAttributes = [
10
+ 'pub-map',
11
+ ];
12
+ actionBindings = new ActionBindings(this);
13
+ outgoingBindings = new PubMap(this);
14
+ processInnerHtml = true;
15
+ allowCustomTemplate = true;
16
+ #scheduled = false;
17
+ #connecting = false;
18
+ /** @type {string | undefined} */
19
+ #markup;
20
+ #rebuild = false;
21
+ #seeded = false;
22
+ /** @type {Record<string, unknown>} */
23
+ #snapshot = {};
24
+
25
+ // Native Itemize uses this class for its generated item owners.
26
+ get Symbiote() {
27
+ return BaseClass;
28
+ }
29
+
30
+ /** @param {string | null} _value */
31
+ set 'pub-map'(_value) {
32
+ this.outgoingBindings.refresh();
33
+ }
34
+
35
+ connectedCallback() {
36
+ this.seedDefaults();
37
+ if (globalThis.__SYMBIOTE_SSR) {
38
+ this.connectFoundation();
39
+ return;
40
+ }
41
+ if (this.#scheduled) { return; }
42
+ this.#scheduled = true;
43
+ queueMicrotask(() => {
44
+ this.#scheduled = false;
45
+ this.connectFoundation();
46
+ });
47
+ }
48
+
49
+ connectFoundation() {
50
+ if (!this.isConnected || this.#connecting) { return; }
51
+ this.#connecting = true;
52
+ try {
53
+ // All foundation tags can upgrade before nested owners initialize.
54
+ let parent = this.parentNode;
55
+ while (parent) {
56
+ if (parent instanceof BaseClass) {
57
+ parent.connectFoundation();
58
+ break;
59
+ }
60
+ parent = parent.parentNode || (typeof ShadowRoot !== 'undefined' && parent instanceof ShadowRoot ? parent.host : null);
61
+ }
62
+ // An ancestor may remove this child while deciding conditional content.
63
+ if (!this.isConnected) { return; }
64
+ if (this.#rebuild) { this.connectedOnce = false; }
65
+ if (!this.connectedOnce) { this.prepare(); }
66
+ super.connectedCallback();
67
+ this.actionBindings.connect();
68
+ this.outgoingBindings.connect();
69
+ } finally {
70
+ this.#connecting = false;
71
+ }
72
+ }
73
+
74
+ seedDefaults() {
75
+ if (this.#seeded) { return; }
76
+ if (this.#markup === undefined) { this.#markup = this.innerHTML; }
77
+ let root = this.#rebuild ? this.authoredContent() : this;
78
+ let defaults = {
79
+ ...readTemplateData(this),
80
+ ...readInitialData(root),
81
+ };
82
+ rememberDefaults(this.localCtx, defaults);
83
+ this.init$ = {
84
+ ...defaults,
85
+ ...this.init$,
86
+ ...this.#snapshot,
87
+ };
88
+ for (let [
89
+ key,
90
+ value,
91
+ ] of Object.entries(this.init$)) {
92
+ if (isDataKey(key)) { this.localCtx.add(key, value); }
93
+ }
94
+ this.#seeded = true;
95
+ }
96
+
97
+ prepare() {
98
+ this.seedDefaults();
99
+ this.templateProcessors.add(declarationProcessor);
100
+ this.templateProcessors.add(initialDataProcessor);
101
+ this.templateProcessors.add(actionProcessor);
102
+ let parsing = this.getAttribute('process-inner-html');
103
+ if (parsing !== null) {
104
+ if (![
105
+ 'true',
106
+ 'false',
107
+ ].includes(parsing)) {
108
+ throw new TypeError('process-inner-html must be true or false.');
109
+ }
110
+ this.processInnerHtml = parsing === 'true';
111
+ }
112
+ }
113
+
114
+ authoredContent() {
115
+ let template = this.ownerDocument.createElement('template');
116
+ template.innerHTML = this.#markup ?? '';
117
+ return /** @type {DocumentFragment} */ (template.content.cloneNode(true));
118
+ }
119
+
120
+ /**
121
+ * @param {string | DocumentFragment} [template]
122
+ * @param {boolean} [shadow]
123
+ */
124
+ render(template, shadow) {
125
+ this.restoreContent();
126
+ super.render(template, shadow);
127
+ this.actionBindings.connect();
128
+ this.outgoingBindings.connect();
129
+ }
130
+
131
+ restoreContent() {
132
+ if (this.#rebuild) {
133
+ this.#rebuild = false;
134
+ this.ref = Object.create(null);
135
+ this.replaceChildren(this.authoredContent());
136
+ }
137
+ }
138
+
139
+ /**
140
+ * @param {Record<string, unknown>} values
141
+ * @param {boolean} [force]
142
+ */
143
+ set$(values, force = false) {
144
+ let itemUpdate = Reflect.has(this, DICT.MCP_ITEM_INDEX_KEY) && Object.keys(values).some(isDataKey);
145
+ if (itemUpdate) {
146
+ this.actionBindings.invalidate();
147
+ }
148
+ // An incoming record also resets invalid DOM drafts absent from state.
149
+ super.set$(values, force || itemUpdate);
150
+ }
151
+
152
+ /**
153
+ * @param {Record<string, unknown>} values
154
+ * @param {boolean} [rewrite]
155
+ */
156
+ add$(values, rewrite = false) {
157
+ if (Reflect.has(this, DICT.MCP_ITEM_INDEX_KEY) && Object.keys(values).some(isDataKey)) {
158
+ this.actionBindings.invalidate();
159
+ }
160
+ super.add$(values, rewrite);
161
+ }
162
+
163
+ disconnectedCallback() {
164
+ this.actionBindings.disconnect();
165
+ this.outgoingBindings.disconnect();
166
+ super.disconnectedCallback();
167
+ }
168
+
169
+ destroyCallback() {
170
+ this.actionBindings.destroy();
171
+ this.outgoingBindings.disconnect();
172
+ // Native teardown removes subscriptions. Reconnect reprocesses authored RAT,
173
+ // retaining state rather than trying to reuse nodes with removed bindings.
174
+ this.#snapshot = Object.fromEntries(Object.entries(this.localCtx.store).filter(([
175
+ key,
176
+ ]) => !key.startsWith('__htmlApp')));
177
+ this.#rebuild = true;
178
+ this.#seeded = false;
179
+ super.destroyCallback();
180
+ }
181
+ }
182
+
183
+ export default BaseClass;
184
+
185
+ BaseClass.rootStyles = css`
186
+ sym-component,
187
+ sym-context,
188
+ sym-collection,
189
+ sym-conditional,
190
+ sym-import,
191
+ sym-router {
192
+ display: contents;
193
+ }
194
+ sym-component[hidden],
195
+ sym-context[hidden],
196
+ sym-collection[hidden],
197
+ sym-conditional[hidden],
198
+ sym-import[hidden],
199
+ sym-router[hidden],
200
+ sym-component[reg] {
201
+ display: none;
202
+ }
203
+ `;
@@ -0,0 +1,369 @@
1
+ # Symbiote HTML-app foundation
2
+
3
+ **Write the application in HTML, including the interactions.**
4
+
5
+ A form adds a task. Its checkbox marks it complete. A filtered list updates immediately, and Save keeps your edits for the next visit. HTML-app lets you describe that whole workflow with HTML tags, attributes and JSON, without writing component classes or event handlers.
6
+
7
+ Symbiote supplies the reactive state and Runtime Agnostic Templates (RAT). Your markup declares the data, connects controls to it, and composes reusable views. The same data can drive several parts of the page, so an edit in one place updates its bound views. Record actions, filtering, navigation and local saving are available declaratively; JSON endpoints and trusted HTML fragments can supply external data and content.
8
+
9
+ **Create your own components in HTML, too.** Declare a custom tag with `sym-component reg="..."`, supply a template and JSON defaults, then reuse it like any other HTML element. Each instance gets its own state and can use declarative bindings and actions. Templates can be inline or referenced with `use-template`; no JavaScript class is needed. See [reusable component declarations](#reusable-component-declarations).
10
+
11
+ **Compose applications from portable HTML chunks.** Split screens into [imported sections](#html-fragments), nest reusable components, and combine them with inline or referenced templates. Bind a chunk to caller-provided data or let its nested components own their state. You can reuse the same markup across views and rearrange the application without rewriting its bindings or adding glue scripts.
12
+
13
+ **Combine Markdown and interactive UI in compact AI output.** In a host with HTML-app loaded and a Markdown renderer that preserves [embedded HTML](https://spec.commonmark.org/0.31.2/#raw-html), prose and interactive components can share one document. An AI agent can generate explanations, HTML chunks and JSON data together, reusing built-in actions instead of writing event handlers and state-management code. For workflows covered by those actions, this can reduce generated code and output token consumption.
14
+
15
+ Start on a static HTTP server with one external module script. Keep native HTML controls and your choice of CSS. When needed, opt into WebMCP to make the declared UI actions discoverable and callable by agents. The application stays readable HTML that people and coding agents can inspect and revise.
16
+
17
+ Try the [compact Todo](./examples/todo-ref.html), explore the [interactive feature guide](./examples/full-app.html), or read [HTML-app and htmx](../docs/html-app-vs-htmx.md) to choose an approach for your application.
18
+
19
+ ## Load the foundation
20
+
21
+ The optional entry registers `sym-component`, `sym-context`, `sym-collection`, `sym-conditional`, `sym-import` and `sym-router`. It works alongside ordinary Symbiote components and leaves the core entry independent. Serve the package's ES modules over HTTP and load the entry:
22
+
23
+ ```html
24
+ <script type="module" src="/vendor/symbiote/html-app/index.js"></script>
25
+
26
+ <sym-context ctx="APP">
27
+ <script type="application/json">
28
+ {
29
+ "title": "Contacts",
30
+ "contact": {"name": "Alex", "role": "Editor"}
31
+ }
32
+ </script>
33
+ <h1>{{title}}</h1>
34
+ <sym-context bind="$: APP/contact" pub-to="APP/contact"
35
+ use-template="#contact-template"></sym-context>
36
+ </sym-context>
37
+
38
+ <template id="contact-template">
39
+ <h2>{{name}}</h2>
40
+ <p>{{role}}</p>
41
+ </template>
42
+ ```
43
+
44
+ For a bundler or an existing module, import `@symbiotejs/symbiote/html-app`. No application build step is required for directly served modules.
45
+
46
+ ### WebMCP
47
+
48
+ Enable automatic UI tools on the external entry script:
49
+
50
+ ```html
51
+ <script type="module" src="/vendor/symbiote/html-app/index.js" webmcp-mode="true"></script>
52
+ ```
53
+
54
+ The literal `"true"` loads WebMCP and enables automatic tools for foundation components before they initialize, including generated items and imported fragments. At startup, the entry reads `document.currentScript` when available, otherwise the first external module script marked `webmcp-mode="true"`. This also supports CDN module wrappers whose URL differs from the imported implementation. The flag is read before asynchronous loading; an available current script takes precedence, including an absent or `"false"` flag. Without an opted-in loader, existing WebMCP settings stay unchanged. The full example opts in; the compact Todo keeps the default. Programmatic imports can use the native [WebMCP activation API](../docs/webmcp.md#activation).
55
+
56
+ ## Examples
57
+
58
+ - [todo-ref.html](./examples/todo-ref.html): a compact, unstyled Todo with creation, editing, completion and removal.
59
+ - [full-app.html](./examples/full-app.html): a styled feature guide. Its navigation loads external sections, each with a short explanation and a working demonstration of state, actions, collections, templates, conditions, imports, requests, storage or routing. Styling uses the [Tailwind Play CDN](https://tailwindcss.com/docs/installation/play-cdn); application behavior remains HTML and JSON.
60
+
61
+ Serve the examples with a static HTTP server. The guide loads initial tasks from `examples/assets/tasks.json`; Collections includes JSON source loading, editing, local saving and restoring in one view. Reload JSON replaces the current list; Restore saved tasks returns to the last browser save. Saved browser data takes precedence over the JSON defaults. Feature sections, the nested import fragment and sample JSON live in `examples/assets/`.
62
+
63
+ Use Send tasks in JSON requests with an HTTP endpoint that accepts the configured method and JSON document. Collections saves in the browser and does not require a write endpoint.
64
+
65
+ ## State and templates
66
+
67
+ - Put one strict JSON object in a direct `<script type="application/json">` child of an owner. Each instance parses its own defaults before its children bind. Referenced templates and Itemize templates can also provide defaults; incoming item data takes precedence. Nested owners read their own data scripts.
68
+ - Declare a child property before addressing it with `bind="$.property: APP/value"`. Use `bind="$: APP/object"` to merge and register a whole object instead.
69
+ - `sym-component` owns local state and processes authored HTML. It supports native `use-template` lookup and Itemize. Native generated item scopes also use the foundation base class.
70
+ - `sym-context` without `ctx` owns local state. With `ctx="APP"`, its local data and `APP/property` refer to the same native PubSub context. Named contexts need unique owners; an existing store is never overwritten.
71
+ - `bind="$: APP/contact"` uses native shallow merging: supplied fields update, missing fields are registered, and omitted fields remain. It does not replace the local state proxy or publish changes back automatically.
72
+ - Optional `pub-to="APP/contact"` publishes a fresh data object after an owned field changes. Incoming merges do not echo. The target must already exist in another context. Use native bindings for incoming state and explicit outgoing publication for edits.
73
+ - `process-inner-html="false"` disables an owner's inner binding parsing. Nested foundation elements still own and process their contents. The default is `true`.
74
+ - Removal releases subscriptions and owned named contexts after the native destruction delay. A move retains state; reconnecting a destroyed instance restores its authored markup and latest data.
75
+ - JSON keys are data-only local properties. Context prefixes and prototype-related keys are rejected. Only trusted templates and binding declarations belong in authored HTML.
76
+
77
+ See Symbiote's [templates](../docs/templates.md), [context](../docs/context.md), [state](../docs/properties.md) and [lists](../docs/list-rendering.md) references for the underlying APIs.
78
+
79
+ ## Declarative actions
80
+
81
+ Use action descriptors on native event bindings. Ordinary named handlers and ToolDescriptor bindings keep their native behavior.
82
+
83
+ ```html
84
+ <sym-context ctx="UI">
85
+ <script type="application/json">
86
+ {
87
+ "open": false,
88
+ "note": "",
89
+ "section": "home"
90
+ }
91
+ </script>
92
+ <button type="button" bind="onclick: [toggle]UI/open">Toggle</button>
93
+ <button type="button" value="settings" bind="onclick: [set]UI/section">Settings</button>
94
+ <label>Note
95
+ <input bind="value: UI/note; oninput: [pub-to-200]UI/note">
96
+ </label>
97
+ </sym-context>
98
+ ```
99
+
100
+ - `[toggle]REF` requires an existing boolean. `[set]REF` publishes the control's native value; `action-data="APP/value"` instead reads typed data through a native context reference. Literal button values `true` and `false` are converted when the target is boolean.
101
+ - `[pub-to]REF` reads text inputs and single selects as strings, checkboxes as booleans, checked radios as their string value, multiple selects as string arrays, and number/range inputs as finite numbers. An empty numeric input publishes null. Text such as `0012` stays text.
102
+ - An optional millisecond suffix, such as `[pub-to-200]`, debounces publication. Values are captured during input handling. Composition remains a draft until completion; incoming target updates, rebinds, removal and item reuse cancel stale publications.
103
+ - References use native local, named, shared and pop-up contexts. Targets must exist and be writable data properties. Non-null target types must match the supplied data. Invalid descriptors and incompatible values fail explicitly; there is no expression evaluation or action-chain syntax.
104
+ - Native disabled fieldsets, read-only controls and inert content block actions. A binding uses its own control, including when an inner icon receives the click.
105
+ - A configured form action validates the form and flushes pending field publications before reading data. A submit button can supply `action-data` or its native value. Only configured form actions prevent navigation; ordinary form submission and named handlers retain their behavior.
106
+ - Framework-generated handler keys are reserved implementation details. Optional WebMCP uses the native event discovery path; enable automatic discovery with the [entry script opt-in](#webmcp) or native JavaScript API.
107
+
108
+ ## Publish several properties
109
+
110
+ ```html
111
+ <sym-component pub-map="APP/section: section; APP/heading: heading">
112
+ <script type="application/json">
113
+ {
114
+ "section": "settings",
115
+ "heading": "Settings"
116
+ }
117
+ </script>
118
+ </sym-component>
119
+ ```
120
+
121
+ Declare the destination fields in their owning context first. `pub-map` publishes local data, including initialization and computed sources, through native context resolution. It coalesces synchronous source changes into one microtask, skips unchanged values, and releases subscriptions when remapped or disconnected. Its writes remain sequential; it is not a transaction across contexts.
122
+
123
+ ## Collections and immutable record actions
124
+
125
+ [Open the basic Todo](./examples/todo-ref.html) through your HTTP server. Its external module script loads the foundation; application behavior is entirely in HTML attributes and JSON.
126
+
127
+ `sym-collection data="APP/tasks"` owns a derived view of an existing array. Records must be JSON objects with unique nonempty string `id` values. IDs remain stable; Itemize metadata stays outside application records and DOM attributes.
128
+
129
+ ```html
130
+ <sym-collection data="APP/tasks" filter="APP/filter"
131
+ search="APP/query" search-fields="title,notes" sort="APP/sort"
132
+ pub-map="APP/shown: count; APP/total: totalCount">
133
+ <ul itemize="items">
134
+ <template>
135
+ <li>
136
+ <label><input type="checkbox" bind="checked: done; onchange: [item-pub]done">Done</label>
137
+ <label>Title<input required bind="value: title; oninput: [item-pub]title"></label>
138
+ <button type="button" bind="onclick: [item-remove]">Delete</button>
139
+ </li>
140
+ </template>
141
+ </ul>
142
+ <p bind="hidden: !empty">No matching records.</p>
143
+ </sym-collection>
144
+ ```
145
+
146
+ - Declare the referenced properties in an owning context. `data` is a writable array reference, not a URL. The derived view properties are `items`, `count`, `totalCount` and `empty`.
147
+ - Optional `filter` references a record of scalar field/value pairs, matched with typed AND equality. Optional `search` references a string and requires comma-separated `search-fields`. Optional `sort` references `{"field":"title","direction":"asc"}` or `desc`. Filtering, search and sorting never replace the source array.
148
+ - Render `items` with native Itemize and an authored template or registered foundation item component. Keyed reconciliation preserves each record's element and focus. No item controls, wrappers or styles are imposed.
149
+ - `[append]REF` and `[prepend]REF` clone the record referenced by `action-data` and insert it at the end or beginning of the source array, generating a missing ID. A form applies native validation and flushes pending field publications first. Optional `action-reset="APP/draft"` restores that property's authored JSON default only after success; invalid or failed operations retain the draft. Filtering and sorting still determine the displayed order.
150
+
151
+ ```html
152
+ <sym-context bind="$: APP/draft" pub-to="APP/draft">
153
+ <form action-data="APP/draft" action-reset="APP/draft"
154
+ bind="onsubmit: [prepend]APP/tasks">
155
+ <input required bind="value: title; oninput: [pub-to-200]title">
156
+ <button type="submit">Add first</button>
157
+ </form>
158
+ </sym-context>
159
+ ```
160
+
161
+ - `[item-pub]FIELD` publishes the control's typed value to an existing field of the current source record. `[item-toggle]FIELD` toggles a boolean. `[item-remove]` removes the record. Fields are local record keys; IDs cannot be edited. Invalid native controls keep their draft without publishing or announcing errors on every keystroke.
162
+ - `[item-pub-200]FIELD` supports the same debounce and composition handling as `[pub-to-200]`. Source changes, retargeting, disposal and item reuse cancel stale work.
163
+ - `[patch-matching]REF` requires explicit `action-match` and `action-data` record references. An empty match patches every record. `[remove-matching]REF` requires a nonempty `action-match`; an empty match cannot clear the array. Matching uses typed AND equality, without expressions.
164
+ - Updates validate before publishing one fresh array and preserve untouched records and fields. JSON-only values, immutable IDs and compatible field types are enforced. The collection releases source subscriptions on removal and rebinds when its reference attributes change.
165
+
166
+ ## Reusable component declarations
167
+
168
+ Register an autonomous custom element from a direct template or a native `use-template` reference:
169
+
170
+ ```html
171
+ <sym-component reg="status-note">
172
+ <template>
173
+ <script type="application/json">{"message":"Ready"}</script>
174
+ <p>{{message}}</p>
175
+ </template>
176
+ </sym-component>
177
+
178
+ <status-note></status-note>
179
+
180
+ <template id="task-item">
181
+ <label><input type="checkbox" bind="checked: done; onchange: [item-pub]done">Done</label>
182
+ <label>Title<input required bind="value: title; oninput: [item-pub]title"></label>
183
+ <button type="button" bind="onclick: [item-remove]">Delete</button>
184
+ </template>
185
+ <sym-component reg="task-item" use-template="#task-item"></sym-component>
186
+ ```
187
+
188
+ - A declaration stays hidden and does not render an instance or process its template actions. Registration upgrades existing instances too. Declarations in a rendered template are registered before Itemize consumes that template.
189
+ - Each instance has its own native context and JSON defaults. Instance JSON, incoming data and native `use-template` overrides retain precedence over declaration defaults.
190
+ - Template lookup checks the containing root before the document. A declaration's `use-template` takes precedence over a direct template. Names are validated by the Custom Elements registry. Identical declarations are idempotent; conflicting declarations or unrelated registered tags fail explicitly. Definitions are static for the page lifetime.
191
+ - Use `item-tag="task-item"` on an Itemize container to use the registered item. Generated items can instead reuse an extracted template directly: `<ul itemize="items" use-template="#task-item"></ul>`. A registered `item-tag` supplies its own template.
192
+
193
+ ## Conditional content
194
+
195
+ ```html
196
+ <sym-conditional when="APP/showDetails" is="true">
197
+ <label>Notes<textarea bind="value: APP/notes; oninput: [pub-to]APP/notes"></textarea></label>
198
+ </sym-conditional>
199
+ <sym-conditional when="APP/section" is="settings" behavior="dom-add">
200
+ <settings-panel></settings-panel>
201
+ </sym-conditional>
202
+ ```
203
+
204
+ - `when` references a declared native data property, including computed sources. Without `is`, matching uses truthiness. With `is`, matching is strict: `true` and `false` become booleans; other literals remain strings. Use `is-type="string"` to match the literal strings `true` or `false`.
205
+ - `behavior="show"` (the default) shows content when matched. `hide` hides it when matched. Both keep the same mounted content and unpublished control drafts.
206
+ - `dom-add` mounts when matched; `dom-remove` removes when matched. Both dispose inactive content immediately, including its actions, pending edits, subscriptions and owned contexts. A later mount creates fresh content from the authored template.
207
+ - Inactive content is hidden and inert. Local bindings retain the conditional owner's context. Nested components keep their own contexts. Attribute changes rebind the condition without retaining old subscriptions.
208
+ - Native `use-template` and `process-inner-html="false"` remain available. No expression evaluation, additional styling or action-chain syntax is introduced.
209
+
210
+ ## Declarative routing
211
+
212
+ `sym-router` configures the existing [AppRouter](../docs/routing.md) from HTML. [The full app](./examples/full-app.html) loads feature sections through reusable templates and imports, while keeping shared contexts mounted without application JavaScript.
213
+
214
+ ```html
215
+ <sym-router ctx="ROUTER">
216
+ <script type="application/json">
217
+ {
218
+ "routes": {
219
+ "tasks": {
220
+ "title": "Tasks",
221
+ "src": "./views/tasks.html",
222
+ "default": true
223
+ },
224
+ "settings": {
225
+ "title": "Settings",
226
+ "src": "./views/settings.html"
227
+ },
228
+ "notFound": {
229
+ "title": "Page not found",
230
+ "src": "./views/not-found.html",
231
+ "error": true
232
+ }
233
+ }
234
+ }
235
+ </script>
236
+ <h1>{{title}}</h1>
237
+ <nav aria-label="Pages">
238
+ <a href="?tasks" bind="onclick: [navigate]ROUTER">Tasks</a>
239
+ <a href="?settings" bind="onclick: [navigate]ROUTER">Settings</a>
240
+ </nav>
241
+ <sym-import bind="@src: ROUTER/+src"></sym-import>
242
+ </sym-router>
243
+ ```
244
+
245
+ - Supply a nonempty `routes` object through inline JSON, native `use-template` defaults, incoming `$` bindings, or `src="./routes.json"` returning `{"routes": {...}}`. With `src` alone, routing waits for validated data and preserves the requested URL; inherited `+loading`, `+loadError` and `[load]ROUTER` provide status and retry. Use the native `title`, `default`, `error` and optional `pattern` fields. Titles and optional fragment `src` values are strings, flags are booleans, and each route may include JSON metadata. Executable `load` functions and module URLs are not part of this HTML API; compose `sym-import` explicitly instead.
246
+ - The required `ctx` name exposes native `route`, `options` and `title` state, including to components outside the router. Computed `+src` reads the selected route's declared `src` from the validated active map, independently of URL options. Bind it to one import's `@src` to replace views; supply a source for the error route too. Without a declared source, `+src` is an empty string and the importer retains its current content. Existing conditionals and extracted templates also work; the router adds no renderer. Reassign `routes` to replace configuration; nested object mutation does not notify.
247
+ - Computed `+params` provides scalar option fields with public data keys for safe native `$` object binding, such as `<sym-context bind="$: ROUTER/+params">`. It excludes context paths, binding prefixes, runtime keys and non-scalar metadata. Declare local defaults for optional parameters; consume values through text bindings or conditions. Native `options` remains available for inspection, while fragment URLs come from `+src`.
248
+ - Without patterns, AppRouter uses URLs such as `?settings`. For path routing, give every route an absolute pattern such as `/tasks/:id`; native matching populates `options`. Path mode requires your server to serve the app entry for those URLs. Use at most one default and one distinct error route.
249
+ - `[navigate]ROUTER` on a native button or select uses its string `value` as the route name. Optional `action-data="APP/parameters"` supplies a record of scalar URL options, including path parameters. A native form can validate and flush pending controls before navigating. Option objects are not mutated.
250
+ - Explicitly bound anchors retain useful `href` values. Plain internal clicks delegate URL matching and navigation to AppRouter; modifier clicks, new targets, downloads, external destinations, unknown routes and fragment links retain browser behavior. Query links to another document also keep normal navigation. Back/Forward uses the native popstate listener. Navigation actions await native guards/loaders, including through optional WebMCP.
251
+ - AppRouter is one application router. A second active `sym-router`, or an already configured independent native router, is rejected. Disconnecting releases its context listener, popstate handler and native map. A move reconnects the same owner; destruction releases its named context. Initialization does not enable WebMCP globally.
252
+ - URL options are input data. Keep template/import URLs and binding declarations authored rather than deriving them from unvalidated options. Native guards remain available to JavaScript integrations; no declarative guard language is added.
253
+
254
+ ## JSON sources and explicit synchronization
255
+
256
+ [The full app](./examples/full-app.html) demonstrates explicit JSON synchronization. Its endpoint accepts a tasks document such as `{"tasks":[]}`. Authorization and persistence belong to the host application.
257
+
258
+ ```html
259
+ <sym-context ctx="APP" src="/api/document" sync="/api/document" sync-keys="title">
260
+ <script type="application/json">{"title":""}</script>
261
+ <form bind="onsubmit: [sync]APP">
262
+ <label>Title
263
+ <input required bind="value: title; oninput: [pub-to-200]title">
264
+ </label>
265
+ <button type="submit" bind="disabled: APP/+busy">Save</button>
266
+ </form>
267
+ <button type="button" bind="onclick: [load]APP; disabled: APP/+busy">Reload</button>
268
+ <p role="alert" bind="textContent: APP/+syncErrorMessage"></p>
269
+ </sym-context>
270
+ ```
271
+
272
+ - `src` automatically loads a JSON object with GET. `[load]APP` refreshes the named provider explicitly. Named references can bind before fetched fields arrive; use named references for source-only properties because pop-up lookup requires a declared ancestor field.
273
+ - Inline JSON initializes defaults. Fetched values merge through native `$` and override unchanged defaults; omitted fields remain. Incoming object-binding keys, published edits and pending debounced edits stay authoritative. A successful `load` event reports `applied` and `retained` field names in its detail.
274
+ - A `[load]APP` control with `action-overwrite` explicitly replaces prior edited or restored fields with JSON source values. Incoming bound fields and edits made after the request starts remain protected. It does not change the browser save; fetch or validation failures leave the current data intact.
275
+ - `sync` alone never writes. `[sync]APP` clones the provider's public JSON data and sends PUT. `sync-method="POST"` or `PATCH` selects an existing endpoint contract. A 204 response or valid JSON acknowledges the submitted snapshot; response data is not merged into newer local edits.
276
+ - `sync-keys` selects comma-separated public fields. Omit it to save JSON fields supplied by defaults, fetched data, incoming merges or authored edits. Prefer an explicit selection when UI state shares the provider. Handler functions, descriptors, computed values and request metadata are excluded; invalid selected data fails before a request is sent.
277
+ - Save through a native form to validate controls and flush pending publications before the snapshot. Concurrent saves share the pending request; newer edits require another explicit save. Starting the other operation while loading or saving reports `BUSY`. Writes are never retried automatically.
278
+ - Request state uses reserved computed properties: `+loading`, `+saving`, `+busy`, `+dirty`, `+revision` and `+savedRevision`. Revisions track selected data changes; dirty state includes pending local edits. Only a successful write acknowledges a submitted revision. A late acknowledgment leaves newer edits dirty.
279
+ - `+loadError` and `+syncError` are separate structured errors with `operation`, `code`, `message` and nullable HTTP `status`. Their `+loadErrorMessage` and `+syncErrorMessage` counterparts are text bindings. Successful operations emit `load` or `sync`; failures emit `error`. Cancellation does not report a request failure.
280
+ - URL changes and disconnection abort active requests and ignore stale results. Useful data and drafts survive failures. Aborting a write stops client acknowledgment; it cannot undo a request already received by the server.
281
+ - URLs must use HTTP(S) without embedded credentials. Requests use same-origin credentials, normal browser CORS and no redirects. The default timeout is 15 seconds and maximum request/response size is 1 MiB; set positive integer `request-timeout` (milliseconds) and `max-bytes` limits when needed. Loading and saving are suppressed during SSR.
282
+ - Source and saved data follow the JSON-only field contract. Reserved keys, handler replacements and incompatible known value types are rejected. The endpoint remains responsible for authorization, application validation, persistence and CSRF protection.
283
+
284
+ ## HTML fragments
285
+
286
+ [The full app](./examples/full-app.html) imports every feature section on navigation. Its HTML imports section also loads a [nested fragment](./examples/assets/guide.html), whose control publishes back to the surrounding preferences context. It also restores selected browser data independently of the API.
287
+
288
+ ```html
289
+ <sym-import src="./examples/assets/guide.html">
290
+ <p>Loading guide...</p>
291
+ </sym-import>
292
+ ```
293
+
294
+ - `sym-import` fetches an authored HTML fragment and replaces its content through native Symbiote bindings. It adds no presentation styles. Local bindings share the import owner's context; nested components own their contexts normally. Incoming `$`, outgoing `pub-map`, context providers, declarations and Itemize work inside imported content.
295
+ - Local `+loading`, `+loadError` and `+loadErrorMessage` provide the same request-state shape as JSON loading. A successful `load` event includes the resolved `url`; failure emits `error`. Bind these events on the import element from its parent owner. Each load clears its previous error. Changing `src` or disconnecting aborts old requests; canceled results do not publish or emit errors.
296
+ - Request or template-validation failure retains the previous fragment and drafts. Successful replacement immediately disposes only the old fragment's actions, pending publications, references, subscriptions and named contexts. Outer bindings stay connected. `process-inner-html="false"` leaves the fragment's ordinary markup unprocessed while nested owners still initialize.
297
+ - Relative HTML URL attributes, source sets and nested JSON/import URLs resolve against the containing fragment URL. Fragment-only links such as `#panel` keep targeting the composed document. CSS `url()` values retain normal browser behavior; use absolute URLs in imported inline styles. Cycles fail explicitly, and nesting stops at 16 fragments.
298
+ - The shared Fetch limits, same-origin credentials, CORS and redirect rules apply. Responses must use `text/html`; imports do not run during SSR.
299
+ - Import only trusted application templates. Executable scripts, native `on*` attributes, executable URL schemes, embedded frames/plugins and document metadata are rejected, including inside templates. Inert `application/json` scripts are supported. HTTP(S) URL attributes are accepted; `href` also accepts `mailto:` and `tel:`. Declarative bindings and custom elements are active application behavior: these checks are not a sanitizer for arbitrary third-party HTML. Use a reviewed sanitization path for untrusted content instead.
300
+
301
+ ## Optional browser persistence
302
+
303
+ Opt in with both a storage key and an explicit comma-separated field list. Nothing is written automatically, and backend `sync` never falls back to browser storage.
304
+
305
+ ```html
306
+ <sym-context ctx="APP" storage-key="document-draft" storage-keys="title">
307
+ <script type="application/json">{"title":"Untitled"}</script>
308
+ <form bind="onsubmit: [persist]APP">
309
+ <label>Title
310
+ <input bind="value: title; oninput: [pub-to-200]title">
311
+ </label>
312
+ <button type="submit">Save in this browser</button>
313
+ </form>
314
+ <button type="button" bind="onclick: [restore]APP">Restore browser data</button>
315
+ <p role="alert" bind="textContent: +storageErrorMessage"></p>
316
+ <sym-conditional when="APP/+storageConflict">
317
+ <p>Another tab changed the saved data. Choose which version to keep.</p>
318
+ <button type="button" bind="onclick: [restore]APP">Use saved data</button>
319
+ <button type="button" action-overwrite bind="onclick: [persist]APP">Keep this draft</button>
320
+ </sym-conditional>
321
+ </sym-context>
322
+ ```
323
+
324
+ - On first connection, selected stored fields restore before `src` starts. Incoming `$` fields and edits or pending drafts win over stored fields; accepted stored fields win over fetched defaults; fetched data wins over inline defaults. A move or reconnection keeps the current draft and checks for intervening storage changes.
325
+ - `[persist]APP` writes only `storage-keys`. Use a native form to validate and flush debounced controls first; pending selected edits outside that form cause `PENDING_DRAFT` rather than saving an older value. Local persistence never clears backend dirty state or acknowledges `savedRevision`.
326
+ - `[restore]APP` explicitly accepts the selected stored fields, discarding their unbound drafts and canceling their pending publications. Incoming bound fields and unselected data remain. A missing entry retains current data. Restoring does not claim backend synchronization.
327
+ - `+storageFound` reports whether the last successful restore found a browser entry or a save created one. A missing entry reports false and leaves current data intact.
328
+ - `+storageDirty` tracks selected changes since local persistence/restoration, including pending edits. `+storageConflict` reports a changed storage entry without automatically replacing or merging data. `+storageError` has `operation`, `code`, `message` and null `status`; `+storageErrorMessage` is its text form. Successful operations emit `persist` or `restore`, and failures emit `error`.
329
+ - Normal persistence refuses changed or invalid entries. An explicit persist control with the boolean `action-overwrite` attribute replaces that entry deliberately. Other tabs receive conflicts through the native [storage event](https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event). A [Web Lock](https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API) serializes participating writers, while an atomic IndexedDB revision check rejects stale localStorage snapshots. Selected data stays in localStorage; IndexedDB holds only revision identifiers. Use the persistence API for writes so both stores stay coordinated.
330
+ - Persistence requires Web Locks in a secure context, such as HTTPS or loopback HTTP, and available IndexedDB revision coordination. Missing Web Locks reports `LOCK_UNAVAILABLE`; unavailable revision coordination reports `STORAGE_UNAVAILABLE`. No unsafe write fallback is selected. Blocked access, quota failures and invalid or incompatible envelopes leave current data intact. Reconfiguration, Restore and disconnection cancel queued writes.
331
+ - A normal restore accepts the saved envelope without writing it. If a raw storage entry is changed independently, or a page closes between reserving a revision and writing its envelope, saving may report a conflict until you review the data and explicitly overwrite it. A failed localStorage write releases its reservation before another save can proceed.
332
+ - The version-1 envelope contains `version`, a unique `revision`, `keys` and `data`. The property set must match `storage-keys` exactly, with compatible known field types. Invalid JSON, unsafe keys and incompatible versions fail visibly; there is no automatic migration. `max-bytes` also bounds storage envelopes, using the same 1 MiB default as requests.
333
+ - Storage is scoped to the browser origin and is accessible to that origin's scripts. Choose distinct application keys and select only appropriate non-secret data. This is optional local persistence, not backup, a database, or cross-device synchronization. Storage access is suppressed during SSR.
334
+
335
+ ## Server rendering and hydration
336
+
337
+ Use the native [SSR API](../docs/ssr.md) after initializing its DOM environment, then import the foundation. Inline JSON contexts, native templates and collections can render without browser requests. Put referenced templates before their consumers in the server input. Server rendering preserves authored action descriptors for client attachment; it does not invoke actions or read browser storage. JSON sources, HTML imports and routing start in the browser. Supply their initial data in the server markup when needed.
338
+
339
+ For templated owners and collections, select the native `ssrMode` flag on the client through a binding, for example `bind="ssrMode: APP/hydrate"` with `"hydrate": true` in the context's inline JSON. The server ignores this flag while rendering. Prefer explicit `textContent` bindings to text tokens for nodes that must react after hydration. Reuse the same templates and initial records on both sides; hydration retains the existing nodes and attaches item actions.
340
+
341
+ Each rendering request must release its context owners before tearing down the DOM environment:
342
+
343
+ ```js
344
+ import { SSR } from '@symbiotejs/symbiote/node';
345
+
346
+ await SSR.init();
347
+ let { BaseClass } = await import('@symbiotejs/symbiote/html-app');
348
+ let html;
349
+ try {
350
+ html = await SSR.processHtml(markup, {
351
+ nonce: responseNonce,
352
+ });
353
+ } finally {
354
+ let owners = [...document.querySelectorAll('*')].filter((element) => element instanceof BaseClass);
355
+ document.body.replaceChildren();
356
+ for (let owner of owners.reverse()) {
357
+ owner.destroy();
358
+ }
359
+ SSR.destroy();
360
+ }
361
+ ```
362
+
363
+ Use the native SSR lifecycle serially within a process; it owns global DOM state. Remote-data SSR, independently nested routers and arbitrary fragment hydration are outside this contract. `sym-import` renders its authored fallback on the server and fetches its content in the browser.
364
+
365
+ ## CSP and template trust
366
+
367
+ The foundation does not evaluate expressions or require inline executable scripts. Serve modules from origins allowed by `script-src` and data/fragments from origins allowed by `connect-src`. Inline `application/json` is inert data. A strict policy can omit both `unsafe-eval` and `unsafe-inline`; server-rendered styles need the native SSR nonce option. The Tailwind browser CDN in the styled example is for demonstration and has its own CSP requirements; use a static stylesheet under a production policy.
368
+
369
+ Imported HTML is trusted application code, including its bindings, custom elements and actions. Executable scripts, native event attributes and executable URLs are rejected, but these checks do not sanitize arbitrary third-party content. Render untrusted text through `textContent`. Keep the [core security contract](../docs/security.md), including Trusted Types, when integrating with a host. Verify the foundation's HTML parsing paths against your host's Trusted Types policy.