0.0.349 • Published 1 month ago

typed-dom v0.0.349

Weekly downloads
231
License
(Apache-2.0 AND M...
Repository
github
Last release
1 month ago

typed-dom

CI

Professional programmers dislike being deprived of control and prefer to have complete control over everything. No magic needed. Only amateurs prefer magic.

Abstract

A value-level and type-level DOM builder.

Visualize DOM structures and Assist DOM access using static types.

const dom: El<"article", HTMLElement, {
  style: El<"style", HTMLStyleElement, string>;
  title: El<"h1", HTMLHeadingElement, string>;
  content: El<"ul", HTMLUListElement, readonly El<"li", HTMLLIElement, string>[]>;
}>

Concepts

  • Statically type and visualize internal structures of DOM objects.
  • Make wrapper APIs of built-in DOM APIs.
  • Exclude complexity and blackboxing.

Assurance

Problems of DOM manipulation arise when the expected DOM structure differs from the actual DOM structure. Typed-DOM assures by type that the expected DOM structure and the actual DOM structure match. Assured reliable DOM manipulation is all you need. Assurance by type is best, and assurance by template is wasteful and inflexible.

ProductApproachProblems
Typed-DOMType-
jQuery-Breakable
ReactTemplateWasteful, Inflexible

Difference

DOM manipulation must be easy and reliable, and it doesn't need virtual DOM or unique syntax. Typed-DOM is a minimal API set for easy and reliable DOM manipulation.

ProductAccessDependenceExtensibilityProblems
Typed-DOMTypeInterfaceAPI, ForkSlow construction
jQueryQueryImplementationPluginBreakable, Implicit dependency
ReactCreate all and search differenceImplementationComponentBreakable, Wasteful, Complex, Uncontrollable, Severely dependent, Incomplete vain reinvention of the browsers

Usage

Build a Typed-DOM component with styling.

import { HTML } from 'typed-dom';

const dom = HTML.article({
  style: HTML.style('@scope { & { color: red; } }'),
  title: HTML.h1('Title'),
  content: HTML.ul([
    HTML.li('item'),
    HTML.li('item'),
  ]),
});

Then this component has the following readable static type generated by type inference.

const dom: El<"article", HTMLElement, {
  style: El<"style", HTMLStyleElement, string>;
  title: El<"h1", HTMLHeadingElement, string>;
  content: El<"ul", HTMLUListElement, readonly El<"li", HTMLLIElement, string>[]>;
}>

// Note: El type is defined as follows.
export interface El<
  T extends string = string,
  E extends Element = Element,
  C extends El.Children = El.Children,
  > {
  readonly tag: string;
  readonly element: E;
  get children(): El.Getter<C>;
  set children(children: El.Setter<C>);
}
export namespace El {
  export type Children =
    | Children.Void
    | Children.Node
    | Children.Text
    | Children.Array
    | Children.Struct;
  export namespace Children {
    export type Void = void;
    export type Node = DocumentFragment;
    export type Text = string;
    export type Array = readonly El[];
    export type Struct = { [field: string]: El; };
  }
  export type Getter<C extends El.Children> = C;
  export type Setter<C extends El.Children> =
    C extends Children.Struct ? Partial<C> :
    C;
  export type Factory<
    M extends TagNameMap,
    C extends El.Children = El.Children,
    > =
    <T extends keyof M & string>(
      baseFactory: BaseFactory<M>,
      tag: T,
      attrs: Attrs<Extract<M[T], Element>>,
      children: C,
    ) => M[T];
}

Using the static type, you can see the internal structure and can safely access to and manipulate it.

// Inspect
dom.element.outerHTML; // '<article class="RANDOM"><style>.RANDOM { color: red; }</style><h1>Title</h1><ul><li>item</li><li>item</li></ul></article>'
dom.children.title.element.outerHTML; // '<h1>Title</h1>'
dom.children.title.children; // 'Title'
dom.children.content.element.outerHTML; // '<ul><li>item</li><li>item</li></ul>'
dom.children.content.children[0].children; // 'item'

// Update
// - Text
dom.children.title.children = 'Text';
dom.children.title.element.outerHTML; // '<h1>Text</h1>'

// - Array
dom.children.content.children = [
  HTML.li('Array'),
];
dom.children.content.element.outerHTML; // '<ul><li>Array</li></ul>'

// - Struct
dom.children = {
  title: HTML.h1('Struct'),
};
dom.children.title.element.outerHTML; // '<h1>Struct</h1>'
dom.children.title = HTML.h1('title');
dom.children.title.element.outerHTML; // '<h1>title</h1>'

Examples

Typed-DOM supports custom elements but they are unrecommended since most purposes of customizations can be realized by customizing proxies or APIs instead of elements.

DOM Components

Define composable DOM components.

import { HTML, El } from 'typed-dom';

class Component implements El {
  private readonly dom = HTML.section({
    style: HTML.style('@scope { & { color: red; } }'),
    content: HTML.ul([
      HTML.li('item'),
    ]),
  });
  public readonly tag = this.dom.tag;
  public readonly element = this.dom.element;
  public get children() {
    return this.dom.children.content.children;
  }
  public set children(children) {
    this.dom.children.content.children = children;
  }
}

Switch to shadow DOM. Transparently accessible to elemets in shadow DOM.

import { Shadow, HTML, El } from 'typed-dom';

class ShadowComponent implements El {
  private readonly dom = Shadow.section({
    style: HTML.style('@scope { & { color: red; } }'),
    content: HTML.ul([
      HTML.li('item'),
    ]),
  });
  public readonly tag = this.dom.tag;
  public readonly element = this.dom.element;
  public get children() {
    return this.dom.children.content.children;
  }
  public set children(children) {
    this.dom.children.content.children = children;
  }
}

Define autonomous DOM components which orient choreography, not orchestration. This coroutine supports the actor model and the supervisor/worker pattern (using spica/supervisor).

import { Shadow, HTML, El } from 'typed-dom';
import { Coroutine } from 'spica/coroutine';

class Component extends Coroutine<number> implements El {
  constructor() {
    super(async function* (this: Component) {
      let count = 0;
      this.text = count;
      while (true) {
        this.element.isConnected || await new Promise<unknown>(resolve =>
          this.element.addEventListener('connect', resolve, { once: true }));
        yield this.text = ++count;
      }
    }, { trigger: 'element', interval: 100 });
  }
  private set text(count: number) {
    this.children = `Counted ${count} times.`;
  }
  private readonly dom = Shadow.section({ onconnect: '' }, {
    style: HTML.style('@scope { & { color: red; } }'),
    content: HTML.p(''),
  });
  public readonly tag = this.dom.tag;
  public readonly element = this.dom.element;
  public get children() {
    return this.dom.children.content.children;
  }
  public set children(children) {
    this.dom.children.content.children = children;
  }
}

i18n

Create a helper factory function for i18n. However, client-side translation is inefficient except live updates due to the following increase in traffic data size.

  • Schema of translation data.
  • Logic of translation.
  • Unused or duplicate data.
import { HTML, El, html, define } from 'typed-dom';
import i18next from 'i18next';

interface TransDataMap {
  'Greeting': { name: string; };
}

const translator = i18next.createInstance({
  lng: 'en',
  resources: {
    en: {
      translation: {
        'Greeting': 'Hello, {{name}}.',
      },
    },
  } satisfies Record<string, { translation: { [P in keyof TransDataMap]: string; }; }>,
});
translator.init();

function intl
  <K extends keyof TransDataMap>
  (text: K, data: TransDataMap[K], factory?: El.Factory<HTMLElementTagNameMap, El.Children.Void>)
  : El.Factory<HTMLElementTagNameMap, El.Children.Void> {
  return (html, tag) => {
    const el = factory?.(html, tag, {}) ?? html(tag);
    el.textContent = translator.t(text, data)
      ?? `{% Failed to translate "${text}". %}`;
    return el;
  };
}

const el = HTML.span(intl('Greeting', { name: 'world' }));
assert(el.children === undefined);
assert(el.element.textContent === 'Hello, world.');

Or

function data
  <K extends keyof TransDataMap>
  (data: TransDataMap[K], factory?: El.Factory<HTMLElementTagNameMap, K>)
  : El.Factory<HTMLElementTagNameMap, K> {
  return (html, tag, _, children) =>
    define(factory?.(html, tag, {}, children) ?? html(tag), {
      onmutate: ev => {
        ev.currentTarget.textContent = translator.t(children, data)
          ?? `{% Failed to translate "${children}". %}`;
      },
    });
}

const el = HTML.span('Greeting', data({ name: 'world' }));
assert(el.children === 'Hello, world.');
assert(el.element.textContent === 'Hello, world.');

APIs

HTML: { tag: (attrs?, children?, factory?) => El; (tag: string, ...): El; };

Create an HTML element proxy.

  • attrs: Record<string, string | EventListener | null | undefined>
  • children: undefined | string | El[] | Record<string, El> | DocumentFragment
  • factory: (html, tag, attrs, children) => HTMLElement
import { HTML, frag } from 'typed-dom';

HTML.p();
HTML.p('text');
HTML.p(frag(['a', html('br'), 'b']));
HTML.p([HTML.a()]);
HTML.p({ link: HTML.a() }]);
HTML.p({ id: 'id' });
HTML.p(() => document.createElement('p'));
HTML.p(() => document.querySelector('p')!);
HTML('p');

