@gramlot/gramlot 0.2.20 → 0.3.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.
Files changed (60) hide show
  1. package/dist/gramlot.js +1343 -303
  2. package/dist/gramlot.min.js +363 -24
  3. package/package.json +6 -3
  4. package/src/binding/ask-dialog.js +2 -2
  5. package/src/binding/inline.js +3 -10
  6. package/src/binding/installation.js +2 -1
  7. package/src/binding/pointer.js +12 -148
  8. package/src/binding/providers.js +2 -1
  9. package/src/binding/runtime.js +2 -1
  10. package/src/bootstrap.d.ts +2 -0
  11. package/src/bootstrap.js +9 -2
  12. package/src/builder/gramlot-builder.js +21 -4
  13. package/src/builder/source.js +11 -10
  14. package/src/components/bases.js +182 -0
  15. package/src/components/buttons.js +254 -0
  16. package/src/components/choice-editor.js +221 -0
  17. package/src/components/choices.js +13 -0
  18. package/src/components/date-calendar.js +139 -0
  19. package/src/components/field-state.js +166 -0
  20. package/src/components/formlet-labels.js +80 -0
  21. package/src/components/index.js +5 -0
  22. package/src/components/inputs.js +196 -0
  23. package/src/components/labelbox.js +74 -0
  24. package/src/components/layout.js +190 -0
  25. package/src/components/parameters.js +6 -0
  26. package/src/components/popup.js +22 -0
  27. package/src/components/registry.js +83 -0
  28. package/src/components/typed-editor.js +260 -0
  29. package/src/components/validation.js +138 -0
  30. package/src/format.js +13 -6
  31. package/src/gramlot.d.ts +5 -1
  32. package/src/gramlot.js +8 -1
  33. package/src/handlers/dom-handler.d.ts +1 -0
  34. package/src/handlers/dom-handler.js +7 -0
  35. package/src/index-page-runtime.js +78 -30
  36. package/src/index-page-styles.js +2 -2
  37. package/src/index-theme.js +1 -1
  38. package/src/renderer/attributes.js +3 -40
  39. package/src/renderer/gramlot-html-renderer.js +4 -3
  40. package/src/renderer/gramlot-renderer.js +62 -4
  41. package/src/server/gramlot-server.d.ts +3 -0
  42. package/src/server/gramlot-server.js +9 -3
  43. package/src/server/index-page.d.ts +1 -0
  44. package/src/server/index-page.js +8 -3
  45. package/src/server/page-base.js +1 -0
  46. package/src/server/page.d.ts +1 -0
  47. package/src/server/resources.d.ts +2 -0
  48. package/src/view/button.js +17 -13
  49. package/src/view/controls.js +152 -4
  50. package/src/view/html.js +18 -0
  51. package/themes/gramlot-base/README.md +6 -0
  52. package/themes/gramlot-base/theme.css +34 -6
  53. package/themes/gramlot-compact/README.md +6 -0
  54. package/themes/gramlot-compact/theme.css +8 -4
  55. package/themes/joanna/README.md +23 -0
  56. package/themes/joanna/theme.css +89 -0
  57. package/themes/mimi/README.md +23 -0
  58. package/themes/mimi/theme.css +89 -0
  59. package/tools/gramlot-tools-inspector.js +42 -18
  60. package/tools/inspector-agent.js +8 -4
@@ -28,6 +28,8 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
28
28
  #resolvedAttributes = new WeakMap();
29
29
  // The resolved projection that `project` hands to the rebuild of a control whose shape changed.
30
30
  #rebuildAttributes = new WeakMap();
31
+ // Own presentation defaults, resolved once in their declaring Source scope.
32
+ #presentationDefaults = new WeakMap();
31
33
 
32
34
  /** The live renderer of one Gramlot page: `binding` is the page's BindingRuntime (§4.3). */
