Compare commits

..

No commits in common. "110cd7822a7562e238373e3c371ffed10516740a" and "5a29b0e662ddbb006918a957815fede5dc506f65" have entirely different histories.

3 changed files with 108 additions and 145 deletions

View file

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

View file

@ -53,8 +53,9 @@ const getCustom = args => args.reduce(
const isElement = object => HTMLElement.prototype.isPrototypeOf(object) const isElement = object => HTMLElement.prototype.isPrototypeOf(object)
const isReactive = object => object const isReactive = object => object
&& (object instanceof EventTarget) && (typeof object == "object")
&& ("subscribe" in object) && ("addEventListener" in object)
&& ("value" in object)
const toChild = arg => { const toChild = arg => {
if (typeof arg == "string" || typeof arg == "number") { if (typeof arg == "string" || typeof arg == "number") {

244
state.js
View file

@ -5,56 +5,82 @@ const kebabToCamel = string => string.replace(/([a-z])-([a-z])/g, (_, a, b) => a
export class ChangeEvent extends Event { export class ChangeEvent extends Event {
#final #final
#values
constructor(...changes) { constructor(...changes) {
super('change') super('change')
this.changes = changes 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() { get final() {
if (!this.#final) { if (!this.#final) {
this.#final = new Map() this.#final = new Map(this.changes)
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 return this.#final
} }
} }
export class SimpleState extends EventTarget { export class SimpleState extends EventTarget {}
#synchronous
export class MapStorage extends Storage {
#map = new Map()
key(index) {
return [...this.#map.keys()][index]
}
getItem(keyName) {
if (this.#map.has(keyName))
return this.#map.get(keyName)
else
return null
}
setItem(keyName, keyValue) {
this.#map.set(keyName, String(keyValue))
}
removeItem(keyName) {
this.#map.delete(keyName)
}
clear() {
this.#map.clear()
}
}
export class State extends SimpleState {
#target
#options
#queue #queue
#forwardCache
#abortController
#nested = new Map() #nested = new Map()
#weakRef = new WeakRef(this) #weakRef = new WeakRef(this)
#abortController = new AbortController
constructor({synchronous, methods}={}) { static isState(object) { return SimpleState.prototype.isPrototypeOf(object) }
constructor(target={}, options={}) {
super() super()
this.#synchronous = !!synchronous
this.#abortController = new AbortController
abortRegistry.register(this, this.#abortController) abortRegistry.register(this, this.#abortController)
this.#options = options
this.#target = 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.deep !== false) {
if (State.isState(old)) this.disown(prop, old)
if (State.isState(value)) this.adopt(prop, value)
}
this.set(prop, value)
}
return true
},
get: (_target, prop) => this.get(prop),
})
this.addEventListener
// Try running a "<name>Changed" method for every changed property // Try running a "<name>Changed" method for every changed property
// Can be disabled to maybe squeeze out some performance // Can be disabled to maybe squeeze out some performance
if (methods ?? true) { if (options.methods ?? true) {
this.addEventListener("change", ({final}) => { this.addEventListener("change", ({final}) => {
final.forEach((value, prop) => { final.forEach((value, prop) => {
if (`${prop}Changed` in this) this[`${prop}Changed`](value) if (`${prop}Changed` in this) this[`${prop}Changed`](value)
@ -63,33 +89,9 @@ export class SimpleState extends EventTarget {
} }
} }
subscribe(prop, callback) { // When you only need one value, you can skip the proxy.
if (!callback) return this.subscribe("value", prop) set value(value) { this.proxy.value = value }
get value() { return this.proxy.value }
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()
}
emit(property, from, to, options={}) {
const change = {property, from, to, ...options}
if (!this.synchronous) {
if (!this.#queue) {
this.#queue = []
queueMicrotask(() => {
this.dispatchEvent(new ChangeEvent(...this.#queue))
this.#queue = undefined
})
}
this.#queue.push(change)
} else {
this.dispatchEvent(new ChangeEvent([change]))
}
}
adopt(prop, state) { adopt(prop, state) {
let handlers = this.#nested.get(state) let handlers = this.#nested.get(state)
@ -99,12 +101,11 @@ export class SimpleState extends EventTarget {
this.#nested.set(state, handlers) this.#nested.set(state, handlers)
} }
const ref = this.#weakRef const ref = this.#weakRef
const handler = () => ref.deref()?.emit(prop, state, state, {state: true}) const handler = () => ref.deref()?.emit(prop, state)
handlers.set(prop, handler) handlers.set(prop, handler)
state.addEventListener("change", handler, {signal: this.ignal}) state.addEventListener("change", handler, {signal: this.#abortController.signal})
} }
disown(prop, state) { disown(prop, state) {
const handlers = this.#nested.get(state) const handlers = this.#nested.get(state)
const handler = handlers.get(prop) const handler = handlers.get(prop)
@ -115,41 +116,21 @@ export class SimpleState extends EventTarget {
} }
} }
get signal() { return this.#abortController.signal } // Anounces that a prop has changed
get synchronous() { return this.#synchronous } emit(prop, value) {
} if (this.#options.defer ?? true) {
if (!this.#queue) {
export class State extends SimpleState { this.#queue = []
#target queueMicrotask(() => {
#shallow this.dispatchEvent(new ChangeEvent(...this.#queue))
#forwardCache this.#queue = undefined
static isState(object) { return SimpleState.prototype.isPrototypeOf(object) }
constructor(target={}, {shallow, ...options}={}) {
super(options)
this.#shallow = !!shallow
this.#target = target
this.values = new Proxy(target, {
set: (_target, prop, value) => {
const old = this.get(prop)
if (old !== value) {
this.emit(prop, old, value)
if (this.#shallow) {
if (State.isState(old)) this.disown(prop, old)
if (State.isState(value)) this.adopt(prop, value)
}
this.set(prop, value)
}
return true
},
get: (_target, prop) => this.get(prop),
}) })
} }
this.#queue.push([prop, value])
set value(value) { this.values.value = value } } else {
get value() { return this.values.value } this.dispatchEvent(new ChangeEvent([prop, value]))
}
}
forward(property="value", fallback) { forward(property="value", fallback) {
if (!this.#forwardCache) this.#forwardCache = new Map() if (!this.#forwardCache) this.#forwardCache = new Map()
@ -165,17 +146,11 @@ export class State extends SimpleState {
} }
} }
set(...args) { set(prop, value) {
if (args.length === 1) return this.set("value", ...args)
const [prop, value] = args
this.#target[prop] = value this.#target[prop] = value
} }
get(...args) { get(prop) {
if (args.length === 0) return this.get("value")
const prop = args[0]
return this.#target[prop] return this.#target[prop]
} }
} }
@ -200,8 +175,8 @@ export class ForwardState extends SimpleState {
const state = ref.deref() const state = ref.deref()
if (state) { if (state) {
const relevantChanges = event.changes const relevantChanges = event.changes
.filter(({property: name}) => name === property) .filter(([name]) => name === property)
.map(({from, to}) => ({property: "value", from, to})) .map(([_, value]) => ["value", value])
if (relevantChanges.length > 0) if (relevantChanges.length > 0)
state.dispatchEvent(new ChangeEvent(...relevantChanges)) state.dispatchEvent(new ChangeEvent(...relevantChanges))
} else { } else {
@ -210,8 +185,8 @@ export class ForwardState extends SimpleState {
}, {signal: abortController.signal}) }, {signal: abortController.signal})
} }
get value() { return this.#backend.values[this.#property] ?? this.#fallback } get value() { return this.#backend.proxy[this.#property] ?? this.#fallback }
set value(value) { this.#backend.values[this.#property] = value } set value(value) { this.#backend.proxy[this.#property] = value }
} }
class StorageChangeEvent extends Event { class StorageChangeEvent extends Event {
@ -226,13 +201,16 @@ class StorageChangeEvent extends Event {
export class StoredState extends State { export class StoredState extends State {
#storage #storage
#valueKey
constructor(init, options={}) { constructor(init, options={}) {
super({}, options) super({}, options)
this.#storage = options.storage ?? localStorage ?? new MapStorage() this.#storage = options.storage ?? localStorage ?? new MapStorage()
this.#valueKey = options.key ?? 'value'
// Initialise storage from defaults // 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) if (this.#storage[prop] === undefined)
this.set(prop, value) this.set(prop, value)
} }
@ -248,7 +226,9 @@ export class StoredState extends State {
// Listen for changes from other windows // Listen for changes from other windows
const handler = event => { const handler = event => {
if (event.targetState !== this && event.storageArea == this.#storage) { 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) addEventListener("storage", handler)
@ -256,12 +236,14 @@ export class StoredState extends State {
} }
set(prop, value) { set(prop, value) {
if (prop == "value") prop = this.#valueKey
const json = JSON.stringify(value) const json = JSON.stringify(value)
dispatchEvent(new StorageChangeEvent(this.#storage, prop, json, this)) dispatchEvent(new StorageChangeEvent(this.#storage, prop, json, this))
this.#storage[prop] = json this.#storage[prop] = json
} }
get(prop) { get(prop) {
if (prop == "value") prop = this.#valueKey
const value = this.#storage[prop] const value = this.#storage[prop]
return value && JSON.parse(value) return value && JSON.parse(value)
} }
@ -272,8 +254,8 @@ const attributeObserver = new MutationObserver(mutations => {
if (type == "attributes") { if (type == "attributes") {
const next = target.getAttribute(name) const next = target.getAttribute(name)
const camelName = kebabToCamel(name) const camelName = kebabToCamel(name)
if (String(target.state.values[camelName]) !== next) if (String(target.state.proxy[camelName]) !== next)
target.state.values[camelName] = next target.state.proxy[camelName] = next
} }
} }
}) })
@ -285,8 +267,8 @@ export const component = (generator, name) => {
super() 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 => [kebabToCamel(attribute.name), attribute.value])))
this.state.addEventListener("change", event => { this.state.addEventListener("change", event => {
for (const {property, to: value} of event.changes) { for (const [name, value] of event.changes) {
const kebabName = camelToKebab(property) const kebabName = camelToKebab(name)
if (this.getAttribute(kebabName) !== String(value)) if (this.getAttribute(kebabName) !== String(value))
this.setAttribute(kebabName, value) this.setAttribute(kebabName, value)
} }
@ -302,12 +284,14 @@ export const component = (generator, name) => {
class ComposedState extends SimpleState { class ComposedState extends SimpleState {
#func #func
#states #states
#options
constructor(func, options, ...states) { constructor(func, options, ...states) {
super(options) super()
this.#func = func this.#func = func
this.#states = states this.#states = states
this.#options = options
const abortController = new AbortController() const abortController = new AbortController()
abortRegistry.register(this, abortController) abortRegistry.register(this, abortController)
@ -325,7 +309,7 @@ class ComposedState extends SimpleState {
#microtaskQueued #microtaskQueued
scheduleUpdate() { scheduleUpdate() {
if (this.defer) { if (this.#options.defer) {
if (!this.#microtaskQueued) { if (!this.#microtaskQueued) {
queueMicrotask(() => { queueMicrotask(() => {
this.#microtaskQueued = false this.#microtaskQueued = false
@ -339,10 +323,8 @@ class ComposedState extends SimpleState {
} }
update() { update() {
const value = this.#func(...this.#states.map(state => state.value)) this.value = this.#func(...this.#states.map(state => state.value))
const change = {property: "value", from: this.value, to: value} this.dispatchEvent(new ChangeEvent([["value", this.value]]))
this.value = value
this.dispatchEvent(new ChangeEvent([change]))
} }
} }
@ -364,6 +346,7 @@ const mutationObserver = new MutationObserver(mutations => {
export class DOMState extends SimpleState { export class DOMState extends SimpleState {
#target #target
#defer
#getValue #getValue
#equal #equal
@ -371,7 +354,8 @@ export class DOMState extends SimpleState {
#changedValue = false #changedValue = false
constructor(target, options) { constructor(target, options) {
super(options) super()
this.#defer = options.defer ?? false
this.#target = target this.#target = target
this.#getValue = options.get ?? (target => target.value) this.#getValue = options.get ?? (target => target.value)
this.#equal = options.equal ?? ((a, b) => a===b) this.#equal = options.equal ?? ((a, b) => a===b)
@ -399,7 +383,7 @@ export class DOMState extends SimpleState {
this.#old = current this.#old = current
if (this.defer) { if (this.#defer) {
if (!this.#changedValue) { if (!this.#changedValue) {
queueMicrotask(() => { queueMicrotask(() => {
this.#changedValue = false this.#changedValue = false
@ -413,26 +397,4 @@ export class DOMState extends SimpleState {
} }
} }
export class MapStorage extends Storage {
#map = new Map()
key(index) {
return [...this.#map.keys()][index]
}
getItem(keyName) {
if (this.#map.has(keyName))
return this.#map.get(keyName)
else
return null
}
setItem(keyName, keyValue) {
this.#map.set(keyName, String(keyValue))
}
removeItem(keyName) {
this.#map.delete(keyName)
}
clear() {
this.#map.clear()
}
}
export default State export default State