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