33
35
  constructor(builder, source, destination, {binding} = {}) {
@@ -66,7 +68,20 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
66
68
  * its `==` are evaluated once.
67
69
  */
68
70
  evaluateExpressions(node, runtimeAttrs) {
69
- const attrs = this.#rebuildAttributes.get(node) ?? super.evaluateExpressions(node, runtimeAttrs);
71
+ let attrs = this.#rebuildAttributes.get(node) ?? super.evaluateExpressions(node, runtimeAttrs);
72
+ const component = node._getMeta('gramlot_component');
73
+ if (component?.presentationDefaults.length) {
74
+ const declared = node.getAttr();
75
+ this.#presentationDefaults.set(node, Object.fromEntries(Object.entries(attrs)
76
+ .filter(([name]) => Object.hasOwn(declared, name) && component.presentationDefaults.some(prefix => name.startsWith(prefix)))));
77
+ }
78
+ if (component && (component.parameters.value?.binding === 'twoWay' || component.presentationDefaults.length)) {
79
+ const ancestors = [];
80
+ for (let parent = node.parentNode; parent; parent = parent.parentNode) {
81
+ if (this.#presentationDefaults.has(parent)) ancestors.unshift(this.#presentationDefaults.get(parent));
82
+ }
83
+ attrs = Object.assign({}, ...ancestors, attrs);
84
+ }
70
85
  this.#rebuildAttributes.delete(node);
71
86
  this.#resolvedAttributes.set(node, attrs);
72
87
  return attrs;
@@ -125,9 +140,12 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
125
140
  let attrs = runtimeAttrs;
126
141
  item = this.expressionValue(node, item);
127
142
  if (this.getRender(node.builder) === this) {
128
- [item, attrs] = displayItem(item, this.restoreNativeAttributes(node, runtimeAttrs),
143
+ attrs = this.restoreNativeAttributes(node, runtimeAttrs);
144
+ // Component parameters (including format/locale/dtype) belong to its editor.
145
+ if (!node._getMeta('gramlot_component')) [item, attrs] = displayItem(item, attrs,
129
146
  (value, options) => this._binding.gramlot.format(value, options));
130
147
  }
148
+ attrs = this.componentAttributes(node, attrs);
131
149
  const children = Array.isArray(item) ? item : [];
132
150
  const text = Array.isArray(item) ? attrs._text : item;
133
151
  const resolved = this.#resolvedAttributes.get(node);
@@ -458,6 +476,7 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
458
476
  const record = this.records.get(node);
459
477
  if (!record?.element) return;
460
478
  const renderer = this.getRender(node.builder);
479
+ const previousDefaults = this.#presentationDefaults.get(node);
461
480
  const [value, runtimeAttrs] = node.builder.runtimeValues(node);
462
481
  const [, resolvedAttrs] = renderer._handleMeta(node, runtimeAttrs);
463
482
  const resolved = this.#resolvedAttributes.get(node);
@@ -472,18 +491,55 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
472
491
  let attrs = node._getMeta('subbuilder') ? resolvedAttrs : renderer.adaptAttrs(resolvedAttrs);
473
492
  const branch = node.value instanceof SourceBag;
474
493
  let text = branch ? [] : this.expressionValue(node, value);
475
- if (renderer === this) [text, attrs] = displayItem(text, this.restoreNativeAttributes(node, attrs),
476
- (value, options) => this._binding.gramlot.format(value, options));
494
+ if (renderer === this) {
495
+ attrs = this.restoreNativeAttributes(node, attrs);
496
+ if (!node._getMeta('gramlot_component')) [text, attrs] = displayItem(text, attrs,
497
+ (value, options) => this._binding.gramlot.format(value, options));
498
+ }
499
+ attrs = this.componentAttributes(node, attrs);
477
500
  this.html.update(record, node, attrs, branch ? attrs._text : text, resolved.visible ?? null);
478
501
  this.#projectControl(record, node, attrs, change);
479
502
  record.control?.refresh();
480
503
  record.button?.refresh();
481
504
  this.#connectEvents(record);
505
+ const defaults = this.#presentationDefaults.get(node);
506
+ if (defaults) {
507
+ const changed = new Set([...Object.keys(previousDefaults ?? {}), ...Object.keys(defaults)]
508
+ .filter(name => !Object.is(previousDefaults?.[name], defaults[name])));
509
+ if (changed.size) this.#refreshPresentation(node, changed);
510
+ }
482
511
  if (record.element.localName === 'option' || record.element.localName === 'optgroup') {
483
512
  this.#optionsChanged(record.parent);
484
513
  }
485
514
  }
486
515
 
516
+ /** Only affected consumers project; nested providers mask their own declared defaults. */
517
+ #refreshPresentation(parent, changed) {
518
+ if (!(parent.value instanceof SourceBag)) return;
519
+ for (const child of parent.value.getNodes()) {
520
+ const component = child._getMeta('gramlot_component');
521
+ const declared = child.getAttr();
522
+ let inherited = changed;
523
+ if (component?.presentationDefaults.length) {
524
+ inherited = new Set([...changed].filter(name => !Object.hasOwn(declared, name)));
525
+ } else if (component?.parameters.value?.binding === 'twoWay'
526
+ && [...changed].some(name => !Object.hasOwn(declared, name))) {
527
+ this.project(child);
528
+ }
529
+ if (inherited.size) this.#refreshPresentation(child, inherited);
530
+ }
531
+ }
532
+
533
+ /** Component parameters use resolved Source values, before HTML-only filtering (e.g. validate_*). */
534
+ componentAttributes(node, attrs) {
535
+ const component = node._getMeta('gramlot_component');
536
+ if (!component) return attrs;
537
+ const resolved = this.#resolvedAttributes.get(node);
538
+ const parameters = Object.fromEntries([...new Set([...Object.keys(component.parameters), ...Object.keys(resolved).filter(name => name.startsWith('validate_'))])]
539
+ .filter(name => Object.hasOwn(resolved, name)).map(name => [name, resolved[name]]));
540
+ return {...attrs, ...parameters};
541
+ }
542
+
487
543
  /**
488
544
  * The resolved `value` to the ControlAdapter of `record` when the node declares a `value`, or declared
489
545
  * one at the previous projection: its removal shows the control empty once, as html.js did (S10).
@@ -610,6 +666,8 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
610
666
  record.end?.remove();
611
667
  record.parent?.children.delete(node);
612
668
  this.records.delete(node);
669
+ this.#resolvedAttributes.delete(node);
670
+ this.#presentationDefaults.delete(node);
613
671
  if (errors.length) throw new AggregateError(errors, 'Source cleanup failed');
614
672
  }
615
673
 
@@ -58,10 +58,13 @@ export interface GramlotServerOptions {
58
58
  pageTtl?: number;
59
59
  /** Maximum number of registered pages. */
