skooma-js/observable.js

516 lines
12 KiB
JavaScript
Raw Normal View History

/** @type FinalizationRegistry<AbortController> */
2024-01-15 10:02:44 +00:00
const abortRegistry = new FinalizationRegistry(controller => controller.abort())
2023-12-27 16:02:22 +00:00
/** @param {String} string */
const camelToKebab = string => string.replace(/([a-z])([A-Z])/g, (_, a, b) => `${a}-${b.toLowerCase()}`)
/** @param {String} string */
const kebabToCamel = string => string.replace(/([a-z])-([a-z])/g, (_, a, b) => a+b.toUpperCase())
const identity = object=>object
const target = Symbol("Proxy Target")
/* Custom Event Classes */
2024-06-24 10:26:41 +00:00
/**
* @typedef {Object} Change
* @property {string} property
* @property {any} from
* @property {any} to
* @property {boolean} mutation - The change happened inside the value without a new assignment
*/
/** Event fired for every change before the internal state has been updated that can be canceled. */
export class SynchronousChangeEvent extends Event {
2024-06-24 10:26:41 +00:00
/** @param {Change} change */
constructor(change) {
super('synchronous', {cancelable: true})
2024-06-24 09:31:19 +00:00
this.change = Object.freeze(change)
}
}
2024-06-24 10:26:41 +00:00
/** Event fired for one or more changed values after the internal state has been updated. */
export class MultiChangeEvent extends Event {
2024-06-24 10:26:41 +00:00
/** @type {any} */
#final
2024-06-24 10:26:41 +00:00
/** @type {any} */
#values
2024-06-24 10:26:41 +00:00
/** @param {Change[]} changes */
constructor(...changes) {
super('change')
this.changes = changes
}
get values() {
if (!this.#values) {
const values = new Map()
for (const {property, from, to} of this.changes) {
let list = values.get(property)
if (!list) {
list = [from]
values.set(property, list)
}
list.push(to)
}
this.#values = values
}
return this.#values
}
get final() {
if (!this.#final) {
this.#final = new Map()
for (const [property, list] of this.values) {
if (list[0] !== list[list.length-1]) {
this.#final.set(property, list[list.length-1])
}
}
}
return this.#final
}
}
export class ValueChangeEvent extends MultiChangeEvent {
get value() {
return this.final.value
}
}
/* Observable Classes */
export class Observable extends EventTarget {
#synchronous
2024-06-24 10:26:41 +00:00
/** @type Change[]> */
#queue
#abortController = new AbortController
2023-12-27 18:44:50 +00:00
#ref = new WeakRef(this)
get ref() { return this.#ref }
2024-06-24 09:31:19 +00:00
constructor({synchronous=false}={}) {
super()
2024-06-24 09:31:19 +00:00
Object.defineProperty(this, "observable", {value: true, configurable: false, writable: false})
if (this.constructor === Observable) {
throw new TypeError("Cannot instantiate abstract class")
}
this.#synchronous = !!synchronous
2023-12-27 18:44:50 +00:00
abortRegistry.register(this, this.#abortController)
this.proxy = new Proxy(this.constructor.prototype.proxy, {
get: (target, prop) => target.call(this, prop)
})
}
2024-06-24 10:26:41 +00:00
/**
* @param {string} prop
*/
proxy(prop, {get=undefined, set=undefined, ...options}={}) {
const proxy = new ProxiedObservableValue(this, prop, options)
if (get) proxy.get = get
if (set) proxy.set = set
return proxy
}
2024-06-24 10:26:41 +00:00
/**
* @param {string} prop
2024-06-24 11:04:42 +00:00
* @param {function(any):void} callback
2024-06-24 10:26:41 +00:00
*/
subscribe(prop, callback) {
const controller = new AbortController()
2024-06-24 10:26:41 +00:00
// @ts-ignore
this.addEventListener("change", ({final}) => {
if (final.has(prop)) return callback(final.get(prop))
}, {signal: controller.signal})
2024-06-24 10:26:41 +00:00
callback(this[prop])
return () => controller.abort()
}
2024-06-24 10:26:41 +00:00
/** Queues up a change event
* @param {string} property - Name of the changed property
* @param {any} from
* @param {any} to
* @param {boolean} mutation - whether a change was an assignment or a mutation (nested change)
*/
enqueue(property, from, to, mutation=false) {
const change = {property, from, to, mutation}
if (!this.dispatchEvent(new SynchronousChangeEvent(change))) return false
if (!this.synchronous) {
if (!this.#queue) {
this.#queue = []
queueMicrotask(() => {
this.emit(...this.#queue)
this.#queue = undefined
})
}
this.#queue.push(change)
} else {
this.emit(change)
}
return true
}
2024-06-24 10:26:41 +00:00
/** @param {any[]} _args */
emit(..._args) {
throw new TypeError(`${this.constructor.name} did not define an 'emit' method`)
2023-12-27 18:44:50 +00:00
}
get signal() { return this.#abortController.signal }
get synchronous() { return this.#synchronous }
}
export class ObservableObject extends Observable {
2024-06-24 11:04:42 +00:00
/**
* @param {Object} target
* @param {Object} options
*/
constructor(target={}, {shallow=true, ...options}={}) {
super(options)
2024-06-24 11:04:42 +00:00
Object.defineProperty(this, "target", target)
this.values = new Proxy(target, {
2024-06-24 11:04:42 +00:00
/**
* @param {Object} target
* @param {String} prop
* @param {any} value
*/
set: (target, prop, value) => {
const old = target[prop]
if (old === value) {
return true
} else {
if (this.enqueue(prop, old, value)) {
2024-06-24 11:04:42 +00:00
if (!shallow) {
if (old instanceof Observable) this.disown(prop, old)
if (value instanceof Observable) this.adopt(prop, value)
}
target[prop] = value
return true
} else {
return false
}
}
},
2024-06-24 11:04:42 +00:00
/**
* @param {Object} target
* @param {String} prop
*/
get: (target, prop) => target[prop],
})
}
2024-06-24 11:04:42 +00:00
/**
* @param {string} prop
* @param {Object} options
*/
proxy(prop, {get=undefined, set=undefined, ...options}={}) {
const proxy = new ProxiedObservableValue(this, prop, {values: this.values, ...options})
if (get) proxy.get = get
if (set) proxy.set = set
return proxy
}
2024-06-24 11:04:42 +00:00
/** @param {Change[]} changes */
emit(...changes) {
this.dispatchEvent(new MultiChangeEvent(...changes))
}
/** @type Map<Observable, Map<String, Function>> */
#nested = new Map()
2024-06-24 11:04:42 +00:00
/** Adopts an obsercable to be notified of its changes
* @param {string} prop
* @param {Observable} observable
*/
adopt(prop, observable) {
let handlers = this.#nested.get(observable)
if (!handlers) {
// Actual adoption
handlers = new Map()
this.#nested.set(observable, handlers)
}
const ref = this.ref
const handler = () => ref.deref()?.emit(prop, observable, observable, {observable: true})
handlers.set(prop, handler)
observable.addEventListener("change", handler, {signal: this.signal})
}
2024-01-24 15:11:22 +00:00
2024-06-24 11:04:42 +00:00
/** Undoes the adoption of a nested observable, cancelling the associated event hook
* @param {string} prop
* @param {Observable} observable
*/
disown(prop, observable) {
const handlers = this.#nested.get(observable)
const handler = handlers.get(prop)
observable.removeEventListener("change", handler)
handlers.delete(prop)
if (handlers.size == 0) {
this.#nested.delete(observable)
}
}
}
export class ObservableValue extends Observable {
#value
2024-06-24 11:04:42 +00:00
/**
* @param {any} value
* @param {Object} options
*/
constructor(value, options) {
super(options)
this.#value = value
}
get value() { return this.#value }
set value(value) {
if (this.enqueue("value", this.#value, value)) {
this.#value = value
2024-01-24 08:24:41 +00:00
}
}
2024-06-24 10:26:41 +00:00
/**
2024-06-24 11:04:42 +00:00
* @param {string} prop
* @param {function(any):void} callback
2024-06-24 10:26:41 +00:00
*/
2024-06-24 11:04:42 +00:00
subscribe(prop, callback) {
// @ts-ignore
if (typeof(prop) == "function") [prop, callback] = ["value", prop]
this.constructor.prototype.subscribe.call(this, prop, callback)
2024-06-24 10:26:41 +00:00
}
2024-06-24 11:04:42 +00:00
/** @param {Change[]} changes */
emit(...changes) {
this.dispatchEvent(new ValueChangeEvent(...changes))
}
}
class ProxiedObservableValue extends ObservableValue {
#values
#prop
2024-06-24 11:04:42 +00:00
/**
* @param {Observable} backend
* @param {string} prop
*/
constructor(backend, prop, {values=backend, ...options}={}) {
super(options)
this.#values = values
this.#prop = prop
const ref = this.ref
backend.addEventListener("synchronous", event => {
const {property, from, to, ...rest} = event.change
if (property == this.#prop) {
ref.deref()?.enqueue({
property,
from: this.get(from),
to: this.get(to),
...rest
})
}
}, { signal: this.signal })
2024-01-24 08:24:41 +00:00
}
get = identity
set = identity
get value() { return this.get(this.#values[this.#prop]) }
set value(value) { this.#values[this.#prop] = this.set(value) }
}
const attributeObserver = new MutationObserver(mutations => {
for (const {type, target, attributeName: name} of mutations) {
if (type == "attributes") {
const next = target.getAttribute(name)
const camelName = kebabToCamel(name)
if (String(target.state.values[camelName]) !== next)
target.state.values[camelName] = next
}
}
})
export const component = (name, generator, methods) => {
if (typeof name === "function") {
methods = generator
generator = name
name = camelToKebab(generator.name)
}
2023-12-27 16:02:22 +00:00
const Element = class extends HTMLElement{
constructor() {
super()
const target = Object.fromEntries([...this.attributes].map(attribute => [kebabToCamel(attribute.name), attribute.value]))
this.state = new ObservableObject(target)
this.state.addEventListener("change", event => {
for (const {property, to: value} of event.changes) {
const kebabName = camelToKebab(property)
if (this.getAttribute(kebabName) !== String(value))
this.setAttribute(kebabName, value)
}
})
attributeObserver.observe(this, {attributes: true})
const content = generator.call(this, this.state)
if (content) this.replaceChildren(content)
}
2023-12-27 16:02:22 +00:00
}
if (methods) {
Object.defineProperties(Element.prototype, Object.getOwnPropertyDescriptors(methods))
}
2023-12-27 16:02:22 +00:00
customElements.define(name, Element)
return Element;
}
class ObservableComposition extends ObservableValue {
2023-12-27 16:02:22 +00:00
#func
#states
constructor(func, options, ...states) {
super(options)
2023-12-27 16:02:22 +00:00
this.#func = func
this.#states = states
const abortController = new AbortController()
abortRegistry.register(this, abortController)
const ref = new WeakRef(this)
states.forEach(state => {
state.addEventListener("change", () => {
ref.deref()?.scheduleUpdate()
2023-12-27 16:02:22 +00:00
}, {signal: abortController.signal})
})
this.update()
}
#microtaskQueued
scheduleUpdate() {
2024-01-24 15:11:22 +00:00
if (this.synchronous) {
this.update()
} else {
2023-12-27 16:02:22 +00:00
if (!this.#microtaskQueued) {
queueMicrotask(() => {
this.#microtaskQueued = false
this.update()
})
this.#microtaskQueued = true
2023-12-27 16:02:22 +00:00
}
}
}
update() {
const value = this.#func(...this.#states.map(state => state.value))
const change = {property: "value", from: this.value, to: value}
this.value = value
this.emit(change)
2023-12-27 16:02:22 +00:00
}
}
export const compose = func => (...states) => new ObservableComposition(func, {}, ...states)
2024-01-10 19:42:09 +00:00
class MutationEvent extends Event {
constructor() {
super("mutation", {bubbles: true})
2024-01-10 19:42:09 +00:00
}
}
const mutationObserver = new MutationObserver(mutations => {
for (const mutation of mutations) {
mutation.target.dispatchEvent(new MutationEvent())
}
})
export class ObservableElement extends Observable {
#getValue
#equal
#value
2024-01-10 19:42:09 +00:00
#changedValue = false
2024-06-24 09:29:05 +00:00
/**
* @param {HTMLElement} target
*/
constructor(target, {get=undefined, equal=undefined, ...options}={}) {
// @ts-ignore
super(options)
2024-06-24 09:31:19 +00:00
Object.defineProperty(this, "target", {value: target, configurable: false, writable: false})
this.#getValue = get ?? (target => target.value)
this.#equal = equal ?? ((a, b) => a===b)
this.#value = this.#getValue(target)
2024-01-10 19:42:09 +00:00
const controller = new AbortController()
target.addEventListener("mutation", event => { this.update(event) }, {signal: controller.signal})
abortRegistry.register(this, controller)
2024-01-10 19:42:09 +00:00
mutationObserver.observe(target, {
attributes: true,
childList: true,
characterData: true,
subtree: true,
})
}
get value() { return this.#value }
2024-01-10 19:42:09 +00:00
update() {
2024-06-24 09:29:05 +00:00
const current = this.#getValue(this.target)
if (this.#equal(this.#value, current)) return
this.#value = current
2024-01-24 15:11:22 +00:00
if (this.synchronous) {
2024-06-24 09:29:05 +00:00
this.dispatchEvent(new ValueChangeEvent(["value", current]))
2024-01-24 15:11:22 +00:00
} else {
2024-01-10 19:42:09 +00:00
if (!this.#changedValue) {
queueMicrotask(() => {
this.#changedValue = false
2024-06-24 09:29:05 +00:00
this.dispatchEvent(new ValueChangeEvent(["value", this.#changedValue]))
2024-01-10 19:42:09 +00:00
})
this.#changedValue = current
}
}
}
}
export class MapStorage extends Storage {
#map = new Map()
2024-06-24 09:29:05 +00:00
/**
* @param {number} index
* @return {string}
*/
key(index) {
return [...this.#map.keys()][index]
}
2024-06-24 09:29:05 +00:00
/**
* @param {string} keyName
* @return {any}
*/
getItem(keyName) {
if (this.#map.has(keyName))
return this.#map.get(keyName)
else
return null
}
2024-06-24 09:29:05 +00:00
/**
* @param {string} keyName
* @param {any} keyValue
*/
setItem(keyName, keyValue) {
this.#map.set(keyName, String(keyValue))
}
2024-06-24 09:29:05 +00:00
/** @param {string} keyName */
removeItem(keyName) {
this.#map.delete(keyName)
}
clear() {
this.#map.clear()
}
}