mosaic 1.1.0 → 2.1.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.
@@ -0,0 +1,4 @@
1
+ import type { ActionHandlers, Controller, MosaicConfig } from "./types.js";
2
+ export type { ActionHandlers, RenderContext, EventContext, Attributes, AttributeValue, Classes, TextValue, Controller, Dispatch, ElementConfig, EventBindings, MosaicConfig, StoreConfig, StringKey, SyncKey, } from "./types.js";
3
+ export declare const Mosaic: <State extends object = Record<string, never>, Actions extends ActionHandlers<State> = {}>(rootNode: Element, config: MosaicConfig<State, Actions>) => Controller<State, Actions>;
4
+ export declare const $: typeof Mosaic;
@@ -0,0 +1,3 @@
1
+ import type { StateStore } from "./store.js";
2
+ import type { ActionHandlers, MosaicConfig } from "./types.js";
3
+ export declare function initialise<State extends object, Actions extends ActionHandlers<State>>(rootNode: Element, config: MosaicConfig<State, Actions>, store: StateStore<State, Actions>): void;
@@ -0,0 +1,5 @@
1
+ export declare const Message: <Args extends unknown[]>() => {
2
+ clear(): void;
3
+ subscribe(callback: (...args: Args) => void): () => void;
4
+ publish(...args: Args): unknown[];
5
+ };
@@ -0,0 +1,9 @@
1
+ import type { ActionHandlers, Controller, StoreConfig } from "./types.js";
2
+ export interface StateStore<State extends object, Actions> {
3
+ controller: Controller<State, Actions>;
4
+ initialise(state: State, render: (state: State) => void): void;
5
+ patch(state: Partial<State>): void;
6
+ own(cleanup: () => void): void;
7
+ isDestroyed(): boolean;
8
+ }
9
+ export declare function Store<State extends object, Actions extends ActionHandlers<State> = {}>({ actions: actionHandlers, getState: getStateWrapper, }: StoreConfig<State, Actions>): StateStore<State, Actions>;
@@ -0,0 +1,52 @@
1
+ export type ActionHandlers<State extends object> = Record<string, (state: State, payload: never) => State>;
2
+ type Payload<Handler> = Handler extends (state: never, ...payload: infer Args) => unknown ? Args : never;
3
+ export type Dispatch<Actions> = <Name extends keyof Actions & string>(name: Name, ...payload: Payload<Actions[Name]>) => Promise<void>;
4
+ export interface Controller<State extends object, Actions = {}> {
5
+ dispatch: Dispatch<Actions>;
6
+ getState(): State;
7
+ destroy(): void;
8
+ subscribe(callback: (state: State) => void): () => void;
9
+ }
10
+ export type AttributeValue = string | number | boolean | null | undefined;
11
+ export type Attributes = Record<string, AttributeValue>;
12
+ export type TextValue = string | number | boolean | null | undefined;
13
+ export type Classes = Record<string, boolean>;
14
+ export type StringKey<State> = {
15
+ [Key in keyof State]-?: State[Key] extends string ? Key : never;
16
+ }[keyof State] & string;
17
+ export type SyncKey<State> = {
18
+ [Key in keyof State]-?: State[Key] extends string | boolean ? Key : never;
19
+ }[keyof State] & string;
20
+ export interface RenderContext<State extends object> {
21
+ state: State;
22
+ element: Element;
23
+ index: number;
24
+ }
25
+ export interface EventContext<State extends object, Actions = {}, E extends Event = Event> {
26
+ state: State;
27
+ element: Element;
28
+ index: number;
29
+ event: E;
30
+ dispatch: Dispatch<Actions>;
31
+ getState(): State;
32
+ }
33
+ type Events = HTMLElementEventMap;
34
+ export type EventBindings<State extends object, Actions> = {
35
+ [Name in keyof Events]?: (keyof Actions & string) | ((context: EventContext<State, Actions, Events[Name]>) => void | Promise<void>);
36
+ };
37
+ export interface ElementConfig<State extends object, Actions = {}> {
38
+ attribute?: (context: RenderContext<State>) => Attributes | null | undefined;
39
+ text?: (context: RenderContext<State>) => TextValue;
40
+ class?: (context: RenderContext<State>) => Classes | null | undefined;
41
+ on?: EventBindings<State, Actions>;
42
+ sync?: SyncKey<State>;
43
+ }
44
+ export interface StoreConfig<State extends object, Actions extends ActionHandlers<State> = {}> {
45
+ actions?: Actions & ActionHandlers<State>;
46
+ getState?: (state: State) => State;
47
+ }
48
+ export interface MosaicConfig<State extends object, Actions extends ActionHandlers<State> = {}> extends StoreConfig<State, Actions> {
49
+ state?: State;
50
+ elements?: Record<string, ElementConfig<State, Actions>>;
51
+ }
52
+ export {};
@@ -0,0 +1,4 @@
1
+ import type { Attributes, Classes, TextValue } from "./types.js";
2
+ export declare function write(node: Element, attributes: Attributes | null | undefined): void;
3
+ export declare function writeText(node: Element, value: TextValue): void;
4
+ export declare function writeClasses(node: Element, classes: Classes | null | undefined): void;
package/package.json CHANGED
@@ -1,33 +1,66 @@
1
1
  {
2
2
  "name": "mosaic",
3
3
  "type": "module",
4
- "version": "1.1.0",
4
+ "version": "2.1.0",
5
5
  "description": "A JavaScript library for progressive enhancing HTML",
6
- "main": "dist/mosaic.min.js",
7
- "browser": "dist/mosaic.min.js",
6
+ "main": "dist/mosaic.js",
7
+ "browser": "dist/mosaic.js",
8
8
  "unpkg": "dist/mosaic.min.js",
9
- "module": "src/index.js",
9
+ "module": "dist/mosaic.js",
10
+ "types": "dist/types/index.d.ts",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/defx/mosaic.git"
14
+ },
15
+ "homepage": "https://github.com/defx/mosaic#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/defx/mosaic/issues"
18
+ },
10
19
  "scripts": {
11
- "test": "mocha-express --coverage",
12
- "test:watch": "mocha-express --watch",
20
+ "dev": "vite",
21
+ "typecheck": "tsc --noEmit",
22
+ "test": "vitest run",
23
+ "test:watch": "vitest --watch",
24
+ "test:coverage": "vitest run --coverage",
25
+ "test:install-browsers": "playwright install chromium firefox webkit",
13
26
  "size": "gzip -c9 ./dist/mosaic.min.js | wc -c",
14
- "build": "rm -rf dist && rollup -c && npm run size",
15
- "prepublish": "npm run build"
27
+ "build": "rm -rf dist cjs && npm run typecheck && tsc -p tsconfig.build.json && rollup -c && npm run size",
28
+ "test:all": "vitest run --config vitest.all.config.ts",
29
+ "test:package": "npm run build && node scripts/check-package.mjs",
30
+ "prepack": "npm run build"
16
31
  },