60
60
  maxPages?: number;
61
+ /** Application collections: generated Builder grammar and root-relative browser module URL. */
62
+ collections?: {grammar: Record<string, unknown>; module: string}[];
61
63
  }
62
64
 
63
65
  /** The result of `registerPage`. */
64
66
  export interface RegisteredPage {
67
+ devices?: Array<'desktop' | 'tablet' | 'phone'>;
65
68
  locale?: string;
66
69
  timeZone?: string;
67
70
  /** The id of the registered page. */
@@ -64,7 +64,7 @@ const prefixed = (prefix, url) => url.startsWith('/') && !url.startsWith('//') ?
64
64
  */
65
65
  export class GramlotServer {
66
66
  constructor({runtimeUrl = '/assets/gramlot.js', rpcUrl = '/gramlot/rpc', closeUrl = '/gramlot/close',
67
- rootId = 'gramlot-root', pageTtl = 1800, maxPages = 1000} = {}) {
67
+ rootId = 'gramlot-root', pageTtl = 1800, maxPages = 1000, collections = []} = {}) {
68
68
  if (typeof pageTtl !== 'number' || pageTtl <= 0 ||
69
69
  !Number.isFinite(performance.now() + pageTtl * 1000) ||
70
70
  !Number.isSafeInteger(maxPages) || maxPages < 1) {
@@ -72,6 +72,7 @@ export class GramlotServer {
72
72
  }
73
73
  Object.assign(this, {runtimeUrl, rpcUrl, closeUrl, rootId, pageTtl, maxPages});
74
74
  this.pages = new Map();
75
+ this.collections = [...collections];
75
76
  }
76
77
 
77
78
  /** The Page class of path, or PageNotFound. */
@@ -122,11 +123,13 @@ export class GramlotServer {
122
123
  throw new TypeError('Page modules must export a subclass of Page');
123
124
  }
124
125
  const resources = loadOrder(await this.resolveResources(path, PageClass));
126
+ if (this.collections.length) resources.collections = this.collections.map(item => item.module);
125
127
  this.prune();
126
128
  if (this.pages.size >= this.maxPages) throw new ServerCapacity('Page registry capacity reached');
127
129
  const pageId = crypto.randomUUID().replaceAll('-', '');
128
130
  this.pages.set(pageId, {PageClass, owner, expires: performance.now() + this.pageTtl * 1000});
129
131
  return {pageId, title: PageClass.title, resources,
132
+ ...(PageClass.devices.length ? {devices: [...PageClass.devices]} : {}),
130
133
  ...(PageClass.locale == null ? {} : {locale: PageClass.locale}),
131
134
  ...(PageClass.timeZone == null ? {} : {timeZone: PageClass.timeZone})};
132
135
  }
@@ -135,15 +138,17 @@ export class GramlotServer {
135
138
  * by the adapter, added once to the root-relative bootstrap URLs. */
136
139
  async openPage(path, {owner = null, prefix = ''} = {}) {
137
140
  if (typeof prefix !== 'string') throw new TypeError('Mount prefix must be a string');
138
- const {pageId, title, resources, locale, timeZone} = await this.registerPage(path, {owner});
141
+ const {pageId, title, resources, locale, timeZone, devices} = await this.registerPage(path, {owner});
139
142
  try {
140
143
  const nonce = createNonce();
141
144
  // The CSS links and the JS modules reach the page through PageBootstrap (§4.12, D9).
142
145
  const bootstrap = scriptJson({
143
146
  config: {pageId, rpcUrl: prefixed(prefix, this.rpcUrl), closeUrl: prefixed(prefix, this.closeUrl),
144
147
  rootId: this.rootId, capabilities: this.capabilities,
148
+ ...(devices === undefined ? {} : {devices}),
145
149
  ...(locale === undefined ? {} : {locale}), ...(timeZone === undefined ? {} : {timeZone})},
146
- resources: {css: resources.css.map(url => prefixed(prefix, url)),
150
+ resources: {...(resources.collections ? {collections: resources.collections.map(url => prefixed(prefix, url))} : {}),
151
+ css: resources.css.map(url => prefixed(prefix, url)),
147
152
  js: resources.js.map(({url, group}) => ({url: prefixed(prefix, url), group}))},
148
153
  });
149
154
  const document = new GramlotBuilder();
@@ -214,6 +219,7 @@ export class GramlotServer {
214
219
  if (!source) return callable.call(page, params);
215
220
  const builder = new record.PageClass.sourceBuilder(name,
216
221
  {auth: elementRule => this.#authOutcome(elementRule, owner)});
222
+ for (const collection of this.collections) builder.loadCollection(collection.grammar);
217
223
  const result = await callable.call(page, builder.root, params);
218
224
  if (result !== undefined && result !== null) throw new TypeError('Source methods populate root and return no value');
219
225
  return builder.toTytx();
@@ -9,6 +9,7 @@ export class IndexPage extends Page {
9
9
  introduction(pane: any): void;
10
10
  groupPanel(pane: any, group: IndexGroup): void;
11
11
  panel(pane: any, item: IndexItem): void;
12
+ header(shell: any): void;
12
13
  footer(pane: any): void;
13
14
  behavior(pane: any): void;
14
15
  }
@@ -12,6 +12,7 @@ export class IndexPage extends GramlotPage {
12
12
  main(root) {
13
13
  const families = this.constructor.navigation;
14
14
  const shell = root.div({class: 'index-shell', id: this.constructor.shellId});
15
+ this.header(shell);
15
16
  const sidebar = shell.aside({class: 'index-sidebar', id: 'index-sidebar'});
16
17
  const brand = sidebar.header();
17
18
  if (this.constructor.logoUrl) brand.img({src: this.constructor.logoUrl, alt: this.constructor.title, class: 'index-logo'});
@@ -33,12 +34,12 @@ export class IndexPage extends GramlotPage {
33
34
  aria_valuemin: 120, aria_valuemax: 460, aria_valuenow: 240});
34
35
  const content = shell.main({class: 'index-main'});
35
36
  const tabs = content.div({class: 'index-tabs', role: 'tablist', aria_label: 'Open pages'});
36
- tabs.button('Introduction', {type: 'button', role: 'tab', id: 'tab-intro',
37
+ tabs.html_button('Introduction', {type: 'button', role: 'tab', id: 'tab-intro',
37
38
  aria_controls: 'panel-intro',
38
39
  aria_selected: 'true', tabindex: -1, hidden: false});
39
40
  for (const family of families) {
40
41
  for (const {key, title} of [family, ...family.children]) {
41
- tabs.button(title, {type: 'button', role: 'tab', id: `tab-${key}`,
42
+ tabs.html_button(title, {type: 'button', role: 'tab', id: `tab-${key}`,
42
43
  aria_controls: `panel-${key}`,
43
44
  aria_selected: 'false', tabindex: -1, hidden: true});
44
45
  }
@@ -61,6 +62,8 @@ export class IndexPage extends GramlotPage {
61
62
  this.behavior(shell);
62
63
  }
63
64
 
65
+ header(shell) {}
66
+
64
67
  behavior(shell) {
65
68
  shell.dataController({func: 'indexMount', _onStart: true, shell_id: this.constructor.shellId});
66
69
  }
@@ -75,6 +78,8 @@ export class IndexPage extends GramlotPage {
75
78
  const appearance = theme.select({id: 'index-appearance', value: 'compact'});
76
79
  appearance.option('Base', {value: 'base', selected: false});
77
80
  appearance.option('Compact', {value: 'compact', selected: true});
81
+ appearance.option('mimi', {value: 'mimi'});
82
+ appearance.option('joanna', {value: 'joanna'});
78
83
  const color = footer.div({class: 'index-theme'});
79
84
  color.html_label('Color mode', {for: 'index-theme'});
80
85
  const choices = color.select({id: 'index-theme', value: 'light'});
@@ -88,7 +93,7 @@ export class IndexPage extends GramlotPage {
88
93
  if (this.constructor.installable) {
89
94
  const app = footer.details({class: 'index-install'});
90
95
  app.summary('Install app');
91
- app.button('Install', {type: 'button', id: 'index-install-button', hidden: true});
96
+ app.html_button('Install', {type: 'button', id: 'index-install-button', hidden: true});
92
97
  app.p('', {id: 'index-install-status', role: 'status'});
93
98
  app.p('Chrome: use Install page as app in the browser menu. Safari on macOS Sonoma or later: File > Add to Dock.');
94
99
  app.p('Use HTTPS or localhost. For a static export, serve the directory; direct file opening is not installable. Keep the server running for hosted pages.');
@@ -48,6 +48,7 @@ function declare(PageClass, methodName, marker, auth) {
48
48
  /** Server-side page base; unrelated to browser view components. */
49
49
  export class Page {
50
50
  static title = 'Gramlot';
51
+ static devices = [];
51
52
  static locale = null;
52
53
  static timeZone = null;
53
54
  static installable = false;
@@ -19,6 +19,7 @@ export function endpointMethod(page: Page, name: string): Function | null;
19
19
  export class Page {
20
20
  /** The title of the page document. */
21
21
  static title: string;
22
+ static devices: Array<'desktop' | 'tablet' | 'phone'>;
22
23
  static locale: string | null;
23
24
  static timeZone: string | null;
24
25
  static installable: boolean;
@@ -22,6 +22,8 @@ export function parseRequires(text: string): string[];
22
22
  export interface Resources {
23
23
  /** CSS URLs. */
24
24
  css: string[];
25
+ /** Application collection module URLs, added by GramlotServer. */
26
+ collections?: string[];
25
27
  /** JS module URLs with their Logic group. */
26
28
  js: {url: string; group: string | null}[];
27
29
  }
@@ -1,16 +1,9 @@
1
- /**
2
- * The click of a `<button>` (source plan §2 Button, §4.11, S12). One mechanism per button (P10): the
3
- * `dataController` or `dataRpc` nested in it, `action`, or the `fire`/`fire_*` family. The nested
4
- * provider is a normal ControllerProvider or RpcProvider (B7); the click is one more trigger. Controller, `action` and counter use
5
- * the button's own node, also when the click hits a descendant (R11).
6
- *
7
- * R3, provisional: only a button with a mechanism gets `type="button"` when the author wrote no
8
- * `type`, and its click stops propagating; no `preventDefault`. A button without a mechanism stays
9
- * native. A closed NodeBinding does nothing (R12).
1
+ /** Shared command engine for the built-in button components (GC-310 §045).
2
+ * One action, nested provider or fire mechanism. Components own presentation and
3
+ * target selection; this binding owns execution, ask, delay and disposal.
10
4
  */
11
5
 
12
6
  import {AskDialog} from '../binding/ask-dialog.js';
13
- import {XHTML_NS} from '../renderer/attributes.js';
14
7
 
15
8
  export class ButtonBinding {
16
9
  #binding;
@@ -21,7 +14,7 @@ export class ButtonBinding {
21
14
  /** The binding of a Gramlot button; html_button remains native despite its DOM tag. */
22
15
  static for(binding, record) {
23
16
  const element = record.element;
24
- if (binding.node.nodeTag !== 'button' || element?.namespaceURI !== XHTML_NS || element.localName !== 'button') return null;
17
+ if (!element?.constructor.gramlotComponent?.command) return null;
25
18
  return new ButtonBinding(binding, record);
26
19
  }
27
20
 
@@ -65,6 +58,8 @@ export class ButtonBinding {
65
58
  /** Check the mechanism, apply R3's `type`, then listen to `click`. */
66
59
  attach() {
67
60
  this.refresh();
61
+ this.element.activateCommand = event => this.onClick(event);
62
+ this.element.attachCommand();
68
63
  this.element.addEventListener('click', this);
69
64
  }
70
65
 
@@ -81,6 +76,8 @@ export class ButtonBinding {
81
76
 
82
77
  detach() {
83
78
  this.element.removeEventListener('click', this);
79
+ this.element.releaseCommand();
80
+ delete this.element.activateCommand;
84
81
  this.#cancelDelay?.();
85
82
  }
86
83
 
@@ -94,7 +91,14 @@ export class ButtonBinding {
94
91
  * the mechanism. An error propagates from the listener.
95
92
  */
96
93
  onClick(event) {
97
- if (this.binding.closed) return;
94
+ if (this.binding.closed || this.element.disabled) return;
95
+ const target = this.element.commandTarget(event);
96
+ if (target === null) return;
97
+ if (target !== this.element) {
98
+ event.stopPropagation();
99
+ return target.activateCommand(event);
100
+ }
101
+ if (!this.element.prepareCommand(event)) return;
98
102
  const mechanism = this.mechanism;
99
103
  if (!mechanism) return;
100
104
  event.stopPropagation();
@@ -144,7 +148,7 @@ export class ButtonBinding {
144
148
  return {...this.binding.runtime.renderer.references.resolveArguments(authored), event, _counter: counter, modifiers};
145
149
  };
146
150
  const execute = result => {
147
- if (this.binding.closed || result === null) return;
151
+ if (this.binding.closed || this.element.disabled || result === null) return;
148
152
  const values = {...read(), ...result};
149
153
  if (result) values._askResult = result;
150
154
  this.binding.runtime.inlineCompiler.compile(node, 'action', node.getAttr('action'), Object.keys(values))(values);
@@ -5,6 +5,8 @@
5
5
  * Checkbox and radio consume `value` as a boolean; RadioGroups gives the radios of a group their name.
6
6
  */
7
7
 
8
+ import {createDecimal, isDecimal, getDecimalLibrary} from '@genrojs/tytx';
9
+ import {Bag} from '@genrojs/bag';
8
10
  import {XHTML_NS} from '../renderer/attributes.js';
9
11
 
10
12
  // The elements whose `type`, `multiple` and `group` have no setter: a change rebuilds (C04.1, D7).
@@ -22,6 +24,9 @@ export class ControlAdapter {
22
24
  static liveWrites = false;
23
25
  // Whether a literal `value` is also written as the default a native form Reset restores.
24
26
  static writesDefault = true;
27
+ static preservesUnchangedValue = false;
28
+ #projectedValue;
29
+ #hasProjectedValue = false;
25
30
  #binding;
26
31
  #record;
27
32
  #committing = false;
@@ -41,6 +46,10 @@ export class ControlAdapter {
41
46
  */
42
47
  static classFor(element, attrs) {
43
48
  if (element.namespaceURI !== XHTML_NS) return null;
49
+ if (element.constructor.gramlotComponent) {
50
+ if (element.constructor.gramlotComponent.parameters.value?.binding !== 'twoWay') return null;
51
+ return element.control.type === 'radio' ? ComponentRadioControl : ComponentControl;
52
+ }
44
53
  if (element.localName === 'textarea') return TextControl;
45
54
  if (element.localName === 'select') return SelectControl;
46
55
  if (element.localName !== 'input') return null;
@@ -54,6 +63,7 @@ export class ControlAdapter {
54
63
  * `attrs` are the attributes of the renderer's resolved projection (`^`, `=` and `==` resolved).
55
64
  */
56
65
  static shape(element, attrs) {
66
+ if (element?.constructor.gramlotComponent?.parameters.value?.binding === 'twoWay' && element.control.type === 'radio') return JSON.stringify([attrs.group ?? null]);
57
67
  if (element?.namespaceURI !== XHTML_NS || !CONTROL_TAGS.has(element.localName)) return null;
58
68
  return JSON.stringify(REBUILD_ATTRIBUTES.map(name => attrs[name] ?? null));
59
69
  }
@@ -66,6 +76,7 @@ export class ControlAdapter {
66
76
  get binding() { return this.#binding; }
67
77
  get element() { return this.#record.element; }
68
78
  get node() { return this.binding.node; }
79
+ get eventElement() { return this.element; }
69
80
  /** The attributes of the last resolved projection of the node (`^`, `=` and `==` resolved). */
70
81
  get resolved() { return this.#record.resolved; }
71
82
  /**
@@ -88,6 +99,9 @@ export class ControlAdapter {
88
99
  this.#pending = true;
89
100
  return;
90
101
  }
102
+ if (this.constructor.preservesUnchangedValue && this.#hasProjectedValue && this.same(this.#projectedValue, value)) return;
103
+ this.#projectedValue = value;
104
+ this.#hasProjectedValue = true;
91
105
  if (this.#committing && this.same(this.read(), value)) return;
92
106
  if (this.constructor.writesDefault && !this.node.pointerType(this.node.getAttr('value'))) {
93
107
  this.writeDefault(value);
@@ -129,13 +143,13 @@ export class ControlAdapter {
129
143
  * input and writes nothing (gate decision 5); a null path raises from the listener (Q7). A closed
130
144
  * NodeBinding writes nothing (R12).
131
145
  */
132
- commit(event) {
146
+ commit(event, value = this.read()) {
133
147
  if (this.binding.closed) return;
134
148
  const pointer = this.node.getAttr('value');
135
149
  if (this.node.pointerType(pointer) !== '^') return;
136
150
  this.#committing = true;
137
151
  try {
138
- this.node.setRelativeData(pointer.slice(1), this.read());
152
+ this.node.setRelativeData(pointer.slice(1), value);
139
153
  } finally {
140
154
  this.#committing = false;
141
155
  }
@@ -143,13 +157,13 @@ export class ControlAdapter {
143
157
 
144
158
  attach() {
145
159
  for (const type of ['input', 'change', 'compositionstart', 'compositionend']) {
146
- this.element.addEventListener(type, this);
160
+ this.eventElement.addEventListener(type, this);
147
161
  }
148
162
  }
149
163
 
150
164
  detach() {
151
165
  for (const type of ['input', 'change', 'compositionstart', 'compositionend']) {
152
- this.element.removeEventListener(type, this);
166
+ this.eventElement.removeEventListener(type, this);
153
167
  }
154
168
  this.#pending = false;
155
169
  }
@@ -181,6 +195,41 @@ export class ControlAdapter {
181
195
  }
182
196
  }
183
197
 
198
+ /** Custom controls share the existing typed commit, IME and cleanup machinery. */
199
+ class ComponentControl extends ControlAdapter {
200
+ static writesDefault = false;
201
+ static preservesUnchangedValue = true;
202
+ get eventElement() { return this.element.control; }
203
+ attach() {
204
+ this.element.setPageContext(componentContext(this));
205
+ super.attach();
206
+ }
207
+ project(value, change) {
208
+ if (this.element.shouldProjectControlValue(value)) super.project(value, change);
209
+ }
210
+ same(a, b) { return this.element.sameControlValue(a, b); }
211
+ detach() { this.element.releaseControl(); super.detach(); }
212
+ commit(event) {
213
+ if (this.binding.closed || this.element.control.disabled || this.element.control.readOnly) return;
214
+ commitComponent(this.element, this.element.acceptControlValue(), result => super.commit(event, result.value));
215
+ }
216
+ get writeEvent() {
217
+ if (this.element.commitOnChange) return 'change';
218
+ const control = this.element.control;
219
+ return this.live && (control.localName === 'textarea' || ['text', 'password', 'range', 'color'].includes(control.type)) ? 'input' : 'change';
220
+ }
221
+ read() { return this.element.readControlValue(); }
222
+ write(value) { this.element.writeControlValue(value); }
223
+ handleEvent(event) {
224
+ super.handleEvent(event);
225
+ // Native change does not cross a shadow boundary; expose it to connect_onchange.
226
+ if (!event.composed && !this.binding.closed && ['input', 'change'].includes(event.type)) {
227
+ const Event = this.element.ownerDocument.defaultView.Event;
228
+ this.element.dispatchEvent(new Event(event.type, {bubbles: true, composed: true}));
229
+ }
230
+ }
231
+ }
232
+
184
233
  /** text, password, email, url, tel, search, textarea: a string; the empty string stays. */
185
234
  export class TextControl extends ControlAdapter {
186
235
  static liveWrites = true;
@@ -395,6 +444,54 @@ export class RadioControl extends CheckboxControl {
395
444
  }
396
445
  }
397
446
 
447
+ /** A single radio component joins the same Source-scoped groups as native radios. */
448
+ class ComponentRadioControl extends RadioControl {
449
+ static writesDefault = false;
450
+ get host() { return super.element; }
451
+ get element() { return this.host.control; }
452
+ project(value, change) {
453
+ if (this.host.shouldProjectControlValue(value)) super.project(value, change);
454
+ }
455
+ commit(event) {
456
+ if (this.binding.closed || this.element.disabled || this.element.readOnly) return;
457
+ commitComponent(this.host, this.host.acceptControlValue(), () => super.commit(event));
458
+ }
459
+ read() { return this.host.readControlValue(); }
460
+ write(value) { this.host.writeControlValue(value); }
461
+ attach() {
462
+ this.host.setPageContext(componentContext(this));
463
+ super.attach();
464
+ this.element.addEventListener('keydown', this);
465
+ }
466
+ detach() {
467
+ this.host.releaseControl();
468
+ this.element.removeEventListener('keydown', this);
469
+ super.detach();
470
+ }
471
+ handleEvent(event) {
472
+ if (this.binding.closed) return;
473
+ // Separate shadow roots cannot use the browser's same-tree radio navigation.
474
+ if (event.type === 'keydown') {
475
+ if (this.resolved.group == null || !['ArrowLeft', 'ArrowUp', 'ArrowRight', 'ArrowDown'].includes(event.key)) return;
476
+ const peers = this.groups.peersOf(this.resolved.group, formNode(this.node))
477
+ .filter(peer => !peer.binding.closed && !peer.element.disabled);
478
+ const index = peers.indexOf(this);
479
+ if (index < 0) return;
480
+ event.preventDefault();
481
+ const delta = ['ArrowLeft', 'ArrowUp'].includes(event.key) ? -1 : 1;
482
+ const next = peers[(index + delta + peers.length) % peers.length];
483
+ next.element.focus();
484
+ next.element.click();
485
+ return;
486
+ }
487
+ super.handleEvent(event);
488
+ if (!event.composed && !this.binding.closed && ['input', 'change'].includes(event.type)) {
489
+ const Event = this.host.ownerDocument.defaultView.Event;
490
+ this.host.dispatchEvent(new Event(event.type, {bubbles: true, composed: true}));
491
+ }
492
+ }
493
+ }
494
+
398
495
  /**
399
496
  * The radio groups of one live renderer (P11). A group is the `group` value within its form: the
400
497
  * nearest Source ancestor with `formId` or `form=true`, or none. The generated `name` joins the
@@ -467,3 +564,54 @@ const INPUT_CONTROLS = {
467
564
  hidden: null, file: null,
468
565
  button: null, submit: null, reset: null, image: null,
469
566
  };
567
+
568
+
569
+ /** Component validation uses the same Source, activated code and RPC services as controllers. */
570
+ function componentContext(adapter) {
571
+ const {binding, node} = adapter, app = binding.runtime.gramlot;
572
+ const invoke = (attribute, code, keywords, expression = false) => {
573
+ if (!expression && /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(code)) {
574
+ const {group, method} = app.src.logicRegistry.resolve(code, node);
575
+ return method.call(group, node, keywords);
576
+ }
577
+ return binding.runtime.inlineCompiler.compile(node, attribute, code, Object.keys(keywords),
578
+ expression ? `return (${code});` : code)(keywords);
579
+ };
580
+ return {
581
+ locale:app.locale, timeZone:app.timeZone, createDecimal, isDecimal, getDecimalLibrary,
582
+ isActive:() => !binding.closed,
583
+ callLogic:(name, keywords) => {
584
+ const {group, method} = app.src.logicRegistry.resolve(name, node);
585
+ return method.call(group, node, keywords);
586
+ },
587
+ format:(value, options) => app.format(value, options), invoke,
588
+ remote:(method, keywords, signal) => app.rpc.call('data', method, keywords, {signal}),
589
+ validationCurrent:() => {
590
+ const pointer = node.getAttr('value');
591
+ const path = node.pointerType(pointer) ? node.absDatapath(pointer) : null;
592
+ return () => !binding.closed && node.getAttr('value') === pointer && (path === null || node.absDatapath(pointer) === path);
593
+ },
594
+ finishValidation:({ok, result, rules}) => {
595
+ if (binding.closed) return;
596
+ if (ok) for (const patch of result.datachanges) node.getRelativeData('.').update(patch);
597
+ const attribute = ok ? 'validate_onAccept' : 'validate_onReject';
598
+ if (rules[attribute]) {
599
+ const report = error => console.error('Validation notification failed:', error);
600
+ try {
601
+ const validations = Object.fromEntries(Object.entries(rules).map(([key, value]) => [key.slice(9), value]));
602
+ const returned = invoke(attribute, rules[attribute], {value:result.value, result, validations, userChange:true});
603
+ if (returned instanceof Promise) returned.catch(report);
604
+ } catch (error) { report(error); }
605
+ }
606
+ },
607
+ checkDataPatch:patch => {
608
+ if (!(patch instanceof Bag)) throw new TypeError('Validation data changes must be a Bag.');
609
+ if (!(node.getRelativeData('.') instanceof Bag)) throw new TypeError('Validation data changes require a Bag datapath.');
610
+ }
611
+ };
612
+ }
613
+ function commitComponent(host, outcome, commit) {
614
+ const finish = result => { if (result.ok && result.isCurrent()) { commit(result); host.finishValidation(result); } };
615
+ if (outcome instanceof Promise) outcome.then(finish).catch(error => console.error('Validation notification failed:', error));
616
+ else finish(outcome);
617
+ }
package/src/view/html.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import {SourceBag, META_ATTRS, resolveRenderTag, sourceAttributeItems, SvgBuilder} from '@genrojs/builders';
2
2
  import {ControlAdapter} from './controls.js';
3
3
  import {SVG_NS, XHTML_NS} from '../renderer/attributes.js';
4
+ import {requireNoScriptAttributes, requireStyleClassAttributes} from '../renderer/attributes.js';
4
5
  import {webcomponentCode} from '../webcomponent.js';
5
6
 
6
7
  const DEFAULT_TEXT = Symbol('source text');
@@ -61,6 +62,7 @@ export class HtmlElement {
61
62
  throw new TypeError('HTML text must be scalar');
62
63
  }
63
64
  for (const [key, value] of Object.entries(node.attr)) {
65
+ if (key === 'value' && this.definition(node).meta.gramlot_component) continue;
64
66
  if (this.metadataAttributes.has(key) || ['ask', '_ask'].includes(key) || (value && typeof value === 'object' && Object.hasOwn(value, '$gramlotRef'))) continue;
65
67
  if (value != null && !['string', 'number', 'boolean'].includes(typeof value)) {
66
68
  throw new TypeError(`HTML attribute ${key} must be scalar`);
@@ -79,6 +81,15 @@ export class HtmlElement {
79
81
  tag ??= defaultTag;
80
82
  const element = namespace === XHTML_NS
81
83
  ? document.createElement(tag) : document.createElementNS(namespace, tag);
84
+ if (meta.gramlot_component && element.constructor.gramlotComponent?.tag !== tag) {
85
+ throw new Error(`Component collection must be activated before rendering ${tag}`);
86
+ }
87
+ if (meta.gramlot_component?.dataScope) {
88
+ element.readDataScope = () => {
89
+ if (!node.getAttr('datapath')) throw new Error('Data scope requires an explicit datapath');
90
+ return node.getRelativeData('.');
91
+ };
92
+ }
82
93
  const text = document.createTextNode(this.text(node));
83
94
  if (namespace !== XHTML_NS || !meta.void) element.append(text);
84
95
  const record = {element, text, tag};
@@ -108,6 +119,13 @@ export class HtmlElement {
108
119
  const isHtml = element.namespaceURI === XHTML_NS;
109
120
  const renderAttributes = this.definition(node).meta.render_attributes ?? {};
110
121
  const previous = record.attrs ?? {};
122
+ if (this.definition(node).meta.gramlot_component) {
123
+ attrs = element.projectAttributes(attrs, values => {
124
+ requireNoScriptAttributes(node, values, node.builder.constructor.dialectPrefixes);
125
+ requireStyleClassAttributes(node, values, node.builder.constructor.dialectPrefixes);
126
+ return node.builder.renderer_html.adaptAttrs(values);
127
+ });
128
+ }
111
129
  attrs = Object.fromEntries(sourceAttributeItems({...attrs, ...renderAttributes}));
112
130
  const controlled = ControlAdapter.classFor(element, attrs) !== null;
113
131
  if (textValue === DEFAULT_TEXT) textValue = this.text(node);
@@ -36,3 +36,9 @@ Modern evergreen browsers are the intended target. Cascade layers, `clamp()`, CS
36
36
  Syntax highlighting uses `.hljs-*` token classes mapped to the same semantic colors in light and dark mode. Python and JavaScript detection belongs to the runtime; the theme only styles the resulting code spans.
37
37
 
38
38
  The base text size is 14px with compact headings and spacing. Navigation surfaces use the tokens `--gramlot-navigation` and `--gramlot-navigation-text`, the approved navy surface; a selected item uses the blue and the brand accent the yellow of the existing palette, not new colors.
39
+
40
+
41
+ For additional compact palettes, load `mimi/theme.css` or
42
+ `joanna/theme.css` after Base and Compact. Both inherit the same semantic
43
+ variables and style input components as well as ordinary HTML. See
44
+ [theme profiles](../../docs/public/096-themes-and-css.md#gc-096-017).