SVG: { tag: (attrs?, children?, factory?) => El; (tag: string, ...): El; };

Create an SVG element proxy.

  • attrs: Record<string, string | EventListener | null | undefined>
  • children: undefined | string | El[] | Record<string, El> | DocumentFragment
  • factory: (svg, tag, attrs, children) => SVGElement
import { SVG } from 'typed-dom';

SVG.svg();

Math: { tag: (attrs?, children?, factory?) => El; (tag: string, ...): El; };

Create an MathML element proxy.

  • attrs: Record<string, string | EventListener | null | undefined>
  • children: undefined | string | El[] | Record<string, El> | DocumentFragment
  • factory: (svg, tag, attrs, children) => MathMLElement
import { Math } from 'typed-dom';

Math.math();

Shadow: { tag: (attrs?, children?, factory?) => El; (tag: string, ...): El; };

Create an HTML element proxy assigning the children to the own open shadow DOM.

  • attrs: Record<string, string | EventListener | null | undefined>
  • children: undefined | string | El[] | Record<string, El> | DocumentFragment
  • factory: (html, tag, attrs, children) => HTMLElement
import { Shadow } from 'typed-dom';

Shadow.section();

API

Create APIs

All the APIs creating an element can be recreated as follows:

import { API, NS, shadow, element } from 'typed-dom';

