Compare commits

..

1 commit

Author SHA1 Message Date
7a789d407e [WIP] Major refactor and API change for version 2.0 2024-01-17 15:16:46 +01:00
3 changed files with 141 additions and 141 deletions

View file

@ -12,6 +12,8 @@ class ChildObserver extends MutationObserver {
} }
} }
const childObserver = new ChildObserver()
export const lense = (methods, extra) => { export const lense = (methods, extra) => {
if (extra) return lense(extra)(methods) if (extra) return lense(extra)(methods)
@ -22,12 +24,12 @@ export const lense = (methods, extra) => {
} else if (prop === Symbol.iterator) { } else if (prop === Symbol.iterator) {
return function*() { return function*() {
for (const child of target.children) { for (const child of target.children) {
yield methods.get.call(child) yield methods.get(child)
} }
} }
} else if (prop.match?.call(prop, /^[0-9]+$/)) { } else if (prop.match?.call(prop, /^[0-9]+$/)) {
const child = target.children[prop] const child = target.children[prop]
if (child) return methods.get.call(child) if (child) return methods.get(child)
return child return child
} else { } else {
return Array.prototype[prop] return Array.prototype[prop]
@ -37,7 +39,7 @@ export const lense = (methods, extra) => {
if (prop.match?.call(prop, /^[0-9]+$/)) { if (prop.match?.call(prop, /^[0-9]+$/)) {
const child = target.children[prop] const child = target.children[prop]
if (child) { if (child) {
methods.set.call(child, value) methods.set(child, value)
return true return true
} else { } else {
for (let i = target.children.length; i < Number(prop); i++) { for (let i = target.children.length; i < Number(prop); i++) {
@ -45,8 +47,8 @@ export const lense = (methods, extra) => {
} }
const element = methods.new(value) const element = methods.new(value)
target.appendChild(element) target.appendChild(element)
if (methods.get.call(element) !== value) if (methods.get(element) !== value)
methods.set.call(element, value) methods.set(element, value)
return true return true
} }
} else if (prop == "length") { } else if (prop == "length") {
@ -69,8 +71,14 @@ export const lense = (methods, extra) => {
} }
return element => { return element => {
if (!(element instanceof Element)) throw(new Error("Creating domLense on non-element")) const proxy = new Proxy(element, traps)
return new Proxy(element, traps)
if (methods.event) childObserver.observe(element)
if (typeof methods.event === "function") element.addEventListener("change", event => {
methods.event(proxy, element, event.detail)
})
return proxy
} }
} }

154
skooma.js
View file

@ -1,30 +1,37 @@
/*
A functional HTML generation library.
Example:
html.label(
html.span("Delete everything", {class: ["warning", "important"]}),
html.button("Click", {onClick: e => document.body.innerHTML=""}),
)
or
html.ul([1, 2, 3, 4, 5].map(x => html.li(x)), {class: "numbers"})
*/
// Keep a referee alive until a referrer is collected // Keep a referee alive until a referrer is collected
const weakReferences = new WeakMap() const weakReferences = new WeakMap()
const untilDeathDoThemPart = (referrer, reference) => { const untilDeathDoThemPart = (referrer, reference) => {
if (!weakReferences.has(referrer)) weakReferences.set(referrer, new Set()) if (!weakReferences.has(referrer)) {
weakReferences.set(referrer, new Set())
}
weakReferences.get(referrer).add(reference) weakReferences.get(referrer).add(reference)
} }
// Like AbortController, but resets after each abort
class MultiAbortController {
#controller = new AbortController()
get signal() { return this.#controller.signal }
abort() { this.#controller.abort(); this.#controller = new AbortController() }
}
export const empty = Symbol("Explicit empty argument for Skooma") export const empty = Symbol("Explicit empty argument for Skooma")
const snakeToCSS = key => key.replace(/^[A-Z]/, a => "-"+a).replace(/[A-Z]/g, a => '-'+a.toLowerCase()) const keyToPropName = key => key.replace(/^[A-Z]/, a => "-"+a).replace(/[A-Z]/g, a => '-'+a.toLowerCase())
const insertStyles = (rule, styles) => { const insertStyles = (rule, styles) => {
for (const [key, value] of Object.entries(styles)) for (const [key, value] of Object.entries(styles))
if (typeof value == "undefined") if (typeof value == "undefined")
rule.removeProperty(snakeToCSS(key)) rule.removeProperty(keyToPropName(key))
else else
rule.setProperty(snakeToCSS(key), value.toString()) rule.setProperty(keyToPropName(key), value.toString())
} }
const processAttribute = (attribute) => { const parseAttribute = (attribute) => {
if (typeof attribute == "string" || typeof attribute == "number") if (typeof attribute == "string" || typeof attribute == "number")
return attribute return attribute
else if (attribute && "join" in attribute) else if (attribute && "join" in attribute)
@ -43,54 +50,55 @@ const getCustom = args => args.reduce(
,undefined ,undefined
) )
export const isReactive = object => object const isElement = object => HTMLElement.prototype.isPrototypeOf(object)
&& typeof object == "object"
&& !(object instanceof HTMLElement) const isReactive = object => object
&& object.subscribe && (object instanceof EventTarget)
&& ("subscribe" in object)
const toChild = arg => { const toChild = arg => {
if (typeof arg == "string" || typeof arg == "number") if (typeof arg == "string" || typeof arg == "number") {
return document.createTextNode(arg) return document.createTextNode(arg)
else if (arg instanceof HTMLElement) } else if (isElement(arg)) {
return arg return arg
else if (isReactive(arg)) } else if (isReactive(arg)) {
return reactiveChild(arg) return reactiveChild(arg)
}
} }
const reactiveChild = reactive => { const reactiveChild = reactive => {
let ref const ref = new WeakRef(toChild(reactive.value))
const abort = reactive.subscribe(value => { reactive.addEventListener("change", () => {
if (ref && !ref.deref()) return abort() const value = ref.deref()
const child = toChild(value) ?? document.createComment("Placeholder for reactive content") if (value)
untilDeathDoThemPart(child, reactive) value.replaceWith(reactiveChild(reactive))
if (ref) ref.deref().replaceWith(child) }, {once: true})
ref = new WeakRef(child) untilDeathDoThemPart(ref.deref(), reactive)
})
return ref.deref() return ref.deref()
} }
const specialAttributes = { const specialAttributes = {
value: { value: {
get() { return this.value }, get: element => element.value,
set(value) { set: (element, value) => {
this.setAttribute("value", value) element.setAttribute("value", value)
this.value = value element.value = value
}, },
hook(callback) { this.addEventListener("input", callback) } hook: (element, callback) => { element.addEventListener("input", callback) }
}, },
style: { style: {
set(value) { insertStyles(this.style, value) } set: (element, value) => { insertStyles(element.style, value) }
}, },
dataset: { dataset: {
set(value) { set: (element, value) => {
for (const [attribute2, value2] of Object.entries(value)) { for (const [attribute2, value2] of Object.entries(value)) {
this.dataset[attribute2] = processAttribute(value2) element.dataset[attribute2] = parseAttribute(value2)
} }
} }
}, },
shadowRoot: { shadowRoot: {
set(value) { set: (element, value) => {
processArgs((this.shadowRoot || this.attachShadow({mode: "open"})), value) parseArgs((element.shadowRoot || element.attachShadow({mode: "open"})), null, value)
} }
} }
} }
@ -100,56 +108,58 @@ const setAttribute = (element, attribute, value, cleanupSignal) => {
if (isReactive(value)) if (isReactive(value))
setReactiveAttribute(element, attribute, value) setReactiveAttribute(element, attribute, value)
else if (typeof value === "function") else if (typeof value === "function")
element.addEventListener(attribute, value, {signal: cleanupSignal}) element.addEventListener(attribute.replace(/^on[A-Z]/, x => x.charAt(x.length-1).toLowerCase()), value, {signal: cleanupSignal})
else if (special?.set) else if (special) {
special.set.call(element, value) special.set(element, value)
}
else if (value === true) else if (value === true)
{if (!element.hasAttribute(attribute)) element.setAttribute(attribute, '')} {if (!element.hasAttribute(attribute)) element.setAttribute(attribute, '')}
else if (value === false) else if (value === false)
element.removeAttribute(attribute) element.removeAttribute(attribute)
else { else {
element.setAttribute(attribute, processAttribute(value)) element.setAttribute(attribute, parseAttribute(value))
} }
} }
// (Two-way) binding between an attribute and a state container const setReactiveAttribute = (element, attribute, reactive, abortController) => {
const setReactiveAttribute = (element, attribute, reactive) => {
untilDeathDoThemPart(element, reactive) untilDeathDoThemPart(element, reactive)
const multiAbort = new MultiAbortController()
let old if (abortController) abortController.abort()
reactive.subscribe(value => { abortController = new AbortController()
old = value
multiAbort.abort() const ref = new WeakRef(element)
setAttribute(element, attribute, value, multiAbort.signal) setAttribute(element, attribute, reactive.value, abortController.signal)
})
reactive.addEventListener("change", () => {
const element = ref.deref()
if (element)
setReactiveAttribute(element, attribute, reactive, abortController)
}, {once: true})
const special = specialAttributes[attribute] const special = specialAttributes[attribute]
if (special?.hook && reactive.set) { if (special?.hook) {
special.hook.call(element, () => { special.hook(element, () => {
const value = special.get.call(element, attribute) const value = special.get(element, attribute)
if (value != old) reactive.set(value) if (value != reactive.value) reactive.value = value
}) })
} }
} }
const processArgs = (element, ...args) => { const parseArgs = (element, before, ...args) => {
if (element.content) element = element.content if (element.content) element = element.content
for (const arg of args) if (arg !== empty) { for (const arg of args) if (arg !== empty) {
if (arg instanceof Array) { const child = toChild(arg)
processArgs(element, ...arg) if (child)
} else { element.insertBefore(child, before)
const child = toChild(arg) else if (arg === undefined || arg == null)
if (child) console.warn(`An argument of type ${typeof arg} has been ignored`, element)
element.append(child) else if (typeof arg == "function")
else if (arg === undefined || arg == null) arg(element)
console.warn(`An argument of type ${typeof arg} has been ignored`, element) else if ("length" in arg)
else if (typeof arg == "function" && arg.length == 0) parseArgs(element, before, ...arg)
processArgs(element, arg()) else
else if (typeof arg == "function") for (const key in arg)
arg(element) setAttribute(element, key, arg[key])
else
for (const key in arg)
setAttribute(element, key, arg[key])
}
} }
} }
@ -163,7 +173,7 @@ const node = (name, args, options) => {
element = document.createElementNS(options.xmlns, name, opts) element = document.createElementNS(options.xmlns, name, opts)
else else
element = document.createElement(name, opts) element = document.createElement(name, opts)
processArgs(element, args) parseArgs(element, null, args)
return element return element
} }

106
state.js
View file

@ -74,9 +74,6 @@ export class SimpleState extends EventTarget {
return () => controller.abort() return () => controller.abort()
} }
get() { return this.value }
set(value) { this.value = value }
emit(property, from, to, options={}) { emit(property, from, to, options={}) {
const change = {property, from, to, ...options} const change = {property, from, to, ...options}
if (!this.synchronous) { if (!this.synchronous) {
@ -124,6 +121,7 @@ export class SimpleState extends EventTarget {
export class State extends SimpleState { export class State extends SimpleState {
#target #target
#shallow #shallow
#forwardCache
static isState(object) { return SimpleState.prototype.isPrototypeOf(object) } static isState(object) { return SimpleState.prototype.isPrototypeOf(object) }
@ -149,52 +147,58 @@ export class State extends SimpleState {
}) })
} }
forward(property="value", methods) { set value(value) { this.values.value = value }
return new ForwardState(this, property, methods) get value() { return this.values.value }
forward(property="value") {
if (!this.#forwardCache) this.#forwardCache = new Map()
const cached = this.#forwardCache.get(property)?.deref()
if (cached) {
return cached
} else {
const forwarded = new ForwardState(this, property)
const ref = new WeakRef(forwarded)
this.#forwardCache.set(property, ref)
forwardFinalizationRegistry.register(forwarded, [this.#forwardCache, property])
return forwarded
}
} }
set(prop, value) { set(...args) {
if (arguments.length === 1) return this.set("value", prop) if (args.length === 1) return this.set("value", ...args)
const [prop, value] = args
this.#target[prop] = value this.#target[prop] = value
} }
get(prop="value") { get(...args) {
if (args.length === 0) return this.get("value")
const prop = args[0]
return this.#target[prop] return this.#target[prop]
} }
set value(value) { this.set(value) }
get value() { return this.get() }
} }
const forwardFinalizationRegistry = new FinalizationRegistry(([cache, name]) => {
cache.remove(name)
})
export class ForwardState extends SimpleState { export class ForwardState extends SimpleState {
#backend #backend
#property #property
#methods
constructor(backend, property, methods = {}) { constructor(backend, property) {
super() super()
this.#methods = methods
this.#backend = backend this.#backend = backend
this.#property = property this.#property = property
const ref = new WeakRef(this) const ref = new WeakRef(this)
const abortController = new AbortController() const abortController = new AbortController()
abortRegistry.register(this, abortController)
backend.addEventListener("change", event => { backend.addEventListener("change", event => {
const state = ref.deref() const state = ref.deref()
if (state) { if (state) {
let relevantChanges = event.changes const relevantChanges = event.changes
.filter(({property: name}) => name === property) .filter(({property: name}) => name === property)
const get = methods.get .map(({from, to}) => ({property: "value", from, to}))
if (methods.get) {
relevantChanges = relevantChanges.map(
({from, to}) => ({property: "value", from: get(from), to: get(to)})
)
} else {
relevantChanges = relevantChanges.map(
({from, to}) => ({property: "value", from, to})
)
}
if (relevantChanges.length > 0) if (relevantChanges.length > 0)
state.dispatchEvent(new ChangeEvent(...relevantChanges)) state.dispatchEvent(new ChangeEvent(...relevantChanges))
} else { } else {
@ -203,23 +207,8 @@ export class ForwardState extends SimpleState {
}, {signal: abortController.signal}) }, {signal: abortController.signal})
} }
get value() { get value() { return this.#backend.values[this.#property]}
const methods = this.#methods set value(value) { this.#backend.values[this.#property] = value }
if (methods.get) {
return methods.get(this.#backend.values[this.#property])
} else {
return this.#backend.values[this.#property]
}
}
set value(value) {
const methods = this.#methods
if (methods.set) {
this.#backend.values[this.#property] = methods.set(value)
} else {
this.#backend.values[this.#property] = value
}
}
} }
class StorageChangeEvent extends Event { class StorageChangeEvent extends Event {
@ -286,12 +275,8 @@ const attributeObserver = new MutationObserver(mutations => {
} }
}) })
export const component = (name, generator, methods) => { export const component = (generator, name) => {
if (typeof name === "function") { name = name ?? camelToKebab(generator.name)
methods = generator
generator = name
name = camelToKebab(generator.name)
}
const Element = class extends HTMLElement{ const Element = class extends HTMLElement{
constructor() { constructor() {
super() super()
@ -304,12 +289,9 @@ export const component = (name, generator, methods) => {
} }
}) })
attributeObserver.observe(this, {attributes: true}) attributeObserver.observe(this, {attributes: true})
this.replaceChildren(generator.call(this, this.state)) this.replaceChildren(generator(this))
} }
} }
if (methods) {
Object.defineProperties(Element.prototype, Object.getOwnPropertyDescriptors(methods))
}
customElements.define(name, Element) customElements.define(name, Element)
return Element; return Element;
} }
@ -340,9 +322,7 @@ class ComposedState extends SimpleState {
#microtaskQueued #microtaskQueued
scheduleUpdate() { scheduleUpdate() {
if (this.synchronous) { if (this.defer) {
this.update()
} else {
if (!this.#microtaskQueued) { if (!this.#microtaskQueued) {
queueMicrotask(() => { queueMicrotask(() => {
this.#microtaskQueued = false this.#microtaskQueued = false
@ -350,6 +330,8 @@ class ComposedState extends SimpleState {
}) })
} }
this.#microtaskQueued = true this.#microtaskQueued = true
} else {
this.update()
} }
} }
@ -357,11 +339,11 @@ class ComposedState extends SimpleState {
const value = this.#func(...this.#states.map(state => state.value)) const value = this.#func(...this.#states.map(state => state.value))
const change = {property: "value", from: this.value, to: value} const change = {property: "value", from: this.value, to: value}
this.value = value this.value = value
this.dispatchEvent(new ChangeEvent(change)) this.dispatchEvent(new ChangeEvent([change]))
} }
} }
export const compose = func => (...states) => new ComposedState(func, {}, ...states) export const compose = func => (...states) => new ComposedState(func, {defer: true}, ...states)
const eventName = "mutation" const eventName = "mutation"
@ -414,9 +396,7 @@ export class DOMState extends SimpleState {
this.#old = current this.#old = current
if (this.synchronous) { if (this.defer) {
this.dispatchEvent(new ChangeEvent(["value", current]))
} else {
if (!this.#changedValue) { if (!this.#changedValue) {
queueMicrotask(() => { queueMicrotask(() => {
this.#changedValue = false this.#changedValue = false
@ -424,6 +404,8 @@ export class DOMState extends SimpleState {
}) })
this.#changedValue = current this.#changedValue = current
} }
} else {
this.dispatchEvent(new ChangeEvent(["value", current]))
} }
} }
} }