Compare commits

..

No commits in common. "main" and "v1.6.1" have entirely different histories.
main ... v1.6.1

4 changed files with 29 additions and 201 deletions

View file

@ -1,85 +0,0 @@
class ChildObserver extends MutationObserver {
constructor() {
super(mutations => {
for (const mutation of mutations) {
mutation.target.dispatchEvent(new CustomEvent("change", {detail: mutation}))
}
})
}
observe(element) {
MutationObserver.prototype.observe.call(this, element, { childList: true })
}
}
const childObserver = new ChildObserver()
export const lense = (methods, extra) => {
if (extra) return lense(extra)(methods)
const traps = {
get(target, prop) {
if (prop === "length") {
return target.children.length
} else if (prop === Symbol.iterator) {
return function*() {
for (const child of target.children) {
yield methods.get(child)
}
}
} else if (prop.match?.call(prop, /^[0-9]+$/)) {
const child = target.children[prop]
if (child) return methods.get(child)
return child
} else {
return Array.prototype[prop]
}
},
set(target, prop, value) {
if (prop.match?.call(prop, /^[0-9]+$/)) {
const child = target.children[prop]
if (child) {
methods.set(child, value)
return true
} else {
for (let i = target.children.length; i < Number(prop); i++) {
target.appendChild(methods.new(undefined))
}
const element = methods.new(value)
target.appendChild(element)
if (methods.get(element) !== value)
methods.set(element, value)
return true
}
} else if (prop == "length") {
if (value == target.children.length)
return true
else
return false
}
},
deleteProperty(target, prop) {
if (prop.match?.call(prop, /^[0-9]+$/)) {
const child = target.children[prop]
if (child) child.remove()
return true
}
},
has(target, prop) {
return (prop === Symbol.iterator) || (prop in target.children) || (prop in Array.prototype)
}
}
return element => {
const proxy = 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
}
}
export default lense

View file