const html = element<HTMLElementTagNameMap>(document, NS.HTML);
const svg = element<SVGElementTagNameMap>(document, NS.SVG);
const math = element<MathMLElementTagNameMap>(document, NS.Math);

const Shadow = API<ShadowHostHTMLElementTagNameMap>(html, shadow);
const HTML = API<HTMLElementTagNameMap>(html);
const SVG = API<SVGElementTagNameMap>(svg);
const Math = API<MathMLElementTagNameMap>(math);

A closed shadow DOM API can be created as follows:

const Shadow = API<ShadowHostHTMLElementTagNameMap>(html, el => shadow(el, { mode: 'closed' }));

Extend APIs

Custom elements can be created by extending ShadowHostHTMLElementTagNameMap, HTMLElementTagNameMap, or SVGElementTagNameMap interface.

import { Shadow, HTML } from 'typed-dom';

declare global {
  interface ShadowHostHTMLElementTagNameMap {
    'custom-tag': HTMLElement;
  }
  interface HTMLElementTagNameMap {
    'custom': HTMLElement;
  }
}

window.customElements.define('custom-tag', class extends HTMLElement { });
Shadow('custom-tag').element.outerHTML; // '<custom-tag></custom-tag>'
HTML('custom-tag').element.outerHTML; // '<custom-tag></custom-tag>'
HTML.custom().element.outerHTML; // '<custom></custom>'

However, since scoped custom elements don't inherit global custom elements you shouldn't extend the built-in interfaces such as HTMLElementTagNameMap. Instead, you should create new interfaces and new APIs to define custom elements.

import { API, shadow, html } from 'typed-dom';

interface CustomShadowHostElementTagNameMap extends ShadowHostHTMLElementTagNameMap {
  'custom-tag': HTMLElement;
}
interface CustomHTMLElementTagNameMap extends HTMLElementTagNameMap, CustomShadowHostElementTagNameMap {
  'custom': HTMLElement;
}

