@jsweb/ui 1.3.0 → 1.3.1

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.
@@ -0,0 +1,135 @@
1
+ ---
2
+ name: update-documentation
3
+ description: >-
4
+ Audits recent codebase changes in @jsweb/ui (src/, package.json, config files) and synchronizes all documentation files (README.md, PROJECT.md, SKILL.md, and CHANGELOG.md). Use this skill whenever the user asks to update, synchronize, or refresh documentation, or after adding/modifying directives, reactivity mechanisms, APIs, event modifiers, or releasing new versions.
5
+ ---
6
+
7
+ # Update Documentation Skill (@jsweb/ui)
8
+
9
+ This skill guides the agent through auditing codebase changes and systematically synchronizing all project documentation files (`README.md`, `PROJECT.md`, `SKILL.md`, `CHANGELOG.md`) to reflect the latest APIs, directives, modifiers, release notes, and architectural behaviors.
10
+
11
+ ---
12
+
13
+ ## Target Documentation Files
14
+
15
+ | File | Audience | Purpose | Language |
16
+ | :----------------------------------------------------------------- | :--------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------- | :------------------- |
17
+ | [`README.md`](file:///d:/Projetos/github/jsweb/ui/README.md) | Developers & End Users | Public GitHub/NPM documentation, quickstart, installation, directives reference table, and usage examples. | Portuguese / English |
18
+ | [`PROJECT.md`](file:///d:/Projetos/github/jsweb/ui/PROJECT.md) | Maintainers & Architecture | Technical specification, core engine mechanics (Reactivity, Evaluator, Parser), architectural pillars, and requirements. | Portuguese |
19
+ | [`SKILL.md`](file:///d:/Projetos/github/jsweb/ui/SKILL.md) | AI Coding Agents | Operational knowledge base installed via `npx skills add @jsweb/ui`, defining rules, directives, APIs, patterns, and agent constraints. | English |
20
+ | [`CHANGELOG.md`](file:///d:/Projetos/github/jsweb/ui/CHANGELOG.md) | All (Users, Maintainers, AI) | Curated chronological log of notable changes (Added, Changed, Deprecated, Removed, Fixed, Security) adhering to Keep a Changelog. | Portuguese |
21
+
22
+ ---
23
+
24
+ ## Workflow: Step-by-Step Procedure
25
+
26
+ ```mermaid
27
+ flowchart TD
28
+ A["1. Inspect Git Changes & Source Code"] --> B["2. Compare Source with Current Docs"]
29
+ B --> C["3. Update README.md"]
30
+ B --> D["4. Update PROJECT.md"]
31
+ B --> E["5. Update SKILL.md"]
32
+ B --> F["6. Update CHANGELOG.md"]
33
+ C & D & E & F --> G["7. Verify Build & Copy with npm run build"]
34
+ G --> H["8. Report Summary to User"]
35
+ ```
36
+
37
+ ### Step 1: Inspect Changes and Current Source
38
+
39
+ 1. Check git status and recent diffs:
40
+ ```bash
41
+ git status
42
+ git diff HEAD
43
+ ```
44
+ 2. Inspect the core implementation files in `src/`:
45
+ - [`src/reactivity.ts`](file:///d:/Projetos/github/jsweb/ui/src/reactivity.ts): Check `reactive()`, `watch()`, `effect()`, `ReactiveEffect`, tracking, trigger behavior, bypassed types, or computed handling.
46
+ - [`src/parser.ts`](file:///d:/Projetos/github/jsweb/ui/src/parser.ts): Check directives (`:scope`, `:text`, `:bind`, `:if`, `:for`, `:key`, `:class`, `:style`, `:ref`, `:[attr]`, `@[event]`), event modifiers (`.prevent`, `.stop`, `.self`, `.outside`), and context helpers (`$refs`, `$emit`, `$index`, `$key`).
47
+ - [`src/evaluator.ts`](file:///d:/Projetos/github/jsweb/ui/src/evaluator.ts): Check expression sandboxing, `evaluate()`, and `evaluateEvent()`.
48
+ - [`src/index.ts`](file:///d:/Projetos/github/jsweb/ui/src/index.ts): Check public exports and global window attachments (`window.jsweb.ui`).
49
+ - [`package.json`](file:///d:/Projetos/github/jsweb/ui/package.json): Check version bumps, dependencies, entry points, or scripts.
50
+
51
+ ### Step 2: Identify Discrepancies Across Documentation
52
+
53
+ Check whether any of the following changed:
54
+
55
+ - **New or changed directives**: Did the syntax, prefix, or behavior change?
56
+ - **New or changed event modifiers**: Are there new modifiers (e.g. `.debounce`, `.throttle`, `.once`) or modifications to existing ones?
57
+ - **Reactivity enhancements**: Changes to deep reactivity, collections, watch options, or computed getters?
58
+ - **API signatures**: Changes to parameters, options, or return types for `createScope`, `reactive`, or `watch`?
59
+ - **Context helpers**: Any newly exposed helper (like `$parent`, `$root`, `$dispatch`, etc.)?
60
+ - **Distribution / Build**: Changes to UMD/ESM paths, global variable name (`jsweb.ui`), or CDN URLs?
61
+
62
+ ### Step 3: Synchronize Each Documentation File
63
+
64
+ #### A. Updating `README.md`
65
+
66
+ - Keep the directive summary table up to date with exact syntax, shorthand, and clear examples.
67
+ - Update code snippets demonstrating CDN standalone usage and ESM bundler usage.
68
+ - Ensure the event modifiers and `$refs` / `$emit` section matches actual runtime behavior.
69
+ - Document any breaking changes or version upgrades clearly.
70
+
71
+ #### B. Updating `PROJECT.md`
72
+
73
+ - Update the Technical Specifications (Section 3: Reatividade, Avaliador, Parser).
74
+ - Keep Section 4 (Sintaxe e Diretivas) aligned with the exact implementation in `parser.ts`.
75
+ - Document any architectural decisions (e.g., memory management, cleanup hooks, node recycling).
76
+
77
+ #### C. Updating `SKILL.md` (Root)
78
+
79
+ - Ensure YAML frontmatter `description` contains comprehensive trigger keywords.
80
+ - Update the API Reference section with precise TypeScript signatures and return types.
81
+ - Ensure the Template Directives reference accurately describes:
82
+ - Form controls supported by `:bind` (input types, select, checkbox, radio).
83
+ - Array and reconciliation behavior of `:for` and `:key`.
84
+ - Class and style object/array evaluation rules.
85
+ - `$refs` behavior (single element vs. nested `Map` in keyed loops).
86
+ - Event modifiers and their exact execution flow.
87
+ - Maintain the "Critical Rules for AI Coding Agents" section (DOs and DON'Ts).
88
+
89
+ #### D. Updating `CHANGELOG.md`
90
+
91
+ - Adhere strictly to [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/) format.
92
+ - Group changes under `[Unreleased]` (or the specific version header if tagging/bumping version):
93
+ - `### Added` for new features or capabilities.
94
+ - `### Changed` for changes in existing functionality.
95
+ - `### Deprecated` for soon-to-be removed features.
96
+ - `### Removed` for now removed features.
97
+ - `### Fixed` for any bug fixes.
98
+ - `### Security` in case of vulnerabilities.
99
+ - Provide concise, user-focused descriptions with code references.
100
+
101
+ ### Step 4: Validate Formatting and Build
102
+
103
+ 1. Format all modified files with Prettier:
104
+ ```bash
105
+ npm run format
106
+ ```
107
+ 2. Run the build to ensure type safety and that `publish.js` syncs `README.md`, `LICENSE`, `SKILL.md`, and `CHANGELOG.md` to `dist/`:
108
+ ```bash
109
+ npm run build
110
+ ```
111
+ 3. Verify that `dist/README.md`, `dist/SKILL.md`, and `dist/CHANGELOG.md` contain the updated contents.
112
+
113
+ ### Step 5: Report to User
114
+
115
+ Present a concise summary of:
116
+
117
+ - Which files were updated ([README.md](file:///d:/Projetos/github/jsweb/ui/README.md), [PROJECT.md](file:///d:/Projetos/github/jsweb/ui/PROJECT.md), [SKILL.md](file:///d:/Projetos/github/jsweb/ui/SKILL.md), [CHANGELOG.md](file:///d:/Projetos/github/jsweb/ui/CHANGELOG.md)).
118
+ - Specific sections added, modified, or removed in each file.
119
+ - Confirmation that `npm run build` and `npm run format` passed cleanly.
120
+
121
+ ---
122
+
123
+ ## Documentation Checklist
124
+
125
+ When updating documentation, verify each of these items:
126
+
127
+ - [ ] All directives in `parser.ts` are listed in both long form (`ui:*`) and shorthand (`:*`).
128
+ - [ ] All event modifiers supported in `processEventBinding` are documented.
129
+ - [ ] `$refs` behavior is accurately described (Map instance; nested Map in `:for` loops with `:key`).
130
+ - [ ] `$emit` parameters and CustomEvent details (`bubbles: true`, `composed: true`) are correct.
131
+ - [ ] Code snippets use valid modern JavaScript/TypeScript syntax.
132
+ - [ ] `CHANGELOG.md` has all notable modifications recorded under `[Unreleased]` or version tag.
133
+ - [ ] Version numbers in examples or text match `package.json`.
134
+ - [ ] Prettier formatting is applied (`npm run format`).
135
+ - [ ] `npm run build` succeeds and copies updated files to `dist/`.
package/CHANGELOG.md ADDED
@@ -0,0 +1,137 @@
1
+ # Changelog
2
+
3
+ Todas as alterações notáveis neste projeto serão documentadas neste arquivo.
4
+
5
+ O formato é baseado em [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/) e este projeto adere ao [Semantic Versioning](https://semver.org/).
6
+
7
+ ---
8
+
9
+ ## [Unreleased]
10
+
11
+ ---
12
+
13
+ ## [1.3.1] - 2026-09-24
14
+
15
+ ### Added
16
+
17
+ - **Tipagem Contextual `ThisType<T & ScopeContext>`**: Inclusão de `ThisType` na assinatura de `reactive` e `createScope`, fornecendo autocomplete e tipagem estrita de `this` em métodos e _getters_ de objetos literais, com acesso direto a `$refs`, `$emit` e `$el` como propriedades não-opcionais.
18
+ - **Classe Base `Scope` e Interface `ScopeContext`**: Exportação da classe utilitária `Scope` e da interface `ScopeContext` para suporte nativo e tipado a arquiteturas orientadas a objetos (`class MyScope extends Scope`). Na classe `Scope`, `$el` e `$refs` são propriedades somente leitura (com `$refs` mantendo sua instância original de Map viva) e `$emit` como método `protected` com disparo nativo em `$el`, permitindo sobrescrita (`override`) nas subclasses.
19
+ - **Tipagem Genérica em `watch<T>`**: Aprimoramento da assinatura de `watch` para inferência de tipos em `newValue` e `oldValue`.
20
+ - **Skill Aberta para Agentes de IA (`SKILL.md`)**: Arquivo [`SKILL.md`](./SKILL.md) na raiz do projeto para integração direta com agentes de IA via `npx skills add @jsweb/ui`.
21
+ - **Skill de Workspace (`update-documentation`)**: Skill em [`.agents/skills/update-documentation/SKILL.md`](./.agents/skills/update-documentation/SKILL.md) para auditoria e sincronização contínua de documentação.
22
+ - **Histórico Semântico de Versões (`CHANGELOG.md`)**: Arquivo [`CHANGELOG.md`](./CHANGELOG.md) baseado no padrão Keep a Changelog.
23
+ - **Automação de Build e Metadados**: Atualização do script [`publish.js`](./publish.js) para sincronizar `SKILL.md` e `CHANGELOG.md` na pasta `dist/` durante o build do pacote NPM.
24
+ - **Script de Publicação**: Adicionado script `npm run push` no `package.json` para automatizar o envio de tags git e publicação no NPM.
25
+
26
+ ---
27
+
28
+ ## [1.3.0] - 2026-09-18
29
+
30
+ ### Added
31
+
32
+ - **Diretiva `:ref` / `ui:ref`**: Indexação reativa de elementos DOM no helper contextual `$refs` (`Map`).
33
+ - **Refs Aninhadas em Listas**: Em loops `:for` com `:key`, `$refs.get(name)` retorna um `Map` aninhado indexado pela chave do item (`$key`).
34
+ - **Cleanup Automático de Refs**: Remoção de referências do `$refs` quando nós são destruídos por `:if` ou `:for`.
35
+ - **Modificador de Evento `.outside`**: Captura cliques e eventos fora do elemento (ideal para modais e dropdowns) com remoção automática do listener no `document` ao desconectar o nó.
36
+ - **Reconciliação e Reciclagem de Nós DOM em Listas**: Rastreamento de nós pelo `:key` em `:for`, reaproveitando instâncias existentes e evitando reflows desnecessários.
37
+
38
+ ---
39
+
40
+ ## [1.2.8] - 2026-05-20
41
+
42
+ ### Refactored
43
+
44
+ - Limpeza de imports e remoção de código não utilizado no parser e no core.
45
+
46
+ ---
47
+
48
+ ## [1.2.7] - 2026-05-20
49
+
50
+ ### Added
51
+
52
+ - Suporte aprimorado à função `watch` com observação profunda (_deep traverse_) e suporte a `{ immediate: true }`.
53
+
54
+ ---
55
+
56
+ ## [1.2.6] - 2026-05-20
57
+
58
+ ### Added
59
+
60
+ - **Diretiva `:class` / `ui:class`**: Bind reativo de classes CSS via objeto booleano, array ou string, preservando classes estáticas.
61
+ - **Diretiva `:style` / `ui:style`**: Bind reativo para estilos inline com limpeza automática de propriedades removidas.
62
+
63
+ ---
64
+
65
+ ## [1.2.5] - 2026-05-18
66
+
67
+ ### Fixed
68
+
69
+ - Tratamento de erros nas funções de avaliação (`evaluate` e `evaluateEvent`).
70
+ - Ajuste no contexto `this` para getters em propriedades computadas.
71
+
72
+ ---
73
+
74
+ ## [1.2.4] - 2026-05-18
75
+
76
+ ### Added
77
+
78
+ - Suporte automático a propriedades computadas via _getters_ nativos (`get prop() { ... }`) em objetos envolvidos por `reactive()`.
79
+
80
+ ---
81
+
82
+ ## [1.2.3] - 2026-05-18
83
+
84
+ ### Added
85
+
86
+ - Script de automação `preversion` no `package.json` para executar o build antes de gerar versões.
87
+
88
+ ### Refactored
89
+
90
+ - Remoção da função legada `hasDirective`.
91
+
92
+ ---
93
+
94
+ ## [1.2.2] - 2026-05-18
95
+
96
+ ### Refactored
97
+
98
+ - Simplificação do logging de avisos no motor de avaliação.
99
+
100
+ ---
101
+
102
+ ## [1.2.1] - 2026-05-17
103
+
104
+ ### Added
105
+
106
+ - Script `publish.js` para geração de pacote mínimo em `dist/` e automação de publicação NPM.
107
+
108
+ ---
109
+
110
+ ## [1.2.0] - 2026-05-09
111
+
112
+ ### Added
113
+
114
+ - Exportação da API `watch(source, callback, options?)` para observação de estados reativos.
115
+ - Reorganização dos exports principais (`createScope`, `reactive`, `watch`).
116
+
117
+ ---
118
+
119
+ ## [1.1.0] - 2026-05-09
120
+
121
+ ### Added
122
+
123
+ - Injeção do helper contextual `$emit(eventName, detail?)` para disparo de `CustomEvent` nativos (`bubbles: true`, `composed: true`).
124
+ - Padronização do nome do método de montagem para `createScope`.
125
+
126
+ ---
127
+
128
+ ## [1.0.0] - 2026-05-07
129
+
130
+ ### Added
131
+
132
+ - Primeiro lançamento estável do `@jsweb/ui`.
133
+ - Motor de reatividade de grão fino baseado em `Proxy` e `ReactiveEffect` (sem Virtual DOM).
134
+ - Avaliador de expressões dinâmicas em sandbox.
135
+ - Diretivas fundamentais: `ui:scope`, `ui:text`, `ui:bind`, `ui:if`, `ui:for`, `ui:[attr]` e `ui@[event]`.
136
+ - Modificadores de evento `.prevent`, `.stop` e `.self`.
137
+ - Distribuição dual: ESM para bundlers e UMD/Standalone para uso direto via CDN.
package/PROJECT.md CHANGED
@@ -10,7 +10,7 @@
10
10
  - **Dual Distribution:**
11
11
  - **Standalone:** Arquivo único (IIFE/UMD) para inclusão via `<script src="...">`.
12
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.
13
+ - **Hybrid Context:** Suporte a definição de estado via Objetos Literais (POJOs) tipados contextualmente via `ThisType<T & ScopeContext>` ou Classes TypeScript estendendo a classe base `Scope`.
14
14
  - **Template Engine:** Baseado em atributos customizados no HTML (`ui:*` para diretivas e `ui@*` para eventos, com shorthands `@`, `:`).
15
15
 
16
16
  ## 3. Especificações do Motor (Core)
@@ -25,7 +25,8 @@
25
25
  - **Lifecycle:** Deve ser possível criar efeitos que reajam a mudanças no ciclo de vida do componente.
26
26
  - **Cleanup:** Deve ser possível limpar os efeitos quando os componentes forem removidos do DOM.
27
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.
28
+ - **Computed:** Deve ser possível criar propriedades computadas que reajam a mudanças em propriedades específicas do estado (via _getters_ nativos).
29
+ - **TypeScript First DX:** Tipagem estrita de `this` via `ThisType<T & ScopeContext>` para objetos literais e classe utilitária `Scope` para POJOs orientados a objetos.
29
30
  - **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
 
31
32
  ### B. Avaliador de Expressões (The Evaluator)
package/README.md CHANGED
@@ -174,6 +174,10 @@ O atributo `ui:ref` ou `:ref` indexa o elemento diretamente em um objeto `Map` a
174
174
 
175
175
  ### TypeScript / ESM
176
176
 
177
+ #### Abordagem com Objeto Literal (`ThisType`)
178
+
179
+ Graças ao utilitário `ThisType<T & ScopeContext>`, dentro dos métodos e _getters_ do objeto literal você tem autocomplete e tipagem estrita de `this`, incluindo as propriedades do objeto e os helpers `$refs` e `$emit`:
180
+
177
181
  ```typescript
178
182
  import { createScope, reactive, watch } from '@jsweb/ui'
179
183
 
@@ -181,15 +185,22 @@ const scope = reactive({
181
185
  count: 0,
182
186
  inc: 'Incremento',
183
187
  dec: 'Decremento',
188
+
189
+ get double() {
190
+ return this.count * 2
191
+ },
192
+
184
193
  increment() {
185
194
  this.count++
195
+ this.$emit('changed', this.count)
196
+ this.$refs.get('meuInput')?.focus()
186
197
  },
187
198
  decrement() {
188
199
  this.count--
189
200
  },
190
201
  })
191
202
 
192
- // Observa mudanças com suporte a oldValue/newValue e disparo imediato opcional
203
+ // Observa mudanças com suporte a tipagem genérica, oldValue/newValue e disparo imediato
193
204
  const unwatch = watch(
194
205
  () => scope.count,
195
206
  (newVal, oldVal) => {
@@ -201,27 +212,81 @@ const unwatch = watch(
201
212
  createScope('#container', { scope })
202
213
  ```
203
214
 
215
+ #### Abordagem Orientada a Objetos com a Classe `Scope`
216
+
217
+ Você também pode utilizar classes TypeScript estendendo a classe base `Scope` fornecida pelo framework:
218
+
219
+ ```typescript
220
+ import { createScope, reactive, Scope } from '@jsweb/ui'
221
+
222
+ class ContadorScope extends Scope {
223
+ count = 0
224
+ inc = 'Incremento'
225
+ dec = 'Decremento'
226
+
227
+ get double() {
228
+ return this.count * 2
229
+ }
230
+
231
+ increment() {
232
+ this.count++
233
+ this.$emit('changed', this.count)
234
+ this.$refs.get('meuInput')?.focus()
235
+ }
236
+
237
+ decrement() {
238
+ this.count--
239
+ }
240
+
241
+ // É possível sobrescrever o método $emit se desejar lógica customizada:
242
+ protected override $emit(event: string, detail?: any) {
243
+ console.log(`[Contador] Evento disparado: ${event}`, detail)
244
+ super.$emit(event, detail)
245
+ }
246
+ }
247
+
248
+ const scope = reactive(new ContadorScope())
249
+ createScope('#container', { scope })
250
+ ```
251
+
204
252
  ## API JavaScript / TypeScript
205
253
 
206
- ### `createScope(selectorOrElement, context?)`
254
+ ### `createScope<T>(selectorOrElement, context?)`
207
255
 
208
256
  Inicializa e amarra a reatividade ao elemento DOM ou seletor especificado.
209
257
 
210
258
  - **`selectorOrElement`**: Seletor CSS (ex: `'#app'`, `'body'`) ou instância de `HTMLElement`.
211
- - **`context`**: Objeto inicial de contexto/estado compartilhado (opcional). Injeta automaticamente o helper `$emit` no escopo.
259
+ - **`context`**: Objeto inicial de contexto/estado compartilhado (opcional), tipado contextualmente com `ThisType<T & ScopeContext>`. Injeta automaticamente os helpers `$emit` e `$refs`.
212
260
 
213
261
  ### `reactive(target)`
214
262
 
215
263
  Envolve um objeto ou array em um `Proxy` de reatividade de grão fino (_fine-grained_).
216
264
 
217
- - Suporta reatividade profunda (_deep reactivity_).
218
- - Intercepta mutações em arrays (`push`, `pop`, `splice`, etc.) e mutações de propriedades em objetos.
265
+ - **Objeto Literal**: Tipado com `ThisType<T & ScopeContext>` para inferência e autocomplete de `this` (incluindo computeds via _getters_ e helpers contextuais `$refs`, `$emit` e `$el` prontos para uso sem necessidade de `?.`).
266
+ - **Instâncias de Classes**: Suporta instâncias que estendem `Scope` ou classes POJO personalizadas.
267
+ - **Arrays**: Intercepta métodos de mutação (`push`, `pop`, `splice`, etc.) e gerencia dependências de tamanho (`length`).
268
+ - **Suporta reatividade profunda** (_deep reactivity_).
269
+
270
+ ### `Scope`
271
+
272
+ Classe base utilitária para definição de escopos orientados a objetos em TypeScript. Já possui `$el` e `$refs` implementados como somente leitura e `$emit` com implementação padrão como método `protected`, permitindo sobrescrita (`override`) nas subclasses.
273
+
274
+ ```typescript
275
+ export class Scope {
276
+ readonly $el: HTMLElement
277
+ protected readonly $refs: Map<string, any>
278
+ protected $emit(event: string, detail?: any): void
279
+ declare $index?: number
280
+ declare $key?: any
281
+ constructor(init?: Record<string, any>)
282
+ }
283
+ ```
219
284
 
220
- ### `watch(source, callback, options?)`
285
+ ### `watch<T>(source, callback, options?)`
221
286
 
222
287
  Observa alterações reativas e executa uma função de callback quando o valor mudar.
223
288
 
224
289
  - **`source`**: Objeto reativo completo ou função getter que retorna o valor a ser observado (ex: `() => state.count`).
225
- - **`callback`**: `(newValue: any, oldValue: any) => void`.
290
+ - **`callback`**: `(newValue: T, oldValue: T | undefined) => void`.
226
291
  - **`options`**: `{ immediate?: boolean }` para acionar a callback imediatamente na primeira execução.
227
292
  - **Retorno**: Função de cancelamento `stop()` que encerra a observação e limpa dependências.