@jsweb/ui 1.3.0 → 1.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +155 -0
- package/README.md +72 -7
- package/SKILL.md +609 -0
- package/index.es.js +2 -0
- package/index.es.js.map +1 -0
- package/index.umd.js +2 -0
- package/index.umd.js.map +1 -0
- package/package.json +10 -23
- package/src/index.d.ts +4 -0
- package/{dist/src → src}/parser.d.ts +2 -1
- package/src/reactivity.d.ts +48 -0
- package/.github/workflows/npm-publish.yml +0 -19
- package/.prettierignore +0 -3
- package/.prettierrc +0 -7
- package/PROJECT.md +0 -106
- package/dist/LICENSE +0 -21
- package/dist/README.md +0 -227
- package/dist/index.es.js +0 -2
- package/dist/index.es.js.map +0 -1
- package/dist/index.umd.js +0 -2
- package/dist/index.umd.js.map +0 -1
- package/dist/package.json +0 -34
- package/dist/src/index.d.ts +0 -3
- package/dist/src/reactivity.d.ts +0 -24
- package/dist/vite.config.d.ts +0 -2
- package/index.html +0 -196
- package/publish.js +0 -34
- package/src/evaluator.ts +0 -29
- package/src/index.ts +0 -10
- package/src/parser.ts +0 -480
- package/src/reactivity.ts +0 -185
- package/tsconfig.json +0 -23
- package/vite.config.ts +0 -16
- /package/{dist/index.d.ts → index.d.ts} +0 -0
- /package/{dist/src → src}/evaluator.d.ts +0 -0
package/index.es.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.es.js","names":[],"sources":["../src/reactivity.ts","../src/evaluator.ts","../src/parser.ts","../src/index.ts"],"sourcesContent":["let activeEffect: symbol | null = null\nconst targetMap = new WeakMap<\n object,\n Map<string | symbol, Set<ReactiveEffect>>\n>()\nconst proxyMap = new WeakMap<object, any>()\nconst effectMap = new WeakMap<symbol, ReactiveEffect>()\n\nexport class ReactiveEffect {\n active = true\n deps: Set<Set<ReactiveEffect>> = new Set()\n\n constructor(public fn: () => void) {}\n\n run() {\n if (!this.active) return this.fn()\n\n this.cleanup()\n\n activeEffect = Symbol()\n effectMap.set(activeEffect, this)\n\n try {\n return this.fn()\n } finally {\n effectMap.delete(activeEffect)\n activeEffect = null\n }\n }\n\n stop() {\n if (this.active) {\n this.cleanup()\n this.active = false\n }\n }\n\n cleanup() {\n this.deps.forEach((dep) => dep.delete(this))\n this.deps.clear()\n }\n\n effect() {\n return {\n run: () => this.run(),\n stop: () => this.stop(),\n }\n }\n}\n\nexport function effect(fn: () => void) {\n const ref = new ReactiveEffect(fn)\n ref.run()\n return ref.effect()\n}\n\nexport function track(target: object, key: string | symbol) {\n if (activeEffect) {\n let depsMap = targetMap.get(target)\n if (!depsMap) {\n depsMap = new Map()\n targetMap.set(target, depsMap)\n }\n\n let dep = depsMap.get(key)\n if (!dep) {\n dep = new Set()\n depsMap.set(key, dep)\n }\n\n const active = effectMap.get(activeEffect)\n if (active) {\n dep.add(active)\n active.deps.add(dep)\n }\n }\n}\n\nexport function trigger(target: object, key: string | symbol) {\n const depsMap = targetMap.get(target)\n if (!depsMap) return\n\n const dep = depsMap.get(key)\n if (dep) {\n const effects = new Set(dep)\n effects.forEach((effect) => effect.run())\n }\n}\n\nexport interface ScopeContext {\n /** Elemento DOM raiz associado ao escopo (somente leitura) */\n readonly $el: HTMLElement\n /** Map nativo indexando elementos referenciados via ui:ref / :ref (somente leitura) */\n readonly $refs: Map<string, any>\n /** Despacha CustomEvents nativos (bubbles: true, composed: true) */\n $emit: (event: string, detail?: any) => void\n /** Índice numérico da iteração atual em loops ui:for / :for */\n $index?: number\n /** Chave de identificação da iteração em loops ui:for / :for */\n $key?: any\n}\n\nexport class Scope {\n /** Elemento DOM raiz ao qual o escopo foi acoplado (somente leitura) */\n declare readonly $el: HTMLElement\n\n /** Map nativo indexando elementos referenciados via ui:ref / :ref (somente leitura) */\n protected readonly $refs: Map<string, any> = new Map<string, any>()\n\n /** Despacha CustomEvents nativos (bubbles: true, composed: true) */\n protected $emit(event: string, detail?: any): void {\n const target = this.$el || (typeof window !== 'undefined' ? window : null)\n target?.dispatchEvent(\n new CustomEvent(event, { detail, bubbles: true, composed: true }),\n )\n }\n\n declare $index?: number\n declare $key?: any\n\n constructor(init?: Record<string, any>) {\n if (init && typeof init === 'object') {\n Object.assign(this, init)\n }\n }\n}\n\nexport function reactive<T extends any[]>(target: T): T\nexport function reactive<T extends object>(\n target: T & ThisType<T & ScopeContext>,\n): T & ScopeContext\nexport function reactive<T extends object>(target: T): any {\n const notObject = typeof target !== 'object' || target === null\n if (notObject) return target\n\n if (\n target instanceof Map ||\n target instanceof Set ||\n target instanceof WeakMap ||\n target instanceof WeakSet ||\n target instanceof Date ||\n target instanceof RegExp ||\n (typeof Node === 'function' && target instanceof Node)\n ) {\n return target\n }\n\n const isReactive = Object.hasOwn(target, '_isReactive')\n if (isReactive) return target\n\n const existingProxy = proxyMap.get(target)\n if (existingProxy) return existingProxy\n\n const proxy = new Proxy(target, {\n get(obj, key, receiver) {\n if (key === '_isReactive') return true\n track(obj, key)\n\n const res = Reflect.get(obj, key, receiver)\n // deep reactivity\n return typeof res === 'object' && res !== null ? reactive(res) : res\n },\n set(obj, key, value, receiver) {\n const isArray = Array.isArray(obj)\n const oldValue = Reflect.get(obj, key, receiver)\n const hadKey =\n isArray && String(Number(key)) === key\n ? Number(key) < obj.length\n : Object.hasOwn(obj, key)\n\n const result = Reflect.set(obj, key, value, receiver)\n\n if (!hadKey) {\n trigger(obj, key)\n if (isArray && key !== 'length') {\n trigger(obj, 'length')\n }\n } else if (oldValue !== value) {\n trigger(obj, key)\n }\n\n return result\n },\n })\n\n proxyMap.set(target, proxy)\n return proxy\n}\n\nexport function traverse(value: any, seen = new Set()) {\n if (typeof value !== 'object' || value === null || seen.has(value)) {\n return value\n }\n seen.add(value)\n for (const key in value) {\n traverse(value[key], seen)\n }\n return value\n}\n\nexport function watch<T>(\n source: (() => T) | any,\n cb: (newValue: T, oldValue: T | undefined) => void,\n options?: { immediate?: boolean },\n): () => void {\n let oldValue: any\n let isFirstRun = true\n\n const getter = source instanceof Function ? source : () => traverse(source)\n\n const runner = effect(() => {\n const newValue = getter()\n\n if (isFirstRun) {\n isFirstRun = false\n oldValue = newValue\n if (options?.immediate) {\n cb(newValue, undefined)\n }\n } else {\n cb(newValue, oldValue)\n oldValue = newValue\n }\n })\n\n return runner.stop\n}\n","export function evaluate(\n expression: string,\n context: Record<string, any> = {},\n) {\n try {\n const fn = new Function(`with(this) { return ${expression} }`)\n return fn.call(context)\n } catch {\n return undefined\n }\n}\n\nexport function evaluateEvent(\n $event: Event,\n expression: string,\n context: Record<string, any> = {},\n) {\n try {\n const exp = expression.trim()\n const isIdentifier = /^[a-zA-Z_$][0-9a-zA-Z_$.]*$/.test(exp)\n const code = `${exp} instanceof Function ? ${exp}.call(this, $event) : ${exp}`\n const result = isIdentifier ? code : exp\n const fn = new Function('$event', `with(this) { ${result} }`)\n\n fn.call(context, $event)\n } catch {\n console.warn(`[jsweb/ui] Error evaluating event: ${expression}`)\n }\n}\n","import { effect, reactive, type ScopeContext } from './reactivity'\nimport { evaluate, evaluateEvent } from './evaluator'\n\nexport type Context = Record<string, any>\n\ninterface BoundNode extends Node {\n _effects?: Array<() => void>\n}\n\nexport function cleanupTree(node: Node) {\n const bNode = node as BoundNode\n if (bNode._effects) {\n bNode._effects.forEach((stop) => stop())\n bNode._effects = []\n }\n const children = Array.from(node.childNodes)\n for (const child of children) cleanupTree(child)\n}\n\nexport function createContext(scope: any, context: Context = {}): Context {\n const reactiveScope = scope._isReactive ? scope : reactive(scope)\n\n return new Proxy(reactiveScope, {\n get(target, prop) {\n if (prop === '_isContext') return true\n if (prop in target) return Reflect.get(target, prop, target)\n if (prop in context) {\n return Reflect.get(context, prop, context)\n }\n return Reflect.get(target, prop, target)\n },\n set(target, prop, value) {\n if (prop in target) return Reflect.set(target, prop, value, target)\n if (prop in context) {\n return Reflect.set(context, prop, value, context)\n }\n return Reflect.set(target, prop, value, target)\n },\n has(target, prop) {\n if (prop in target) return true\n if (prop in context) return true\n return false\n },\n })\n}\n\nexport function parseNode(node: Node, context: Context) {\n if (node.nodeType !== Node.ELEMENT_NODE) return\n\n const el = node as HTMLElement\n const scope = processScope(el, context)\n if (!scope) return\n\n const forAttrs = ['ui:for', ':for']\n const forDirective = getDirectiveValue(el, forAttrs)\n if (forDirective) {\n removeDirectiveAttributes(el, forAttrs)\n processFor(el, forDirective, scope)\n return\n }\n\n const ifAttrs = ['ui:if', ':if']\n const ifDirective = getDirectiveValue(el, ifAttrs)\n if (ifDirective) {\n removeDirectiveAttributes(el, ifAttrs)\n processIf(el, ifDirective, scope)\n }\n\n processAttributes(el, scope)\n\n const children = Array.from(el.childNodes)\n for (const child of children) parseNode(child, scope)\n}\n\nexport function createScope<T extends object = Context>(\n selectorOrElement: string | HTMLElement,\n context?: T & ThisType<T & ScopeContext>,\n) {\n const el =\n typeof selectorOrElement === 'string'\n ? document.querySelector(selectorOrElement)\n : selectorOrElement\n\n if (el) {\n const ctx = (context ?? {}) as Context\n ctx.$el = el\n\n if (!ctx.$emit) {\n ctx.$emit = (eventName: string, detail?: any) => {\n el.dispatchEvent(\n new CustomEvent(eventName, { detail, bubbles: true, composed: true }),\n )\n }\n }\n\n if (!ctx.$refs) {\n ctx.$refs = new Map<string, any>()\n }\n\n parseNode(el, ctx)\n } else {\n console.warn('[jsweb/ui] Element not found:', selectorOrElement)\n }\n}\n\nfunction bindEffect(node: Node, fn: () => void) {\n const e = effect(fn)\n const bNode = node as BoundNode\n bNode._effects ??= []\n bNode._effects.push(e.stop)\n}\n\nfunction getDirectiveValue(el: HTMLElement, names: string[]) {\n for (const name of names) {\n const value = el.getAttribute(name)\n if (value !== null) return value\n }\n return null\n}\n\nfunction removeDirectiveAttributes(el: HTMLElement, names: string[]) {\n for (const name of names) {\n el.removeAttribute(name)\n }\n}\n\nfunction processScope(el: HTMLElement, context: Context) {\n const attrs = ['ui:scope', ':scope']\n const directive = getDirectiveValue(el, attrs)\n if (!directive) return context\n\n const scope = evaluate(directive, context)\n if (!scope) return undefined\n\n removeDirectiveAttributes(el, attrs)\n\n scope.$el = el\n\n if (!scope.$emit) {\n scope.$emit = (event: string, detail?: any) => {\n el.dispatchEvent(\n new CustomEvent(event, { detail, bubbles: true, composed: true }),\n )\n }\n }\n\n if (!scope.$refs) {\n scope.$refs = context.$refs ?? new Map<string, any>()\n }\n\n return createContext(scope, context)\n}\n\nfunction processFor(el: HTMLElement, expr: string, context: Context) {\n const parent = el.parentNode\n if (!parent) return\n\n const match = /^\\s*(.+)\\s+(?:in|of)\\s+(.+)\\s*$/.exec(expr)\n if (!match) {\n return console.warn(`[jsweb/ui] Invalid ui:for expression: ${expr}`)\n }\n const [, itemName, listName] = match\n\n const keyAttr = ['ui:key', ':key']\n const keyDirective = getDirectiveValue(el, keyAttr)\n removeDirectiveAttributes(el, keyAttr)\n\n const uuid = crypto.randomUUID()\n const comment = document.createComment(` ui:for ${uuid} `)\n el.replaceWith(comment)\n\n interface RenderedNode {\n key: any\n el: HTMLElement\n scope: any\n }\n let renderedNodes: RenderedNode[] = []\n\n bindEffect(comment, () => {\n const list = evaluate(listName, context)\n\n if (!Array.isArray(list)) {\n renderedNodes.forEach((node) => {\n node.el.remove()\n cleanupTree(node.el)\n })\n renderedNodes = []\n return\n }\n\n const newNodes: RenderedNode[] = []\n const oldNodesByKey = new Map<any, RenderedNode>()\n renderedNodes.forEach((node) => oldNodesByKey.set(node.key, node))\n\n list.forEach((item, index) => {\n let key: any = index\n\n if (keyDirective) {\n const tempContext = createContext(\n { [itemName]: item, $index: index },\n context,\n )\n key = evaluate(keyDirective, tempContext)\n }\n\n let node = oldNodesByKey.get(key)\n if (node) {\n // Reuse node\n node.scope[itemName] = item\n node.scope.$index = index\n node.scope.$key = key\n node.scope.$el = node.el\n oldNodesByKey.delete(key)\n } else {\n // Create new node\n const clone = el.cloneNode(true) as HTMLElement\n const scope = {\n [itemName]: item,\n $index: index,\n $key: key,\n $el: clone,\n }\n const reactiveScope = reactive(scope)\n const localContext = createContext(reactiveScope, context)\n parseNode(clone, localContext)\n node = { key, el: clone, scope: reactiveScope }\n }\n\n newNodes.push(node)\n })\n\n // Remove un-reused nodes\n oldNodesByKey.forEach((node) => {\n node.el.remove()\n cleanupTree(node.el)\n })\n\n // Reorder and insert new DOM nodes\n let currentAnchor = comment.nextSibling\n newNodes.forEach((node) => {\n if (currentAnchor === node.el) {\n currentAnchor = currentAnchor.nextSibling\n } else {\n comment.parentNode?.insertBefore(node.el, currentAnchor)\n }\n })\n\n renderedNodes = newNodes\n })\n}\n\nfunction processIf(el: HTMLElement, expr: string, context: Context) {\n const parent = el.parentNode\n if (!parent) return\n\n const uuid = crypto.randomUUID()\n const comment = document.createComment(` ui:if ${uuid} `)\n el.before(comment)\n\n bindEffect(comment, () => {\n const val = evaluate(expr, context)\n if (val) {\n if (!el.parentNode) {\n comment.parentNode?.insertBefore(el, comment.nextSibling)\n }\n } else if (el.parentNode) {\n el.remove()\n }\n })\n}\n\nfunction processAttributes(el: HTMLElement, context: Context) {\n const attrs = Array.from(el.attributes)\n\n for (const attr of attrs) {\n const { name, value } = attr\n const isText = ['ui:text', ':text'].includes(name)\n const isTwoWayBind = ['ui:bind', ':bind'].includes(name)\n const isClassBind = ['ui:class', ':class'].includes(name)\n const isStyleBind = ['ui:style', ':style'].includes(name)\n const isRef = ['ui:ref', ':ref'].includes(name)\n const isAttrBind = name.startsWith('ui:') || name.startsWith(':')\n const isEvent = name.startsWith('ui@') || name.startsWith('@')\n\n if (isText) {\n processTextBinding(el, value, context)\n el.removeAttribute(name)\n } else if (isTwoWayBind) {\n processTwoWayBinding(el, value, context)\n el.removeAttribute(name)\n } else if (isClassBind) {\n processClassBinding(el, value, context)\n el.removeAttribute(name)\n } else if (isStyleBind) {\n processStyleBinding(el, value, context)\n el.removeAttribute(name)\n } else if (isRef) {\n processRef(el, value, context)\n el.removeAttribute(name)\n } else if (isAttrBind) {\n const bound = name.split(':').pop()!\n processAttrBinding(el, bound, value, context)\n el.removeAttribute(name)\n } else if (isEvent) {\n processEventBinding(el, name, value, context)\n el.removeAttribute(name)\n }\n }\n}\n\nfunction processRef(el: HTMLElement, expr: string, context: Context) {\n const refName = expr.trim().replace(/^['\"]|['\"]$/g, '')\n if (!refName) return\n\n const refs = context.$refs as Map<string, any>\n if (!refs) return\n\n const key = context.$key\n\n if (key !== undefined) {\n let group = refs.get(refName)\n if (!(group instanceof Map)) {\n group = new Map<any, HTMLElement>()\n refs.set(refName, group)\n }\n group.set(key, el)\n } else {\n refs.set(refName, el)\n }\n\n const bNode = el as BoundNode\n bNode._effects ??= []\n bNode._effects.push(() => {\n if (key !== undefined) {\n const group = refs.get(refName)\n if (group instanceof Map) {\n group.delete(key)\n if (group.size === 0) {\n refs.delete(refName)\n }\n }\n } else if (refs.get(refName) === el) {\n refs.delete(refName)\n }\n })\n}\n\nfunction processTextBinding(el: HTMLElement, expr: string, context: Context) {\n bindEffect(el, () => {\n const val = evaluate(expr, context)\n el.textContent = val !== undefined && val !== null ? String(val) : ''\n })\n}\n\nfunction processTwoWayBinding(el: HTMLElement, expr: string, context: Context) {\n const isCheckbox = el instanceof HTMLInputElement && el.type === 'checkbox'\n const isRadio = el instanceof HTMLInputElement && el.type === 'radio'\n\n // 1. Reactive state to DOM\n bindEffect(el, () => {\n const val = evaluate(expr, context)\n if (isCheckbox) {\n el.checked = !!val\n } else if (isRadio) {\n el.checked = el.value === String(val)\n } else {\n const target = el as\n | HTMLInputElement\n | HTMLSelectElement\n | HTMLTextAreaElement\n target.value = val == null ? '' : String(val)\n }\n })\n\n // 2. DOM to Reactive state\n const isChange = isCheckbox || isRadio || el instanceof HTMLSelectElement\n const eventName = isChange ? 'change' : 'input'\n el.addEventListener(eventName, ($event) => {\n const target = isCheckbox ? 'checked' : 'value'\n const value = `$event.target.${target}`\n evaluateEvent($event, `${expr} = ${value}`, context)\n })\n}\n\nfunction processAttrBinding(\n el: HTMLElement,\n attr: string,\n expr: string,\n context: Context,\n) {\n bindEffect(el, () => {\n const val = evaluate(expr, context)\n if (val === null || val === undefined || val === false) {\n el.removeAttribute(attr)\n } else if (val === true) {\n el.setAttribute(attr, '')\n } else {\n el.setAttribute(attr, String(val))\n }\n })\n}\n\nfunction processClassBinding(el: HTMLElement, expr: string, context: Context) {\n let oldClasses = new Set<string>()\n\n bindEffect(el, () => {\n const val = evaluate(expr, context)\n const newClasses = new Set<string>()\n const addClass = (c: string) => c && newClasses.add(c)\n const addClasses = (c: string) => c.split(/\\s+/).forEach(addClass)\n\n if (typeof val === 'string') addClasses(val)\n else if (Array.isArray(val)) {\n val.flat().forEach((c: any) => {\n if (typeof c === 'string') addClasses(c)\n })\n } else if (typeof val === 'object' && val !== null) {\n Object.entries(val).forEach(([c, condition]: [string, any]) => {\n if (condition) addClasses(c)\n })\n }\n\n oldClasses.forEach((c) => {\n if (!newClasses.has(c)) el.classList.remove(c)\n })\n newClasses.forEach((c) => {\n if (!oldClasses.has(c)) el.classList.add(c)\n })\n\n oldClasses = newClasses\n })\n}\n\nfunction processStyleBinding(el: HTMLElement, expr: string, context: Context) {\n let oldStyles: Record<string, any> = {}\n\n bindEffect(el, () => {\n const val = evaluate(expr, context)\n const newStyles = typeof val === 'object' && val !== null ? val : {}\n\n for (const key in oldStyles) {\n if (!(key in newStyles)) {\n ;(el.style as any)[key] = ''\n }\n }\n\n for (const key in newStyles) {\n if (oldStyles[key] !== newStyles[key]) {\n ;(el.style as any)[key] = newStyles[key]\n }\n }\n\n oldStyles = { ...newStyles }\n })\n}\n\nfunction processEventBinding(\n el: HTMLElement,\n evt: string,\n expr: string,\n context: Context,\n) {\n const refs = evt.split('@').pop()!\n const [name, ...modifiers] = refs.split('.')\n\n const isOutside = modifiers.includes('outside')\n const target = isOutside ? document : el\n\n const handler: EventListener = ($event: Event) => {\n if (!el.isConnected) return\n\n const isTargetNode = $event.target instanceof Node\n\n if (isOutside && isTargetNode && el.contains($event.target)) return\n if (modifiers.includes('self') && $event.target !== el) return\n\n if (modifiers.includes('prevent')) $event.preventDefault()\n if (modifiers.includes('stop')) $event.stopPropagation()\n\n evaluateEvent($event, expr, context)\n }\n\n target.addEventListener(name, handler)\n\n if (isOutside) {\n const bNode = el as BoundNode\n bNode._effects ??= []\n bNode._effects.push(() => target.removeEventListener(name, handler))\n }\n}\n","import { reactive, watch, Scope, type ScopeContext } from './reactivity'\nimport { createScope, type Context } from './parser'\n\nexport { reactive, watch, createScope, Scope }\nexport type { ScopeContext, Context }\n\nif (typeof window !== 'undefined') {\n const w = window as any\n w.jsweb = w.jsweb || {}\n w.jsweb.ui = { createScope, reactive, watch, Scope }\n}\n"],"mappings":"AAAA,IAAI,EAA8B,KAC5B,iBAAY,IAAI,QAIhB,iBAAW,IAAI,QACf,iBAAY,IAAI,QAET,EAAb,MAIqB,GAHnB,QAAS,EACT,oBAAiC,IAAI,IAErC,WAAA,CAAY,GAAO,KAAA,GAAA,CAAiB,CAEpC,GAAA,GACE,IAAK,KAAK,OAAQ,OAAO,KAAK,KAE9B,KAAK,UAEL,EAAe,SACf,EAAU,IAAI,EAAc,MAE5B,IACE,OAAO,KAAK,IACd,CAAA,QACE,EAAU,OAAO,GACjB,EAAe,IACjB,CACF,CAEA,IAAA,GACM,KAAK,SACP,KAAK,UACL,KAAK,QAAS,EAElB,CAEA,OAAA,GACE,KAAK,KAAK,QAAS,GAAQ,EAAI,OAAO,OACtC,KAAK,KAAK,OACZ,CAEA,MAAA,GACE,MAAO,CACL,IAAA,IAAW,KAAK,MAChB,KAAA,IAAY,KAAK,OAErB,GAGF,SAAgB,EAAO,GACrB,MAAM,EAAM,IAAI,EAAe,GAE/B,OADA,EAAI,MACG,EAAI,QACb,CAwBA,SAAgB,EAAQ,EAAgB,GACtC,MAAM,EAAU,EAAU,IAAI,GAC9B,IAAK,EAAS,OAEd,MAAM,EAAM,EAAQ,IAAI,GACpB,GAEF,IADoB,IAAI,GAChB,QAAS,GAAW,EAAO,MAEvC,CAeA,IAAa,EAAb,MAKE,qBAA6C,IAAI,IAGjD,KAAA,CAAgB,EAAe,I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M,GACrB,EAA2B,iBAAR,GAA4B,OAAR,EAAe,EAAM,CAAC,EAEnE,IAAK,MAAM,KAAO,EACV,KAAO,IACV,EAAI,MAAc,GAAO,IAI9B,IAAK,MAAM,KAAO,EACZ,EAAU,KAAS,EAAU,KAC9B,EAAI,MAAc,GAAO,EAAU,IAIxC,EAAY,IAAK,IAErB,CAEA,SAAS,EACP,EACA,EACA,EACA,GAGA,MAAO,KAAS,GADH,EAAI,MAAM,KAAK,MACM,MAAM,KAElC,EAAY,EAAU,SAAS,WAC/B,EAAS,EAAY,SAAW,EAEhC,EAA0B,IAC9B,IAAK,EAAG,YAAa,OAErB,MAAM,EAAe,EAAO,kBAAkB,KAE1C,GAAa,GAAgB,EAAG,SAAS,EAAO,SAChD,EAAU,SAAS,SAAW,EAAO,SAAW,IAEhD,EAAU,SAAS,YAAY,EAAO,iBACtC,EAAU,SAAS,SAAS,EAAO,kBAEvC,EAAc,EAAQ,EAAM,KAK9B,GAFA,EAAO,iBAAiB,EAAM,GAE1B,EAAW,CACb,MAAM,EAAQ,EACd,EAAM,WAAa,GACnB,EAAM,SAAS,KAAA,IAAW,EAAO,oBAAoB,EAAM,GAC7D,CACF,CCneA,GAAsB,oBAAX,OAAwB,CACjC,MAAM,EAAI,OACV,EAAE,MAAQ,EAAE,OAAS,CAAC,EACtB,EAAE,MAAM,GAAK,CAAE,cAAa,WAAU,QAAO,QAC/C"}
|
package/index.umd.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@jsweb/ui"]={})}(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});var t=null,n=new WeakMap,o=new WeakMap,s=new WeakMap,i=class{fn;active=!0;deps=new Set;constructor(e){this.fn=e}run(){if(!this.active)return this.fn();this.cleanup(),t=Symbol(),s.set(t,this);try{return this.fn()}finally{s.delete(t),t=null}}stop(){this.active&&(this.cleanup(),this.active=!1)}cleanup(){this.deps.forEach(e=>e.delete(this)),this.deps.clear()}effect(){return{run:()=>this.run(),stop:()=>this.stop()}}};function c(e){const t=new i(e);return t.run(),t.effect()}function r(e,t){const o=n.get(e);if(!o)return;const s=o.get(t);s&&new Set(s).forEach(e=>e.run())}var f=class{$refs=new Map;$emit(e,t){(this.$el||("undefined"!=typeof window?window:null))?.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}constructor(e){e&&"object"==typeof e&&Object.assign(this,e)}};function u(e){if("object"!=typeof e||null===e)return e;if(e instanceof Map||e instanceof Set||e instanceof WeakMap||e instanceof WeakSet||e instanceof Date||e instanceof RegExp||"function"==typeof Node&&e instanceof Node)return e;if(Object.hasOwn(e,"_isReactive"))return e;const i=o.get(e);if(i)return i;const c=new Proxy(e,{get(e,o,i){if("_isReactive"===o)return!0;!function(e,o){if(t){let i=n.get(e);i||(i=new Map,n.set(e,i));let c=i.get(o);c||(c=new Set,i.set(o,c));const r=s.get(t);r&&(c.add(r),r.deps.add(c))}}(e,o);const c=Reflect.get(e,o,i);return"object"==typeof c&&null!==c?u(c):c},set(e,t,n,o){const s=Array.isArray(e),i=Reflect.get(e,t,o),c=s&&String(Number(t))===t?Number(t)<e.length:Object.hasOwn(e,t),f=Reflect.set(e,t,n,o);return c?i!==n&&r(e,t):(r(e,t),s&&"length"!==t&&r(e,"length")),f}});return o.set(e,c),c}function a(e,t=new Set){if("object"!=typeof e||null===e||t.has(e))return e;t.add(e);for(const n in e)a(e[n],t);return e}function l(e,t,n){let o,s=!0;const i=e instanceof Function?e:()=>a(e);return c(()=>{const e=i();s?(s=!1,o=e,n?.immediate&&t(e,void 0)):(t(e,o),o=e)}).stop}function d(e,t={}){try{return new Function(`with(this) { return ${e} }`).call(t)}catch{return}}function p(e,t,n={}){try{const o=t.trim(),s=/^[a-zA-Z_$][0-9a-zA-Z_$.]*$/.test(o);new Function("$event",`with(this) { ${s?`${o} instanceof Function ? ${o}.call(this, $event) : ${o}`:o} }`).call(n,e)}catch{console.warn(`[jsweb/ui] Error evaluating event: ${t}`)}}function h(e){const t=e;t._effects&&(t._effects.forEach(e=>e()),t._effects=[]);const n=Array.from(e.childNodes);for(const o of n)h(o)}function b(e,t={}){const n=e._isReactive?e:u(e);return new Proxy(n,{get:(e,n)=>"_isContext"===n||(n in e?Reflect.get(e,n,e):n in t?Reflect.get(t,n,t):Reflect.get(e,n,e)),set:(e,n,o)=>n in e?Reflect.set(e,n,o,e):n in t?Reflect.set(t,n,o,t):Reflect.set(e,n,o,e),has:(e,n)=>n in e||n in t})}function m(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return;const n=e,o=function(e,t){const n=["ui:scope",":scope"],o=w(e,n);if(!o)return t;const s=d(o,t);if(!s)return;g(e,n),s.$el=e,s.$emit||(s.$emit=(t,n)=>{e.dispatchEvent(new CustomEvent(t,{detail:n,bubbles:!0,composed:!0}))});s.$refs||(s.$refs=t.$refs??new Map);return b(s,t)}(n,t);if(!o)return;const s=["ui:for",":for"],i=w(n,s);if(i)return g(n,s),void function(e,t,n){if(!e.parentNode)return;const o=/^\s*(.+)\s+(?:in|of)\s+(.+)\s*$/.exec(t);if(!o)return console.warn(`[jsweb/ui] Invalid ui:for expression: ${t}`);const[,s,i]=o,c=["ui:key",":key"],r=w(e,c);g(e,c);const f=crypto.randomUUID(),a=document.createComment(` ui:for ${f} `);e.replaceWith(a);let l=[];y(a,()=>{const t=d(i,n);if(!Array.isArray(t))return l.forEach(e=>{e.el.remove(),h(e.el)}),void(l=[]);const o=[],c=new Map;l.forEach(e=>c.set(e.key,e)),t.forEach((t,i)=>{let f=i;if(r){const e=b({[s]:t,$index:i},n);f=d(r,e)}let a=c.get(f);if(a)a.scope[s]=t,a.scope.$index=i,a.scope.$key=f,a.scope.$el=a.el,c.delete(f);else{const o=e.cloneNode(!0),c=u({[s]:t,$index:i,$key:f,$el:o});m(o,b(c,n)),a={key:f,el:o,scope:c}}o.push(a)}),c.forEach(e=>{e.el.remove(),h(e.el)});let f=a.nextSibling;o.forEach(e=>{f===e.el?f=f.nextSibling:a.parentNode?.insertBefore(e.el,f)}),l=o})}(n,i,o);const c=["ui:if",":if"],r=w(n,c);r&&(g(n,c),function(e,t,n){if(!e.parentNode)return;const o=crypto.randomUUID(),s=document.createComment(` ui:if ${o} `);e.before(s),y(s,()=>{d(t,n)?e.parentNode||s.parentNode?.insertBefore(e,s.nextSibling):e.parentNode&&e.remove()})}(n,r,o)),function(e,t){const n=Array.from(e.attributes);for(const o of n){const{name:n,value:s}=o,i=["ui:text",":text"].includes(n),c=["ui:bind",":bind"].includes(n),r=["ui:class",":class"].includes(n),f=["ui:style",":style"].includes(n),u=["ui:ref",":ref"].includes(n),a=n.startsWith("ui:")||n.startsWith(":"),l=n.startsWith("ui@")||n.startsWith("@");i?(E(e,s,t),e.removeAttribute(n)):c?(S(e,s,t),e.removeAttribute(n)):r?(j(e,s,t),e.removeAttribute(n)):f?(x(e,s,t),e.removeAttribute(n)):u?($(e,s,t),e.removeAttribute(n)):a?(A(e,n.split(":").pop(),s,t),e.removeAttribute(n)):l&&(M(e,n,s,t),e.removeAttribute(n))}}(n,o);const f=Array.from(n.childNodes);for(const u of f)m(u,o)}function v(e,t){const n="string"==typeof e?document.querySelector(e):e;if(n){const e=t??{};e.$el=n,e.$emit||(e.$emit=(e,t)=>{n.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}),e.$refs||(e.$refs=new Map),m(n,e)}else console.warn("[jsweb/ui] Element not found:",e)}function y(e,t){const n=c(t),o=e;o._effects??=[],o._effects.push(n.stop)}function w(e,t){for(const n of t){const t=e.getAttribute(n);if(null!==t)return t}return null}function g(e,t){for(const n of t)e.removeAttribute(n)}function $(e,t,n){const o=t.trim().replace(/^['"]|['"]$/g,"");if(!o)return;const s=n.$refs;if(!s)return;const i=n.$key;if(void 0!==i){let t=s.get(o);t instanceof Map||(t=new Map,s.set(o,t)),t.set(i,e)}else s.set(o,e);const c=e;c._effects??=[],c._effects.push(()=>{if(void 0!==i){const e=s.get(o);e instanceof Map&&(e.delete(i),0===e.size&&s.delete(o))}else s.get(o)===e&&s.delete(o)})}function E(e,t,n){y(e,()=>{const o=d(t,n);e.textContent=null!=o?String(o):""})}function S(e,t,n){const o=e instanceof HTMLInputElement&&"checkbox"===e.type,s=e instanceof HTMLInputElement&&"radio"===e.type;y(e,()=>{const i=d(t,n);if(o)e.checked=!!i;else if(s)e.checked=e.value===String(i);else{e.value=null==i?"":String(i)}});const i=o||s||e instanceof HTMLSelectElement?"change":"input";e.addEventListener(i,e=>{p(e,`${t} = ${"$event.target."+(o?"checked":"value")}`,n)})}function A(e,t,n,o){y(e,()=>{const s=d(n,o);null==s||!1===s?e.removeAttribute(t):!0===s?e.setAttribute(t,""):e.setAttribute(t,String(s))})}function j(e,t,n){let o=new Set;y(e,()=>{const s=d(t,n),i=new Set,c=e=>e&&i.add(e),r=e=>e.split(/\s+/).forEach(c);"string"==typeof s?r(s):Array.isArray(s)?s.flat().forEach(e=>{"string"==typeof e&&r(e)}):"object"==typeof s&&null!==s&&Object.entries(s).forEach(([e,t])=>{t&&r(e)}),o.forEach(t=>{i.has(t)||e.classList.remove(t)}),i.forEach(t=>{o.has(t)||e.classList.add(t)}),o=i})}function x(e,t,n){let o={};y(e,()=>{const s=d(t,n),i="object"==typeof s&&null!==s?s:{};for(const t in o)t in i||(e.style[t]="");for(const t in i)o[t]!==i[t]&&(e.style[t]=i[t]);o={...i}})}function M(e,t,n,o){const[s,...i]=t.split("@").pop().split("."),c=i.includes("outside"),r=c?document:e,f=t=>{if(!e.isConnected)return;const s=t.target instanceof Node;c&&s&&e.contains(t.target)||i.includes("self")&&t.target!==e||(i.includes("prevent")&&t.preventDefault(),i.includes("stop")&&t.stopPropagation(),p(t,n,o))};if(r.addEventListener(s,f),c){const t=e;t._effects??=[],t._effects.push(()=>r.removeEventListener(s,f))}}if("undefined"!=typeof window){const e=window;e.jsweb=e.jsweb||{},e.jsweb.ui={createScope:v,reactive:u,watch:l,Scope:f}}e.Scope=f,e.createScope=v,e.reactive=u,e.watch=l});
|
|
2
|
+
//# sourceMappingURL=index.umd.js.map
|
package/index.umd.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.umd.js","names":[],"sources":["../src/reactivity.ts","../src/evaluator.ts","../src/parser.ts","../src/index.ts"],"sourcesContent":["let activeEffect: symbol | null = null\nconst targetMap = new WeakMap<\n object,\n Map<string | symbol, Set<ReactiveEffect>>\n>()\nconst proxyMap = new WeakMap<object, any>()\nconst effectMap = new WeakMap<symbol, ReactiveEffect>()\n\nexport class ReactiveEffect {\n active = true\n deps: Set<Set<ReactiveEffect>> = new Set()\n\n constructor(public fn: () => void) {}\n\n run() {\n if (!this.active) return this.fn()\n\n this.cleanup()\n\n activeEffect = Symbol()\n effectMap.set(activeEffect, this)\n\n try {\n return this.fn()\n } finally {\n effectMap.delete(activeEffect)\n activeEffect = null\n }\n }\n\n stop() {\n if (this.active) {\n this.cleanup()\n this.active = false\n }\n }\n\n cleanup() {\n this.deps.forEach((dep) => dep.delete(this))\n this.deps.clear()\n }\n\n effect() {\n return {\n run: () => this.run(),\n stop: () => this.stop(),\n }\n }\n}\n\nexport function effect(fn: () => void) {\n const ref = new ReactiveEffect(fn)\n ref.run()\n return ref.effect()\n}\n\nexport function track(target: object, key: string | symbol) {\n if (activeEffect) {\n let depsMap = targetMap.get(target)\n if (!depsMap) {\n depsMap = new Map()\n targetMap.set(target, depsMap)\n }\n\n let dep = depsMap.get(key)\n if (!dep) {\n dep = new Set()\n depsMap.set(key, dep)\n }\n\n const active = effectMap.get(activeEffect)\n if (active) {\n dep.add(active)\n active.deps.add(dep)\n }\n }\n}\n\nexport function trigger(target: object, key: string | symbol) {\n const depsMap = targetMap.get(target)\n if (!depsMap) return\n\n const dep = depsMap.get(key)\n if (dep) {\n const effects = new Set(dep)\n effects.forEach((effect) => effect.run())\n }\n}\n\nexport interface ScopeContext {\n /** Elemento DOM raiz associado ao escopo (somente leitura) */\n readonly $el: HTMLElement\n /** Map nativo indexando elementos referenciados via ui:ref / :ref (somente leitura) */\n readonly $refs: Map<string, any>\n /** Despacha CustomEvents nativos (bubbles: true, composed: true) */\n $emit: (event: string, detail?: any) => void\n /** Índice numérico da iteração atual em loops ui:for / :for */\n $index?: number\n /** Chave de identificação da iteração em loops ui:for / :for */\n $key?: any\n}\n\nexport class Scope {\n /** Elemento DOM raiz ao qual o escopo foi acoplado (somente leitura) */\n declare readonly $el: HTMLElement\n\n /** Map nativo indexando elementos referenciados via ui:ref / :ref (somente leitura) */\n protected readonly $refs: Map<string, any> = new Map<string, any>()\n\n /** Despacha CustomEvents nativos (bubbles: true, composed: true) */\n protected $emit(event: string, detail?: any): void {\n const target = this.$el || (typeof window !== 'undefined' ? window : null)\n target?.dispatchEvent(\n new CustomEvent(event, { detail, bubbles: true, composed: true }),\n )\n }\n\n declare $index?: number\n declare $key?: any\n\n constructor(init?: Record<string, any>) {\n if (init && typeof init === 'object') {\n Object.assign(this, init)\n }\n }\n}\n\nexport function reactive<T extends any[]>(target: T): T\nexport function reactive<T extends object>(\n target: T & ThisType<T & ScopeContext>,\n): T & ScopeContext\nexport function reactive<T extends object>(target: T): any {\n const notObject = typeof target !== 'object' || target === null\n if (notObject) return target\n\n if (\n target instanceof Map ||\n target instanceof Set ||\n target instanceof WeakMap ||\n target instanceof WeakSet ||\n target instanceof Date ||\n target instanceof RegExp ||\n (typeof Node === 'function' && target instanceof Node)\n ) {\n return target\n }\n\n const isReactive = Object.hasOwn(target, '_isReactive')\n if (isReactive) return target\n\n const existingProxy = proxyMap.get(target)\n if (existingProxy) return existingProxy\n\n const proxy = new Proxy(target, {\n get(obj, key, receiver) {\n if (key === '_isReactive') return true\n track(obj, key)\n\n const res = Reflect.get(obj, key, receiver)\n // deep reactivity\n return typeof res === 'object' && res !== null ? reactive(res) : res\n },\n set(obj, key, value, receiver) {\n const isArray = Array.isArray(obj)\n const oldValue = Reflect.get(obj, key, receiver)\n const hadKey =\n isArray && String(Number(key)) === key\n ? Number(key) < obj.length\n : Object.hasOwn(obj, key)\n\n const result = Reflect.set(obj, key, value, receiver)\n\n if (!hadKey) {\n trigger(obj, key)\n if (isArray && key !== 'length') {\n trigger(obj, 'length')\n }\n } else if (oldValue !== value) {\n trigger(obj, key)\n }\n\n return result\n },\n })\n\n proxyMap.set(target, proxy)\n return proxy\n}\n\nexport function traverse(value: any, seen = new Set()) {\n if (typeof value !== 'object' || value === null || seen.has(value)) {\n return value\n }\n seen.add(value)\n for (const key in value) {\n traverse(value[key], seen)\n }\n return value\n}\n\nexport function watch<T>(\n source: (() => T) | any,\n cb: (newValue: T, oldValue: T | undefined) => void,\n options?: { immediate?: boolean },\n): () => void {\n let oldValue: any\n let isFirstRun = true\n\n const getter = source instanceof Function ? source : () => traverse(source)\n\n const runner = effect(() => {\n const newValue = getter()\n\n if (isFirstRun) {\n isFirstRun = false\n oldValue = newValue\n if (options?.immediate) {\n cb(newValue, undefined)\n }\n } else {\n cb(newValue, oldValue)\n oldValue = newValue\n }\n })\n\n return runner.stop\n}\n","export function evaluate(\n expression: string,\n context: Record<string, any> = {},\n) {\n try {\n const fn = new Function(`with(this) { return ${expression} }`)\n return fn.call(context)\n } catch {\n return undefined\n }\n}\n\nexport function evaluateEvent(\n $event: Event,\n expression: string,\n context: Record<string, any> = {},\n) {\n try {\n const exp = expression.trim()\n const isIdentifier = /^[a-zA-Z_$][0-9a-zA-Z_$.]*$/.test(exp)\n const code = `${exp} instanceof Function ? ${exp}.call(this, $event) : ${exp}`\n const result = isIdentifier ? code : exp\n const fn = new Function('$event', `with(this) { ${result} }`)\n\n fn.call(context, $event)\n } catch {\n console.warn(`[jsweb/ui] Error evaluating event: ${expression}`)\n }\n}\n","import { effect, reactive, type ScopeContext } from './reactivity'\nimport { evaluate, evaluateEvent } from './evaluator'\n\nexport type Context = Record<string, any>\n\ninterface BoundNode extends Node {\n _effects?: Array<() => void>\n}\n\nexport function cleanupTree(node: Node) {\n const bNode = node as BoundNode\n if (bNode._effects) {\n bNode._effects.forEach((stop) => stop())\n bNode._effects = []\n }\n const children = Array.from(node.childNodes)\n for (const child of children) cleanupTree(child)\n}\n\nexport function createContext(scope: any, context: Context = {}): Context {\n const reactiveScope = scope._isReactive ? scope : reactive(scope)\n\n return new Proxy(reactiveScope, {\n get(target, prop) {\n if (prop === '_isContext') return true\n if (prop in target) return Reflect.get(target, prop, target)\n if (prop in context) {\n return Reflect.get(context, prop, context)\n }\n return Reflect.get(target, prop, target)\n },\n set(target, prop, value) {\n if (prop in target) return Reflect.set(target, prop, value, target)\n if (prop in context) {\n return Reflect.set(context, prop, value, context)\n }\n return Reflect.set(target, prop, value, target)\n },\n has(target, prop) {\n if (prop in target) return true\n if (prop in context) return true\n return false\n },\n })\n}\n\nexport function parseNode(node: Node, context: Context) {\n if (node.nodeType !== Node.ELEMENT_NODE) return\n\n const el = node as HTMLElement\n const scope = processScope(el, context)\n if (!scope) return\n\n const forAttrs = ['ui:for', ':for']\n const forDirective = getDirectiveValue(el, forAttrs)\n if (forDirective) {\n removeDirectiveAttributes(el, forAttrs)\n processFor(el, forDirective, scope)\n return\n }\n\n const ifAttrs = ['ui:if', ':if']\n const ifDirective = getDirectiveValue(el, ifAttrs)\n if (ifDirective) {\n removeDirectiveAttributes(el, ifAttrs)\n processIf(el, ifDirective, scope)\n }\n\n processAttributes(el, scope)\n\n const children = Array.from(el.childNodes)\n for (const child of children) parseNode(child, scope)\n}\n\nexport function createScope<T extends object = Context>(\n selectorOrElement: string | HTMLElement,\n context?: T & ThisType<T & ScopeContext>,\n) {\n const el =\n typeof selectorOrElement === 'string'\n ? document.querySelector(selectorOrElement)\n : selectorOrElement\n\n if (el) {\n const ctx = (context ?? {}) as Context\n ctx.$el = el\n\n if (!ctx.$emit) {\n ctx.$emit = (eventName: string, detail?: any) => {\n el.dispatchEvent(\n new CustomEvent(eventName, { detail, bubbles: true, composed: true }),\n )\n }\n }\n\n if (!ctx.$refs) {\n ctx.$refs = new Map<string, any>()\n }\n\n parseNode(el, ctx)\n } else {\n console.warn('[jsweb/ui] Element not found:', selectorOrElement)\n }\n}\n\nfunction bindEffect(node: Node, fn: () => void) {\n const e = effect(fn)\n const bNode = node as BoundNode\n bNode._effects ??= []\n bNode._effects.push(e.stop)\n}\n\nfunction getDirectiveValue(el: HTMLElement, names: string[]) {\n for (const name of names) {\n const value = el.getAttribute(name)\n if (value !== null) return value\n }\n return null\n}\n\nfunction removeDirectiveAttributes(el: HTMLElement, names: string[]) {\n for (const name of names) {\n el.removeAttribute(name)\n }\n}\n\nfunction processScope(el: HTMLElement, context: Context) {\n const attrs = ['ui:scope', ':scope']\n const directive = getDirectiveValue(el, attrs)\n if (!directive) return context\n\n const scope = evaluate(directive, context)\n if (!scope) return undefined\n\n removeDirectiveAttributes(el, attrs)\n\n scope.$el = el\n\n if (!scope.$emit) {\n scope.$emit = (event: string, detail?: any) => {\n el.dispatchEvent(\n new CustomEvent(event, { detail, bubbles: true, composed: true }),\n )\n }\n }\n\n if (!scope.$refs) {\n scope.$refs = context.$refs ?? new Map<string, any>()\n }\n\n return createContext(scope, context)\n}\n\nfunction processFor(el: HTMLElement, expr: string, context: Context) {\n const parent = el.parentNode\n if (!parent) return\n\n const match = /^\\s*(.+)\\s+(?:in|of)\\s+(.+)\\s*$/.exec(expr)\n if (!match) {\n return console.warn(`[jsweb/ui] Invalid ui:for expression: ${expr}`)\n }\n const [, itemName, listName] = match\n\n const keyAttr = ['ui:key', ':key']\n const keyDirective = getDirectiveValue(el, keyAttr)\n removeDirectiveAttributes(el, keyAttr)\n\n const uuid = crypto.randomUUID()\n const comment = document.createComment(` ui:for ${uuid} `)\n el.replaceWith(comment)\n\n interface RenderedNode {\n key: any\n el: HTMLElement\n scope: any\n }\n let renderedNodes: RenderedNode[] = []\n\n bindEffect(comment, () => {\n const list = evaluate(listName, context)\n\n if (!Array.isArray(list)) {\n renderedNodes.forEach((node) => {\n node.el.remove()\n cleanupTree(node.el)\n })\n renderedNodes = []\n return\n }\n\n const newNodes: RenderedNode[] = []\n const oldNodesByKey = new Map<any, RenderedNode>()\n renderedNodes.forEach((node) => oldNodesByKey.set(node.key, node))\n\n list.forEach((item, index) => {\n let key: any = index\n\n if (keyDirective) {\n const tempContext = createContext(\n { [itemName]: item, $index: index },\n context,\n )\n key = evaluate(keyDirective, tempContext)\n }\n\n let node = oldNodesByKey.get(key)\n if (node) {\n // Reuse node\n node.scope[itemName] = item\n node.scope.$index = index\n node.scope.$key = key\n node.scope.$el = node.el\n oldNodesByKey.delete(key)\n } else {\n // Create new node\n const clone = el.cloneNode(true) as HTMLElement\n const scope = {\n [itemName]: item,\n $index: index,\n $key: key,\n $el: clone,\n }\n const reactiveScope = reactive(scope)\n const localContext = createContext(reactiveScope, context)\n parseNode(clone, localContext)\n node = { key, el: clone, scope: reactiveScope }\n }\n\n newNodes.push(node)\n })\n\n // Remove un-reused nodes\n oldNodesByKey.forEach((node) => {\n node.el.remove()\n cleanupTree(node.el)\n })\n\n // Reorder and insert new DOM nodes\n let currentAnchor = comment.nextSibling\n newNodes.forEach((node) => {\n if (currentAnchor === node.el) {\n currentAnchor = currentAnchor.nextSibling\n } else {\n comment.parentNode?.insertBefore(node.el, currentAnchor)\n }\n })\n\n renderedNodes = newNodes\n })\n}\n\nfunction processIf(el: HTMLElement, expr: string, context: Context) {\n const parent = el.parentNode\n if (!parent) return\n\n const uuid = crypto.randomUUID()\n const comment = document.createComment(` ui:if ${uuid} `)\n el.before(comment)\n\n bindEffect(comment, () => {\n const val = evaluate(expr, context)\n if (val) {\n if (!el.parentNode) {\n comment.parentNode?.insertBefore(el, comment.nextSibling)\n }\n } else if (el.parentNode) {\n el.remove()\n }\n })\n}\n\nfunction processAttributes(el: HTMLElement, context: Context) {\n const attrs = Array.from(el.attributes)\n\n for (const attr of attrs) {\n const { name, value } = attr\n const isText = ['ui:text', ':text'].includes(name)\n const isTwoWayBind = ['ui:bind', ':bind'].includes(name)\n const isClassBind = ['ui:class', ':class'].includes(name)\n const isStyleBind = ['ui:style', ':style'].includes(name)\n const isRef = ['ui:ref', ':ref'].includes(name)\n const isAttrBind = name.startsWith('ui:') || name.startsWith(':')\n const isEvent = name.startsWith('ui@') || name.startsWith('@')\n\n if (isText) {\n processTextBinding(el, value, context)\n el.removeAttribute(name)\n } else if (isTwoWayBind) {\n processTwoWayBinding(el, value, context)\n el.removeAttribute(name)\n } else if (isClassBind) {\n processClassBinding(el, value, context)\n el.removeAttribute(name)\n } else if (isStyleBind) {\n processStyleBinding(el, value, context)\n el.removeAttribute(name)\n } else if (isRef) {\n processRef(el, value, context)\n el.removeAttribute(name)\n } else if (isAttrBind) {\n const bound = name.split(':').pop()!\n processAttrBinding(el, bound, value, context)\n el.removeAttribute(name)\n } else if (isEvent) {\n processEventBinding(el, name, value, context)\n el.removeAttribute(name)\n }\n }\n}\n\nfunction processRef(el: HTMLElement, expr: string, context: Context) {\n const refName = expr.trim().replace(/^['\"]|['\"]$/g, '')\n if (!refName) return\n\n const refs = context.$refs as Map<string, any>\n if (!refs) return\n\n const key = context.$key\n\n if (key !== undefined) {\n let group = refs.get(refName)\n if (!(group instanceof Map)) {\n group = new Map<any, HTMLElement>()\n refs.set(refName, group)\n }\n group.set(key, el)\n } else {\n refs.set(refName, el)\n }\n\n const bNode = el as BoundNode\n bNode._effects ??= []\n bNode._effects.push(() => {\n if (key !== undefined) {\n const group = refs.get(refName)\n if (group instanceof Map) {\n group.delete(key)\n if (group.size === 0) {\n refs.delete(refName)\n }\n }\n } else if (refs.get(refName) === el) {\n refs.delete(refName)\n }\n })\n}\n\nfunction processTextBinding(el: HTMLElement, expr: string, context: Context) {\n bindEffect(el, () => {\n const val = evaluate(expr, context)\n el.textContent = val !== undefined && val !== null ? String(val) : ''\n })\n}\n\nfunction processTwoWayBinding(el: HTMLElement, expr: string, context: Context) {\n const isCheckbox = el instanceof HTMLInputElement && el.type === 'checkbox'\n const isRadio = el instanceof HTMLInputElement && el.type === 'radio'\n\n // 1. Reactive state to DOM\n bindEffect(el, () => {\n const val = evaluate(expr, context)\n if (isCheckbox) {\n el.checked = !!val\n } else if (isRadio) {\n el.checked = el.value === String(val)\n } else {\n const target = el as\n | HTMLInputElement\n | HTMLSelectElement\n | HTMLTextAreaElement\n target.value = val == null ? '' : String(val)\n }\n })\n\n // 2. DOM to Reactive state\n const isChange = isCheckbox || isRadio || el instanceof HTMLSelectElement\n const eventName = isChange ? 'change' : 'input'\n el.addEventListener(eventName, ($event) => {\n const target = isCheckbox ? 'checked' : 'value'\n const value = `$event.target.${target}`\n evaluateEvent($event, `${expr} = ${value}`, context)\n })\n}\n\nfunction processAttrBinding(\n el: HTMLElement,\n attr: string,\n expr: string,\n context: Context,\n) {\n bindEffect(el, () => {\n const val = evaluate(expr, context)\n if (val === null || val === undefined || val === false) {\n el.removeAttribute(attr)\n } else if (val === true) {\n el.setAttribute(attr, '')\n } else {\n el.setAttribute(attr, String(val))\n }\n })\n}\n\nfunction processClassBinding(el: HTMLElement, expr: string, context: Context) {\n let oldClasses = new Set<string>()\n\n bindEffect(el, () => {\n const val = evaluate(expr, context)\n const newClasses = new Set<string>()\n const addClass = (c: string) => c && newClasses.add(c)\n const addClasses = (c: string) => c.split(/\\s+/).forEach(addClass)\n\n if (typeof val === 'string') addClasses(val)\n else if (Array.isArray(val)) {\n val.flat().forEach((c: any) => {\n if (typeof c === 'string') addClasses(c)\n })\n } else if (typeof val === 'object' && val !== null) {\n Object.entries(val).forEach(([c, condition]: [string, any]) => {\n if (condition) addClasses(c)\n })\n }\n\n oldClasses.forEach((c) => {\n if (!newClasses.has(c)) el.classList.remove(c)\n })\n newClasses.forEach((c) => {\n if (!oldClasses.has(c)) el.classList.add(c)\n })\n\n oldClasses = newClasses\n })\n}\n\nfunction processStyleBinding(el: HTMLElement, expr: string, context: Context) {\n let oldStyles: Record<string, any> = {}\n\n bindEffect(el, () => {\n const val = evaluate(expr, context)\n const newStyles = typeof val === 'object' && val !== null ? val : {}\n\n for (const key in oldStyles) {\n if (!(key in newStyles)) {\n ;(el.style as any)[key] = ''\n }\n }\n\n for (const key in newStyles) {\n if (oldStyles[key] !== newStyles[key]) {\n ;(el.style as any)[key] = newStyles[key]\n }\n }\n\n oldStyles = { ...newStyles }\n })\n}\n\nfunction processEventBinding(\n el: HTMLElement,\n evt: string,\n expr: string,\n context: Context,\n) {\n const refs = evt.split('@').pop()!\n const [name, ...modifiers] = refs.split('.')\n\n const isOutside = modifiers.includes('outside')\n const target = isOutside ? document : el\n\n const handler: EventListener = ($event: Event) => {\n if (!el.isConnected) return\n\n const isTargetNode = $event.target instanceof Node\n\n if (isOutside && isTargetNode && el.contains($event.target)) return\n if (modifiers.includes('self') && $event.target !== el) return\n\n if (modifiers.includes('prevent')) $event.preventDefault()\n if (modifiers.includes('stop')) $event.stopPropagation()\n\n evaluateEvent($event, expr, context)\n }\n\n target.addEventListener(name, handler)\n\n if (isOutside) {\n const bNode = el as BoundNode\n bNode._effects ??= []\n bNode._effects.push(() => target.removeEventListener(name, handler))\n }\n}\n","import { reactive, watch, Scope, type ScopeContext } from './reactivity'\nimport { createScope, type Context } from './parser'\n\nexport { reactive, watch, createScope, Scope }\nexport type { ScopeContext, Context }\n\nif (typeof window !== 'undefined') {\n const w = window as any\n w.jsweb = w.jsweb || {}\n w.jsweb.ui = { createScope, reactive, watch, Scope }\n}\n"],"mappings":"mSAAA,IAAI,EAA8B,KAC5B,EAAY,IAAI,QAIhB,EAAW,IAAI,QACf,EAAY,IAAI,QAET,EAAb,MAIqB,GAHnB,QAAS,EACT,KAAiC,IAAI,IAErC,WAAA,CAAY,GAAO,KAAA,GAAA,CAAiB,CAEpC,GAAA,GACE,IAAK,KAAK,OAAQ,OAAO,KAAK,KAE9B,KAAK,UAEL,EAAe,SACf,EAAU,IAAI,EAAc,MAE5B,IACE,OAAO,KAAK,IACd,CAAA,QACE,EAAU,OAAO,GACjB,EAAe,IACjB,CACF,CAEA,I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,CACF,CCneA,GAAsB,oBAAX,OAAwB,CACjC,MAAM,EAAI,OACV,EAAE,MAAQ,EAAE,OAAS,CAAC,EACtB,EAAE,MAAM,GAAK,CAAE,cAAa,WAAU,QAAO,QAC/C"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jsweb/ui",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.2",
|
|
4
4
|
"description": "JS Web Microframework",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"js",
|
|
@@ -21,30 +21,17 @@
|
|
|
21
21
|
"license": "MIT",
|
|
22
22
|
"author": "Alex Bruno Cáceres <email@alexbruno.dev>",
|
|
23
23
|
"type": "module",
|
|
24
|
-
"main": "
|
|
25
|
-
"module": "
|
|
26
|
-
"types": "
|
|
24
|
+
"main": "index.umd.js",
|
|
25
|
+
"module": "index.es.js",
|
|
26
|
+
"types": "index.d.ts",
|
|
27
27
|
"exports": {
|
|
28
28
|
".": {
|
|
29
|
-
"import": "./
|
|
30
|
-
"require": "./
|
|
31
|
-
"types": "./
|
|
29
|
+
"import": "./index.es.js",
|
|
30
|
+
"require": "./index.umd.js",
|
|
31
|
+
"types": "./index.d.ts"
|
|
32
32
|
}
|
|
33
33
|
},
|
|
34
|
-
"
|
|
35
|
-
"
|
|
36
|
-
"build": "tsc && vite build && node publish.js",
|
|
37
|
-
"preview": "vite preview",
|
|
38
|
-
"format": "prettier --write .",
|
|
39
|
-
"test": "echo 'test'",
|
|
40
|
-
"preversion": "npm run build",
|
|
41
|
-
"postversion": "git push && git push --tags"
|
|
42
|
-
},
|
|
43
|
-
"devDependencies": {
|
|
44
|
-
"prettier": "^3.8.3",
|
|
45
|
-
"terser": "^5.46.2",
|
|
46
|
-
"typescript": "^6.0.3",
|
|
47
|
-
"vite": "^8.0.10",
|
|
48
|
-
"vite-plugin-dts": "^5.0.0"
|
|
34
|
+
"publishConfig": {
|
|
35
|
+
"access": "public"
|
|
49
36
|
}
|
|
50
|
-
}
|
|
37
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { ScopeContext } from './reactivity';
|
|
1
2
|
export type Context = Record<string, any>;
|
|
2
3
|
export declare function cleanupTree(node: Node): void;
|
|
3
4
|
export declare function createContext(scope: any, context?: Context): Context;
|
|
4
5
|
export declare function parseNode(node: Node, context: Context): void;
|
|
5
|
-
export declare function createScope(selectorOrElement: string | HTMLElement, context?:
|
|
6
|
+
export declare function createScope<T extends object = Context>(selectorOrElement: string | HTMLElement, context?: T & ThisType<T & ScopeContext>): void;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
export declare class ReactiveEffect {
|
|
2
|
+
fn: () => void;
|
|
3
|
+
active: boolean;
|
|
4
|
+
deps: Set<Set<ReactiveEffect>>;
|
|
5
|
+
constructor(fn: () => void);
|
|
6
|
+
run(): void;
|
|
7
|
+
stop(): void;
|
|
8
|
+
cleanup(): void;
|
|
9
|
+
effect(): {
|
|
10
|
+
run: () => void;
|
|
11
|
+
stop: () => void;
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export declare function effect(fn: () => void): {
|
|
15
|
+
run: () => void;
|
|
16
|
+
stop: () => void;
|
|
17
|
+
};
|
|
18
|
+
export declare function track(target: object, key: string | symbol): void;
|
|
19
|
+
export declare function trigger(target: object, key: string | symbol): void;
|
|
20
|
+
export interface ScopeContext {
|
|
21
|
+
/** Elemento DOM raiz associado ao escopo (somente leitura) */
|
|
22
|
+
readonly $el: HTMLElement;
|
|
23
|
+
/** Map nativo indexando elementos referenciados via ui:ref / :ref (somente leitura) */
|
|
24
|
+
readonly $refs: Map<string, any>;
|
|
25
|
+
/** Despacha CustomEvents nativos (bubbles: true, composed: true) */
|
|
26
|
+
$emit: (event: string, detail?: any) => void;
|
|
27
|
+
/** Índice numérico da iteração atual em loops ui:for / :for */
|
|
28
|
+
$index?: number;
|
|
29
|
+
/** Chave de identificação da iteração em loops ui:for / :for */
|
|
30
|
+
$key?: any;
|
|
31
|
+
}
|
|
32
|
+
export declare class Scope {
|
|
33
|
+
/** Elemento DOM raiz ao qual o escopo foi acoplado (somente leitura) */
|
|
34
|
+
readonly $el: HTMLElement;
|
|
35
|
+
/** Map nativo indexando elementos referenciados via ui:ref / :ref (somente leitura) */
|
|
36
|
+
protected readonly $refs: Map<string, any>;
|
|
37
|
+
/** Despacha CustomEvents nativos (bubbles: true, composed: true) */
|
|
38
|
+
protected $emit(event: string, detail?: any): void;
|
|
39
|
+
$index?: number;
|
|
40
|
+
$key?: any;
|
|
41
|
+
constructor(init?: Record<string, any>);
|
|
42
|
+
}
|
|
43
|
+
export declare function reactive<T extends any[]>(target: T): T;
|
|
44
|
+
export declare function reactive<T extends object>(target: T & ThisType<T & ScopeContext>): T & ScopeContext;
|
|
45
|
+
export declare function traverse(value: any, seen?: Set<unknown>): any;
|
|
46
|
+
export declare function watch<T>(source: (() => T) | any, cb: (newValue: T, oldValue: T | undefined) => void, options?: {
|
|
47
|
+
immediate?: boolean;
|
|
48
|
+
}): () => void;
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
name: NPM Publish
|
|
2
|
-
|
|
3
|
-
on:
|
|
4
|
-
push:
|
|
5
|
-
tags:
|
|
6
|
-
- v*
|
|
7
|
-
|
|
8
|
-
jobs:
|
|
9
|
-
publish:
|
|
10
|
-
runs-on: ubuntu-latest
|
|
11
|
-
steps:
|
|
12
|
-
- uses: actions/checkout@v6
|
|
13
|
-
- uses: actions/setup-node@v6
|
|
14
|
-
with:
|
|
15
|
-
node-version: 22
|
|
16
|
-
registry-url: https://registry.npmjs.org/
|
|
17
|
-
- run: npm i
|
|
18
|
-
- run: npm run build
|
|
19
|
-
- run: npm publish ./dist --access public
|
package/.prettierignore
DELETED
package/.prettierrc
DELETED
package/PROJECT.md
DELETED
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
# Especificação Técnica: Micro-Framework JS/TS (Codinome: @jsweb/ui)
|
|
2
|
-
|
|
3
|
-
## 1. Visão Geral
|
|
4
|
-
|
|
5
|
-
**@jsweb/ui** é um micro-framework frontend focado em _Progressive Enhancement_ e DX (Developer Experience). Ele deve oferecer a reatividade moderna de frameworks como Vue 3 (Composition API) e a simplicidade de uso direto no HTML do Alpine.js, sem a necessidade obrigatória de um build step, mas totalmente otimizado para árvores de dependência (tree-shaking) quando usado em ambientes build-tooling.
|
|
6
|
-
|
|
7
|
-
## 2. Pilares Arquiteturais
|
|
8
|
-
|
|
9
|
-
- **No Virtual DOM:** Utilização de reatividade de grão fino (Fine-grained reactivity) via `Proxy` ou `Signals`. Atualizações diretas no DOM real.
|
|
10
|
-
- **Dual Distribution:**
|
|
11
|
-
- **Standalone:** Arquivo único (IIFE/UMD) para inclusão via `<script src="...">`.
|
|
12
|
-
- **Module:** Pacote ESM com exports nomeados para suporte a Tree-Shaking.
|
|
13
|
-
- **Hybrid Context:** Suporte a definição de estado via Objetos Literais (POJOs) ou Classes TypeScript.
|
|
14
|
-
- **Template Engine:** Baseado em atributos customizados no HTML (`ui:*` para diretivas e `ui@*` para eventos, com shorthands `@`, `:`).
|
|
15
|
-
|
|
16
|
-
## 3. Especificações do Motor (Core)
|
|
17
|
-
|
|
18
|
-
### A. Sistema de Reatividade
|
|
19
|
-
|
|
20
|
-
- **Mecanismo:** Proxy-based em conjunto com a classe `ReactiveEffect`. O estado é interceptado para disparar "efeitos" com gerenciamento preciso de dependências, controle de ciclo de vida (`stop`, `cleanup`) e otimizado contra vazamento de memória.
|
|
21
|
-
- **Global State:** Deve ser possível exportar um objeto reativo de um arquivo e importá-lo em múltiplos componentes/contextos, tornando-o um estado compartilhado.
|
|
22
|
-
- **Global Effect:** Deve ser possível criar efeitos globais que reajam a mudanças em qualquer estado compartilhado.
|
|
23
|
-
- **Local State:** Deve ser possível criar estados locais que reajam a mudanças apenas dentro do escopo do componente.
|
|
24
|
-
- **Local Effect:** Deve ser possível criar efeitos locais que reajam a mudanças apenas dentro do escopo do componente.
|
|
25
|
-
- **Lifecycle:** Deve ser possível criar efeitos que reajam a mudanças no ciclo de vida do componente.
|
|
26
|
-
- **Cleanup:** Deve ser possível limpar os efeitos quando os componentes forem removidos do DOM.
|
|
27
|
-
- **Watchers:** Implementado via API `watch`, permitindo reagir a mudanças em propriedades com acesso ao valor anterior/novo e disparo imediato (`immediate`).
|
|
28
|
-
- **Computed:** Deve ser possível criar propriedades computadas que reajam a mudanças em propriedades específicas do estado.
|
|
29
|
-
- **Composition API:** Deve ser possível usar a Composition API para criar efeitos e reatividade e aninhar efeitos e reatividade em outros efeitos e reatividade.
|
|
30
|
-
|
|
31
|
-
### B. Avaliador de Expressões (The Evaluator)
|
|
32
|
-
|
|
33
|
-
- **Implementação:** Uso de `new Function()` com `with(this)`.
|
|
34
|
-
- **Estratégia de Execução:** Para avaliar expressões declaradas no HTML de forma encapsulada (sandboxed):
|
|
35
|
-
1. O motor encapsula o objeto/escopo em um Proxy de Contexto para resolução de dependências.
|
|
36
|
-
2. Constrói a função dinâmica: `new Function('with(this) { ... }')`.
|
|
37
|
-
3. Executa a função passando o escopo reativo atrelado ao `this`.
|
|
38
|
-
4. Para eventos, também expõe a variável nativa `$event`.
|
|
39
|
-
|
|
40
|
-
### C. Parser de Template
|
|
41
|
-
|
|
42
|
-
- **Traversal:** Utilizar `TreeWalker` ou recursão otimizada para identificar diretivas.
|
|
43
|
-
- **Limpeza:** Atributos `ui:*`, `ui:@*`, `@*` e `:*` devem ser removidos do DOM após a inicialização para manter o HTML limpo.
|
|
44
|
-
|
|
45
|
-
## 4. Sintaxe e Diretivas
|
|
46
|
-
|
|
47
|
-
| Diretiva | Atalho | Descrição | Exemplo |
|
|
48
|
-
| :----------- | :--------- | :----------------------------------------------------------------------------------- | :----------------------------------------- |
|
|
49
|
-
| `ui:scope` | `:scope` | Define o objeto de estado/contexto para o elemento e seus filhos. | `<div :scope="{ count: 0 }">` |
|
|
50
|
-
| `ui:text` | `:text` | Sincroniza o `textContent` com uma variável ou expressão. | `<span :text="count"></span>` |
|
|
51
|
-
| `ui:bind` | `:bind` | Two-way data binding para inputs, checkboxes, radios, selects e textareas. | `<input :bind="name">` |
|
|
52
|
-
| `ui:if` | `:if` | Adiciona/Remove o elemento do DOM (via Comment Node placeholder). | `<div :if="count > 0">` |
|
|
53
|
-
| `ui:for` | `:for` | Renderiza uma lista de elementos a partir de um array (`in` ou `of`). | `<li :for="item of items">` |
|
|
54
|
-
| `ui:key` | `:key` | Chave de reconciliação para reaproveitamento e reciclagem de nós DOM em listas. | `<li :for="item of items" :key="item.id">` |
|
|
55
|
-
| `ui:class` | `:class` | Bind dinâmico para classes CSS (objeto booleano, array ou string). | `<div :class="{ active: isActive }">` |
|
|
56
|
-
| `ui:style` | `:style` | Bind dinâmico para estilos inline (objeto chave/valor de estilos CSS). | `<div :style="{ color: textColor }">` |
|
|
57
|
-
| `ui:ref` | `:ref` | Indexa elementos HTML em um Map acessível via `$refs` (suporta chaves de lista). | `<input :ref="myInput">` |
|
|
58
|
-
| `ui:[attr]` | `:[attr]` | Bind de atributos HTML nativos com suporte a valores booleanos (ex: disabled, href). | `<button :disabled="count > 10">` |
|
|
59
|
-
| `ui@[event]` | `@[event]` | Event listeners com suporte a `$event` e modificadores encadeados. | `<button @click.prevent="save">` |
|
|
60
|
-
|
|
61
|
-
### Modificadores de Eventos
|
|
62
|
-
|
|
63
|
-
- `.prevent`: Executa `$event.preventDefault()`.
|
|
64
|
-
- `.stop`: Executa `$event.stopPropagation()`.
|
|
65
|
-
- `.self`: Executa o manipulador apenas se `$event.target === el`.
|
|
66
|
-
- `.outside`: Executa o manipulador quando o evento ocorre fora do elemento (com cleanup de listener no document ao desconectar o nó).
|
|
67
|
-
|
|
68
|
-
### Helpers e Variáveis Contextuais
|
|
69
|
-
|
|
70
|
-
- `$refs`: Instância de `Map` nativa indexando elementos referenciados (elementos únicos ou Maps aninhados para itens de loops com `:key`).
|
|
71
|
-
- `$emit(eventName, detail?)`: Despacha CustomEvents (`bubbles: true`, `composed: true`) a partir do escopo atual.
|
|
72
|
-
- `$event`: Objeto nativo do evento disparado, disponível nas expressões de eventos ou repassado como 1º argumento na sintaxe de referência direta.
|
|
73
|
-
- `$index`: Índice numérico atual da iteração em loops `ui:for` / `:for`.
|
|
74
|
-
|
|
75
|
-
## 5. Requisitos de Engenharia (Instruções para a IA)
|
|
76
|
-
|
|
77
|
-
- **Linguagem:** TypeScript Estrito.
|
|
78
|
-
- **Bundle Tool:** Vite (configurado para `build.lib` com formatos `es` e `umd`).
|
|
79
|
-
- **Memory Management:** Garantir o `cleanup` de event listeners e observadores quando elementos `ui:if` ou `ui:for` forem removidos.
|
|
80
|
-
- **Zero Dependencies:** O core não deve ter dependências externas de runtime.
|
|
81
|
-
- **Estilo de Código:** Funcional, modular, com comentários JSDoc claros para explicar o funcionamento interno do Proxy, do Parser e das diretivas.
|
|
82
|
-
|
|
83
|
-
---
|
|
84
|
-
|
|
85
|
-
### Stack de Build (Vite)
|
|
86
|
-
|
|
87
|
-
Para o `vite.config.ts`, utilize esta abordagem para satisfazer os requisitos de "Standalone" e "Module":
|
|
88
|
-
|
|
89
|
-
```typescript
|
|
90
|
-
import { defineConfig } from 'vite'
|
|
91
|
-
import dts from 'vite-plugin-dts'
|
|
92
|
-
|
|
93
|
-
export default defineConfig({
|
|
94
|
-
build: {
|
|
95
|
-
lib: {
|
|
96
|
-
entry: './src/index.ts',
|
|
97
|
-
name: 'jswebui',
|
|
98
|
-
fileName: (format) => `ui.${format}.js`,
|
|
99
|
-
formats: ['es', 'umd'],
|
|
100
|
-
},
|
|
101
|
-
sourcemap: true,
|
|
102
|
-
minify: 'terser',
|
|
103
|
-
},
|
|
104
|
-
plugins: [dts()], // Gera os tipos .d.ts automaticamente
|
|
105
|
-
})
|
|
106
|
-
```
|
package/dist/LICENSE
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2026 jsweb
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|