export const Shadow = API<CustomShadowHostElementTagNameMap>(html, shadow);
export const HTML = API<CustomHTMLElementTagNameMap>(html);

Ideally, you should define custom elements only as scoped custom elements.

import { API, NS, shadow, html as h, element } from 'typed-dom';

interface ShadowHostScopedCustomHTMLElementTagNameMap extends ShadowHostHTMLElementTagNameMap {
  'custom-tag': HTMLElement;
}
interface ScopedCustomHTMLElementTagNameMap extends HTMLElementTagNameMap, ShadowHostScopedCustomHTMLElementTagNameMap {
  'custom': HTMLElement;
}

// Note that the following code is based on the unstandardized APIs of scoped custom elements.
const registry = new CustomElementRegistry();
// This Host function creates a proxy and makes its shadow DOM in the base document (light DOM).
export const Host = API<ShadowHostHTMLElementTagNameMap>(h, el =>
  shadow(el, { mode: 'open', registry }));
// This html function creates a scoped custom element in a shadow DOM.
export const html = element<ScopedCustomHTMLElementTagNameMap>(
  shadow('body', { mode: 'open', registry }),
  NS.HTML);
// This HTML function creates a scoped custom element proxy in a shadow DOM.
export const HTML = API<ScopedCustomHTMLElementTagNameMap>(html);
// This Shadow function creates a scoped custom element proxy and makes its shadow DOM in a shadow DOM.
export const Shadow = API<ShadowHostScopedCustomHTMLElementTagNameMap>(html, shadow);

Others

  • El
  • NS
  • Attrs
  • Children
  • Factory
  • shadow
  • frag
  • html
  • svg
  • math
  • text
  • define
  • append
  • prepend
  • defrag
  • listen
  • once
  • delegate
  • bind
  • currentTarget
  • querySelectorAll
  • querySelectorWith
  • querySelectorAllWith
  • scope

Events

These events are enabled only when an event listener is set using the Typed-DOM APIs.

mutate

The mutate event is dispatched when the children property value is changed.

connect

The connect event is dispatched when added to another proxy connected to the context object.

disconnect

The disconnect event is dispatched when removed from the parent proxy connected to the context object.

0.0.349

1 month ago

0.0.348

6 months ago

0.0.337

11 months ago

0.0.336

11 months ago

0.0.335

11 months ago

0.0.339

11 months ago

0.0.338

11 months ago

0.0.347

8 months ago

0.0.346

9 months ago

0.0.345

9 months ago

0.0.340

10 months ago

0.0.344

9 months ago

0.0.343

9 months ago

0.0.342

9 months ago

0.0.341

10 months ago

0.0.319

1 year ago

0.0.318

1 year ago

0.0.317

1 year ago

0.0.316

1 year ago

0.0.326

1 year ago

0.0.325

1 year ago

0.0.324

1 year ago

0.0.323

1 year ago

0.0.329

1 year ago

0.0.328

1 year ago

0.0.327

1 year ago

0.0.322

1 year ago

0.0.321

1 year ago

0.0.320

1 year ago

0.0.334

12 months ago

0.0.333

12 months ago

0.0.332

1 year ago

0.0.331

1 year ago

0.0.330

1 year ago

0.0.315

1 year ago

0.0.314

1 year ago

0.0.313

1 year ago

0.0.312

2 years ago

0.0.311

2 years ago

0.0.310

2 years ago

0.0.309

2 years ago

0.0.304

2 years ago

0.0.303

2 years ago

0.0.302

2 years ago

0.0.308

2 years ago

0.0.307

2 years ago

0.0.306

2 years ago

0.0.305

2 years ago

0.0.301

2 years ago

0.0.300

2 years ago

0.0.296

2 years ago

0.0.295

2 years ago

0.0.294

2 years ago

0.0.293

2 years ago

0.0.299

2 years ago

0.0.298

2 years ago

0.0.297

2 years ago

0.0.292

2 years ago

0.0.291

2 years ago

0.0.290

2 years ago

0.0.279

2 years ago

0.0.274

2 years ago

0.0.273

2 years ago

0.0.272

2 years ago

0.0.271

2 years ago

0.0.278

2 years ago

0.0.277

2 years ago

0.0.276

2 years ago

0.0.275