17
32
  "keywords": [],
18
33
  "author": "",
19
34
  "license": "MIT",
20
35
  "files": [
21
- "src",
22
- "dist",
23
- "cjs"
36
+ "dist/mosaic.js",
37
+ "dist/mosaic.min.js",
38
+ "dist/types"
24
39
  ],
25
40
  "directories": {
26
41
  "test": "test"
27
42
  },
28
43
  "devDependencies": {
29
- "mocha-express": "^0.1.2",
44
+ "@vitest/browser-playwright": "5.0.5",
45
+ "@vitest/coverage-v8": "5.0.5",
46
+ "@types/node": "^24.0.0",
47
+ "playwright": "1.64.1",
30
48
  "rollup": "^2.79.1",
31
- "rollup-plugin-terser": "^7.0.2"
49
+ "rollup-plugin-terser": "^7.0.2",
50
+ "typescript": "7.0.2",
51
+ "vite": "8.3.4",
52
+ "vitest": "5.0.5"
53
+ },
54
+ "exports": {
55
+ ".": {
56
+ "types": "./dist/types/index.d.ts",
57
+ "import": "./dist/mosaic.js",
58
+ "default": "./dist/mosaic.js"
59
+ },
60
+ "./dist/mosaic.min.js": {
61
+ "types": "./dist/types/index.d.ts",
62
+ "import": "./dist/mosaic.min.js",
63
+ "default": "./dist/mosaic.min.js"
64
+ }
32
65
  }
