From ae0455f91392498e50d46aa3fdc63924aae0f6ee Mon Sep 17 00:00:00 2001 From: Jan Andrle Date: Tue, 21 Nov 2023 14:37:57 +0100 Subject: [PATCH] :hammer: docs+addons --- dist/esm-with-signals.d.ts | 73 ++++++++----------- dist/esm.d.ts | 73 ++++++++----------- docs/elements.html | 30 +++++--- docs/events.html | 10 +-- docs/index.html | 4 +- .../examples/elements/dekaAssign.js | 16 +++- .../examples/events/templateWithListeners.js | 2 +- docs_src/elements.html.js | 9 ++- docs_src/events.html.js | 22 +++--- docs_src/index.html.js | 5 +- docs_src/ssr.js | 2 +- index.d.ts | 41 ++++++----- src/dom.js | 6 +- 13 files changed, 149 insertions(+), 144 deletions(-) diff --git a/dist/esm-with-signals.d.ts b/dist/esm-with-signals.d.ts index 9341c2f..af78f55 100644 --- a/dist/esm-with-signals.d.ts +++ b/dist/esm-with-signals.d.ts @@ -11,8 +11,10 @@ type SupportedElement= | ddePublicElementTagNameMap[keyof ddePublicElementTagNameMap]; declare global { type ddeComponentAttributes= Record | undefined | string; - type ddeElementModifier= (element: El)=> El; + type ddeElementAddon= (element: El)=> El | void; } +type PascalCase= +`${Capitalize}${string}`; type AttrsModified= { /** * Use string like in HTML (internally uses `*.setAttribute("style", *)`), or object representation (like DOM API). @@ -30,7 +32,7 @@ type AttrsModified= { * Sets `aria-*` simiraly to `dataset` * */ ariaset: Record, -} +} & Record<`=${string}` | `data${PascalCase}` | `aria${PascalCase}`, string> & Record<`.${string}`, any> /** * Just element attributtes * @@ -40,57 +42,65 @@ type AttrsModified= { * @private */ type ElementAttributes= Omit & AttrsModified; +export function classListDeclarative(element: El, classList: AttrsModified["classList"]): El export function assign(element: El, ...attrs_array: Partial>[]): El +export function assignAttribute>(element: El, attr: ATT, value: ElementAttributes[ATT]): ElementAttributes[ATT] + type ExtendedHTMLElementTagNameMap= HTMLElementTagNameMap & CustomElementTagNameMap & ddePublicElementTagNameMap export function el( tag_name: TAG, attrs?: string | Partial>, - ...modifiers: ddeElementModifier[] + ...modifiers: ddeElementAddon[] ): ExtendedHTMLElementTagNameMap[TAG] export function el( tag_name?: "<>", ): DocumentFragment + export function el< A extends ddeComponentAttributes, C extends (attr: A)=> SupportedElement | DocumentFragment>( fComponent: C, attrs?: A, - ...modifiers: ddeElementModifier>[] + ...modifiers: ddeElementAddon>[] ): ReturnType + export function el( tag_name: string, attrs?: string | Record, - ...modifiers: ddeElementModifier[] + ...modifiers: ddeElementAddon[] ): HTMLElement + export function elNS( namespace: "http://www.w3.org/2000/svg" ): ( tag_name: TAG, attrs?: string | Partial<{ [key in KEYS]: SVGElementTagNameMap[TAG][key] | string | number | boolean }>, - ...modifiers: ddeElementModifier[] + ...modifiers: ddeElementAddon[] )=> SVGElementTagNameMap[TAG] export function elNS( namespace: "http://www.w3.org/1998/Math/MathML" ): ( tag_name: TAG, attrs?: string | Partial<{ [key in KEYS]: MathMLElementTagNameMap[TAG][key] | string | number | boolean }>, - ...modifiers: ddeElementModifier[] + ...modifiers: ddeElementAddon[] )=> MathMLElementTagNameMap[TAG] export function elNS( namespace: string ): ( tag_name: string, attrs?: string | Record, - ...modifiers: ddeElementModifier[] + ...modifiers: ddeElementAddon[] )=> SupportedElement + export function chainableAppend(el: EL): EL; + export function dispatchEvent(element: SupportedElement, name: keyof DocumentEventMap): void; export function dispatchEvent(element: SupportedElement, name: string, data: any): void; interface On{ /** Listens to the DOM event. See {@link Document.addEventListener} */ < - EE extends ddeElementModifier, - El extends ( EE extends ddeElementModifier ? El : never ), + EE extends ddeElementAddon, + El extends ( EE extends ddeElementAddon ? El : never ), Event extends keyof DocumentEventMap>( type: Event, listener: (this: El, ev: DocumentEventMap[Event]) => any, @@ -98,31 +108,32 @@ interface On{ ) : EE; /** Listens to the element is connected to the live DOM. In case of custom elements uses [`connectedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ connected< - EE extends ddeElementModifier, - El extends ( EE extends ddeElementModifier ? El : never ) + EE extends ddeElementAddon, + El extends ( EE extends ddeElementAddon ? El : never ) >( listener: (el: El) => any, options?: AddEventListenerOptions ) : EE; /** Listens to the element is disconnected from the live DOM. In case of custom elements uses [`disconnectedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ disconnected< - EE extends ddeElementModifier, - El extends ( EE extends ddeElementModifier ? El : never ) + EE extends ddeElementAddon, + El extends ( EE extends ddeElementAddon ? El : never ) >( listener: (el: El) => any, options?: AddEventListenerOptions ) : EE; /** Listens to the element attribute changes. In case of custom elements uses [`attributeChangedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ attributeChanged< - EE extends ddeElementModifier, - El extends ( EE extends ddeElementModifier ? El : never ) + EE extends ddeElementAddon, + El extends ( EE extends ddeElementAddon ? El : never ) >( listener: (el: El) => any, options?: AddEventListenerOptions ) : EE; } export const on: On; -type Scope= { scope: Node | Function | Object, host: ddeElementModifier, custom_element: false | HTMLElement, prevent: boolean } + +type Scope= { scope: Node | Function | Object, host: ddeElementAddon, custom_element: false | HTMLElement, prevent: boolean } /** Current scope created last time the `el(Function)` was invoke. (Or {@link scope.push}) */ export const scope: { current: Scope, @@ -132,10 +143,10 @@ export const scope: { preventDefault(prevent: T): T, /** * This represents reference to the current host element — `scope.host()`. - * It can be also used to register Modifier (function to be called when component is initized) + * It can be also used to register Addon (function to be called when component is initized) * — `scope.host(on.connected(console.log))`. * */ - host: ddeElementModifier, + host: ddeElementAddon, state: Scope[], /** Adds new child scope. All attributes are inherited by default. */ @@ -145,29 +156,7 @@ export const scope: { /** Removes last/current child scope. */ pop(): ReturnType["pop"]>, }; -/* - * TODO TypeScript HACK (better way?) - * this doesnt works - * ```ts - * interface element extends Node{ - * prototype: el; - * append(...els: (SupportedElement | DocumentFragment | string | element)[]): el - * } - * export function el( - * tag_name?: "<>", - * ): element - * ``` - * …as its complains here - * ```ts - * const d= el("div"); - * const f= (a: HTMLDivElement)=> a; - * f(d); //← - * document.head.append( //← - * el("script", { src: "https://flems.io/flems.html", type: "text/javascript", charset: "utf-8" }), - * ); - * ``` - * TODO for SVG - * */ + type ddeAppend= (...nodes: (Node | string)[])=> el; declare global{ interface HTMLAnchorElement{ diff --git a/dist/esm.d.ts b/dist/esm.d.ts index bdeb6d0..5aab9ef 100644 --- a/dist/esm.d.ts +++ b/dist/esm.d.ts @@ -11,8 +11,10 @@ type SupportedElement= | ddePublicElementTagNameMap[keyof ddePublicElementTagNameMap]; declare global { type ddeComponentAttributes= Record | undefined | string; - type ddeElementModifier= (element: El)=> El; + type ddeElementAddon= (element: El)=> El | void; } +type PascalCase= +`${Capitalize}${string}`; type AttrsModified= { /** * Use string like in HTML (internally uses `*.setAttribute("style", *)`), or object representation (like DOM API). @@ -30,7 +32,7 @@ type AttrsModified= { * Sets `aria-*` simiraly to `dataset` * */ ariaset: Record, -} +} & Record<`=${string}` | `data${PascalCase}` | `aria${PascalCase}`, string> & Record<`.${string}`, any> /** * Just element attributtes * @@ -40,57 +42,65 @@ type AttrsModified= { * @private */ type ElementAttributes= Omit & AttrsModified; +export function classListDeclarative(element: El, classList: AttrsModified["classList"]): El export function assign(element: El, ...attrs_array: Partial>[]): El +export function assignAttribute>(element: El, attr: ATT, value: ElementAttributes[ATT]): ElementAttributes[ATT] + type ExtendedHTMLElementTagNameMap= HTMLElementTagNameMap & CustomElementTagNameMap & ddePublicElementTagNameMap export function el( tag_name: TAG, attrs?: string | Partial>, - ...modifiers: ddeElementModifier[] + ...modifiers: ddeElementAddon[] ): ExtendedHTMLElementTagNameMap[TAG] export function el( tag_name?: "<>", ): DocumentFragment + export function el< A extends ddeComponentAttributes, C extends (attr: A)=> SupportedElement | DocumentFragment>( fComponent: C, attrs?: A, - ...modifiers: ddeElementModifier>[] + ...modifiers: ddeElementAddon>[] ): ReturnType + export function el( tag_name: string, attrs?: string | Record, - ...modifiers: ddeElementModifier[] + ...modifiers: ddeElementAddon[] ): HTMLElement + export function elNS( namespace: "http://www.w3.org/2000/svg" ): ( tag_name: TAG, attrs?: string | Partial<{ [key in KEYS]: SVGElementTagNameMap[TAG][key] | string | number | boolean }>, - ...modifiers: ddeElementModifier[] + ...modifiers: ddeElementAddon[] )=> SVGElementTagNameMap[TAG] export function elNS( namespace: "http://www.w3.org/1998/Math/MathML" ): ( tag_name: TAG, attrs?: string | Partial<{ [key in KEYS]: MathMLElementTagNameMap[TAG][key] | string | number | boolean }>, - ...modifiers: ddeElementModifier[] + ...modifiers: ddeElementAddon[] )=> MathMLElementTagNameMap[TAG] export function elNS( namespace: string ): ( tag_name: string, attrs?: string | Record, - ...modifiers: ddeElementModifier[] + ...modifiers: ddeElementAddon[] )=> SupportedElement + export function chainableAppend(el: EL): EL; + export function dispatchEvent(element: SupportedElement, name: keyof DocumentEventMap): void; export function dispatchEvent(element: SupportedElement, name: string, data: any): void; interface On{ /** Listens to the DOM event. See {@link Document.addEventListener} */ < - EE extends ddeElementModifier, - El extends ( EE extends ddeElementModifier ? El : never ), + EE extends ddeElementAddon, + El extends ( EE extends ddeElementAddon ? El : never ), Event extends keyof DocumentEventMap>( type: Event, listener: (this: El, ev: DocumentEventMap[Event]) => any, @@ -98,31 +108,32 @@ interface On{ ) : EE; /** Listens to the element is connected to the live DOM. In case of custom elements uses [`connectedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ connected< - EE extends ddeElementModifier, - El extends ( EE extends ddeElementModifier ? El : never ) + EE extends ddeElementAddon, + El extends ( EE extends ddeElementAddon ? El : never ) >( listener: (el: El) => any, options?: AddEventListenerOptions ) : EE; /** Listens to the element is disconnected from the live DOM. In case of custom elements uses [`disconnectedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ disconnected< - EE extends ddeElementModifier, - El extends ( EE extends ddeElementModifier ? El : never ) + EE extends ddeElementAddon, + El extends ( EE extends ddeElementAddon ? El : never ) >( listener: (el: El) => any, options?: AddEventListenerOptions ) : EE; /** Listens to the element attribute changes. In case of custom elements uses [`attributeChangedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ attributeChanged< - EE extends ddeElementModifier, - El extends ( EE extends ddeElementModifier ? El : never ) + EE extends ddeElementAddon, + El extends ( EE extends ddeElementAddon ? El : never ) >( listener: (el: El) => any, options?: AddEventListenerOptions ) : EE; } export const on: On; -type Scope= { scope: Node | Function | Object, host: ddeElementModifier, custom_element: false | HTMLElement, prevent: boolean } + +type Scope= { scope: Node | Function | Object, host: ddeElementAddon, custom_element: false | HTMLElement, prevent: boolean } /** Current scope created last time the `el(Function)` was invoke. (Or {@link scope.push}) */ export const scope: { current: Scope, @@ -132,10 +143,10 @@ export const scope: { preventDefault(prevent: T): T, /** * This represents reference to the current host element — `scope.host()`. - * It can be also used to register Modifier (function to be called when component is initized) + * It can be also used to register Addon (function to be called when component is initized) * — `scope.host(on.connected(console.log))`. * */ - host: ddeElementModifier, + host: ddeElementAddon, state: Scope[], /** Adds new child scope. All attributes are inherited by default. */ @@ -145,29 +156,7 @@ export const scope: { /** Removes last/current child scope. */ pop(): ReturnType["pop"]>, }; -/* - * TODO TypeScript HACK (better way?) - * this doesnt works - * ```ts - * interface element extends Node{ - * prototype: el; - * append(...els: (SupportedElement | DocumentFragment | string | element)[]): el - * } - * export function el( - * tag_name?: "<>", - * ): element - * ``` - * …as its complains here - * ```ts - * const d= el("div"); - * const f= (a: HTMLDivElement)=> a; - * f(d); //← - * document.head.append( //← - * el("script", { src: "https://flems.io/flems.html", type: "text/javascript", charset: "utf-8" }), - * ); - * ``` - * TODO for SVG - * */ + type ddeAppend= (...nodes: (Node | string)[])=> el; declare global{ interface HTMLAnchorElement{ diff --git a/docs/elements.html b/docs/elements.html index cd7635b..374d3f0 100644 --- a/docs/elements.html +++ b/docs/elements.html @@ -1,4 +1,4 @@ -`deka-dom-el` — Elements

`deka-dom-el` — Elements

Basic concepts of elements modifications and creations.

Native JavaScript DOM elements creations

Let’s go through all patterns we would like to use and what needs to be improved for better experience.

Creating element(s) (with custom attributes)

You can create a native DOM element by using the document.createElement(). It is also possible to provide a some attribute(s) declaratively using Object.assign(). More precisely, this way you can sets some IDL also known as a JavaScript property.

document.body.append( +`deka-dom-el` — Elements

`deka-dom-el` — Elements

Basic concepts of elements modifications and creations.

Native JavaScript DOM elements creations

Let’s go through all patterns we would like to use and what needs to be improved for better experience.

Creating element(s) (with custom attributes)

You can create a native DOM element by using the document.createElement(). It is also possible to provide a some attribute(s) declaratively using Object.assign(). More precisely, this way you can sets some IDL also known as a JavaScript property.

document.body.append( document.createElement("div") ); console.log( @@ -12,7 +12,7 @@ document.body.append( { textContent: "Element’s text content.", style: "color: coral;" } ) ); -

To make this easier, you can use the el function. Internally in basic examples, it is wrapper around assign(document.createElement(…), { … }).

import { el, assign } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; +

To make this easier, you can use the el function. Internally in basic examples, it is wrapper around assign(document.createElement(…), { … }).

import { el, assign } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; const color= "lightcoral"; document.body.append( el("p", { textContent: "Hello (first time)", style: { color } }) @@ -23,18 +23,25 @@ document.body.append( { textContent: "Hello (second time)", style: { color } } ) ); -

The assign function provides improved behaviour of Object.assign(). You can declaratively sets any IDL and attribute of the given element. Function prefers IDL and fallback to the element.setAttribute if there is no writable property in the element prototype.

You can study all JavaScript elements interfaces to the corresponding HTML elements. All HTML elements inherits from HTMLElement. To see all available IDLs for example for paragraphs, see HTMLParagraphElement. Moreover, the assign provides a way to sets declaratively some convenient properties:

  • It is possible to sets data-*/aria-* attributes using object notation.
  • In opposite, it is also possible to sets data-*/aria-* attribute using camelCase notation.
  • You can use string or object as a value for style property.
  • className (IDL – preffered)/class are ways to add CSS class to the element. You can use string (similarly to class="…" syntax in HTML) or array of strings. This is handy to concat conditional classes.
  • Use classList to toggle specific classes. This will be handy later when the reactivity via signals is beeing introduced.
  • The assign also accepts the undefined as a value for any property to remove it from the element declaratively. Also for some IDL the corresponding attribute is removed as it can be confusing. For example, natievly the element’s id is removed by setting the IDL to an empty string.

For processing, the assign internally uses assignAttribute and classListDeclarative.

import { assignAttribute, classListDeclarative } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; +

The assign function provides improved behaviour of Object.assign(). You can declaratively sets any IDL and attribute of the given element. Function prefers IDL and fallback to the element.setAttribute if there is no writable property in the element prototype.

You can study all JavaScript elements interfaces to the corresponding HTML elements. All HTML elements inherits from HTMLElement. To see all available IDLs for example for paragraphs, see HTMLParagraphElement. Moreover, the assign provides a way to sets declaratively some convenient properties:

  • It is possible to sets data-*/aria-* attributes using object notation.
  • In opposite, it is also possible to sets data-*/aria-* attribute using camelCase notation.
  • You can use string or object as a value for style property.
  • className (IDL – preffered)/class are ways to add CSS class to the element. You can use string (similarly to class="…" syntax in HTML) or array of strings. This is handy to concat conditional classes.
  • Use classList to toggle specific classes. This will be handy later when the reactivity via signals is beeing introduced.
  • The assign also accepts the undefined as a value for any property to remove it from the element declaratively. Also for some IDL the corresponding attribute is removed as it can be confusing. For example, natievly the element’s id is removed by setting the IDL to an empty string.
  • You can use = or . to force processing given key as attribute/property of the element.

For processing, the assign internally uses assignAttribute and classListDeclarative.

import { assign, assignAttribute, classListDeclarative } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; const paragraph= document.createElement("p"); assignAttribute(paragraph, "textContent", "Hello, world!"); + +assignAttribute(paragraph, "style", "color: red; font-weight: bold;"); assignAttribute(paragraph, "style", { color: "navy" }); assignAttribute(paragraph, "dataTest1", "v1"); assignAttribute(paragraph, "dataset", { test2: "v2" }); -assignAttribute(paragraph, "ariaLabel", "v1"); -assignAttribute(paragraph, "ariaset", { role: "none" }); - +assign(paragraph, { //textContent and style see above + ariaLabel: "v1", //data* see above + ariaset: { role: "none" }, // dataset see above + "=onclick": "console.log(event)", + onmouseout: console.info, + ".something": "something", + classList: {} //see below +}); classListDeclarative(paragraph, { classAdd: true, @@ -45,10 +52,11 @@ classListDeclarative(paragraph, { }); console.log(paragraph.outerHTML); +console.log("paragraph.something=", paragraph.something); document.body.append( paragraph ); -

Native JavaScript templating

By default, the native JS has no good way to define HTML template using DOM API:

document.body.append( +

Native JavaScript templating

By default, the native JS has no good way to define HTML template using DOM API:

document.body.append( document.createElement("div"), document.createElement("span"), document.createElement("main") @@ -59,7 +67,7 @@ const template= document.createElement("main").append( document.createElement("span"), ); console.log(typeof template==="undefined"); -

This library therefore overwrites the append method of created elements to always return parent element.

import { el } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; +

This library therefore overwrites the append method of created elements to always return parent element.

import { el } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; document.head.append( el("style").append( "tr, td{ border: 1px solid red; padding: 1em; }", @@ -94,7 +102,7 @@ document.body.append( ) ) ); -

Basic (state-less) components

You can use functions for encapsulation (repeating) logic. The el accepts function as first argument. In that case, the function should return dom elements and the second argument for el is argument for given element.

import { el } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; +

Basic (state-less) components

You can use functions for encapsulation (repeating) logic. The el accepts function as first argument. In that case, the function should return dom elements and the second argument for el is argument for given element.

import { el } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; document.head.append( el("style").append( ".class1{ font-weight: bold; }", @@ -111,7 +119,7 @@ function component({ className, textContent }){ el("p", textContent) ); } -

As you can see, in case of state-less/basic components there is no difference between calling component function directly or using el function.

It is nice to use similar naming convention as native DOM API. This allows us to use the destructuring assignment syntax and keep track of the native API (things are best remembered through regular use).

Creating non-HTML elements

Similarly to the native DOM API (document.createElementNS) for non-HTML elements we need to tell JavaScript which kind of the element to create. We can use the elNS function:

import { elNS, assign } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; +

As you can see, in case of state-less/basic components there is no difference between calling component function directly or using el function.

It is nice to use similar naming convention as native DOM API. This allows us to use the destructuring assignment syntax and keep track of the native API (things are best remembered through regular use).

Creating non-HTML elements

Similarly to the native DOM API (document.createElementNS) for non-HTML elements we need to tell JavaScript which kind of the element to create. We can use the elNS function:

import { elNS, assign } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; const elSVG= elNS("http://www.w3.org/2000/svg"); const elMath= elNS("http://www.w3.org/1998/Math/MathML"); document.body.append( @@ -122,4 +130,4 @@ document.body.append( console.log( document.body.innerHTML.includes("<svg></svg><math></math>") ) -
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/events.html b/docs/events.html index bacf977..f8aca87 100644 --- a/docs/events.html +++ b/docs/events.html @@ -1,4 +1,4 @@ -`deka-dom-el` — Events and Modifiers

`deka-dom-el` — Events and Modifiers

Using not only events in UI declaratively.

Listenning to the native DOM events and other Modifiers

We quickly introduce helper to listening to the native DOM events. And library syntax/pattern so-called Modifier to incorporate not only this in UI templates declaratively.

Events and listenners

In JavaScript you can listen to the native DOM events of the given element by using element.addEventListener(type, listener, options). The library provides an alternative (on) accepting the differen order of the arguments:

import { el, on } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; +`deka-dom-el` — Events and Addons

`deka-dom-el` — Events and Addons

Using not only events in UI declaratively.

Listenning to the native DOM events and other Addons

We quickly introduce helper to listening to the native DOM events. And library syntax/pattern so-called Addon to incorporate not only this in UI templates declaratively.

Events and listenners

In JavaScript you can listen to the native DOM events of the given element by using element.addEventListener(type, listener, options). The library provides an alternative (on) accepting the differen order of the arguments:

import { el, on } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; const log= mark=> console.log.bind(console, mark); const button= el("button", "Test click"); @@ -8,7 +8,7 @@ on("click", log("`on`"), { once: true })(button); document.body.append( button ); -

…this is actually one of the two differences. The another one is thaton accepts only object as the options (but it is still optional).

The other difference is that there is no off function. You can remove listener declaratively using AbortSignal:

import { el, on } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; +

…this is actually one of the two differences. The another one is thaton accepts only object as the options (but it is still optional).

The other difference is that there is no off function. You can remove listener declaratively using AbortSignal:

import { el, on } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; const log= mark=> console.log.bind(console, mark); const abort_controller= new AbortController(); @@ -21,10 +21,10 @@ on("click", log("`on`"), { signal })(button); document.body.append( button, " ", el("button", { textContent: "Off", onclick: ()=> abort_controller.abort() }) ); -

Modifiers

From practical point of view, Modifiers are just functions that accept any html element as their first parameter. You can see that the on(…) fullfills this requirement.

You can use Modifiers as ≥3rd argument of el function. This way is possible to extends you templates by additional (3rd party) functionalities. But for now mainly, you can add events listeners:

import { el, on } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; +

Addons

From practical point of view, Addons are just functions that accept any html element as their first parameter. You can see that the on(…) fullfills this requirement.

You can use Addons as ≥3rd argument of el function. This way is possible to extends you templates by additional (3rd party) functionalities. But for now mainly, you can add events listeners:

import { el, on } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; const abort_controller= new AbortController(); const { signal }= abort_controller; -/** @type {ddeElementModifier<HTMLButtonElement>} */ +/** @type {ddeElementAddon<HTMLButtonElement>} */ const onclickOff= on("click", ()=> abort_controller.abort(), { signal }); /** @type {(ref?: HTMLOutputElement)=> HTMLOutputElement | null} */ const ref= (store=> ref=> ref ? (store= ref) : store)(null); @@ -45,4 +45,4 @@ function update(event){ "\n" ); } -

As the example shows, you can also provide types in JSDoc+TypeScript by using global type ddeElementModifier. Also notice, you can use Modifiers to get element reference.

Life cycle events

Modifiers are called immediately when the element is created, event it is not connected to live DOM yet.

\ No newline at end of file +

As the example shows, you can also provide types in JSDoc+TypeScript by using global type ddeElementAddon. Also notice, you can use Addons to get element reference.

Life cycle events

Addons are called immediately when the element is created, event it is not connected to live DOM yet.

\ No newline at end of file diff --git a/docs/index.html b/docs/index.html index d4de445..bbb3d0a 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,4 +1,4 @@ -`deka-dom-el` — Introduction

`deka-dom-el` — Introduction

Introducing a library.

The library tries to provide pure JavaScript tool(s) to create reactive interfaces.

We start with creating and modifying a static elements and end up with UI templates. From document.createElement to el. Then we go through the native events system and the way to include it declaratively in UI templates. From element.addEventListener to on.

Next step is providing interactivity not only for our UI templates. We introduce signals (S) and how them incorporate to UI templates.

Now we will clarify how the signals are incorporated into our templates with regard to application performance. This is not the only reason the library uses scopes. We will look at how they work in components represented in JavaScript by functions.

import { el } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; +`deka-dom-el` — Introduction

`deka-dom-el` — Introduction

Introducing a library.

The library tries to provide pure JavaScript tool(s) to create reactive interfaces.

We start with creating and modifying a static elements and end up with UI templates. From document.createElement to el. Then we go through the native events system and the way to include it declaratively in UI templates. From element.addEventListener to on.

Next step is providing interactivity not only for our UI templates. We introduce signals (S) and how them incorporate to UI templates.

Now we will clarify how the signals are incorporated into our templates with regard to application performance. This is not the only reason the library uses scopes. We will look at how they work in components represented in JavaScript by functions.

import { el } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; import { S } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; const clicks= S(0); document.body.append( @@ -13,4 +13,4 @@ document.body.append( }) ) ); -
\ No newline at end of file +
\ No newline at end of file diff --git a/docs_src/components/examples/elements/dekaAssign.js b/docs_src/components/examples/elements/dekaAssign.js index 2477732..70009c1 100644 --- a/docs_src/components/examples/elements/dekaAssign.js +++ b/docs_src/components/examples/elements/dekaAssign.js @@ -1,15 +1,22 @@ -import { assignAttribute, classListDeclarative } from "deka-dom-el"; +import { assign, assignAttribute, classListDeclarative } from "deka-dom-el"; const paragraph= document.createElement("p"); assignAttribute(paragraph, "textContent", "Hello, world!"); + +assignAttribute(paragraph, "style", "color: red; font-weight: bold;"); assignAttribute(paragraph, "style", { color: "navy" }); assignAttribute(paragraph, "dataTest1", "v1"); assignAttribute(paragraph, "dataset", { test2: "v2" }); -assignAttribute(paragraph, "ariaLabel", "v1"); -assignAttribute(paragraph, "ariaset", { role: "none" }); - +assign(paragraph, { //textContent and style see above + ariaLabel: "v1", //data* see above + ariaset: { role: "none" }, // dataset see above + "=onclick": "console.log(event)", + onmouseout: console.info, + ".something": "something", + classList: {} //see below +}); classListDeclarative(paragraph, { classAdd: true, @@ -20,6 +27,7 @@ classListDeclarative(paragraph, { }); console.log(paragraph.outerHTML); +console.log("paragraph.something=", paragraph.something); document.body.append( paragraph ); diff --git a/docs_src/components/examples/events/templateWithListeners.js b/docs_src/components/examples/events/templateWithListeners.js index 8216e2b..72c66e8 100644 --- a/docs_src/components/examples/events/templateWithListeners.js +++ b/docs_src/components/examples/events/templateWithListeners.js @@ -1,7 +1,7 @@ import { el, on } from "deka-dom-el"; const abort_controller= new AbortController(); const { signal }= abort_controller; -/** @type {ddeElementModifier} */ +/** @type {ddeElementAddon} */ const onclickOff= on("click", ()=> abort_controller.abort(), { signal }); /** @type {(ref?: HTMLOutputElement)=> HTMLOutputElement | null} */ const ref= (store=> ref=> ref ? (store= ref) : store)(null); diff --git a/docs_src/elements.html.js b/docs_src/elements.html.js index f69239c..5258a70 100644 --- a/docs_src/elements.html.js +++ b/docs_src/elements.html.js @@ -1,11 +1,13 @@ import "./global.css.js"; import { el } from "deka-dom-el"; + +import { header } from "./layout/head.html.js"; import { example } from "./components/example.html.js"; +import { prevNext } from "./components/prevNext.html.js"; /** @param {string} url */ const fileURL= url=> new URL(url, import.meta.url); -import { header } from "./layout/head.html.js"; -import { prevNext } from "./components/prevNext.html.js"; + /** @param {import("./types.d.ts").PageAttrs} attrs */ export function page({ pkg, info }){ const page_id= info.id; @@ -71,6 +73,9 @@ export function page({ pkg, info }){ el("em").append( "For example, natievly the element’s ", el("code", "id"), " is removed by setting the IDL to an empty string." ) + ), + el("li").append( + "You can use ", el("code", "="), " or ", el("code", "."), " to force processing given key as attribute/property of the element." ) ), el("p").append( diff --git a/docs_src/events.html.js b/docs_src/events.html.js index a1026aa..53ca9db 100644 --- a/docs_src/events.html.js +++ b/docs_src/events.html.js @@ -1,22 +1,24 @@ import "./global.css.js"; import { el } from "deka-dom-el"; + +import { header } from "./layout/head.html.js"; import { example } from "./components/example.html.js"; +import { prevNext } from "./components/prevNext.html.js"; /** @param {string} url */ const fileURL= url=> new URL(url, import.meta.url); -import { header } from "./layout/head.html.js"; -import { prevNext } from "./components/prevNext.html.js"; + /** @param {import("./types.d.ts").PageAttrs} attrs */ export function page({ pkg, info }){ const page_id= info.id; return el().append( el(header, { info, pkg }), el("main").append( - el("h2", "Listenning to the native DOM events and other Modifiers"), + el("h2", "Listenning to the native DOM events and other Addons"), el("p").append( "We quickly introduce helper to listening to the native DOM events.", " ", - "And library syntax/pattern so-called ", el("em", "Modifier"), " to", + "And library syntax/pattern so-called ", el("em", "Addon"), " to", " incorporate not only this in UI templates declaratively." ), @@ -43,23 +45,23 @@ export function page({ pkg, info }){ ), el(example, { src: fileURL("./components/examples/events/abortSignal.js"), page_id }), - el("h3", "Modifiers"), + el("h3", "Addons"), el("p").append( - "From practical point of view, ", el("em", "Modifiers"), " are just functions that accept any html element", + "From practical point of view, ", el("em", "Addons"), " are just functions that accept any html element", " as their first parameter. You can see that the ", el("code", "on(…)"), " fullfills this requirement." ), el("p").append( - "You can use Modifiers as ≥3rd argument of ", el("code", "el"), " function. This way is possible to extends", + "You can use Addons as ≥3rd argument of ", el("code", "el"), " function. This way is possible to extends", " you templates by additional (3rd party) functionalities. But for now mainly, you can add events listeners:" ), el(example, { src: fileURL("./components/examples/events/templateWithListeners.js"), page_id }), el("p").append( - "As the example shows, you can also provide types in JSDoc+TypeScript by using global type ", el("code", "ddeElementModifier"), ".", + "As the example shows, you can also provide types in JSDoc+TypeScript by using global type ", el("code", "ddeElementAddon"), ".", " ", - "Also notice, you can use Modifiers to get element reference.", + "Also notice, you can use Addons to get element reference.", ), el("h3", "Life cycle events"), - el("p", "Modifiers are called immediately when the element is created, event it is not connected to live DOM yet."), + el("p", "Addons are called immediately when the element is created, event it is not connected to live DOM yet."), // todo // dispatchEvent diff --git a/docs_src/index.html.js b/docs_src/index.html.js index c7a8abd..1ae31e2 100644 --- a/docs_src/index.html.js +++ b/docs_src/index.html.js @@ -1,9 +1,10 @@ -import { el } from "deka-dom-el"; import "./global.css.js"; -import { example } from "./components/example.html.js"; +import { el } from "deka-dom-el"; import { header } from "./layout/head.html.js"; +import { example } from "./components/example.html.js"; import { prevNext } from "./components/prevNext.html.js"; + /** @param {import("./types.d.ts").PageAttrs} attrs */ export function page({ pkg, info }){ const page_id= info.id; diff --git a/docs_src/ssr.js b/docs_src/ssr.js index 890f048..f44235c 100644 --- a/docs_src/ssr.js +++ b/docs_src/ssr.js @@ -5,7 +5,7 @@ export const path_target= { export const pages= [ { id: "index", href: "./", title: "Introduction", description: "Introducing a library." }, { id: "elements", href: "elements", title: "Elements", description: "Basic concepts of elements modifications and creations." }, - { id: "events", href: "events", title: "Events and Modifiers", description: "Using not only events in UI declaratively." }, + { id: "events", href: "events", title: "Events and Addons", description: "Using not only events in UI declaratively." }, ]; /** * @typedef registerClientFile diff --git a/index.d.ts b/index.d.ts index 5febfb7..038750a 100644 --- a/index.d.ts +++ b/index.d.ts @@ -11,8 +11,9 @@ type SupportedElement= | ddePublicElementTagNameMap[keyof ddePublicElementTagNameMap]; declare global { type ddeComponentAttributes= Record | undefined | string; - type ddeElementModifier= (element: El)=> El; + type ddeElementAddon= (element: El)=> El | void; } +type PascalCase= `${Capitalize}${string}`; type AttrsModified= { /** * Use string like in HTML (internally uses `*.setAttribute("style", *)`), or object representation (like DOM API). @@ -30,7 +31,7 @@ type AttrsModified= { * Sets `aria-*` simiraly to `dataset` * */ ariaset: Record, -} +} & Record<`=${string}` | `data${PascalCase}` | `aria${PascalCase}`, string> & Record<`.${string}`, any> /** * Just element attributtes * @@ -40,13 +41,15 @@ type AttrsModified= { * @private */ type ElementAttributes= Omit & AttrsModified; +export function classListDeclarative(element: El, classList: AttrsModified["classList"]): El export function assign(element: El, ...attrs_array: Partial>[]): El +export function assignAttribute>(element: El, attr: ATT, value: ElementAttributes[ATT]): ElementAttributes[ATT] type ExtendedHTMLElementTagNameMap= HTMLElementTagNameMap & CustomElementTagNameMap & ddePublicElementTagNameMap export function el( tag_name: TAG, attrs?: string | Partial>, - ...modifiers: ddeElementModifier[] + ...modifiers: ddeElementAddon[] ): ExtendedHTMLElementTagNameMap[TAG] export function el( tag_name?: "<>", @@ -57,13 +60,13 @@ export function el< C extends (attr: A)=> SupportedElement | DocumentFragment>( fComponent: C, attrs?: A, - ...modifiers: ddeElementModifier>[] + ...modifiers: ddeElementAddon>[] ): ReturnType export function el( tag_name: string, attrs?: string | Record, - ...modifiers: ddeElementModifier[] + ...modifiers: ddeElementAddon[] ): HTMLElement export function elNS( @@ -71,21 +74,21 @@ export function elNS( ): ( tag_name: TAG, attrs?: string | Partial<{ [key in KEYS]: SVGElementTagNameMap[TAG][key] | string | number | boolean }>, - ...modifiers: ddeElementModifier[] + ...modifiers: ddeElementAddon[] )=> SVGElementTagNameMap[TAG] export function elNS( namespace: "http://www.w3.org/1998/Math/MathML" ): ( tag_name: TAG, attrs?: string | Partial<{ [key in KEYS]: MathMLElementTagNameMap[TAG][key] | string | number | boolean }>, - ...modifiers: ddeElementModifier[] + ...modifiers: ddeElementAddon[] )=> MathMLElementTagNameMap[TAG] export function elNS( namespace: string ): ( tag_name: string, attrs?: string | Record, - ...modifiers: ddeElementModifier[] + ...modifiers: ddeElementAddon[] )=> SupportedElement export function chainableAppend(el: EL): EL; @@ -95,8 +98,8 @@ export function dispatchEvent(element: SupportedElement, name: string, data: any interface On{ /** Listens to the DOM event. See {@link Document.addEventListener} */ < - EE extends ddeElementModifier, - El extends ( EE extends ddeElementModifier ? El : never ), + EE extends ddeElementAddon, + El extends ( EE extends ddeElementAddon ? El : never ), Event extends keyof DocumentEventMap>( type: Event, listener: (this: El, ev: DocumentEventMap[Event]) => any, @@ -104,24 +107,24 @@ interface On{ ) : EE; /** Listens to the element is connected to the live DOM. In case of custom elements uses [`connectedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ connected< - EE extends ddeElementModifier, - El extends ( EE extends ddeElementModifier ? El : never ) + EE extends ddeElementAddon, + El extends ( EE extends ddeElementAddon ? El : never ) >( listener: (el: El) => any, options?: AddEventListenerOptions ) : EE; /** Listens to the element is disconnected from the live DOM. In case of custom elements uses [`disconnectedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ disconnected< - EE extends ddeElementModifier, - El extends ( EE extends ddeElementModifier ? El : never ) + EE extends ddeElementAddon, + El extends ( EE extends ddeElementAddon ? El : never ) >( listener: (el: El) => any, options?: AddEventListenerOptions ) : EE; /** Listens to the element attribute changes. In case of custom elements uses [`attributeChangedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ attributeChanged< - EE extends ddeElementModifier, - El extends ( EE extends ddeElementModifier ? El : never ) + EE extends ddeElementAddon, + El extends ( EE extends ddeElementAddon ? El : never ) >( listener: (el: El) => any, options?: AddEventListenerOptions @@ -129,7 +132,7 @@ interface On{ } export const on: On; -type Scope= { scope: Node | Function | Object, host: ddeElementModifier, custom_element: false | HTMLElement, prevent: boolean } +type Scope= { scope: Node | Function | Object, host: ddeElementAddon, custom_element: false | HTMLElement, prevent: boolean } /** Current scope created last time the `el(Function)` was invoke. (Or {@link scope.push}) */ export const scope: { current: Scope, @@ -139,10 +142,10 @@ export const scope: { preventDefault(prevent: T): T, /** * This represents reference to the current host element — `scope.host()`. - * It can be also used to register Modifier (function to be called when component is initized) + * It can be also used to register Addon (function to be called when component is initized) * — `scope.host(on.connected(console.log))`. * */ - host: ddeElementModifier, + host: ddeElementAddon, state: Scope[], /** Adds new child scope. All attributes are inherited by default. */ diff --git a/src/dom.js b/src/dom.js index 9492c7d..93572c6 100644 --- a/src/dom.js +++ b/src/dom.js @@ -30,7 +30,7 @@ export const scope= { function append(...els){ this.appendOriginal(...els); return this; } export function chainableAppend(el){ if(el.append===append) return el; el.appendOriginal= el.append; el.append= append; return el; } let namespace; -export function createElement(tag, attributes, ...modifiers){ +export function createElement(tag, attributes, ...addons){ /* jshint maxcomplexity: 15 */ const s= signals(this); let scoped= 0; @@ -41,7 +41,7 @@ export function createElement(tag, attributes, ...modifiers){ switch(true){ case typeof tag==="function": { scoped= 1; - scope.push({ scope: tag, host: (...c)=> c.length ? (scoped===1 ? modifiers.unshift(...c) : c.forEach(c=> c(el_host)), undefined) : el_host }); + scope.push({ scope: tag, host: (...c)=> c.length ? (scoped===1 ? addons.unshift(...c) : c.forEach(c=> c(el_host)), undefined) : el_host }); el= tag(attributes || undefined); const is_fragment= el instanceof DocumentFragment; if(el.nodeName==="#comment") break; @@ -61,7 +61,7 @@ export function createElement(tag, attributes, ...modifiers){ } chainableAppend(el); if(!el_host) el_host= el; - modifiers.forEach(c=> c(el_host)); + addons.forEach(c=> c(el_host)); if(scoped) scope.pop(); scoped= 2; return el;