2 years ago

0.0.270

2 years ago

0.0.285

2 years ago

0.0.284

2 years ago

0.0.283

2 years ago

0.0.282

2 years ago

0.0.289

2 years ago

0.0.288

2 years ago

0.0.287

2 years ago

0.0.286

2 years ago

0.0.281

2 years ago

0.0.280

2 years ago

0.0.259

2 years ago

0.0.258

2 years ago

0.0.257

2 years ago

0.0.256

2 years ago

0.0.255

2 years ago

0.0.254

2 years ago

0.0.269

2 years ago

0.0.268

2 years ago

0.0.263

2 years ago

0.0.262

2 years ago

0.0.261

2 years ago

0.0.260

2 years ago

0.0.267

2 years ago

0.0.266

2 years ago

0.0.265

2 years ago

0.0.264

2 years ago

0.0.252

2 years ago

0.0.251

2 years ago

0.0.250

2 years ago

0.0.253

2 years ago

0.0.249

2 years ago

0.0.248

2 years ago

0.0.247

2 years ago

0.0.246

2 years ago

0.0.245

2 years ago

0.0.244

3 years ago

0.0.243

3 years ago

0.0.238

3 years ago

0.0.239

3 years ago

0.0.241

3 years ago

0.0.240

3 years ago

0.0.242

3 years ago

0.0.237

3 years ago

0.0.236

3 years ago

0.0.235

3 years ago

0.0.234

3 years ago

0.0.229

3 years ago

0.0.228

3 years ago

0.0.230

3 years ago

0.0.233

3 years ago

0.0.232

3 years ago

0.0.231

3 years ago

0.0.227

3 years ago

0.0.226

3 years ago

0.0.225

3 years ago

0.0.224

3 years ago

0.0.223

3 years ago

0.0.222

3 years ago

0.0.221

3 years ago

0.0.220

3 years ago

0.0.219

3 years ago

0.0.218

3 years ago

0.0.217

3 years ago

0.0.216

3 years ago

0.0.215

3 years ago

0.0.214

3 years ago

0.0.213

3 years ago

0.0.212

3 years ago

0.0.211

3 years ago

0.0.210

3 years ago

0.0.209

3 years ago

0.0.208

3 years ago

0.0.207

3 years ago

0.0.206

3 years ago

0.0.205

3 years ago

0.0.204

3 years ago

0.0.203

3 years ago

0.0.202

3 years ago

0.0.201

3 years ago

0.0.200

4 years ago

0.0.199

4 years ago

0.0.198

4 years ago

0.0.197

4 years ago

0.0.196

4 years ago

0.0.195

4 years ago

0.0.194

4 years ago

0.0.193

4 years ago

0.0.192

4 years ago

0.0.191

4 years ago

0.0.190

4 years ago

0.0.189

4 years ago

0.0.188

4 years ago

0.0.187

4 years ago

0.0.186

4 years ago

0.0.185

4 years ago

0.0.184

4 years ago

0.0.183

4 years ago

0.0.182

4 years ago

0.0.181

4 years ago

0.0.180

4 years ago

0.0.179

4 years ago

0.0.178

4 years ago

0.0.177

4 years ago

0.0.176

4 years ago

0.0.175

4 years ago

0.0.174

4 years ago

0.0.173

4 years ago

0.0.172

4 years ago

0.0.171

4 years ago

0.0.170

4 years ago

0.0.169

4 years ago

0.0.168

4 years ago

0.0.167

4 years ago

0.0.166

4 years ago

0.0.165

4 years ago

0.0.164

4 years ago

0.0.163

4 years ago

0.0.162

4 years ago

0.0.161

4 years ago

0.0.160

4 years ago

0.0.159

4 years ago

0.0.158

4 years ago

0.0.157

4 years ago

0.0.156

4 years ago

0.0.155

4 years ago

0.0.154

4 years ago

0.0.153

4 years ago

0.0.152

4 years ago

0.0.151

4 years ago

0.0.150

4 years ago

0.0.149

4 years ago

0.0.148

4 years ago

0.0.147

4 years ago

0.0.146

4 years ago

0.0.145

5 years ago

0.0.144

5 years ago

0.0.143

5 years ago

0.0.142

5 years ago

0.0.141

5 years ago