@ -1,6 +1,6 @@
{
"name": "skooma",
"version": "1.7.0",
"version": "1.6.1",
"author": "darkwiiplayer",
"license": "Unlicense",
"main": "skooma.js",

View file

@ -10,7 +10,6 @@ or
html.ul([1, 2, 3, 4, 5].map(x => html.li(x)), {class: "numbers"})
*/
// Keep a referee alive until a referrer is collected
const weakReferences = new WeakMap()
const untilDeathDoThemPart = (referrer, reference) => {
if (!weakReferences.has(referrer)) {
@ -185,12 +184,11 @@ const nameSpacedProxy = (options={}) => new Proxy(Window, {
export const html = nameSpacedProxy({nameFilter: name => name.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()})
export const svg = nameSpacedProxy({xmlns: "http://www.w3.org/2000/svg"})
export default html
// Other utility exports
// Wraps an event handler in a function that calls preventDefault on the event
export const handle = fn => event => { event.preventDefault(); return fn(event) }
export const handle = fn => event => { fn(event); event.preventDefault() }
// Wraps a list of elements in a document fragment
export const fragment = (...elements) => {

139
state.js
View file

@ -1,7 +1,4 @@
const abortRegistry = new FinalizationRegistry(controller => controller.abort())
const camelToKebab = string => string.replace(/([a-z])([A-Z])/g, (_, a, b) => `${a}-${b.toLowerCase()}`)
const kebabToCamel = string => string.replace(/([a-z])-([a-z])/g, (_, a, b) => a+b.toUpperCase())
export const abortRegistry = new FinalizationRegistry(controller => controller.abort())
export class ChangeEvent extends Event {
#final
@ -17,7 +14,7 @@ export class ChangeEvent extends Event {
}
}
export class SimpleState extends EventTarget {}
class SimpleState extends EventTarget {}
export class MapStorage extends Storage {
#map = new Map()
@ -60,12 +57,12 @@ export class State extends SimpleState {
this.#options = options
this.#target = target
this.values = new Proxy(target, {
this.proxy = new Proxy(target, {
set: (_target, prop, value) => {
const old = this.get(prop)
if (old !== value) {
this.emit(prop, value)
if (this.#options.shallow) {
if (this.#options.deep !== false) {
if (State.isState(old)) this.disown(prop, old)
if (State.isState(value)) this.adopt(prop, value)
}
@ -90,8 +87,8 @@ export class State extends SimpleState {
}
// When you only need one value, you can skip the proxy.
set value(value) { this.values.value = value }
get value() { return this.values.value }
set value(value) { this.proxy.value = value }
get value() { return this.proxy.value }
adopt(prop, state) {
let handlers = this.#nested.get(state)
@ -146,33 +143,13 @@ export class State extends SimpleState {
}
}
set(...args) {
if (args.length === 1) return this.set("value", ...args)
const [prop, value] = args
set(prop, value) {
this.#target[prop] = value
}
get(...args) {
if (args.length === 0) return this.get("value")
const prop = args[0]
get(prop) {
return this.#target[prop]
}
subscribe(prop, callback) {
if (!callback) return this.subscribe("value", prop)
const controller = new AbortController()
this.addEventListener("change", ({final}) => {
if (final.has(prop)) return callback(final.get(prop))
}, {signal: controller.signal})
callback(this.value)
return () => controller.abort()
}
// Backwards compatibility
get proxy() { return this.values }
}
const forwardFinalizationRegistry = new FinalizationRegistry(([cache, name]) => {
@ -205,11 +182,11 @@ export class ForwardState extends SimpleState {
}, {signal: abortController.signal})
}
get value() { return this.#backend.values[this.#property] ?? this.#fallback }
set value(value) { this.#backend.values[this.#property] = value }
get value() { return this.#backend.proxy[this.#property] ?? this.#fallback }
set value(value) { this.#backend.proxy[this.#property] = value }
}
class StorageChangeEvent extends Event {
export class StorageChangeEvent extends Event {
constructor(storage, key, value, targetState) {
super("storagechange")
this.storageArea = storage
@ -221,13 +198,16 @@ class StorageChangeEvent extends Event {
export class StoredState extends State {
#storage
#valueKey
constructor(init, options={}) {
super({}, options)
this.#storage = options.storage ?? localStorage ?? new MapStorage()
this.#valueKey = options.key ?? 'value'
// Initialise storage from defaults
for (const [prop, value] of Object.entries(init)) {
for (let [prop, value] of Object.entries(init)) {
if (prop === 'value') prop = this.#valueKey
if (this.#storage[prop] === undefined)
this.set(prop, value)
}
@ -243,7 +223,9 @@ export class StoredState extends State {
// Listen for changes from other windows
const handler = event => {
if (event.targetState !== this && event.storageArea == this.#storage) {
this.emit(event.key, JSON.parse(event.newValue))
let prop = event.key
if (prop === this.#valueKey) prop = 'value'
this.emit(prop, JSON.parse(event.newValue))
}
}
addEventListener("storage", handler)
@ -251,12 +233,14 @@ export class StoredState extends State {
}
set(prop, value) {
if (prop == "value") prop = this.#valueKey
const json = JSON.stringify(value)
dispatchEvent(new StorageChangeEvent(this.#storage, prop, json, this))
this.#storage[prop] = json
}
get(prop) {
if (prop == "value") prop = this.#valueKey
const value = this.#storage[prop]
return value && JSON.parse(value)
}
@ -266,28 +250,26 @@ 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
if (String(target.state.proxy[name]) !== next)
target.state.proxy[name] = next
}
}
})
export const component = (generator, name) => {
name = name ?? camelToKebab(generator.name)
name = name ?? generator.name.replace(/([a-z])([A-Z])/g, (_, a, b) => `${a}-${b.toLowerCase()}`)
const Element = class extends HTMLElement{
constructor() {
super()
this.state = new State(Object.fromEntries([...this.attributes].map(attribute => [kebabToCamel(attribute.name), attribute.value])))
this.state = new State(Object.fromEntries([...this.attributes].map(attribute => [attribute.name, attribute.value])))
this.state.addEventListener("change", event => {
for (const [name, value] of event.changes) {
const kebabName = camelToKebab(name)
if (this.getAttribute(kebabName) !== String(value))
this.setAttribute(kebabName, value)
if (this.getAttribute(name) !== String(value))
this.setAttribute(name, value)
}
})
attributeObserver.observe(this, {attributes: true})
this.replaceChildren(generator(this))
this.replaceChildren(generator(this.state))
}
}
customElements.define(name, Element)
@ -343,71 +325,4 @@ class ComposedState extends SimpleState {
export const compose = func => (...states) => new ComposedState(func, {defer: true}, ...states)
const eventName = "mutation"
class MutationEvent extends Event {
constructor() {
super(eventName, {bubbles: true})
}
}
const mutationObserver = new MutationObserver(mutations => {
for (const mutation of mutations) {
mutation.target.dispatchEvent(new MutationEvent())
}
})
export class DOMState extends SimpleState {
#target
#defer
#getValue
#equal
#old
#changedValue = false
constructor(target, options) {
super()
this.#defer = options.defer ?? false
this.#target = target
this.#getValue = options.get ?? (target => target.value)
this.#equal = options.equal ?? ((a, b) => a===b)
this.#old = this.#getValue(target)
const controller = new AbortController()
target.addEventListener(eventName, event=>{this.update(event)}, {signal: controller.signal})
abortRegistry.register(this, controller)
mutationObserver.observe(target, {
attributes: true,
childList: true,
characterData: true,
subtree: true,
})
}
get value() { return this.#old }
update() {
const current = this.#getValue(this.#target)
if (this.#equal(this.#old, current)) return
this.#old = current
if (this.#defer) {
if (!this.#changedValue) {
queueMicrotask(() => {
this.#changedValue = false
this.dispatchEvent(new ChangeEvent(["value", this.#changedValue]))
})
this.#changedValue = current
}
} else {
this.dispatchEvent(new ChangeEvent(["value", current]))
}
}
}
export default State