@gramlot/gramlot 0.2.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.
@@ -0,0 +1,64 @@
1
+ /**
2
+ * `connect_on<event>` (source plan §2 Button, §4.11, S12): one DOM listener per attribute, bound to the
3
+ * element of the node that declares it. The DOM event is the name after `connect_on`, lower-cased
4
+ * (`connect_onclick` → `click`, `connect_onBlur` → `blur`). A value of dotted identifiers
5
+ * (`group.method`) is named logic, resolved by LogicRegistry at every event (a missing name raises,
6
+ * no fallback to inline, S09); any other value is inline code with `this` = the node and the
7
+ * parameter `event`. The handler runs with the declaring node, also when the event hits a
8
+ * descendant (R11). A closed NodeBinding does nothing (R12); an error propagates from the listener.
9
+ */
10
+
11
+ const PREFIX = 'connect_on';
12
+ const NAMED_LOGIC = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/;
13
+
14
+ export class NativeEventBinding {
15
+ #binding;
16
+ #record;
17
+ #eventName;
18
+ #handler;
19
+ #attribute;
20
+
21
+ /** The `connect_on<event>` attributes of `node` with a value, as `[attribute, eventName, handler]`. */
22
+ static declared(node) {
23
+ return Object.entries(node.getAttr() ?? {})
24
+ .filter(([name, value]) => name.startsWith(PREFIX) && name.length > PREFIX.length && value != null)
25
+ .map(([name, value]) => [name, name.slice(PREFIX.length).toLowerCase(), value]);
26
+ }
27
+
28
+ constructor(binding, record, eventName, handler, attribute = `${PREFIX}${eventName}`) {
29
+ this.#binding = binding;
30
+ this.#record = record;
31
+ this.#eventName = eventName;
32
+ this.#handler = handler;
33
+ this.#attribute = attribute;
34
+ }
35
+
36
+ get binding() { return this.#binding; }
37
+ get node() { return this.binding.node; }
38
+ get element() { return this.#record.element; }
39
+ get eventName() { return this.#eventName; }
40
+ get handler() { return this.#handler; }
41
+ /** The Source attribute that declares the listener, as written. */
42
+ get attribute() { return this.#attribute; }
43
+
44
+ attach() {
45
+ this.element.addEventListener(this.eventName, this);
46
+ }
47
+
48
+ detach() {
49
+ this.element.removeEventListener(this.eventName, this);
50
+ }
51
+
52
+ /** Run the handler with the declaring node and the event. */
53
+ handleEvent(event) {
54
+ if (this.binding.closed) return;
55
+ const node = this.node;
56
+ const runtime = this.binding.runtime;
57
+ if (NAMED_LOGIC.test(this.handler)) {
58
+ const {group, method} = runtime.logicRegistry.resolve(this.handler, node);
59
+ method.call(group, node, event);
60
+ return;
61
+ }
62
+ runtime.inlineCompiler.compile(node, this.attribute, this.handler, ['event'])({event});
63
+ }
64
+ }
@@ -0,0 +1,154 @@
1
+ import {SourceBag, META_ATTRS, resolveRenderTag, sourceAttributeItems, SvgBuilder} from '@genrojs/builders';
2
+ import {ControlAdapter} from './controls.js';
3
+ import {SVG_NS, XHTML_NS} from '../renderer/attributes.js';
4
+
5
+ const DEFAULT_TEXT = Symbol('source text');
6
+ const ATTRIBUTE_NS = {
7
+ xmlns: 'http://www.w3.org/2000/xmlns/',
8
+ xlink: 'http://www.w3.org/1999/xlink',
9
+ xml: 'http://www.w3.org/XML/1998/namespace',
10
+ };
11
+
12
+ // Attribute presence and native property reflection are DOM concerns. The active grammar owns
13
+ // which attributes a declaration accepts.
14
+ const BOOLEAN_PROPERTIES = new Set([
15
+ 'allowFullscreen', 'async', 'autofocus', 'autoplay', 'checked', 'controls', 'default',
16
+ 'defer', 'disabled', 'formNoValidate', 'hidden', 'inert', 'isMap', 'itemscope', 'loop',
17
+ 'multiple', 'muted', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly',
18
+ 'required', 'reversed', 'selected',
19
+ ]);
20
+ const REFLECTED_PROPERTIES = new Set(['checked', 'muted', 'selected', 'value']);
21
+ const PROPERTY_NAMES = new Map([
22
+ ['allowfullscreen', 'allowFullscreen'], ['formnovalidate', 'formNoValidate'],
23
+ ['ismap', 'isMap'], ['nomodule', 'noModule'], ['novalidate', 'noValidate'],
24
+ ['playsinline', 'playsInline'], ['readonly', 'readOnly'],
25
+ ]);
26
+
27
+ function domPropertyName(name) {
28
+ const camel = name.replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());
29
+ return PROPERTY_NAMES.get(camel.toLowerCase()) ?? camel;
30
+ }
31
+
32
+ /**
33
+ * Native elements in HTML documents, including embedded SVG. Grammar stays on the builder; attribute
34
+ * names and style arrive adapted by the renderers (GramlotHtmlRenderer, GramlotSvgRenderer).
35
+ */
36
+ export class HtmlElement {
37
+ constructor({metadataAttributes = []} = {}) {
38
+ this.metadataAttributes = new Set([...META_ATTRS, '_text', ...metadataAttributes]);
39
+ }
40
+
41
+ definition(node) {
42
+ const builder = node.builder;
43
+ const declaration = builder.schema[builder.schemaTag(node.nodeTag)];
44
+ const meta = {...declaration._meta, ...node.getAttr('_meta')};
45
+ const tag = resolveRenderTag(node.nodeTag, {
46
+ renderTag: meta.render_tag, ns: node.getAttr('ns'),
47
+ dialectName: builder.constructor._name,
48
+ });
49
+ // A foreignObject is an SVG element even when its descendants use an HTML builder.
50
+ const namespace = tag === 'foreignObject' ? SVG_NS
51
+ : meta.render_attributes?.xmlns ?? node.getAttr('xmlns')
52
+ ?? (builder instanceof SvgBuilder ? SVG_NS : XHTML_NS);
53
+ return {meta, namespace, tag};
54
+ }
55
+
56
+ validate(node, builder = node.builder) {
57
+ const branch = node.value instanceof SourceBag;
58
+ const text = branch ? node.getAttr('_text') : node.value;
59
+ if (text != null && !['string', 'number', 'boolean'].includes(typeof text)) {
60
+ throw new TypeError('HTML text must be scalar');
61
+ }
62
+ for (const [key, value] of Object.entries(node.attr)) {
63
+ if (this.metadataAttributes.has(key)) continue;
64
+ if (value != null && !['string', 'number', 'boolean'].includes(typeof value)) {
65
+ throw new TypeError(`HTML attribute ${key} must be scalar`);
66
+ }
67
+ }
68
+ const declaredAttrs = Object.fromEntries(Object.entries(node.attr)
69
+ .filter(([key]) => !this.metadataAttributes.has(key)));
70
+ const childTags = branch
71
+ ? node.value.getNodes().map(child => child.nodeTag).filter(Boolean)
72
+ : [];
73
+ builder.validateNode(node, {value: text, attrs: declaredAttrs, childTags});
74
+ }
75
+
76
+ create(node, document, tag = null, attrs = node.attr, visible = null) {
77
+ const {tag: defaultTag, namespace, meta} = this.definition(node);
78
+ tag ??= defaultTag;
79
+ const element = namespace === XHTML_NS
80
+ ? document.createElement(tag) : document.createElementNS(namespace, tag);
81
+ const text = document.createTextNode(this.text(node));
82
+ if (namespace !== XHTML_NS || !meta.void) element.append(text);
83
+ const record = {element, text, tag};
84
+ this.update(record, node, attrs, DEFAULT_TEXT, visible);
85
+ return record;
86
+ }
87
+
88
+ matches(record, node) {
89
+ const {tag, namespace} = this.definition(node);
90
+ return (namespace === XHTML_NS ? record.tag.toLowerCase() === tag.toLowerCase() : record.tag === tag)
91
+ && record.element.namespaceURI === namespace;
92
+ }
93
+
94
+ compose(record, text, children) {
95
+ record.text.data = text ?? '';
96
+ for (const child of children) record.element.append(child);
97
+ }
98
+
99
+ /**
100
+ * Apply `attrs` and the text; the declaration's `render_attributes` win. `visible === false`
101
+ * sets `style.visibility = 'hidden'` after the attributes, so a `style` change keeps it; any
102
+ * other value gives the current `style` back (V1, legacy genro_wdg.js). The `value` of a form
103
+ * control belongs to its ControlAdapter: neither the attribute nor the property is written here.
104
+ */
105
+ update(record, node, attrs = node.attr, textValue = DEFAULT_TEXT, visible = null) {
106
+ const {element, text} = record;
107
+ const isHtml = element.namespaceURI === XHTML_NS;
108
+ const renderAttributes = this.definition(node).meta.render_attributes ?? {};
109
+ const previous = record.attrs ?? {};
110
+ attrs = Object.fromEntries(sourceAttributeItems({...attrs, ...renderAttributes}));
111
+ const controlled = ControlAdapter.classFor(element, attrs) !== null;
112
+ if (textValue === DEFAULT_TEXT) textValue = this.text(node);
113
+ const nextText = textValue == null ? '' : String(textValue);
114
+ if (text.data !== nextText) text.data = nextText;
115
+ for (const key of new Set([...Object.keys(previous), ...Object.keys(attrs)])) {
116
+ if (this.metadataAttributes.has(key) || (controlled && key === 'value')) continue;
117
+ const value = attrs[key];
118
+ const attrName = key;
119
+ const propertyName = domPropertyName(attrName);
120
+ const isBoolean = isHtml && BOOLEAN_PROPERTIES.has(propertyName)
121
+ && typeof element[propertyName] === 'boolean';
122
+ const prefix = attrName === 'xmlns' ? 'xmlns'
123
+ : (attrName.includes(':') ? attrName.split(':')[0] : '');
124
+ const namespace = Object.hasOwn(ATTRIBUTE_NS, prefix) ? ATTRIBUTE_NS[prefix] : null;
125
+ if (!Object.is(previous[key], value)) {
126
+ if (value == null || (isBoolean && !value)) {
127
+ if (namespace) element.removeAttributeNS(namespace, attrName.split(':').at(-1));
128
+ else element.removeAttribute(attrName);
129
+ } else if (namespace) element.setAttributeNS(namespace, attrName, String(value));
130
+ else element.setAttribute(attrName, isBoolean ? '' : String(value));
131
+ }
132
+ if (isHtml && (isBoolean || REFLECTED_PROPERTIES.has(propertyName)) && propertyName in element) {
133
+ const target = propertyName === 'value' ? (value == null ? '' : String(value)) : Boolean(value);
134
+ if (element[propertyName] !== target) element[propertyName] = target;
135
+ }
136
+ }
137
+ if (visible === false) {
138
+ if (element.style.visibility !== 'hidden') element.style.visibility = 'hidden';
139
+ } else if (record.visible === false) {
140
+ if (attrs.style == null) element.removeAttribute('style');
141
+ else element.setAttribute('style', String(attrs.style));
142
+ }
143
+ record.visible = visible;
144
+ // Retain what was applied, including metadata, so later updates can remove it.
145
+ record.attrs = attrs;
146
+ }
147
+
148
+ text(node) {
149
+ if (node.value instanceof SourceBag) {
150
+ return node.getAttr('_text') == null ? '' : String(node.attr._text);
151
+ }
152
+ return node.value == null ? '' : String(node.value);
153
+ }
154
+ }