Compare commits

..

6 commits

3 changed files with 145 additions and 108 deletions

View file

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

View file

@ -53,9 +53,8 @@ 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
&& (typeof object == "object") && (object instanceof EventTarget)
&& ("addEventListener" in object) && ("subscribe" 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,82 +5,56 @@ 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.changes) 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 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
static isState(object) { return SimpleState.prototype.isPrototypeOf(object) } constructor({synchronous, methods}={}) {
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 (options.methods ?? true) { if (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)
@ -89,9 +63,33 @@ export class State extends SimpleState {
} }
} }
// When you only need one value, you can skip the proxy. subscribe(prop, callback) {
set value(value) { this.proxy.value = value } if (!callback) return this.subscribe("value", prop)
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)
@ -101,11 +99,12 @@ export class State extends SimpleState {
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) const handler = () => ref.deref()?.emit(prop, state, state, {state: true})
handlers.set(prop, handler) handlers.set(prop, handler)
state.addEventListener("change", handler, {signal: this.#abortController.signal}) state.addEventListener("change", handler, {signal: this.ignal})
} }
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)
@ -116,21 +115,41 @@ export class State extends SimpleState {
} }
} }
// Anounces that a prop has changed get signal() { return this.#abortController.signal }
emit(prop, value) { get synchronous() { return this.#synchronous }
if (this.#options.defer ?? true) { }
if (!this.#queue) {
this.#queue = [] export class State extends SimpleState {
queueMicrotask(() => { #target
this.dispatchEvent(new ChangeEvent(...this.#queue)) #shallow
this.#queue = undefined #forwardCache
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])
} else { set value(value) { this.values.value = value }
this.dispatchEvent(new ChangeEvent([prop, value])) get value() { return this.values.value }
}
}
forward(property="value", fallback) { forward(property="value", fallback) {
if (!this.#forwardCache) this.#forwardCache = new Map() if (!this.#forwardCache) this.#forwardCache = new Map()
@ -146,11 +165,17 @@ export class State extends SimpleState {
} }
} }
set(prop, value) { set(...args) {
if (args.length === 1) return this.set("value", ...args)
const [prop, value] = args
this.#target[prop] = value this.#target[prop] = value
} }
get(prop) { get(...args) {
if (args.length === 0) return this.get("value")
const prop = args[0]
return this.#target[prop] return this.#target[prop]
} }
} }
@ -175,8 +200,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(([name]) => name === property) .filter(({property: name}) => name === property)
.map(([_, value]) => ["value", value]) .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 {
@ -185,8 +210,8 @@ export class ForwardState extends SimpleState {
}, {signal: abortController.signal}) }, {signal: abortController.signal})
} }
get value() { return this.#backend.proxy[this.#property] ?? this.#fallback } get value() { return this.#backend.values[this.#property] ?? this.#fallback }
set value(value) { this.#backend.proxy[this.#property] = value } set value(value) { this.#backend.values[this.#property] = value }
} }
class StorageChangeEvent extends Event { class StorageChangeEvent extends Event {
@ -201,16 +226,13 @@ 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 (let [prop, value] of Object.entries(init)) { for (const [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)
} }
@ -226,9 +248,7 @@ 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) {
let prop = event.key this.emit(event.key, JSON.parse(event.newValue))
if (prop === this.#valueKey) prop = 'value'
this.emit(prop, JSON.parse(event.newValue))
} }
} }
addEventListener("storage", handler) addEventListener("storage", handler)
@ -236,14 +256,12 @@ 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)
} }
@ -254,8 +272,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.proxy[camelName]) !== next) if (String(target.state.values[camelName]) !== next)
target.state.proxy[camelName] = next target.state.values[camelName] = next
} }
} }
}) })
@ -267,8 +285,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 [name, value] of event.changes) { for (const {property, to: value} of event.changes) {
const kebabName = camelToKebab(name) const kebabName = camelToKebab(property)
if (this.getAttribute(kebabName) !== String(value)) if (this.getAttribute(kebabName) !== String(value))
this.setAttribute(kebabName, value) this.setAttribute(kebabName, value)
} }
@ -284,14 +302,12 @@ 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() super(options)
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)
@ -309,7 +325,7 @@ class ComposedState extends SimpleState {
#microtaskQueued #microtaskQueued
scheduleUpdate() { scheduleUpdate() {
if (this.#options.defer) { if (this.defer) {
if (!this.#microtaskQueued) { if (!this.#microtaskQueued) {
queueMicrotask(() => { queueMicrotask(() => {
this.#microtaskQueued = false this.#microtaskQueued = false
@ -323,8 +339,10 @@ class ComposedState extends SimpleState {
} }
update() { update() {
this.value = this.#func(...this.#states.map(state => state.value)) const value = this.#func(...this.#states.map(state => state.value))
this.dispatchEvent(new ChangeEvent([["value", this.value]])) const change = {property: "value", from: this.value, to: value}
this.value = value
this.dispatchEvent(new ChangeEvent([change]))
} }
} }
@ -346,7 +364,6 @@ const mutationObserver = new MutationObserver(mutations => {
export class DOMState extends SimpleState { export class DOMState extends SimpleState {
#target #target
#defer
#getValue #getValue
#equal #equal
@ -354,8 +371,7 @@ export class DOMState extends SimpleState {
#changedValue = false #changedValue = false
constructor(target, options) { constructor(target, options) {
super() super(options)
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)
@ -383,7 +399,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
@ -397,4 +413,26 @@ 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