neobiz 4.7.2 → 5.1.0

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/readme.md CHANGED
@@ -1,735 +1,719 @@
1
- <!-- @format -->
1
+ # Neobiz.js v5.0.x
2
2
 
3
- # Documentation Neobiz.js 4.7.x
3
+ > **A simple view engine that has 100% JS features**
4
4
 
5
- > A simple view engine that has 100% JS features
5
+ ## Changelog
6
6
 
7
- Neobiz.js is pure in JS lang, transform Object into HTML
7
+ ### 5.1.0 – 2026-11-27
8
8
 
9
- fix error `outFIle`
9
+ - Default `nodoctype` is now `true`.
10
+ - XSS‑safe escaping for text and attributes (`escapeHtml`, `escapeAttr`).
11
+ - Support for class list resolution (`class` can be string, array, or object).
12
+ - CSS nesting with `&` and pseudo‑selectors; `compileCss` now handles `@media`.
13
+ - New selector engine for `.query()` supporting descendant, child, attribute, pseudo‑classes, and `:not`.
14
+ - Declarative control flow: `when`, `elseIf`, `else`, and `switch`/`cases`.
15
+ - Subtree caching via `cache` property and `clearCache`.
16
+ - Async error boundaries (`fallback`, `onError`).
17
+ - Streaming SSR (`_renderStream`) with proper fallback handling.
18
+ - DOM mounting API (`mount`) with event binding and scoped styles.
19
+ - Added CommonJS named exports for all public APIs.
10
20
 
11
- ## Updates:
21
+ Neobiz.js allows you to construct, compose, query, style, and render HTML structures using native JavaScript objects. It eliminates template compilers, JSX transpilation, and external runtime dependencies—working identically in **Node.js** and **Browsers** to generate pure HTML strings or manipulate the live DOM.
12
22
 
13
- - fix event bugs
14
- - Boolean attributes / non-value attribute (example: disabled, readonly)
23
+ **now inline style automatically rendered without explicite .cssText **
15
24
 
