From f4ceff5b10f8b6b291e0885011c21d18717eb08a Mon Sep 17 00:00:00 2001 From: "Sebastian L. K. Sorensen" Date: Sun, 26 Nov 2023 08:34:33 +0100 Subject: [PATCH] refactor: types --- lib/one.js | 50 +++++++++++++++++++------------------------------- 1 file changed, 19 insertions(+), 31 deletions(-) diff --git a/lib/one.js b/lib/one.js index f02adb32..ed4de077 100644 --- a/lib/one.js +++ b/lib/one.js @@ -24,7 +24,7 @@ type Config = { state?: State, parent?: Omit, store?: Store, - setup: Function, + setup?: Function, created?: Function, components?: Array, loop?: { @@ -37,7 +37,6 @@ type Config = { } type Component = Omit - type Components = { [string]: Array } @@ -115,25 +114,21 @@ function one(config: Config): void { template(c) - if (config.components) { - config.components.forEach(component => { - one({ - ...component, - parent: c - }) + config.components?.forEach(component => { + one({ + ...component, + parent: c }) - } + }) - if (setup) { - setup({ - state: c.state, - props: c.props, - parent: c.parent, - store: { get: store.get, set: store.set, length: store.length }, - query: query.bind(c), - computed: computed.bind(c) - }) - } + setup?.({ + state: c.state, + props: c.props, + parent: c.parent, + store: { get: store.get, set: store.set, length: store.length }, + query: query.bind(c), + computed: computed.bind(c) + }) render(c) }) @@ -163,19 +158,14 @@ function template(config: Component) { throw new Error(`One->template: Could not find component ${name}.`) } - if (!config.el) { - throw new Error('One->template: Could not find the element.') - } - - const el = config.el - clone.$one = config.el?.$one + clone.$one = config.el.$one for (const attr of config.el.attributes) { if (config.props && (config.props: Object)[attr.name]) continue clone.setAttribute(attr.name, attr.value) } - el.replaceWith(clone) + config.el.replaceWith(clone) config.el = clone component.el = clone @@ -237,7 +227,7 @@ function createInstance(config: Component): Component { } function query(this: Component, selector: string) { - const el: ?OneElement = this.el?.children.length + const el: ?OneElement = this.el.children.length ? (this.el.querySelector(selector): any) : this.el @@ -282,7 +272,7 @@ function loop( this: Component, el: OneElement, [items, key]: [string, ?Key], - fn: Function, + fn?: Function, parent: ?OneElement = null ) { const parentNode: OneElement = parent ?? (el.parentNode: any) @@ -350,9 +340,7 @@ function loop( parentNode.append(clone) } - if (fn) { - fn({ el: clone, item }) - } + fn?.({ el: clone, item }) }) }