33
66
  }
package/cjs/define.js DELETED
@@ -1,99 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var initialise = require('./initialise.js');
6
- var store = require('./store.js');
7
- var message = require('./message.js');
8
-
9
- const define = (name, configFn) => {
10
- if (customElements.get(name)) return
11
-
12
- customElements.define(
13
- name,
14
- class extends HTMLElement {
15
- async connectedCallback() {
16
- let nextTickSubscribers = [];
17
- const config = configFn(this);
18
-
19
- const api = {
20
- nextTick: (fn) => nextTickSubscribers.push(fn),
21
- };
22
-
23
- const message$1 = message.Message({
24
- postPublish: () => {
25
- nextTickSubscribers.forEach((fn) => fn(state));
26
- nextTickSubscribers = [];
27
- },
28
- });
29
-
30
- const observed = new Set();
31
- const host = this;
32
-
33
- const wrap = (state) => {
34
- return new Proxy(state, {
35
- get(_, name) {
36
- if (observed.has(name) === false) {
37
- Object.defineProperty(host, name, {
38
- get() {
39
- return getState()[name]
40
- },
41
- set(value) {
42
- merge({ [name]: value });
43
- },
44
- });
45
-
46
- observed.add(name);
47
- }
48
- return Reflect.get(...arguments)
49
- },
50
- })
51
- };
52
-
53
- const onChangeCallback = (state) => {
54
- message$1.publish(wrap(state), config);
55
- };
56
-
57
- const store$1 = store.Store({
58
- ...config,
59
- api,
60
- onChangeCallback,
61
- });
62
-
63
- const { getState, merge } = store$1;
64
-
65
- const initialState = initialise.initialise(
66
- this,
67
- message$1.subscribe,
68
- config,
69
- store$1,
70
- ((state) => (typeof state === "function" ? state({}) : state))(
71
- config.state || {}
72
- )
73
- );
74
-
75
- store$1.set(initialState);
76
- onChangeCallback(store$1.getState());
77
-
78
- const sa = this.setAttribute;
79
- this.setAttribute = (name, value) => {
80
- if (observed.has(name)) {
81
- merge({ [name]: value });
82
- }
83
- return sa.apply(this, [name, value])
84
- };
85
- const ra = this.removeAttribute;
86
- this.removeAttribute = (name) => {
87
- if (observed.has(name)) {
88
- merge({ [name]: null });
89
- }
90
- return ra.apply(this, [name])
91
- };
92
-
93
- config.connectedCallback?.(this, store$1);
94
- }
95
- }
96
- );
97
- };
98
-
99
- exports.define = define;
package/cjs/helpers.js DELETED
@@ -1,33 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function cast(v) {
6
- if (typeof v === "string" && v.length) {
7
- return isNaN(v) ? v : +v
8
- }
9
- return v
10
- }
11
-
12
- function castAll(o) {
13
- return Object.fromEntries(Object.entries(o).map(([k, v]) => [k, cast(v)]))
14
- }
15
-
16
- const isPrimitive = (v) => v === null || typeof v !== "object";
17
-
18
- function nodeFromString(str) {
19
- const doc = new DOMParser().parseFromString(str.trim(), "text/html", {
20
- includeShadowRoots: true, // @todo: required?
21
- });
22
-
23
- const errorNode = doc.querySelector("parsererror");
24
-
25
- if (errorNode) ; else {
26
- return doc.head.firstChild || doc.body.firstChild
27
- }
28
- }
29
-
30
- exports.cast = cast;
31
- exports.castAll = castAll;
32
- exports.isPrimitive = isPrimitive;
33
- exports.nodeFromString = nodeFromString;
package/cjs/initialise.js DELETED
@@ -1,118 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var list = require('./list.js');
6
- var xo = require('./xo.js');
7
-
8
- function initialise(rootNode, subscribe, config, store, state = {}) {
9
- const event = {};
10
-
11
- const { elements = [] } = config;
12
-
13
- // derive initial state from input directives...
14
- elements
15
- .filter(({ input }) => input)
16
- .forEach(({ select, input }) => {
17
- const targets = [...rootNode.querySelectorAll(select)];
18
- targets.forEach((target) => {
19
- state = { ...state, [input]: target.value };
20
-
21
- event.input = event.input || [];
22
- event.input.push({
23
- select,
24
- callback: (event) => {
25
- const { target } = event;
26
- store.merge({ [input]: target.value });
27
- },
28
- });
29
- });
30
- });
31
-
32
- // find event listeners
33
- elements.forEach((c) => {
34
- const { select, on } = c;
35
- if (on) {
36
- Object.entries(on).forEach(([type, callback]) => {
37
- event[type] = event[type] || [];
38
- event[type].push({
39
- select,
40
- callback,
41
- });
42
- });
43
- }
44
- });
45
-
46
- //derive initial state from lists...
47
- elements
48
- .filter(({ list }) => list)
49
- .forEach(({ select, list: list$1 }) => {
50
- const targets = [...rootNode.querySelectorAll(select)];
51
- targets.forEach((target) => {
52
- const items = list.listItems(target, list$1.select);
53
- const curr = list.listData(items);
54
- state[list$1.from] = curr;
55
- });
56
- });
57
-
58
- // delegate from the root node
59
- Object.entries(event).forEach(([type, listeners]) => {
60
- rootNode.addEventListener(type, (e) => {
61
- listeners
62
- .filter(({ select }) => e.target.matches(select))
63
- .forEach(({ select, callback }) => {
64
- if (typeof callback === "function") {
65
- callback(e, store);
66
- }
67
- if (typeof callback === "string") {
68
- const { target } = e;
69
-
70
- const targets = [...rootNode.querySelectorAll(select)];
71
-
72
- const index = targets.indexOf(target);
73
-
74
- store.dispatch(callback, { event: e, index });
75
- }
76
- });
77
- });
78
- });
79
-
80
- const onChange = (state) => {
81
- // lists first
82
- elements
83
- .filter(({ list }) => list)
84
- .forEach(({ select, list: list$1 }) => {
85
- const targets = [...rootNode.querySelectorAll(select)];
86
- targets.forEach((target) => {
87
- const items = list.listItems(target, list$1.select);
88
- const curr = list.listData(items);
89
- const next = state[list$1.from];
90
- list.listSync(target, items, curr, next, list$1.template);
91
- });
92
- });
93
-
94
- // then the rest...
95
- elements.forEach((c) => {
96
- const { select, attribute, input } = c;
97
-
98
- const targets = [...rootNode.querySelectorAll(select)];
99
-
100
- targets.forEach((target, i) => {
101
- if (attribute) {
102
- xo.write(target, attribute(state, i));
103
- }
104
- if (input) {
105
- const value = state[input];
106
-
107
- if (target.value !== value) target.value = value;
108
- }
109
- });
110
- });
111
- };
112
-
113
- subscribe(onChange);
114
-
115
- return state
116
- }
117
-
118
- exports.initialise = initialise;
package/cjs/list.js DELETED
@@ -1,76 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var helpers = require('./helpers.js');
6
-
7
- function listItems(listContainerNode, listItemSelector) {
8
- return [...listContainerNode.children].filter((node) =>
9
- node.matches(listItemSelector)
10
- )
11
- }
12
-
13
- function listData(listItems) {
14
- return listItems.map((node) => ({
15
- id: node.id,
16
- ...helpers.castAll(node.dataset),
17
- }))
18
- }
19
-
20
- function listSync(parentNode, nodes, curr, next, template) {
21
- // check if anything has changed
22
- const currIds = curr.map(({ id }) => id);
23
- const nextIds = next.map(({ id }) => id);
24
-
25
- if (currIds.toString() === nextIds.toString()) return
26
-
27
- // removals
28
- curr
29
- .filter((c) => {
30
- return next.find((n) => c.id === n.id) === undefined
31
- })
32
- .forEach(({ id }) => nodes.find((node) => node.id === id)?.remove());
33
-
34
- const [first, ...rest] = next;
35
-
36
- if (!first) return
37
-
38
- let t = first && nodes.find((node) => node.id === first.id);
39
-
40
- if (
41
- !template &&
42
- next.find((c) => {
43
- return curr.find((n) => c.id === n.id) === false
44
- })
45
- ) {
46
- console.error(`Missing template when trying to add items to a list`);
47
- return
48
- }
49
-
50
- if (!t) {
51
- t = helpers.nodeFromString(template(first));
52
-
53
- if (nodes[0]) {
54
- nodes[0].before(t);
55
- } else {
56
- parentNode.append(t);
57
- }
58
- }
59
-
60
- rest.forEach((d) => {
61
- let node =
62
- nodes.find((node) => node.id === d.id) || helpers.nodeFromString(template(d));
63
-
64
- if (node) {
65
- if (t.nextElementSibling !== node) {
66
- // is t.after already a no-op in this case?
67
- t.after(node);
68
- }
69
- t = node;
70
- }
71
- });
72
- }
73
-
74
- exports.listData = listData;
75
- exports.listItems = listItems;
76
- exports.listSync = listSync;
package/cjs/message.js DELETED
@@ -1,18 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- const Message = (callbacks) => {
6
- const subscribers = [];
7
- return {
8
- subscribe(fn) {
9
- subscribers.push(fn);
10
- },
11
- publish(...args) {
12
- subscribers.forEach((fn) => fn(...args));
13
- callbacks.postPublish?.();
14
- },
15
- }
16
- };
17
-
18
- exports.Message = Message;
package/cjs/store.js DELETED
@@ -1,55 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function debounce(fn) {
6
- let id;
7
- return (...args) => {
8
- if (!id) {
9
- id = requestAnimationFrame(() => {
10
- fn(...args);
11
- id = null;
12
- });
13
- }
14
- }
15
- }
16
-
17
- function Store({
18
- action: actionHandlers = {},
19
- getState: getStateWrapper = (v) => v,
20
- onChangeCallback,
21
- api = {},
22
- }) {
23
- let state;
24
-
25
- const transition = debounce(() => onChangeCallback(getState()));
26
-
27
- function set(o) {
28
- state = getStateWrapper({ ...o });
29
- }
30
-
31
- function getState() {
32
- return { ...state }
33
- }
34
-
35
- function dispatch(type, action) {
36
- if (type in actionHandlers) {
37
- const x = actionHandlers[type](getState(), action);
38
- set(x);
39
- transition();
40
- }
41
- }
42
-
43
- return {
44
- dispatch,
45
- getState,
46
- merge: (o) => {
47
- set({ ...getState(), ...o });
48
- transition();
49
- },
50
- set,
51
- ...api,
52
- }
53
- }
54
-
55
- exports.Store = Store;
package/cjs/xo.js DELETED
@@ -1,66 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var helpers = require('./helpers.js');
6
-
7
- const pascalToKebab = (string) =>
8
- string.replace(/[\w]([A-Z])/g, function (m) {
9
- return m[0] + "-" + m[1].toLowerCase()
10
- });
11
-
12
- const kebabToPascal = (string) =>
13
- string.replace(/[\w]-([\w])/g, function (m) {
14
- return m[0] + m[2].toUpperCase()
15
- });
16
-
17
- const objectToClasses = (v = {}) => {
18
- return Object.entries(v)
19
- .reduce((c, [k, v]) => {
20
- if (v) c.push(k);
21
- return c
22
- }, [])
23
- .join(" ")
24
- };
25
-
26
- const write = (node, attrs) => {
27
- for (let [k, v] of Object.entries(attrs || {})) {
28
- k = pascalToKebab(k);
29
-
30
- if (k === "textContent" && node.textContent !== textContent) {
31
- node.textContent = textContent;
32
- continue
33
- }
34
-
35
- if (k === "class") {
36
- v = objectToClasses(v);
37
- }
38
-
39
- if (typeof v === "boolean") {
40
- if (k.startsWith("aria-")) {
41
- v = "" + v;
42
- } else if (v) {
43
- v = "";
44
- }
45
- }
46
-
47
- if (helpers.isPrimitive(v) === false) {
48
- node[kebabToPascal(k)] = v;
49
- continue
50
- }
51
-
52
- let current = node.getAttribute(k);
53
-
54
- if (v === current) continue
55
-
56
- if (typeof v === "string" || typeof v === "number") {
57
- node.setAttribute(k, v);
58
- } else {
59
- node.removeAttribute(k);
60
- }
61
- }
62
- return node
63
- };
64
-
65
- exports.objectToClasses = objectToClasses;
66
- exports.write = write;