lightview 2.3.8 → 2.4.7

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.
Files changed (45) hide show
  1. package/.gemini/CODE_ANALYSIS_AND_IMPROVEMENT_PLAN.md +56 -0
  2. package/AI-GUIDANCE.md +274 -0
  3. package/README.md +35 -0
  4. package/build_tmp/lightview-cdom.js +3934 -0
  5. package/build_tmp/lightview-router.js +185 -0
  6. package/build_tmp/lightview-x.js +1739 -0
  7. package/build_tmp/lightview.js +740 -0
  8. package/components/data-display/diff.js +36 -4
  9. package/docs/api/hypermedia.html +75 -5
  10. package/docs/api/index.html +3 -3
  11. package/docs/api/nav.html +0 -16
  12. package/docs/articles/html-vs-json-partials.md +102 -0
  13. package/docs/articles/lightview-vs-htmx.md +610 -0
  14. package/docs/assets/styles/site.css +16 -7
  15. package/docs/benchmarks/bau-tagged-fragment.js +41 -0
  16. package/docs/benchmarks/tagged-fragment.js +36 -0
  17. package/docs/cdom.html +127 -88
  18. package/docs/components/chart.html +157 -210
  19. package/docs/components/component-nav.html +1 -1
  20. package/docs/components/diff.html +33 -21
  21. package/docs/components/gallery.html +107 -4
  22. package/docs/components/index.css +18 -3
  23. package/docs/components/index.html +20 -9
  24. package/docs/dom-benchmark.html +771 -0
  25. package/docs/getting-started/index.html +42 -2
  26. package/docs/hypermedia/index.html +391 -0
  27. package/docs/hypermedia/nav.html +17 -0
  28. package/docs/index.html +136 -17
  29. package/index.html +59 -10
  30. package/lightview-all.js +223 -67
  31. package/lightview-cdom.js +1 -2
  32. package/lightview-x.js +144 -13
  33. package/lightview.js +85 -277
  34. package/package.json +2 -2
  35. package/src/lightview-cdom.js +1 -5
  36. package/src/lightview-x.js +158 -27
  37. package/src/lightview.js +94 -60
  38. package/docs/articles/calculator-no-javascript-hackernoon.md +0 -283
  39. package/docs/articles/calculator-no-javascript.md +0 -290
  40. package/docs/articles/part1-reference.md +0 -236
  41. package/lightview.js.bak +0 -1
  42. package/test-xpath.html +0 -63
  43. package/test_error.txt +0 -0
  44. package/test_output.txt +0 -0
  45. package/test_output_full.txt +0 -0