16
- ## prev update:
25
+ [Express.js Integration with v4 (old) (`neobiz-express`)](https://www.npmjs.com/package/neobiz-express?activeTab=dependencies)
17
26
 
18
- - `render` method change to `**\_render**`to avoid conflict with another library and add safety check
19
- - render option props improve
20
- - fix bug on child order
27
+ `if you still prefer to use v4, it is under the file name browser_v4.js`
21
28
 
22
- features:
29
+ > the directory /example contains example of implementation
23
30
 
24
- - eventHandler
25
- - Reusable & editable style/css
26
- - Altering object
27
- - Registering component
28
- - Explicit tag name supported
29
-
30
- `read /example dir to better understanding`
31
-
32
- for browser usage use `browser.js` file.
31
+ ---
33
32
 
34
- [link to usage in express.js](https://www.npmjs.com/package/neobiz-express?activeTab=dependencies)
33
+ ## Table of Contents
34
+
35
+ 1. [What's Changed from v4.x (Breaking Changes & Upgrades)](#whats-changed-from-v4x-breaking-changes--upgrades)
36
+ 2. [Installation & Setup](#installation--setup)
37
+ 3. [API Reference](#api-reference)
38
+ 4. [Core Syntax & Fundamentals](#core-syntax--fundamentals)
39
+ 5. [Render Options](#render-options)
40
+ 6. [Declarative Control Flow (`when` & `each`)](#declarative-control-flow-when--each)
41
+ 7. [Shorthand Emmet Keys & Fragments (`$`)](#shorthand-emmet-keys--fragments-)
42
+ 8. [Events & Static Closure Injection (`bind`)](#events--static-closure-injection-bind)
43
+ 9. [Async Components & Data Fetching (`_renderAsync`)](#async-components--data-fetching-_renderasync)
44
+ 10. [Styling: Inline, Global & Auto-Scoped CSS (`.regStyle()` & `.scope()`)](#styling-inline-global--auto-scoped-css-regstyle--scope)
45
+ 11. [Asset Hoisting & Deduplication (`$head`)](#asset-hoisting--deduplication-head)
46
+ 12. [HTML Comment Nodes (`$comment`)](#html-comment-nodes-comment)
47
+ 13. [Custom Directives (`addDirective`)](#custom-directives-adddirective)
48
+ 14. [HTML-to-Object Parser (`.repulse`)](#html-to-object-parser-repulse)
49
+ 15. [Isomorphic `.query()` & Live DOM Manipulation](#isomorphic-query--live-dom-manipulation)
50
+ 16. [Component Registry & Inline Mutation](#component-registry--inline-mutation)
51
+ 17. [Full End-to-End Example](#full-end-to-end-example)
35
52
 
36
53
  ---
37
54
 
38
- ## Example with `vue` in browser
55
+ ## What's Changed from v4.x (Breaking Changes & Upgrades)
39
56
 
40
- page.js
57
+ Version `5.0.x` is a complete architectural rewrite focused on **immutability, pure string output, and declarative ergonomics**:
41
58
 
42
- ```js
43
- import "neobiz";
59
+ | Area | v4.x Behavior | v5.0.x Behavior |
60
+ | :-------------------------------- | :------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
61
+ | **Output Philosophy & `outFile`** | Included `node:fs` `outFile()` tied to Node.js file system. | **100% Pure String Output.** `outFile` and `fs` dependencies are removed so the single codebase runs identically in Node.js, Edge runtimes, and Browsers. Use `fs.writeFile` externally if saving to disk. |
62
+ | **Object Immutability** | Rendering mutated source objects (`delete node.tag`), breaking subsequent renders of the same object. | **Non-mutating compiler.** Source objects remain intact and can be rendered repeatedly without side effects. |
63
+ | **`.repulse` HTML Parser** | Regex-based parser that failed on nested duplicate tags (`<div><div>...</div></div>`) and boolean attributes. | **State-machine HTML tokenizer.** Accurately parses deeply nested identical tags, void elements, boolean attributes, and HTML comments. |
64
+ | **Loops & Conditionals** | Required IIFEs (`(() => { ... })()`), ternary operators, or `[].range().map()`. | Native declarative **`when`** (conditional rendering) and **`each`** (array & numeric iteration with `$item`/`$index` tokens or callback functions). |
65
+ | **Event Closures** | Inline functions lost access to outer scope variables when serialized to HTML strings. | Added **`bind`** property to inject outer variables directly into generated static HTML event handlers. |
66
+ | **CSS Scoping** | Manual class assignment and style block management. | Added **`.regStyle(name)`** and **`.scope(name)`** for automatic attribute-based CSS isolation and `<style>` deduplication. |
67
+ | **DOM & Tree Traversal** | Manual property path traversal via `.alter()`. | Added isomorphic **`.query(selector, cb)`** working identically on pre-render Neobiz objects and live Browser DOM elements. |
68
+ | **`load()` Fallback** | Returned `"not registered"` string when component was missing. | Returns **`null`** when a component name is not found. |
44
69
 
45
- ({
46
- div: {
47
- script: [
48
- { src: "https://unpkg.com/vue@3/dist/vue.global.js" },
49
- { src: "https://unpkg.com/neobiz@3.1.0/browser.js" },
50
- { src: "./my-component.js" },
51
- ],
52
- id: "app",
53
- },
54
- script: {
55
- html() {
56
- const { createApp } = Vue;
70
+ ---
57
71
 
58
- createApp(myComponent).mount("#app");
59
- },
60
- },
61
- }.outFile("./welcome.html"));
72
+ ## Installation & Setup
73
+
74
+ ```bash
75
+ npm install neobiz
62
76
  ```
63
77
 
64
- my-component.js
78
+ **Node.js (ES Modules):**
65
79
 
66
80
  ```js
67
- const myComponent = {
68
- data() {
69
- return { msg: "hi, this is example" };
70
- },
71
- template: { h1: { text: "{{msg}}" } }._render,
72
- };
81
+ import "neobiz";
73
82
  ```
74
83
 
75
- <br>
84
+ **Browser (ES Module):**
76
85
 
77
- | properties | caller | return-type | description |
78
- | -------------- | ------------------------------------- | ----------- | --------------------------------------- |
79
- | \_render | Object | string | rendering to HTML |
80
- | outFile | Object @params destination[string] | void | generate static HTML file |
81
- | range | Array @params length[int], start[int] | Array | shortcut for looping in a range |
82
- | repulse | String | Object | generate object from HTML string |
83
- | css | Object | Object | generate css from object |
84
- | cssText | Object | Object | inline css |
85
- | alter [trials] | Object @params cb[function] | Object | altering object before rendering |
86
- | reg | Object | void | registring an object |
87
- | regm | Object | void | updating the existing registered object |
88
- | load | Object | Object | read an existing registered object |
89
- | unred | Object | void | removing an existing registered object |
90
- | renderOption | Object @params option[Object] | void | set the option for rendering |
86
+ ```html
87
+ <script src="https://cdn.jsdelivr.net/npm/neobiz@5.0.1/index.min.js"></script>
88
+ ```
89
+
90
+ ---
91
91
 
92
- #### Why use this?
92
+ ## API Reference
93
+
94
+ | Method / Property | Caller | Return Type | Description |
95
+ | :--------------------------- | :------------------------------ | :----------------- | :------------------------------------------------------------------------ |
96
+ | `_render` | `Object \| Array` | `string` | Synchronously compiles a Neobiz object into an HTML string. |
97
+ | `_renderAsync` | `Object \| Array` | `Promise<string>` | Resolves all nested Promises in parallel and compiles to an HTML string. |
98
+ | `renderOption(opt)` | Global / `Object` | `void` | Configures rendering behavior (`pretty`, `camelCase`, `nodoctype`, etc.). |
99
+ | `repulse` | `string` | `Object` | Parses an HTML string into a modifiable Neobiz object tree. |
100
+ | `query(sel, cb)` | `Object \| Document \| Element` | `this` | Queries nodes by tag, `#id`, or `.class` across Neobiz trees or live DOM. |
101
+ | `alter(cb)` | `Object` | `this` | Mutates an object inline via callback and returns `this` for chaining. |
102
+ | `regStyle(name)` | `Object` | `this` | Registers a named CSS object for scoped styling. |
103
+ | `scope(name)` | `Object` | `this` | Applies a registered scoped style to an element and all its descendants. |
104
+ | `css` | `Object` | `{ text: string }` | Compiles a JS style object into a `<style>`-ready text object. |
105
+ | `cssText` | `Object` | `string` | Compiles a JS style object into an inline `style="..."` string. |
106
+ | `addDirective(name, fn)` | Global / `Object` | `void` | Registers a custom compiler directive hook. |
107
+ | `removeDirective(name)` | Global / `Object` | `void` | Removes a registered custom directive. |
108
+ | `reg(name)` | `Object` | `this` | Registers a reusable component object under `name`. |
109
+ | `regm(name)` | `Object` | `this` | Updates an existing registered component object. |
110
+ | `load(name)` | Global / `Object` | `Object \| null` | Retrieves a registered component by `name` (returns `null` if missing). |
111
+ | `unreg(name)` | Global / `Object` | `void` | Removes a registered component from memory. |
112
+ | `range(len, start)` | `Array` | `number[]` | Generates an array of sequential numbers for iteration. |
113
+ | `htmlObj` _(Browser)_ | `Element` (Setter) | `void` | Renders a Neobiz object directly into `element.innerHTML`. |
114
+ | `appendObj(obj)` _(Browser)_ | `Element` | `this` | Appends a rendered Neobiz object to the end of a live DOM element. |
93
115
 
94
- - Easy maintance innerHTML rather than literal string
95
- - Generate static html file
96
- - Full control of view. Such as filtering, encrypting the data before serve, or just like conditional and loop case
97
- - Almost no need to learn anything. Just need to learn how to render
98
- - Limitless potential, because it's just js. Almost all library should be compatible
116
+ ---
99
117
 
100
- ## Basic syntax
118
+ ## Core Syntax & Fundamentals
101
119
 
102
- How to use? just import this:
120
+ Wrap object literals in parentheses `(...)` when accessing getters directly, or assign them to a variable:
103
121
 
104
122
  ```js
105
123
  import "neobiz";
106
- ```
107
124
 
108
- It's just an Object! `wrap in () to create a statement or just assign to a var`
125
+ renderOption({ nodoctype: true });
109
126
 
110
- ```js
111
- {
112
- // text property is same as innerText
127
+ const html = {
113
128
  h1: {
129
+ class: "heading",
130
+ style: "color: #DC1E1E",
114
131
  text: "Hello World!",
115
132
  },
116
133
  }._render;
117
- // <h1>Hello World!</h1>
134
+ // <h1 class='heading' style='color: #DC1E1E'>Hello World!</h1>
118
135
  ```
119
136
 
120
- or use call method
137
+ ### Text Escaping vs. Raw HTML (`text` vs. `html`)
121
138
 
122
- ```js
123
- _render.call({
124
- // text property is same as innerText
125
- h1: {
126
- text: "Hello World!",
127
- },
128
- });
129
- ```
130
-
131
- Comments:
139
+ - **`text`**: Automatically escapes HTML entities (`&`, `<`, `>`, `'`) to prevent XSS vulnerabilities.
140
+ - **`html`**: Injects raw HTML strings or serializes a function body directly without escaping.
132
141
 
133
142
  ```js
134
143
  {
135
- // this is comment
136
- /*
137
- this is multi line
138
- */
139
- h1: {
140
- text: "This is heading";
141
- }
142
- }
143
- ```
144
-
145
- properties dom
146
-
147
- ```js
148
- {
149
- h1: {
150
- class:"heading",
151
- text: "Hello World!",
152
- style:"color: #DC1E1E",
153
- }
154
- }
155
- // <h1 class="heading" style="color: #DC1E1E">Hello World!</h1>
144
+ h1: { text: "<script>alert('safe')</script>" },
145
+ div: { html: "<strong>Rendered as raw HTML</strong>" },
146
+ script: {
147
+ html() {
148
+ console.log("Serialized function body inside <script>");
149
+ },
150
+ },
151
+ }._render;
156
152
  ```
157
153
 
158
- boolean attributes
154
+ ### Boolean Attributes (`Null` or `true`)
159
155
 
160
- use `Null` to indicate non-value attributes, do not confuse `Null` to `null`
156
+ Use the built-in `Null` symbol or `true` for valueless HTML attributes (`disabled`, `checked`, `readonly`, `defer`). Setting any attribute to `false`, `null`, or `undefined` omits it completely.
161
157
 
162
158
  ```js
163
159
  {
164
- button: { text: "Hello World!", disabled: Null },
165
- }._render
166
- ```
167
-
168
- innerText & innerHTML:
169
-
170
- ```js
171
- {
172
- h1: { text: "<b>this is a text</b>" },
173
- ul: { html: "<li>this will be render as html</li>" },
174
- }
160
+ input: {
161
+ type: "checkbox",
162
+ checked: Null,
163
+ disabled: true,
164
+ readonly: false, // Omitted
165
+ },
166
+ }._render;
167
+ // <input type='checkbox' checked disabled/>
175
168
  ```
176
169
 
177
- nested dom:
178
-
179
- ```js
180
- {
181
- body: {
182
- h1: {
183
- text: "Hello World!",
184
- }
185
- }
186
- }
187
- ```
170
+ ### Sibling Elements & Explicit Tags
188
171
 
189
- expression & operator
172
+ Because JavaScript objects cannot contain duplicate keys, use an **Array**, **trailing spaces** (`"li "`), or the explicit **`tag`** property:
190
173
 
191
174
  ```js
175
+ // 1. Array for identical sibling tags
192
176
  {
193
- span: [
194
- { text: 24 + 12 / 6 },
195
- { text: !false },
196
- ],
177
+ ul: {
178
+ li: [{ text: "Orange" }, { text: "Banana" }],
179
+ },
197
180
  }
198
- ```
199
-
200
- siblings dom:
201
-
202
- There is a case like this:
203
-
204
- ```html
205
- <li>orange</li>
206
- <li>banana</li>
207
- ```
208
-
209
- Object can not use 2 keys with the same name
210
181
 
211
- ```js
212
- // Don't do this
182
+ // 2. Trailing spaces to preserve exact mixed tag order
213
183
  {
214
- li:{text:"orange"},
215
- li:{text:"banana"},
184
+ li: { text: "Orange" },
185
+ p: { span: { text: "In the middle" } },
186
+ "li ": { text: "Banana" },
216
187
  }
217
188
 
218
- // Do this
189
+ // 3. Explicit `tag` property with custom key names
219
190
  {
220
- li:[
221
- {text:"orange"},
222
- {text:"banana"},
223
- ]
191
+ HeaderNav: { tag: "nav", class: "top-nav" },
192
+ MainBody: { tag: "main", id: "content" },
224
193
  }
225
194
  ```
226
195
 
227
- ## Render Option
196
+ ---
197
+
198
+ ## Render Options
199
+
200
+ Configure compiler behavior globally or for a single render execution using `renderOption()`:
228
201
 
229
202
  ```js
230
203
  renderOption({
231
- camelCase: false,
232
- once: false,
233
- nodoctype: false,
234
- ignoreTag: false,
235
- prefixTag: false,
236
- prefixAttr: false,
204
+ camelCase: false, // Converts camelCase tags & attributes to kebab-case (e.g., ionRouter -> ion-router)
205
+ once: false, // Resets options back to defaults immediately after 1 render
206
+ nodoctype: false, // Omits <!DOCTYPE html> when true
207
+ ignoreTag: false, // Ignores explicit `tag` properties when true
208
+ prefixTag: false, // Prepends a string to all tag names (skip per node with `noprefix: true`)
209
+ prefixAttr: false, // Prepends a string to all attribute names (skip per node with `nopAttr: true`)
210
+ pretty: false, // Formats HTML with newlines & indentation when true (minified single-line when false)
211
+ indentSize: 2, // Spaces per indentation level when `pretty: true`
237
212
  });
238
213
  ```
239
214
 
240
- set once to `true` to use option only for once,
241
- <br>
242
- <br>
243
-
244
- set nodoctype to `true` to remove `<!doctype html>` in the beninging,
245
- <br>
246
- <br>
247
-
248
- set ignoreTag to `true` to unused `tag` properties,
249
- <br>
250
- <br>
251
-
252
- set prefixTag to `something` to add text before `tag`,
253
- <br>
254
- use `noprefix:true` to skip on specific object
255
- <br>
215
+ ---
256
216
 
257
- set prefixAttr to `something` to add text before `attribute`,
258
- <br>
259
- use `nopAttr:true` to skip in specific object
260
- <br>
217
+ ## Declarative Control Flow (`when` & `each`)
261
218
 
262
- set `camelCase` `true` to convert **camelCase** properties to **kebab-case**
219
+ ### Conditional Rendering (`when`)
263
220
 
264
- make sure to set the option before rendering
221
+ Attach `when` to any element or fragment (`$`). If `when` evaluates to falsy (`false`, `null`, `undefined`, `0`, `""`), the element and its entire subtree are skipped cleanly—eliminating ternary operators or IIFEs.
265
222
 
266
223
  ```js
267
- renderOption({
268
- camelCase: true,
269
- });
224
+ const user = { isLoggedIn: true, role: "member" };
270
225
 
271
- render.call({
272
- ionRouter: {},
273
- });
226
+ {
227
+ nav: {
228
+ "a.home": { href: "/", text: "Home" },
229
+ "a.admin": {
230
+ when: user.role === "admin", // Omitted from output
231
+ href: "/admin",
232
+ text: "Admin Panel",
233
+ },
234
+ "button.logout": {
235
+ when: user.isLoggedIn, // Rendered
236
+ text: "Logout",
237
+ },
238
+ },
239
+ }._render;
274
240
  ```
275
241
 
276
- result
277
-
278
- ```html
279
- <ion-router></ion-router>
280
- ```
242
+ ### Declarative Loops (`each`)
281
243
 
282
- ## Explicit tag name
244
+ Replace `.map()` wrappers and `for`/`while` IIFEs with the `each` property. `each` accepts either an **Array** or a **positive integer** (for numeric range loops) and supports two interpolation styles:
283
245
 
284
- What if there is somethings in the middle of list?
246
+ 1. **Function Properties `(item, index) => value`**: Ideal for computed logic, nested objects, `when` filtering, and `bind`.
247
+ 2. **String Placeholder Tokens (`$item`, `$item.prop`, `$index`)**: Zero-function shorthand for simple strings and attributes.
285
248
 
286
- ```html
287
- <li>orange</li>
288
- <p>
289
- <span>This is in the middle</span>
290
- </p>
291
- <li>banana</li>
292
- ```
249
+ ```js
250
+ const products = [
251
+ { id: 101, name: "Mechanical Keyboard", inStock: true },
252
+ { id: 102, name: "4K Monitor", inStock: false },
253
+ { id: 103, name: "Wireless Mouse", inStock: true },
254
+ ];
293
255
 
294
- if we use an array there will share the tag name right? just use this:
256
+ {
257
+ div: {
258
+ // 1. Array iteration + `when` filtering + function properties
259
+ "ul.product-list": {
260
+ "li.product-item": {
261
+ each: products,
262
+ when: (item) => item.inStock, // Skips out-of-stock items automatically
263
+ id: (item) => `prod-${item.id}`,
264
+ text: (item, idx) => `${idx + 1}. ${item.name}`,
265
+ },
266
+ },
295
267
 
296
- > use string as key could distinc an element with just a space
297
- > no need to worry, it will render without space
268
+ // 2. Numeric range iteration (replaces [].range(3)) + string tokens
269
+ "div.pagination": {
270
+ "button.page-btn": {
271
+ each: 3, // Loops 3 times (index 0, 1, 2)
272
+ "data-index": "$index",
273
+ text: (_, i) => `Page ${i + 1}`,
274
+ },
275
+ },
298
276
 
299
- ```js
300
- {
301
- li:{text:"orange"},
302
- p:{span:{text:"This is in the middle"}},
303
- "li ":{text:"banana"},
304
- }
277
+ // 3. String token path interpolation (`$item.prop`)
278
+ "ul.simple": {
279
+ li: {
280
+ each: [{ title: "Docs" }, { title: "API" }],
281
+ text: "$index: $item.title",
282
+ },
283
+ },
284
+ },
285
+ }._render;
305
286
  ```
306
287
 
307
- or write the tag name:
288
+ ---
308
289
 
309
- ```js
310
- {
311
- li: [
312
- { text: "orange" },
313
- { tag: "p", span: { text: "This is in the middle" } },
314
- { text: "banana" },
315
- ],
316
- }
317
- ```
290
+ ## Shorthand Emmet Keys & Fragments (`$`)
318
291
 
319
- also with specifying tag name, we can name it differently:
292
+ ### Shorthand Emmet Keys (`tag#id.class`)
293
+
294
+ Define `id` and `class` names directly inside object keys. Omitting the tag name defaults to `<div>`. Any explicit `class` property inside the object is automatically merged with the key classes.
320
295
 
321
296
  ```js
322
- {
323
- PersonList: ["Arthur", "Zoro"].map((person) => ({
324
- tag: "li",
325
- text: person,
326
- })),
327
- }
297
+ {
298
+ "section#hero.bg-dark.py-12": {
299
+ ".container.mx-auto": {
300
+ "h1.title": { class: "text-3xl", text: "Neobiz.js" },
301
+ },
302
+ },
303
+ }._render;
304
+ // <section id='hero' class='bg-dark py-12'><div class='container mx-auto'><h1 class='title text-3xl'>Neobiz.js</h1></div></section>
328
305
  ```
329
306
 
330
- ### Modify an Object
307
+ ### Fragments (`$`)
331
308
 
332
- use `alter` properties, with function as params. no need to return a value
309
+ Render multiple sibling nodes without introducing an unnecessary wrapper tag. Fragments also support `when` and `each` directly:
333
310
 
334
311
  ```js
335
- const y = {
336
- h1: { text: "Hello World!" },
337
- p: { text: "this is a p" }.alter((e) => (e.class = "lorem")),
338
- }.alter((e) => {
339
- e.h1.text = "thi is altered text";
340
- e.h1.style = { color: "red", fontSize: "150%" }.cssText;
341
- });
312
+ const faqItems = [
313
+ { q: "Is there a build step?", a: "No, it runs natively in JS." },
314
+ { q: "Does it support SSR?", a: "Yes, it outputs pure HTML strings." },
315
+ ];
342
316
 
343
- console.log(y.render);
317
+ {
318
+ dl: {
319
+ $: {
320
+ each: faqItems,
321
+ dt: { text: "$item.q" },
322
+ dd: { text: "$item.a" },
323
+ },
324
+ },
325
+ }._render;
326
+ // <dl><dt>Is there a build step?</dt><dd>No, it runs natively in JS.</dd><dt>Does it support SSR?</dt><dd>Yes, it outputs pure HTML strings.</dd></dl>
344
327
  ```
345
328
 
346
- ### Components / Partials
329
+ ---
330
+
331
+ ## Events & Static Closure Injection (`bind`)
332
+
333
+ In inline event handlers (`onclick`, `oninput`, `onchange`), `this` refers to the target DOM node. Because static HTML outputs cannot retain runtime JavaScript closures from your build environment, use **`bind`** to serialize outer variables directly into the generated event handler:
347
334
 
348
335
  ```js
349
- import header from "./header.v.js"; //function type
350
- import footer from "./footer.v.js"; //object type
336
+ const taxRate = 0.11;
337
+ const items = [
338
+ { name: "Laptop", price: 1000 },
339
+ { name: "Headset", price: 150 },
340
+ ];
351
341
 
352
342
  {
353
- div: header({ user: "dim24" }),
354
- p: { text: "this is text" },
355
- div: footer,
356
- }.render;
343
+ ul: {
344
+ li: {
345
+ each: items,
346
+ button: {
347
+ text: (item) => `Buy ${item.name}`,
348
+ // Pass variables (or a function returning variables inside `each`)
349
+ bind: (item) => ({ item, taxRate }),
350
+ onclick() {
351
+ const total = (item.price * (1 + taxRate)).toFixed(2);
352
+ alert(`${item.name} total with tax: $${total}`);
353
+ },
354
+ },
355
+ },
356
+ },
357
+ }._render;
357
358
  ```
358
359
 
359
- header.v.js
360
+ ---
360
361
 
361
- ```js
362
- export default ({ user }) => ({ h1: { text: `Hi, ${user}` } });
363
- ```
362
+ ## Async Components & Data Fetching (`_renderAsync`)
364
363
 
365
- footer.v.js
364
+ Place `Promise`s or `async` component functions anywhere inside your object tree. Calling `._renderAsync` resolves all nested Promises concurrently via `Promise.all` before compiling the HTML string:
366
365
 
367
366
  ```js
368
- export default {
369
- script: { src: "/assets/js/main.js" },
370
- span: { text: "this is footer" },
367
+ const fetchProfile = async () => ({ username: "dim24", verified: true });
368
+ const fetchNotifications = async () => ["Welcome!", "Profile updated"];
369
+
370
+ const Dashboard = async () => {
371
+ const user = await fetchProfile();
372
+ return {
373
+ "section#dashboard": {
374
+ h1: { text: `Hello, ${user.username}` },
375
+ "span.badge": { when: user.verified, text: "Verified" },
376
+ ul: {
377
+ // Direct Promise inside property
378
+ li: fetchNotifications().then((list) =>
379
+ list.map((msg) => ({ text: msg })),
380
+ ),
381
+ },
382
+ },
383
+ };
371
384
  };
372
- ```
373
385
 
374
- ### reg, regm, load & unreg Components
386
+ const html = await Dashboard()._renderAsync;
387
+ ```
375
388
 
376
- The idea is to make object has resuability
389
+ ---
377
390
 
378
- #### reg & load
391
+ ## Styling: Inline, Global & Auto-Scoped CSS (`.regStyle()` & `.scope()`)
379
392
 
380
- > this function need a single argument to set a name of registering object,
393
+ ### 1. Auto-Scoped CSS (`.regStyle()` & `.scope()`)
381
394
 
382
- there is 2 ways to registering an component:
395
+ Register a named style object once with `.regStyle(name)` and apply it to any component tree with `.scope(name)`. Neobiz automatically:
383
396
 
384
- - through properties method:
397
+ - Injects `data-nb-s="name"` onto the root wrapper and all child elements (respecting nested child scopes).
398
+ - Scopes every CSS selector automatically (use `self` or `:host` to target the root element itself).
399
+ - Deduplicates the generated `<style>` block so it is emitted only **once** per document, even if the component is rendered 100 times inside an `each` loop.
385
400
 
386
401
  ```js
387
- { name:"viewport"}.reg("viewport")
388
- ```
402
+ ({
403
+ self: {
404
+ border: "1px solid #cbd5e1",
405
+ borderRadius: "8px",
406
+ padding: "16px",
407
+ },
408
+ h3: { color: "#0f172a", marginBottom: "8px" },
409
+ "button:hover": { backgroundColor: "#2563eb", color: "#ffffff" },
410
+ "@media (max-width: 600px)": {
411
+ self: { padding: "12px" },
412
+ },
413
+ }).regStyle("card-scope");
389
414
 
390
- - via call method:
415
+ const Card = (title) => ({
416
+ div: {
417
+ h3: { text: title },
418
+ button: { text: "Action" },
419
+ },
420
+ }).scope("card-scope");
391
421
 
392
- ```js
393
- reg.call({ name: "viewport" }, "viewport");
422
+ {
423
+ main: {
424
+ h3: { text: "Unstyled Outside Heading" }, // Not affected by card-scope
425
+ $: [Card("Card 1"), Card("Card 2")],
426
+ },
427
+ }._render;
394
428
  ```
395
429
 
396
- now we can load it's value whenever we want
430
+ ### 2. Inline & Global Style Objects (`cssText` & `css`)
397
431
 
398
432
  ```js
433
+ // Inline style string via `.cssText`
399
434
  {
400
- meta:load("viewport"),
401
- body: {
402
- }
435
+ h1: {
436
+ text: "Inline Styled",
437
+ style: { color: "#1B73F8", fontSize: "24px" }.cssText,
438
+ },
403
439
  }
404
- ```
405
-
406
- #### regm
407
440
 
408
- this function will replace an existing registered object with a new value:
409
-
410
- ```js
411
- const newValue = load("viewport");
412
- newValue.content = "width=device-width, initial-scale=1.0";
441
+ // Standard `<style>` tag via `.css`
442
+ const globalStyles = {
443
+ body: { margin: "0", fontFamily: "sans-serif" },
444
+ ".btn": { padding: "8px 14px", cursor: "pointer" },
445
+ };
413
446
 
414
- newValue.regm("viewport");
447
+ {
448
+ style: globalStyles.css,
449
+ button: { class: "btn", text: "Click Me" },
450
+ }
415
451
  ```
416
452
 
417
- #### unreg
418
-
419
- when we the object doesn't needed anymore, just unreg it:
420
-
421
- ```js
422
- unreg("viewport");
423
- ```
453
+ ---
424
454
 
425
- ### Style
455
+ ## Asset Hoisting & Deduplication (`$head`)
426
456
 
427
- use camel case to css properties
457
+ Modular components often require external stylesheets or scripts. Declare them inside any nested component using **`$head`**. Neobiz hoists all `$head` entries into the document's `<head>`, removes duplicate `src`/`href`/`name` entries while preserving first-seen dependency order, and sorts assets by standard HTML loading priority:
428
458
 
429
- #### inline CSS:
459
+ 1. `<meta>` & `<link rel="preconnect" / "preload">`
460
+ 2. `<link rel="stylesheet">` & `<style>`
461
+ 3. Synchronous `<script>` tags (in component tree order)
462
+ 4. Deferred / async / module `<script defer>` tags
430
463
 
431
464
  ```js
432
- {
433
- h1:{
434
- text:"Hello World",
435
- style:{
436
- color:"#1B73F8",
437
- fontSize:"150%"
438
- }.cssText
439
- }
440
- }
441
- ```
442
-
443
- use style :
465
+ const ChartComponent = () => ({
466
+ $head: [
467
+ { script: { src: "/js/chart.min.js" } },
468
+ { link: { rel: "stylesheet", href: "/css/chart.css" } },
469
+ ],
470
+ "canvas#sales-chart": {},
471
+ });
444
472
 
445
- `global-style.js`:
473
+ const PluginChartComponent = () => ({
474
+ $head: [
475
+ { script: { src: "/js/chart.min.js" } }, // Deduplicated automatically
476
+ { script: { src: "/js/chart-plugin.min.js" } }, // Guaranteed to load AFTER chart.min.js
477
+ { script: { src: "/js/analytics.js", defer: Null } }, // Placed after sync scripts
478
+ ],
479
+ "canvas#plugin-chart": {},
480
+ });
446
481
 
447
- ```js
448
- export default {
449
- h1: {
450
- color: "red",
451
- },
452
- body: {
453
- margin: "0px",
454
- textAlign: "center",
482
+ const page = {
483
+ html: {
484
+ head: { title: { text: "Analytics" } },
485
+ body: {
486
+ $: [ChartComponent(), PluginChartComponent()],
487
+ },
455
488
  },
456
489
  };
457
490
  ```
458
491
 
459
- why should use object css rather than direct css?
492
+ ---
460
493
 
461
- we can easily modify the style
494
+ ## HTML Comment Nodes (`$comment`)
462
495
 
463
- `main-page.js`:
496
+ Emit standard HTML comments anywhere in your tree. Regular comments are automatically stripped when `pretty: false` (minified mode), whereas comments prefixed with `!` are preserved even in minified builds:
464
497
 
465
498
  ```js
466
- import style from "./global-style.js";
467
-
468
- style.body.margin = "12px";
469
-
470
499
  {
471
- style:style.css,
472
- div:{
473
- h1:{text:"Hello World!"}
474
- }
475
- }.render
476
- ```
477
-
478
- reusable style / mixin
479
-
480
- ```js
481
- const flex = (justify, align, direction = "row") => ({
482
- display: "flex",
483
- justifyContent: justify,
484
- alignItems: align,
485
- flexDirection: direction,
486
- });
487
-
488
- const space = {
489
- padding: "6px 8px",
490
- margin: "6px 10px",
491
- };
492
-
493
- console.log({
494
- style: { div: flex("center", "center"), button: { border: "none", ...space } }
495
- .css,
496
- });
500
+ $comment: "! Copyright 2026 Neobiz.js",
501
+ header: {
502
+ $comment: "Primary site navigation",
503
+ nav: { a: { href: "/", text: "Home" } },
504
+ },
505
+ }._render;
497
506
  ```
498
507
 
499
- ### Interacting with DOM
508
+ ---
500
509
 
501
- use `script` to interact with browser with **html** property
510
+ ## Custom Directives (`addDirective`)
502
511
 
503
- wrap the script with a function, or use string
512
+ Register custom compiler property hooks via `addDirective(name, handler)` to transform attributes (`attrs`) or element content (`children`) during compilation:
504
513
 
505
514
  ```js
506
- {
507
- button:{onclick:"sayHi(this)",id:"hi-button"},
508
- script:{
509
- html(){
510
- document.getElementById("hi-button").innerText="Click me!";
511
-
512
- function sayHi(el){
513
- el.innerText="Hi!";
514
- }
515
- }
516
- }
517
- }
518
-
519
- ```
520
-
521
- ### Event
515
+ addDirective("currency", (value, { children }) => {
516
+ children.push(`$${Number(value).toLocaleString("en-US", { minimumFractionDigits: 2 })}`);
517
+ });
522
518
 
523
- you can add an event `this` keyword always refered to the node itseft
519
+ addDirective("lazyImg", (src, { attrs }) => {
520
+ attrs.push(` src='${src}' loading='lazy' decoding='async'`);
521
+ });
524
522
 
525
- ```js
526
523
  {
527
- input:{type:"password",onkeypress(){
528
- if(event.keyCode==13)
529
- alert(this.value)
530
- }},
531
- button:{text:"Click me!",onclick(){
532
- this.innerText = this.innerText=="clicked"?"Click me!":"clicked";
533
- }}
534
- }
524
+ "div.product": {
525
+ img: { lazyImg: "/images/keyboard.webp", alt: "Keyboard" },
526
+ "span.price": { currency: 129.5 },
527
+ },
528
+ }._render;
535
529
  ```
536
530
 
537
- ## Repulse
538
-
539
- If you already have an html file and want to modify it, or make it as a template, just use this
540
-
541
- > this function is still has a lot issues, use only in a simple case
531
+ ---
542
532
 
543
- - need to wrap all tag into a single parent
544
- - recommended to use external script and css
545
- - repetitive / nested could caused weird behavior (help me, please!)
533
+ ## HTML-to-Object Parser (`.repulse`)
546
534
 
547
- I still try to improve this feature. **if you can provide some help** just tell me please... :)
535
+ Convert existing HTML strings into mutable Neobiz objects using the state-machine tokenizer. Supports nested duplicate tags, void elements, boolean attributes, and comments:
548
536
 
549
537
  ```js
550
- const { div } = `
551
- <div>
552
- <h1>Hello dims!</h1>
538
+ const parsed = `
539
+ <div class="wrapper">
540
+ <h1>Welcome</h1>
541
+ <p>First paragraph</p>
542
+ <p>Second paragraph</p>
543
+ <input type="checkbox" checked disabled />
553
544
  </div>
554
545
  `.repulse;
555
546
 
556
- div.id = "main";
557
- div.h1.class = "heading";
558
- div.p = { text: "this is a whole text" };
547
+ parsed.div.id = "main";
548
+ parsed.div["p "].style = { color: "blue" }.cssText;
559
549
 
560
- console.log({ div }.render);
550
+ console.log(parsed._render);
561
551
  ```
562
552
 
563
- result
553
+ ---
564
554
 
565
- ```html
566
- <div id="main">
567
- <h1 class="heading">Hello dims!</h1>
568
- <p>this is a whole text</p>
569
- </div>
570
- ```
555
+ ## Isomorphic `.query()` & Live DOM Manipulation
571
556
 
572
- ## Pass Value
557
+ `.query(selector, callback)` works identically across **pre-render Neobiz objects** and **live Browser DOM elements** (`document` and `Element`). Supports tag selectors (`"img"`), IDs (`"#hero"`), classes (`".card"`), and compound selectors (`"input.required"`):
573
558
 
574
- use shorthand anonym function
559
+ ### 1. Pre-Render Neobiz Object Tree
575
560
 
576
- ```js
577
- console.log(((user) => ({ h1: { text: `Hello, ${user}` } }))("Vins").render);
578
- ```
579
-
580
- or
561
+ Combine `.repulse` with `.query()` to batch-transform converted HTML structures before rendering:
581
562
 
582
563
  ```js
583
- const greeting = (user) => ({ h1: `Hello, ${user}` });
584
-
585
- console.log(greeting("Vins").render);
564
+ const optimizedHtml = rawCmsHtml.repulse
565
+ .query("img", (img) => {
566
+ img.loading = "lazy";
567
+ })
568
+ .query("img.hero", (hero) => {
569
+ hero.loading = "eager";
570
+ hero.fetchpriority = "high";
571
+ })
572
+ .query(".draft-only", (node) => {
573
+ node.when = false; // Remove matching nodes from render output
574
+ })._render;
586
575
  ```
587
576
 
588
- ## Control Flow
577
+ ### 2. Live Browser DOM Runtime
589
578
 
590
- ternary:
579
+ In browsers, `document.query()` and `element.query()` wrap `querySelectorAll` with chainable callbacks, paired with `.htmlObj` and `.appendObj()` to inject Neobiz objects directly into live DOM nodes:
591
580
 
592
581
  ```js
593
- {
594
- h1: status
595
- ? { text: "Hello World!" }
596
- : {
597
- a: { href: "#", text: "You are offline!" },
582
+ // Query and update live DOM elements
583
+ document
584
+ .query("img.lazy", (img) => {
585
+ img.src = img.dataset.src;
586
+ img.classList.remove("lazy");
587
+ })
588
+ .query("#todo-list", (ul) => {
589
+ // Append a Neobiz object directly into the live <ul> element
590
+ ul.appendObj({
591
+ "li.todo-item": {
592
+ text: "New dynamic item",
593
+ button: {
594
+ text: "Remove",
595
+ onclick() {
596
+ this.parentElement.remove();
597
+ },
598
598
  },
599
- }
599
+ },
600
+ });
601
+ });
600
602
  ```
601
603
 
602
- IIFE if-else
603
-
604
- ```js
605
- {
606
- h1: (() => {
607
- let result;
608
- if (status) result = { text: "Hello World!" };
609
- else
610
- result = {
611
- a: { href: "#", text: "You are offline!" },
612
- };
613
- return result;
614
- })(),
615
- }
616
- ```
617
-
618
- normal if else
619
-
620
- ```js
621
- let result;
622
- if (status) result = { text: "Hello World!" };
623
- else
624
- result = {
625
- a: { href: "#", text: "You are offline!" },
626
- };
604
+ ---
627
605
 
628
- //use
629
- {
630
- h1: result,
631
- }
632
- ```
606
+ ## Component Registry & Inline Mutation
633
607
 
634
- IIFE switch-case
608
+ Store, update, retrieve, or delete reusable object templates in memory, or mutate objects inline via `.alter()`:
635
609
 
636
610
  ```js
637
- {
638
- h1: (() => {
639
- let result;
640
- switch (status) {
641
- case true:
642
- result = { text: "Hello World!" };
643
- break;
644
- case false:
645
- result = {
646
- a: { href: "#", text: "You are offline!" },
647
- };
648
- }
649
- return result;
650
- })(),
651
- }
652
- ```
653
-
654
- ## Loop & array manipulation
611
+ // Register a reusable object (returns `this` for chaining)
612
+ { name: "viewport", content: "width=device-width, initial-scale=1.0" }.reg("viewport");
655
613
 
656
- range & map:
614
+ // Load and mutate inline with `.alter()`
615
+ const page = {
616
+ meta: load("viewport"),
617
+ h1: { text: "Draft Title" },
618
+ }.alter((obj) => {
619
+ obj.h1.text = "Published Title";
620
+ });
657
621
 
658
- ```js
622
+ // Update an existing registered object
623
+ { name: "viewport", content: "width=1024" }.regm("viewport");
659
624
 
660
- {
661
- ul: {
662
- li: [].range(8, 1).map((item) => ({ text: "data-" + item })),
663
- },
664
- }
625
+ // Unregister when no longer needed
626
+ unreg("viewport");
665
627
  ```
666
628
 
667
- map
629
+ ---
668
630
 
669
- ```js
670
- {
671
- ul: {
672
- li: ["grape", "banana", "apple"].map((text) => ({ text })),
673
- },
674
- }
675
- ```
631
+ ## Full End-to-End Example
676
632
 
677
- filter
633
+ Combining `$head` hoisting, `.regStyle()` / `.scope()`, `each`, `when`, `bind`, `addDirective`, `.repulse`, `.query()`, and `_renderAsync`:
678
634
 
679
635
  ```js
680
- {
681
- ul: {
682
- li: [].range(8, 1).filter( num => num % 2 == 0 ).map((item) => ({ text: "data-" + item })),
683
- },
684
- }
685
- ```
636
+ import "neobiz";
686
637
 
687
- for
638
+ // 1. Custom directive & scoped style
639
+ addDirective("usd", (val, { children }) =>
640
+ children.push(`$${Number(val).toFixed(2)}`),
641
+ );
688
642
 
689
- ```js
690
- {
691
- ul: {
692
- li: (() => {
693
- const result = [];
694
- for (let i = 1; i < 9; i++) result.push({ text: "data-" + i });
695
- return result;
696
- })(),
643
+ ({
644
+ self: { border: "1px solid #e2e8f0", borderRadius: "8px", padding: "16px" },
645
+ h3: { margin: "0 0 8px 0" },
646
+ ".out-of-stock": { color: "#dc2626", fontWeight: "bold" },
647
+ }).regStyle("item-card");
648
+
649
+ // 2. Reusable component with $head hoisting, bind, when, and scope
650
+ const ItemCard = (item, discount) =>
651
+ ({
652
+ $head: { script: { src: "/assets/cart.js", defer: Null } },
653
+ "article.card": {
654
+ h3: { text: item.name },
655
+ "p.out-of-stock": { when: item.stock === 0, text: "Sold Out" },
656
+ "span.price": { when: item.stock > 0, usd: item.price },
657
+ button: {
658
+ disabled: item.stock === 0,
659
+ text: "Add to Cart",
660
+ bind: { item, discount },
661
+ onclick() {
662
+ const final = (item.price * (1 - discount)).toFixed(2);
663
+ alert(`Added ${item.name} ($${final})`);
664
+ },
665
+ },
697
666
  },
698
- }
699
- ```
700
-
701
- while
702
-
703
- ```js
704
- {
705
- ul: {
706
- li: (() => {
707
- const result = [];
708
- let i = 0;
709
- while (++i < 9) result.push({ text: "data-" + i });
710
- return result;
711
- })(),
667
+ }).scope("item-card");
668
+
669
+ // 3. Async data + repulse + query
670
+ const fetchItems = async () => [
671
+ { name: "Laptop Stand", price: 45, stock: 8 },
672
+ { name: "USB-C Hub", price: 30, stock: 0 },
673
+ ];
674
+
675
+ const PromoBanner =
676
+ `<div class="banner"><img src="/promo.png" alt="Sale"/></div>`.repulse.query(
677
+ "img",
678
+ (img) => {
679
+ img.loading = "lazy";
712
680
  },
713
- }
714
- ```
715
-
716
- ## templating
717
-
718
- this example use single file usage. for modular usage leave to you, or just read the example dir
681
+ );
682
+
683
+ // 4. Assemble and render asynchronously
684
+ const buildPage = async () => {
685
+ const items = await fetchItems();
686
+
687
+ const documentTree = {
688
+ $comment: "! Built with Neobiz.js v5.0",
689
+ html: {
690
+ lang: "en",
691
+ head: {
692
+ meta: { charset: "UTF-8" },
693
+ title: { text: "Hardware Store" },
694
+ },
695
+ body: {
696
+ "main.container": {
697
+ $: [
698
+ PromoBanner,
699
+ {
700
+ "section#catalog": {
701
+ $: {
702
+ each: items,
703
+ // Render ItemCard for each item
704
+ div: (item) => ItemCard(item, 0.1),
705
+ },
706
+ },
707
+ },
708
+ ],
709
+ },
710
+ },
711
+ },
712
+ };
719
713
 
720
- ```js
721
- //template file
722
- const template = (content) => ({
723
- div: {
724
- class: "main wrapper",
725
- div: content,
726
- },
727
- });
714
+ renderOption({ pretty: true, indentSize: 2 });
715
+ return await documentTree._renderAsync;
716
+ };
728
717
 
729
- //content file
730
- template({
731
- h1: { text: "Hello World!" },
732
- });
718
+ console.log(await buildPage());
733
719
  ```
734
-
735
- ### Thank you for read until here.