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.
@@ -1,28 +1,122 @@
1
- /** @format */
2
-
3
1
  import "../index.js";
4
2
 
5
- // inline
6
- console.log(
7
- {
8
- h1: {
9
- text: "this is text",
10
- style: { color: "blue", fontSize: "140%" }.cssText,
11
- },
12
- }.render
13
- );
3
+ // Configure output for clean snippet inspection
4
+ renderOption({
5
+ nodoctype: true,
6
+ pretty: true,
7
+ indentSize: 2,
8
+ });
14
9
 
15
- // tag style
16
- console.log(
17
- {
10
+ // ============================================================================
11
+ // 1. INLINE CSS (`.cssText`)
12
+ // ============================================================================
13
+ // Converts a camelCase JS object into an inline `style="..."` attribute string
14
+ const inlineStyleExample = {
15
+ h1: {
16
+ text: "Inline Styled Heading",
18
17
  style: {
19
- h1: {
20
- // something
21
- },
22
- body: {
23
- margin: "0px",
24
- padding: "0px",
25
- },
26
- }.css,
27
- }.render
28
- );
18
+ color: "#1B73F8",
19
+ fontSize: "24px",
20
+ borderBottom: "2px solid #e2e8f0",
21
+ paddingBottom: "8px",
22
+ }.cssText,
23
+ },
24
+ };
25
+
26
+ console.log("--- 1. Inline CSS (`.cssText`) ---");
27
+ console.log(inlineStyleExample._render);
28
+
29
+ // ============================================================================
30
+ // 2. GLOBAL `<style>` BLOCKS & REUSABLE MIXINS (`.css`)
31
+ // ============================================================================
32
+ // Supports nested selectors, pseudo-classes, and `@media` queries
33
+ const flexCenter = (direction = "row") => ({
34
+ display: "flex",
35
+ justifyContent: "center",
36
+ alignItems: "center",
37
+ flexDirection: direction,
38
+ });
39
+
40
+ const globalStyles = {
41
+ body: {
42
+ margin: "0",
43
+ fontFamily: "system-ui, sans-serif",
44
+ },
45
+ ".container": {
46
+ ...flexCenter("column"),
47
+ minHeight: "100vh",
48
+ padding: "16px",
49
+ },
50
+ ".btn": {
51
+ padding: "10px 20px",
52
+ backgroundColor: "#0f172a",
53
+ color: "#ffffff",
54
+ border: "none",
55
+ borderRadius: "6px",
56
+ },
57
+ "@media (max-width: 600px)": {
58
+ ".btn": {
59
+ width: "100%",
60
+ },
61
+ },
62
+ };
63
+
64
+ // Mutate style rules dynamically before rendering
65
+ globalStyles.body.backgroundColor = "#f8fafc";
66
+
67
+ const globalStyleExample = {
68
+ style: globalStyles.css,
69
+ "div.container": {
70
+ "button.btn": { text: "Global Styled Button" },
71
+ },
72
+ };
73
+
74
+ console.log("\n--- 2. Global `<style>` Block (`.css`) ---");
75
+ console.log(globalStyleExample._render);
76
+
77
+ // ============================================================================
78
+ // 3. AUTO-SCOPED COMPONENT CSS (`.regStyle()` & `.scope()`)
79
+ // ============================================================================
80
+ // Isolates styles to the target component and its descendants using `[data-nb-s]`.
81
+ // Use `self` or `:host` to style the root element itself.
82
+
83
+ ({
84
+ self: {
85
+ border: "1px solid #cbd5e1",
86
+ borderRadius: "10px",
87
+ padding: "16px",
88
+ backgroundColor: "#ffffff",
89
+ },
90
+ h2: {
91
+ margin: "0 0 8px 0",
92
+ color: "#0f172a",
93
+ },
94
+ p: {
95
+ color: "#475569",
96
+ },
97
+ "button:hover": {
98
+ backgroundColor: "#2563eb",
99
+ color: "#ffffff",
100
+ },
101
+ }).regStyle("card-widget");
102
+
103
+ const CardWidget = (title, description) => ({
104
+ div: {
105
+ h2: { text: title },
106
+ p: { text: description },
107
+ button: { text: "Read More" },
108
+ },
109
+ }).scope("card-widget");
110
+
111
+ // Even when rendered multiple times, the scoped `<style>` tag is emitted only once
112
+ const scopedStyleExample = {
113
+ section: {
114
+ $: [
115
+ CardWidget("Card One", "Scoped styles do not leak outside this component."),
116
+ CardWidget("Card Two", "Shares the exact same deduplicated <style> block."),
117
+ ],
118
+ },
119
+ };
120
+
121
+ console.log("\n--- 3. Auto-Scoped CSS (`.regStyle()` & `.scope()`) ---");
122
+ console.log(scopedStyleExample._render);
package/index.js CHANGED
@@ -1,20 +1 @@
1
- /** @format */
2
- require("./browser");
3
- const path = require("path");
4
-
5
- function outFile(source, data) {
6
- const fs = require("fs");
7
- (function () {
8
- const dir = path.dirname(path.resolve(source));
9
- if (!fs.existsSync(dir)) fs.mkdirSync(dir);
10
- fs.writeFileSync(source, data._render);
11
- console.log(`Output file: ${source}`);
12
- })();
13
- return data.render;
14
- }
15
-
16
- Object.defineProperty({}.__proto__, "outFile", {
17
- value: function (goes) {
18
- return outFile(goes, this);
19
- },
20
- });
1
+ const componentRegistry = new Map, styleRegistry = new Map, directiveRegistry = new Map, Null = Symbol("@null"), SCOPE_KEY = Symbol("@scope"), VOID_ELEMENTS = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]), RESERVED_KEYS = new Set(["text", "html", "noprefix", "nopAttr", "tag", "bind", "when", "$head", "each"]), defaultOptions = { camelCase: !1, once: !1, nodoctype: !1, ignoreTag: !1, prefixTag: !1, prefixAttr: !1, pretty: !1, indentSize: 2 }; let currentOption = { ...defaultOptions }; const toKebabCase = e => e.replace(/[A-Z]/g, e => `-${e.toLowerCase()}`), escapeHtml = e => String(e).replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("'", "'"), serializeFunctionBody = e => { const t = e.toString().trim(), n = t.match(/^[^{]*\{([\s\S]*)\}$/); if (n) return n[1].trim(); const r = t.match(/^[^=]*=>\s*([\s\S]*)$/); return r ? r[1].trim() : t }; function parseEmmetKey(e) { const t = e.trim(); if (!t || "$" === t || "$comment" === t) return { tag: t, id: null, classes: [] }; const n = t.match(/^([a-zA-Z0-9-]+)?((?:[#.][a-zA-Z0-9_-]+)*)$/); if (!n || !n[1] && !n[2]) return { tag: t, id: null, classes: [] }; const r = n[1] || "div"; let o = null; const s = [], i = (n[2] || "").match(/[#.][a-zA-Z0-9_-]+/g) || []; for (const e of i) e.startsWith("#") ? o = e.slice(1) : e.startsWith(".") && s.push(e.slice(1)); return { tag: r, id: o, classes: s } } function buildBoundEventCode(e, t) { let n = serializeFunctionBody(e); if (t && "object" == typeof t && !Array.isArray(t)) { const e = Object.entries(t).filter(([e, t]) => /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e) && void 0 !== t); if (e.length > 0) { const t = e.map(([e]) => e).join(", "), r = Object.fromEntries(e); n = `const { ${t} } = ${JSON.stringify(r).replaceAll("<\/script>", "<\\/script>").replaceAll("'", "\\'")}; ${n}` } } return n.replaceAll("'", "'") } function compileScopedCss(e, t) { const n = `[data-nb-s="${t}"]`, r = e => Object.entries(e).map(([e, t]) => { return t && "object" == typeof t ? e.startsWith("@") ? `${e}{${r(t)}}` : `${o = e, o.split(",").map(e => { const t = e.trim(); if ("self" === t || ":host" === t) return n; const r = t.indexOf(":"); return r > 0 ? `${t.slice(0, r)}${n}${t.slice(r)}` : `${t}${n}` }).join(", ")}{${r(t)}}` : `${toKebabCase(e)}:${t};`; var o }).join(""); return r(e) } function collectHeadAssets(e, t) { const n = Array.isArray(e) ? e : [e]; for (const e of n) if (e && "object" == typeof e) for (const [n, r] of Object.entries(e)) { const e = Array.isArray(r) ? r : [r], o = parseEmmetKey(n), s = (r?.tag || o.tag).toLowerCase(); for (const r of e) { if (!r || "object" != typeof r) continue; let e; if (e = r.src ? `${s}:src:${r.src}` : r.href ? `${s}:href:${r.href}` : r.name ? `${s}:name:${r.name}` : r.property ? `${s}:prop:${r.property}` : r.charset ? `${s}:charset` : `${s}:inline:${JSON.stringify(r)}`, t.has(e)) continue; let o = 2; "meta" === s || "link" === s && /preconnect|preload|dns-prefetch/.test(r.rel || "") ? o = 1 : "link" === s || "style" === s ? o = 2 : "script" === s && (o = r.defer || r.async || "module" === r.type ? 4 : 3), t.set(e, { priority: o, node: { [n]: r } }) } } } function interpolateLoopTokens(e, t, n) { return e.includes("$item") || e.includes("$index") ? e.replaceAll("$index", String(n)).replace(/\$item(?:\.([a-zA-Z0-9_$.]+))?/g, (e, n) => { if (!n) return null != t ? String(t) : ""; const r = n.split(".").reduce((e, t) => e?.[t], t); return null != r ? String(r) : "" }) : e } function resolveLoopNode(e, t, n) { if ("function" == typeof e) return e(t, n); if ("string" == typeof e) return interpolateLoopTokens(e, t, n); if (Array.isArray(e)) return e.map(e => resolveLoopNode(e, t, n)); if (null !== e && "object" == typeof e && e !== Null) { const r = {}; e[SCOPE_KEY] && (r[SCOPE_KEY] = e[SCOPE_KEY]); for (const [o, s] of Object.entries(e)) { if ("each" === o) continue; const e = "function" == typeof s && o.toLowerCase().startsWith("on"); r[o] = e ? s : resolveLoopNode(s, t, n) } return r } return e } function expandEachItems(e) { const t = e.each; return ("number" == typeof t && t >= 0 ? Array.from({ length: Math.floor(t) }, (e, t) => t) : Array.isArray(t) ? t : []).map((t, n) => resolveLoopNode(e, t, n)) } function matchNodeSelector(e, t, n) { const r = parseEmmetKey(e), o = (t.tag || r.tag).toLowerCase(); if (n.tag && o !== n.tag.toLowerCase()) return !1; const s = t.id ?? r.id; if (n.id && s !== n.id) return !1; if (n.classes.length > 0) { const e = "string" == typeof t.class ? t.class : "", o = new Set([...r.classes, ...e.split(/\s+/).filter(Boolean)]); for (const e of n.classes) if (!o.has(e)) return !1 } return !0 } function queryTree(e, t, n) { const r = parseEmmetKey(t); /^[#.]/.test(t.trim()) && (r.tag = null); const o = e => { if (e && "object" == typeof e) if (Array.isArray(e)) e.forEach(o); else for (const [t, s] of Object.entries(e)) "$comment" === t || "$head" === t || RESERVED_KEYS.has(t) || (Array.isArray(s) ? s.forEach(e => { e && "object" == typeof e && ("$" !== t.trim() && matchNodeSelector(t, e, r) && n(e), o(e)) }) : s && "object" == typeof s && s !== Null && ("$" !== t.trim() && matchNodeSelector(t, s, r) && n(s), o(s))) }; o(e) } async function resolveAsyncTree(e) { if (e instanceof Promise) return resolveAsyncTree(await e); if ("function" == typeof e) return e; if (Array.isArray(e)) { const t = await Promise.all(e.map(e => resolveAsyncTree(e))); return e[SCOPE_KEY] && (t[SCOPE_KEY] = e[SCOPE_KEY]), t } if (null !== e && "object" == typeof e && e !== Null) { const t = await Promise.all(Object.entries(e).map(async ([e, t]) => [e, await resolveAsyncTree(t)])), n = Object.fromEntries(t); return e[SCOPE_KEY] && (n[SCOPE_KEY] = e[SCOPE_KEY]), n } return e } function htmlToNeobiz(e) { const t = String(e).trim(); if (!t) return {}; const n = t.match(/<!--[\s\S]*?-->|<\/?[^>]+>|[^<]+/g) || [], r = { children: [] }, o = [r]; for (const e of n) { const t = e.trim(); if (!t) continue; const n = o[o.length - 1]; if (t.startsWith("\x3c!--") && t.endsWith("--\x3e")) { const e = t.slice(4, -3).trim(); n.children.push({ isComment: !0, content: e }) } else if (t.startsWith("</")) o.length > 1 && o.pop(); else if (t.startsWith("<")) { const e = t.endsWith("/>"), r = t.match(/^<([a-zA-Z0-9-]+)/); if (!r) continue; const s = r[1].toLowerCase(), i = t.slice(r[0].length, e ? -2 : -1).trim(), c = {}, a = /([a-zA-Z0-9-:@]+)(?:=(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g; let l; for (; null !== (l = a.exec(i));) { const [, e, t, n, r] = l, o = t ?? n ?? r; c[e] = void 0 === o ? Null : o } const p = { tag: s, obj: c, children: [] }; n.children.push(p), e || VOID_ELEMENTS.has(s) || o.push(p) } else n.children.push({ isText: !0, content: t }) } function s(e) { const t = { ...e.obj }, n = new Map; for (const r of e.children) { if (r.isComment) { t.$comment = r.content; continue } if (r.isText) { t.text = t.text ? `${t.text} ${r.content}` : r.content; continue } const e = s(r), o = n.get(r.tag) || 0; n.set(r.tag, o + 1); t[0 === o ? r.tag : `${r.tag}${" ".repeat(o)}`] = e } return t } const i = {}, c = new Map; for (const e of r.children) if (!e.isText && !e.isComment) { const t = c.get(e.tag) || 0; c.set(e.tag, t + 1); i[0 === t ? e.tag : `${e.tag}${" ".repeat(t)}`] = s(e) } return i } function compileNode(e, t, n, r = 0, o = null) { if (null == e || "object" != typeof e) return ""; const s = e[SCOPE_KEY] ?? o; s && n.usedScopes.add(s); const i = t.pretty ? " ".repeat(r * t.indentSize) : "", c = t.pretty ? "\n" : "", a = []; for (const [o, l] of Object.entries(e)) { if (null == l || !1 === l) continue; if ("$comment" === o.trim()) { const e = String(l).replaceAll("--", "- -"), n = e.startsWith("!"); (t.pretty || n) && a.push(`${i}\x3c!-- ${e} --\x3e`); continue } if ("$head" === o.trim()) { collectHeadAssets(l, n.headAssets); continue } if ("$" === o.trim()) { if (!Array.isArray(l) && "object" == typeof l) { if ("each" in l) { const e = expandEachItems(l); for (const o of e) a.push(compileNode(o, t, n, r, s)); continue } if ("when" in l && !l.when) continue } const e = Array.isArray(l) ? l : [l]; for (const o of e) a.push(compileNode(o, t, n, r, s)); continue } if (Array.isArray(l)) { for (const e of l) a.push(compileNode({ [o]: e }, t, n, r, s)); continue } if ("object" != typeof l) continue; if ("each" in l) { const e = expandEachItems(l); for (const i of e) a.push(compileNode({ [o]: i }, t, n, r, s)); continue } if ("when" in l && !l.when) continue; const e = l[SCOPE_KEY] ?? s; e && n.usedScopes.add(e); const p = { ...t, prefixTag: !l.noprefix && t.prefixTag, prefixAttr: !l.nopAttr && t.prefixAttr }, u = parseEmmetKey(o); let f = u.tag; !p.ignoreTag && l.tag && (f = l.tag), p.camelCase && (f = toKebabCase(f)); const d = `${p.prefixTag || ""}${f}`, h = [], y = []; let m = !1; e && "style" !== f && "script" !== f && h.push(` data-nb-s='${e}'`); const $ = l.id ?? u.id, g = [...u.classes, ...l.class ? [String(l.class)] : []]; if ($) { const e = `${p.prefixAttr || ""}id`; h.push(` ${e}='${String($)}'`) } if (g.length > 0) { const e = `${p.prefixAttr || ""}class`; h.push(` ${e}='${g.join(" ")}'`) } for (const [t, o] of Object.entries(l)) { if (void 0 === o || !1 === o || null === o) continue; if ("id" === t || "class" === t) continue; if ("$head" === t) { collectHeadAssets(o, n.headAssets); continue } if (directiveRegistry.has(t)) { directiveRegistry.get(t)(o, { attrs: h, children: y, tagName: d, node: l, escapeHtml: escapeHtml }); continue } if ("text" === t) { y.push(escapeHtml(o)); continue } if ("html" === t) { const e = "function" == typeof o ? serializeFunctionBody(o) : String(o); y.push(e); continue } if (RESERVED_KEYS.has(t)) continue; if (o === Null || !0 === o) { const e = p.camelCase ? toKebabCase(t) : t, n = `${p.prefixAttr || ""}${e}`; h.push(` ${n}`); continue } if ("function" == typeof o) { const e = p.camelCase ? toKebabCase(t) : t, n = buildBoundEventCode(o, l.bind); h.push(` ${e}='${n}'`); continue } if ("object" == typeof o) { m = !0, y.push(compileNode({ [t]: o }, p, n, r + 1, e)); continue } const s = p.camelCase ? toKebabCase(t) : t, i = `${p.prefixAttr || ""}${s}`; h.push(` ${i}='${String(o)}'`) } const E = "head" === f.toLowerCase(), A = E ? "__NB_HEAD_SLOT__" : ""; if (VOID_ELEMENTS.has(f.toLowerCase())) a.push(`${i}<${d}${h.join("")}/>`); else if ((m || E) && t.pretty) { const e = y.length > 0 ? `${c}${y.join(c)}` : ""; a.push(`${i}<${d}${h.join("")}>${e}${A}${c}${i}</${d}>`) } else a.push(`${i}<${d}${h.join("")}>${y.join("")}${A}</${d}>`) } return a.join(c) } function renderEngine(e) { const t = { ...currentOption }; currentOption.once && (currentOption = { ...defaultOptions }); const n = { usedScopes: new Set, headAssets: new Map }, r = t.pretty ? "\n" : "", o = t.nodoctype ? "" : `<!DOCTYPE html>${r}`; let s = Array.isArray(e) ? e.map(e => compileNode(e, t, n, 0, null)).join(r) : compileNode(e, t, n, 0, null); const i = [...n.headAssets.values()].sort((e, t) => e.priority - t.priority).map(e => compileNode(e.node, t, n, s.includes("__NB_HEAD_SLOT__") ? 2 : 0, null)), c = i.length > 0 ? `${r}${i.join(r)}` : ""; s.includes("__NB_HEAD_SLOT__") ? s = s.replace("__NB_HEAD_SLOT__", c) : c && (s = `${i.join(r)}${r}${s}`); const a = []; for (const e of n.usedScopes) styleRegistry.has(e) && a.push(compileScopedCss(styleRegistry.get(e), e)); const l = a.length > 0 ? `${r}<style>${a.join(r)}</style>` : ""; return `${o}${s}${l}` } function compileCss(e, t = !1) { return Object.entries(e).map(([e, t]) => { if (t && "object" == typeof t) return `${e}{${compileCss(t, !0)}}`; return `${toKebabCase(e)}:${t};` }).join(t ? "" : "\n") } if (Object.defineProperties(Object.prototype, { Null: { value: Null }, renderOption: { value(e) { currentOption = { ...defaultOptions, ...e } } }, addDirective: { value(e, t) { "function" == typeof t && directiveRegistry.set(e, t) } }, removeDirective: { value(e) { directiveRegistry.delete(e) } }, regStyle: { value(e) { return styleRegistry.set(e, this), this } }, scope: { value(e) { return this[SCOPE_KEY] = e, this } }, query: { value(e, t) { return "function" == typeof t && queryTree(this, e, t), this } }, _render: { get() { return renderEngine(this) } }, _renderAsync: { get() { return (async () => renderEngine(await resolveAsyncTree(this)))() } }, reg: { value(e) { return componentRegistry.has(e) || componentRegistry.set(e, this), this } }, regm: { value(e) { return componentRegistry.has(e) && componentRegistry.set(e, this), this } }, unreg: { value(e) { componentRegistry.delete(e) } }, load: { value: e => componentRegistry.get(e) ?? null }, css: { get() { return { text: compileCss(this, !1) } } }, cssText: { get() { return compileCss(this, !0) } }, alter: { value(e) { return e(this), this } } }), Object.defineProperty(String.prototype, "repulse", { get() { return htmlToNeobiz(this) } }), Object.defineProperty(Array.prototype, "range", { value: (e, t = 0) => Array.from({ length: e }, (e, n) => t + n) }), "undefined" != typeof Element && "undefined" != typeof Document) { const e = { value(e, t) { return "function" == typeof t && this.querySelectorAll(e).forEach(e => t(e)), this } }; Object.defineProperty(Document.prototype, "query", e), Object.defineProperty(Element.prototype, "query", e), Object.defineProperties(Element.prototype, { htmlObj: { set(e) { const t = { ...currentOption }; currentOption.nodoctype = !0, this.innerHTML = renderEngine(e), currentOption = t } }, appendObj: { value(e) { const t = { ...currentOption }; return currentOption.nodoctype = !0, this.insertAdjacentHTML("beforeend", renderEngine(e)), currentOption = t, this } } }) }