0.0.140

5 years ago

0.0.139

5 years ago

0.0.138

5 years ago

0.0.137

5 years ago

0.0.136

5 years ago

0.0.135

5 years ago

0.0.134

5 years ago

0.0.133

5 years ago

0.0.132

5 years ago

0.0.131

5 years ago

0.0.130

5 years ago

0.0.129

5 years ago

0.0.128

5 years ago

0.0.127

5 years ago

0.0.126

5 years ago

0.0.125

5 years ago

0.0.124

5 years ago

0.0.123

5 years ago

0.0.122

5 years ago

0.0.121

5 years ago

0.0.120

5 years ago

0.0.119

5 years ago

0.0.118

5 years ago

0.0.117

5 years ago

0.0.116

5 years ago

0.0.115

5 years ago

0.0.114

5 years ago

0.0.113

5 years ago

0.0.112

5 years ago

0.0.111

5 years ago

0.0.110

5 years ago

0.0.109

5 years ago

0.0.108

6 years ago

0.0.107

6 years ago

0.0.106

6 years ago

0.0.105

6 years ago

0.0.104

6 years ago

0.0.103

6 years ago

0.0.102

6 years ago

0.0.101

6 years ago

0.0.100

6 years ago

0.0.99

6 years ago

0.0.98

6 years ago

0.0.97

6 years ago

0.0.96

6 years ago

0.0.95

6 years ago

0.0.94

6 years ago

0.0.93

6 years ago

0.0.92

6 years ago

0.0.91

6 years ago

0.0.90

6 years ago

0.0.89

6 years ago

0.0.88

6 years ago

0.0.87

6 years ago

0.0.86

6 years ago

0.0.85

6 years ago

0.0.84

6 years ago

0.0.83

6 years ago

0.0.82

6 years ago

0.0.81

6 years ago

0.0.80

6 years ago

0.0.79

6 years ago

0.0.78

6 years ago

0.0.77

6 years ago

0.0.76

6 years ago

0.0.75

6 years ago

0.0.74

6 years ago

0.0.73

6 years ago

0.0.72

6 years ago

0.0.71

6 years ago

0.0.70

6 years ago

0.0.69

6 years ago

0.0.68

6 years ago

0.0.67

6 years ago

0.0.66

6 years ago

0.0.65

6 years ago

0.0.64

6 years ago

0.0.63

6 years ago

0.0.62

7 years ago

0.0.61

7 years ago

0.0.60

7 years ago

0.0.59

7 years ago

0.0.58

7 years ago

0.0.57

7 years ago

0.0.56

7 years ago

0.0.55

7 years ago

0.0.54

7 years ago

0.0.53

7 years ago

0.0.52

7 years ago

0.0.51

7 years ago

0.0.50

7 years ago

0.0.49

7 years ago

0.0.48

7 years ago

0.0.47

7 years ago

0.0.46

7 years ago

0.0.45

7 years ago

0.0.44

7 years ago

0.0.43

7 years ago

0.0.42

7 years ago

0.0.41

7 years ago

0.0.40

7 years ago

0.0.39

7 years ago

0.0.38

7 years ago

0.0.37

7 years ago

0.0.36

7 years ago

0.0.35

7 years ago

0.0.34

7 years ago

0.0.33

7 years ago

0.0.32

7 years ago

0.0.31

7 years ago

0.0.30

7 years ago

0.0.29

7 years ago

0.0.28

7 years ago

0.0.27

7 years ago

0.0.26

7 years ago

0.0.25

7 years ago

0.0.24

7 years ago

0.0.23

7 years ago

0.0.22

7 years ago

0.0.21

7 years ago

0.0.20

7 years ago

0.0.19

7 years ago

0.0.18

7 years ago

0.0.17

7 years ago

0.0.16

7 years ago

0.0.15

7 years ago

0.0.14

7 years ago

0.0.13

7 years ago

0.0.12

7 years ago

0.0.11

7 years ago

0.0.10

7 years ago

0.0.9

8 years ago

0.0.8

8 years ago

0.0.7

8 years ago

0.0.6

8 years ago

0.0.5

8 years ago

0.0.4

8 years ago

0.0.3

8 years ago

0.0.2

8 years ago

0.0.1

8 years ago

0.0.0

8 years ago