@@ -0,0 +1,56 @@
1
+ # cDOM / JPRX Code Analysis and Improvement Recommendations
2
+
3
+ ## 1. Executive Summary
4
+ This document outlines the analysis of the current JPRX (JSON Reactive Path eXpressions) and cDOM implementation within Lightview. While the system is powerful and integral to the framework's reactivity, its core logic (`jprx/parser.js`) has grown into a monolithic module that mixes tokenization, parsing, evaluation, and runtime state management. The primary recommendation is to refactor this into distinct layers to improve maintainability, performance, and testability.
5
+
6
+ ## 2. Current State Analysis
7
+
8
+ ### 2.1 Code Structure
9
+ * **Monolithic Design**: `jprx/parser.js` is approximately 1,900 lines long. It encapsulates:
10
+ * **Tokenizer**: Regex-based lexer (`tokenize`).
11
+ * **Pratt Parser**: Top-down operator precedence parser.
12
+ * **Evaluator**: `evaluateAST` and `resolvePath` logic.
13
+ * **Runtime Types**: `BindingTarget`, `LazyValue`.
14
+ * **Global Registry**: Storage for helpers and operators.
15
+ * **Coupling**: The parser is tightly coupled with Lightview's specific reactivity model (Signals/Proxies) via direct imports and assumption of `Lightview.state` structure.
16
+
17
+ ### 2.2 Performance
18
+ * **Repeated Parsing**: Currently, there is no visible caching mechanism for parsed ASTs. Every time an expression is evaluated (unless manually memoized externally), it goes through the tokenization and parsing steps.
19
+ * **Object Creation**: The heavy use of intermediate objects during AST traversals and resolution could trigger frequent garbage collection in high-frequency updates.
20
+
21
+ ### 2.3 DX and Reliability
22
+ * **Error Reporting**: Syntax errors in JPRX expressions often result in generic failures or silent returns, making debugging difficult for the end-user.
23
+ * **Complexity**: Adding new operators or features requires modifying the central file, increasing the risk of regressions.
24
+
25
+ ## 3. Improvement Recommendations
26
+
27
+ ### Phase 1: Modularization (High Priority)
28
+ Decompose `jprx/parser.js` into focused modules under a `jprx/core/` directory:
29
+
30
+ 1. **`tokenization.js`**: Pure functions handling string-to-token conversion.
31
+ 2. **`grammar.js`**: Definition of operators, precedence levels, and AST node types.
32
+ 3. **`parser.js`**: The Pratt parser implementation that outputs a pure AST.
33
+ 4. **`runtime.js`**: The `evaluateAST` logic and `BindingTarget`/`LazyValue` classes.
34
+ 5. **`registry.js`**: Singleton or context-based registry for helpers and operators.
35
+
36
+ ### Phase 2: Performance Enhancements
37
+ 1. **LRU Cache for ASTs**: Implement a Least Recently Used cache for the `tokenize -> parse` pipeline. If an expression string `count + 1` is seen again, serve the cached AST immediately.
38
+ 2. **Fast-Path for Simple Paths**: 90% of expressions are likely simple property access (e.g., `user.name`). Implement a proper regex check to bypass the full parser for these cases and use direct traversal.
39
+ 3. **Instruction Caching**: For repeated evaluations of the same AST, consider compiling to a closure (similar to how `new Function` works, but safe and sandboxed) if performance bottlenecks appear.
40
+
41
+ ### Phase 3: Robustness and Validation
42
+ 1. **Fuzz Testing**: Implement grammar-based fuzz testing to ensure the parser does not crash on malformed inputs.
43
+ 2. **Strict Mode**: Introduce a strict mode that throws descriptive errors for undefined paths or invalid operations, rather than silently failing.
44
+ 3. **Type Safety**: If possible, add JSDoc type definitions to all internal AST nodes to aid tooling and potential future TypeScript migration.
45
+
46
+ ## 4. Code Specific Observations
47
+
48
+ * **`BindingTarget` Implementation**: The current "duck-typing" (`isBindingTarget = true`) is practical but could be cleaner using `Symbol.for('jprx.bindingTarget')` to avoid property collision.
49
+ * **Operator Registration**: The dynamic `registerOperator` is powerful but allows overwriting core behavior. Consider locking core operators (math, logic) after initialization.
50
+ * **Reactivity Integration**: The dependency on `Lightview.state` could be abstracted behind an interface (e.g., `IReactiveSource`), allowing JPRX to be used with other state management libraries if desired.
51
+
52
+ ## 5. Next Steps
53
+ 1. Create the `jprx/core` directory structure.
54
+ 2. Move `BindingTarget` and `LazyValue` to a `types.js` file.
55
+ 3. Extract the `tokenize` function and unit test it in isolation.
56
+ 4. Draft the `AST` cache mechanism.
package/AI-GUIDANCE.md ADDED
@@ -0,0 +1,274 @@
1
+ # Lightview AI Guidance
2
+
3
+ This document is the **definitive guide** for Large Language Models (LLMs) on how to effectively use the Lightview library. It covers all development workflows, particularly emphasizing correct source file usage, hypermedia patterns, and dynamic generation.
4
+
5
+ ## Table of Contents
6
+ 1. [Critical: Source Files vs Modules](#source-files)
7
+ 2. [The Four UI Syntaxes](#the-four-ui-syntaxes)
8
+ 3. [Hypermedia & Lightview X](#hypermedia-lightview-x)
9
+ 4. [JPRX & cDOM (AI-Safe Generation)](#jprx-cdom)
10
+ 5. [Component System](#component-system)
11
+ 6. [Routing & Navigation](#routing-navigation)
12
+ 7. [AI Development Strategies](#ai-development-strategies)
13
+ 8. [Deep Links & Resources](#deep-links)
14
+
15
+ ---
16
+
17
+ <a name="source-files"></a>
18
+ ## 1. Critical: Source Files vs Modules
19
+
20
+ **PAY CAREFUL ATTENTION TO FILE TYPES.**
21
+
22
+ * **Standard Scripts (`.js`)**: These files exist in the root and are suitable for direct browser inclusion via script tags or simple bundling.
23
+ * `lightview.js`: The core reactive engine (Signals, State, $, Effect).
24
+ * `lightview-x.js`: The "Extension" module (Hypermedia, src fetching, simple validation, vDOM/oDOM conversion).
25
+ * `lightview-router.js`: The Router implementation.
26
+ * `lightview-cdom.js`: The parser for JPRX and cDOM.
27
+
28
+ * **ES Modules (in subdirectories)**: Files in `jprx/`, `components/`, etc., are ES modules.
29
+ * **Do not** reference these directly in a generic HTML script tag without `type="module"`.
30
+ * **Do** import them in your application logic files (e.g., `import { ... } from './jprx/parser.js'`).
31
+
32
+ **Guidance**: When helping a user set up a new project, prefer importing from the root standard scripts for simplicity, or set up a proper `build.js` if deep module imports are needed.
33
+
34
+ **Note on Syntaxes**:
35
+ - **Tagged API**: Supported in `lightview.js`.
36
+ - **vDOM**: Supported in `lightview.js` (standard `{ tag: ... }` objects).
37
+ - **oDOM**: Requires `lightview-x.js` (converts `{ div: ... }` usage).
38
+
39
+ ---
40
+
41
+ <a name="the-four-ui-syntaxes"></a>
42
+ ## 2. The Four UI Syntaxes
43
+
44
+ Choose the syntax that matches your goal.
45
+
46
+ ### A. Tagged API (Best for Logic)
47
+ Javascript functions representing HTML tags. Best for building applications with complex logic.
48
+ ```javascript
49
+ const { div, h1, button } = Lightview.tags;
50
+ const count = signal(0);
51
+
52
+ const view = div({ class: "p-4" },
53
+ h1("Counter"),
54
+ button({ onclick: () => count.value++ }, () => `Count: ${count.value}`)
55
+ );
56
+ ```
57
+
58
+ ### B. vDOM (Best for Structured Data)
59
+ Explicit JSON structure. Use this when you need a standard, serializable format.
60
+ ```javascript
61
+ const view = {
62
+ tag: "div",
63
+ attributes: { class: "p-4" },
64
+ children: [
65
+ { tag: "h1", children: ["Counter"] },
66
+ { tag: "button", attributes: { onclick: () => count.value++ }, children: [() => `Count: ${count.value}`] }
67
+ ]
68
+ };
69
+ ```
70
+
71
+ ### C. oDOM (Best for Compact Templates)
72
+ "Object DOM" uses keys as tags. It is significantly more concise. **Preferred for configuration-based UIs.**
73
+ ```javascript
74
+ const view = {
75
+ div: {
76
+ class: "p-4",
77
+ children: [
78
+ { h1: "Counter" },
79
+ { button: { onclick: "...", children: ["Increment"] } }
80
+ ]
81
+ }
82
+ };
83
+ ```
84
+
85
+ ### D. Custom Elements (Best for Hybrid Apps)
86
+ Standard HTML tags powered by Lightview. Use these when enhancing an existing HTML page.
87
+ ```html
88
+ <lv-button onclick="alert('clicked')">Click Me</lv-button>
89
+ ```
90
+
91
+ ---
92
+
93
+ <a name="hypermedia-lightview-x"></a>
94
+ ## 3. Hypermedia & Lightview X
95
+
96
+ Lightview X adds powerful **Hypermedia** capabilities to standard HTML elements.
97
+
98
+ ### The `src` and `href` Attributes (Hypermedia)
99
+ * **`src`**: Fetches content and replaces the element or its content.
100
+ * **Support**: `.html`, `.json`, `.vdom`, `.odom`, `.cdom`, `.cdomc`
101
+ * **Usage**: `<div src="/components/user-card.vdom"></div>`
102
+ * **`href`**: Non-standard tags (like `div`) with `href` act as "Links".
103
+ * **Behavior**: Clicking them fetches the content at the URL and replaces the element's `src`.
104
+ * **Targeting**: Use `target="#dest:beforeend"` to direct the content elsewhere.
105
+ * **Usage**: `<div href="/api/next-page" target="#content:beforeend">Load More</div>`
106
+
107
+ ### Advanced Fetches (`data-method` & `data-body`)
108
+ Customize HTTP requests for `src` and `href` actions.
109
+
110
+ * **`data-method`**: Specify the HTTP verb (e.g., `POST`, `PUT`, `DELETE`). Defaults to `GET`.
111
+ * **`data-body`**: The data to send with the request.
112
+ * **CSS Selector (Default)**: Grabs the data from the DOM.
113
+ * `form`: Serialized as `FormData`.
114
+ * `input`/`select`/`textarea`: Sends the current `value`.
115
+ * `checkbox`/`radio`: Sends `value` only if checked.
116
+ * Other elements: Sends `innerText`.
117
+ * **`javascript:expr`**: Evaluates a Javascript expression (has access to `state` and `signal`).
118
+ * **`json:{...}`**: Sends a literal JSON string (sets `Content-Type: application/json`).
119
+ * **`text:...`**: Sends raw text (sets `Content-Type: text/plain`).
120
+ * **GET Requests**: If the method is `GET`, the data from `data-body` is automatically converted into **URL Query Parameters**.
121
+
122
+ **Usage**:
123
+ ```html
124
+ <!-- Post a form -->
125
+ <button href="/api/user/save" data-method="POST" data-body="#user-form">Save</button>
126
+
127
+ <!-- Fetch with query params from an input -->
128
+ <button href="/api/search" data-body="#search-input" target="#results">Search</button>
129
+ ```
130
+
131
+ * **Template Literals**: Supported in HTML, vDOM, and oDOM strings (e.g., `class="${ val > 10 ? 'red' : 'blue' }"`) via `lightview-x.js`.
132
+ * **Gating**:
133
+ 1. **`Lightview.hooks.validateUrl`**: Intercept/block URLs.
134
+ 2. **`lv-before`**: Attribute that gates events (e.g., `lv-before="click: throttle(500)"` or custom functions).
135
+
136
+ ### Logic in Attributes (`template literals`)
137
+ Lightview X allows embedded `${}` expressions in attributes for simple reactivity
138
+ ```javascript
139
+ {
140
+ div: {
141
+ class: "${ count.value > 10 ? 'text-red-500' : 'text-green-500' }",
142
+ children: ["Status"]
143
+ }
144
+ }
145
+ ```
146
+
147
+ ---
148
+
149
+ <a name="jprx-cdom"></a>
150
+ ## 4. JPRX & cDOM (Safe Dynamic UI Generation For Humans and AIs)
151
+
152
+ **cDOM (Computed DOM)** and **JPRX (JSON Reactive Expressions)** allow you to build fully reactive UIs using **only JSON**.
153
+
154
+ ### Syntax Prefixes
155
+ * **`=` (JPRX)**: Navigates **reactive state** (Signals/States). Starts with `=/` for absolute paths.
156
+ * **`#` (cDOM XPath)**: Navigates the **DOM tree** during construction. Use `#../../@id` to skip the text node parent and reach an ancestor's attribute.
157
+
158
+ ### Name Resolution & Scoping
159
+ JPRX uses an **up-tree search** to find signals or states:
160
+ 1. **Search starts** at the element where the expression is defined.
161
+ 2. **Bubbles up** through parent elements looking for a registered name.
162
+ 3. **Falls back** to the global registry.
163
+
164
+ **The `$this` Placeholder**:
165
+ Use `{ scope: $this }` in `=state` or `=signal` to register data specifically at the current element's level. This is essential for creating multiple independent instances of a component.
166
+
167
+ ### The `...` (Explosion) Operator
168
+ * **Infix Mapping (`/path...property`)**: Extracts `property` from every object in the `/path` array. **Inside a function call, it automatically explodes** the results into separate arguments.
169
+ * **Trailing Spread (`/path...`)**: Spreads a direct array reference into individual arguments.
170
+ * **Warning**: Never write `/path...property...`. The trailing dots will be incorrectly included in the property name lookup.
171
+
172
+ | Category | Helpers |
173
+ | :--- | :--- |
174
+ | **Math** | `add`, `subtract`, `multiply`, `divide`, `mod`, `pow`, `abs`, `round`, `ceil`, `floor`, `sqrt`, `negate`, `toPercent` |
175
+ | **Logic** | `and`, `or`, `not`, `if`, `eq`, `neq`, `gt`, `lt`, `gte`, `lte` |
176
+ | **String** | `join`, `concat`, `upper`, `lower`, `trim`, `len`, `split`, `replace`, `capitalize`, `contains` |
177
+ | **Array** | `map`, `filter`, `reduce`, `push`, `pop`, `sort`, `reverse`, `slice`, `find` |
178
+ | **Stats** | `sum`, `avg`, `min`, `max`, `median`, `stdev`, `variance` |
179
+ | **Data** | `lookup(val, searchArr, resultArr)` (VLOOKUP-style) |
180
+ | **State** | `state(val, opts)`, `set(path, val)`, `bind(path)`, `increment`, `decrement`, `toggle` |
181
+ | **DOM** | `#path` (XPath Navigation), `move(target, loc)` |
182
+ | **Net** | `fetchHelper(url, opts)`, `mount(url, opts)` |
183
+
184
+ ### The "Decentralized Layout" Pattern (AI Strategy)
185
+ 1. **Define**: Create a self-contained component with state.
186
+ 2. **Move**: Use `=move('#target')` in `onmount` to teleport it.
187
+ 3. **Stream**: Determine the update needed, generate the `.cdomc`, and let it patch itself.
188
+
189
+ ```javascript
190
+ /* .cdomc format */
191
+ {
192
+ div: {
193
+ id: "widget-1",
194
+ onmount: ["=state({val:0}, {name:'w1', scope:$this})", "=move('#sidebar')"],
195
+ children: [ { p: "Val: =/w1/val" } ]
196
+ }
197
+ }
198
+ ```
199
+
200
+ ---
201
+
202
+ <a name="component-system"></a>
203
+ ## 5. Component System
204
+
205
+ Built on **DaisyUI** and **Tailwind CSS**.
206
+
207
+ * **Import**: `import { Button } from './components/index.js';`
208
+ * **Init**: `LightviewX.initComponents()` (Shadow DOM).
209
+ * **Theming**: `Lightview.setTheme('dark')` or `localStorage.setItem('lightview-theme', 'dark')`.
210
+
211
+ ---
212
+
213
+ <a name="routing-navigation"></a>
214
+ ## 6. Routing & Navigation
215
+
216
+ The `LightviewRouter` uses a pipeline (chain) architecture.
217
+
218
+ ### Advanced: Middleware Chains
219
+ You can chain multiple handlers for a single route. This is powerful for authentication or data pre-loading.
220
+ ```javascript
221
+ const checkAuth = async (ctx) => {
222
+ const user = await getUser();
223
+ if (!user) {
224
+ LightviewRouter.navigate('/login');
225
+ return null; // Stop chain
226
+ }
227
+ return { ...ctx, user }; // Pass data to next handler
228
+ };
229
+
230
+ router.use(
231
+ '/admin/*',
232
+ checkAuth, // 1. Guard
233
+ '/views/admin.html' // 2. Render
234
+ );
235
+ ```
236
+
237
+ ### Route Patterns
238
+ * **Static**: `router.use('/about', 'about.html')`
239
+ * **Wildcard**: `router.use('/docs/*', handler)` -> matches `/docs/api/v1`
240
+ * **Parameters**: `router.use('/users/:id', handler)` -> `ctx.params.id`
241
+ * **Replacement**: `router.use('/blog/:slug', '/content/posts/:slug.html')` -> Maps URL params to file path automatically.
242
+
243
+ ---
244
+
245
+ <a name="ai-development-strategies"></a>
246
+ ## 7. AI Development Strategies
247
+
248
+ **Scenario A: "I need a full web application."**
249
+ * **Strategy**: Use **Tagged API** + **lightview-router.js**.
250
+ * **Output**: Generate `.js` files.
251
+
252
+ **Scenario B: "I need a dynamic dashboard widget of unknown nature at app development time."**
253
+ * **Strategy**: Use **cDOM/JPRX**.
254
+ * **Output**: Stream `.cdomc` chunks.
255
+
256
+ **Scenario C: "I need a config-driven UI."**
257
+ * **Strategy**: Use **oDOM**.
258
+ * **Output**: Generate `.json` config files.
259
+
260
+ ---
261
+
262
+ <a name="deep-links"></a>
263
+ ## 8. Deep Links & Resources
264
+
265
+ * **Documentation Home**: [docs/index.html](docs/index.html)
266
+ * **Core Logic**: [lightview.js](lightview.js) and [docs/api/index.html](docs/api/index.html)
267
+ * **Extension (Hypermedia)**: [lightview-x.js](lightview-x.js) and [docs/api/hypermedia.html](docs/api/hypermedia.html)
268
+ * **Router**: [lightview-router.js](lightview-router.js) and [docs/router.html](docs/router.html)
269
+ * **CDOM/JPRX Parser**: [lightview-cdom.js](lightview-cdom.js) and [docs/cdom.html](docs/cdom.html)
270
+ * **Component Index**: [components/index.js](components/index.js) and [docs/components/index.html](docs/components/index.html)
271
+ * **JPRX Helpers**: [jprx/helpers/](jprx/helpers/) and [docs/cdom#helpers](docs/cdom.html#helpers)
272
+
273
+ ---
274
+ © 2026 AnyWhichWay LLC.
package/README.md CHANGED
@@ -4,6 +4,8 @@ A lightweight reactive UI library with signal-based reactivity and a clean API.
4
4
 
5
5
  Access the full documentation and interactive examples at [lightview.dev](https://lightview.dev).
6
6
 
7
+ LLMs should read [AI-GUIDANCE.md](AI-GUIDANCE.md) for instructions on how to use Lightview.
8
+
7
9
  ## Modular Architecture
8
10
 
9
11
  **Core Library**: ~7.75KB | **Extended (Hypermedia + Components)**: ~20KB | **Router**: ~3KB
@@ -25,6 +27,39 @@ Lightview supports multiple ways to build UIs, allowing you to pick the style th
25
27
 
26
28
  All syntaxes share the same underlying reactive engine based on **Signals** and **State**.
27
29
 
30
+ ## cDOM & JPRX: AI-Assisted Declarative UIs
31
+
32
+ Lightview includes **cDOM** (Computed DOM) powered by **JPRX** (JSON Pointer Reactive eXpressions)—a fully declarative UI layer that requires **zero custom JavaScript**. Much like **XPath** provides a powerful query language for XML, JPRX provides a reactive, formula-based language for JSON state.
33
+
34
+ ### Why This Matters for AI Collaboration
35
+
36
+ Traditional UI development requires AI agents to generate imperative JavaScript code, which introduces security risks (XSS, code injection) and unpredictable behavior. cDOM flips this model:
37
+
38
+ - **Pure Data, No Code**: UIs are defined as JSON structures with reactive expressions—no `eval()`, no `new Function()`, no executable strings.
39
+ - **Safe by Design**: AI agents can generate, modify, and compose UIs without producing potentially harmful code.
40
+ - **Auditable Output**: Every generated UI is a transparent data structure that can be validated, diffed, and sandboxed.
41
+
42
+ ### Example: A Reactive Counter (No JavaScript)
43
+
44
+ ```json
45
+ {
46
+ "state": { "count": 0 },
47
+ "div": {
48
+ "children": [
49
+ { "p": "{$count}" },
50
+ { "button": { "onclick": "{set('count', add(count, 1))}", "children": ["Increment"] } }
51
+ ]
52
+ }
53
+ }
54
+ ```
55
+
56
+ This JSON is **the entire application**. The `{...}` expressions are JPRX—a sandboxed, spreadsheet-like formula language (inspired by **XPath** and **JSON Pointers**) that resolves paths, calls registered helpers, and triggers reactivity automatically.
57
+
58
+ ### Learn More
59
+
60
+ - [cDOM Documentation](https://lightview.dev/docs/cdom)
61
+ - [JPRX Expression Reference](https://lightview.dev/docs/cdom#jprx)
62
+
28
63
  ## Quick Start
29
64
 
30
65
  ### 1. Tagged API (Concise & Expressive)