@zikojs/console 0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 ZAKARIA ELALAOUI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "@zikojs/console",
3
+ "version": "0.1.0",
4
+ "description": "",
5
+ "main": "src/index.js",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "keywords": [
10
+ "zikojs",
11
+ "console",
12
+ "log",
13
+ "dev-tools"
14
+ ],
15
+ "author": "zakaria elalaoui",
16
+ "license": "MIT",
17
+ "type": "module",
18
+ "dependencies": {
19
+ "ziko": "^2.0.0-beta.16.0"
20
+ },
21
+ "scripts": {
22
+ "test": "echo \"Error: no test specified\" && exit 1"
23
+ }
24
+ }
@@ -0,0 +1,29 @@
1
+ const actions = [
2
+ ["Messages", [
3
+ ["log", () => console.log("Hello from VanJS", 42, true, null, undefined)],
4
+ ["info", () => console.info("Server listening on :3000")],
5
+ ["debug", () => console.debug("cache miss", {key: "user:12"})],
6
+ ["warn", () => console.warn("Deprecated: use render() instead")],
7
+ ["error", () => console.error(new Error("Something broke"))],
8
+ ["%s format", () => console.log("%s has %d items %c(styled)", "Cart", 3, "color:red")],
9
+ ["Repeat x5", () => { for (let i = 0; i < 5; i++) console.log("tick") }],
10
+ ]],
11
+ ["Inspect", [
12
+ ["Nested object", () => {
13
+ const o = {user: {name: "Zakaria", tags: ["js", "three", "van"]}, ids: new Set([1, 2]),
14
+ lookup: new Map([["a", 1], ["b", {deep: true}]]), when: new Date(), run() {}, empty: {}}
15
+ o.self = o
16
+ console.log("Click to expand", o)
17
+ }],
18
+ ["DOM node", () => console.log(document.body, document.getElementById("mount"))],
19
+ ["Table", () => console.table([{id: 1, name: "Ada", role: "dev"}, {id: 2, name: "Linus", role: "ops", team: "kernel"}])],
20
+ ]],
21
+ ["Timing and flow", [
22
+ ["Group", () => { console.group("Request"); console.log("parsing"); console.group("Auth"); console.warn("token expires soon"); console.groupEnd(); console.groupEnd() }],
23
+ ["Timer", () => { console.time("work"); setTimeout(() => console.timeEnd("work"), 350) }],
24
+ ["Count", () => console.count("clicks")],
25
+ ["Assert", () => console.assert(1 === 2, "math is hard")],
26
+ ["Rejection", () => Promise.reject(new Error("Unhandled promise"))],
27
+ ["Throw", () => setTimeout(() => { throw new TypeError("Uncaught from timeout") })],
28
+ ]],
29
+ ]
@@ -0,0 +1,28 @@
1
+ import van from "https://cdn.jsdelivr.net/npm/vanjs-core@1.5.3/src/van.js";
2
+
3
+ import { entryNode, nodeEntry } from "../entries/entryNode.js";
4
+
5
+ export const Console = {
6
+ theme: van.state("light")
7
+ };
8
+
9
+ Console.log = entryNode("log", Console.theme);
10
+ Console.info = entryNode("info", Console.theme);
11
+ Console.debug = entryNode("debug", Console.theme);
12
+ Console.warn = entryNode("warn", Console.theme);
13
+ Console.error = entryNode("error", Console.theme);
14
+ Console.table = entryNode("table", Console.theme);
15
+
16
+ Console.group = entryNode("group", Console.theme);
17
+
18
+ Console.groupEnd = () => {
19
+ const node =
20
+ document.createComment("groupEnd");
21
+
22
+ nodeEntry.set(node, {
23
+ method: "groupEnd",
24
+ args: []
25
+ });
26
+
27
+ return node;
28
+ };
@@ -0,0 +1,46 @@
1
+ import van from "https://cdn.jsdelivr.net/npm/vanjs-core@1.5.3/src/van.js";
2
+ import { Row } from "./Row.js";
3
+
4
+ const { div } = van.tags;
5
+
6
+ export function ConsoleBody(visible) {
7
+ let stick = true;
8
+
9
+ const body = div(
10
+ {
11
+ class: "cf-body",
12
+
13
+ onscroll: () => {
14
+ stick =
15
+ body.scrollHeight -
16
+ body.scrollTop -
17
+ body.clientHeight < 24;
18
+ }
19
+ },
20
+
21
+ () =>
22
+ visible.val.length
23
+ ? div(
24
+ visible.val.map(entry =>
25
+ Row(entry)
26
+ )
27
+ )
28
+ : div(
29
+ { class: "cf-empty" },
30
+ "No messages yet. Anything sent to console.* shows up here."
31
+ )
32
+ );
33
+
34
+ van.derive(() => {
35
+ visible.val;
36
+
37
+ requestAnimationFrame(() => {
38
+ if (stick) {
39
+ body.scrollTop =
40
+ body.scrollHeight;
41
+ }
42
+ });
43
+ });
44
+
45
+ return body;
46
+ }
@@ -0,0 +1,141 @@
1
+ import van from "https://cdn.jsdelivr.net/npm/vanjs-core@1.5.3/src/van.js";
2
+
3
+ import { createFeed } from "../feed/createFeed.js";
4
+ import { nodeEntry } from "../entries/entryNode.js";
5
+
6
+ import { ConsoleToolbar } from "./ConsoleToolbar.js";
7
+ import { ConsoleBody } from "./ConsoleBody.js";
8
+ import { ConsolePrompt } from "./ConsolePrompt.js";
9
+
10
+ import { Hook } from "../hook/index.js";
11
+ import {
12
+ fmt,
13
+ safe
14
+ } from "../utils/index.js";
15
+
16
+ const { div } = van.tags;
17
+
18
+ const LEVEL = {
19
+ log: "log",
20
+ dir: "log",
21
+ table: "log",
22
+ group: "log",
23
+
24
+ info: "info",
25
+ debug: "debug",
26
+ warn: "warn",
27
+ error: "error"
28
+ };
29
+
30
+ const LEVELS = [
31
+ "log",
32
+ "info",
33
+ "warn",
34
+ "error",
35
+ "debug"
36
+ ];
37
+
38
+ const isProps = value =>
39
+ value &&
40
+ typeof value === "object" &&
41
+ !(value instanceof Node) &&
42
+ Object.getPrototypeOf(value) === Object.prototype;
43
+
44
+ export function ConsoleFeed(...args) {
45
+ const [props, ...children] =
46
+ isProps(args[0])
47
+ ? args
48
+ : [{}, ...args];
49
+
50
+ const {
51
+ feed = createFeed(),
52
+ variant = "dark",
53
+ repl = true,
54
+ hook = false
55
+ } = props;
56
+
57
+ if (hook) {
58
+ Hook(console, feed.push);
59
+ }
60
+
61
+ children
62
+ .flat(Infinity)
63
+ .forEach(child => {
64
+ const entry = nodeEntry.get(child);
65
+
66
+ if (entry) {
67
+ feed.push(entry);
68
+ }
69
+ });
70
+
71
+ const theme =
72
+ typeof variant === "string"
73
+ ? van.state(variant)
74
+ : variant;
75
+
76
+ const levels = Object.fromEntries(
77
+ LEVELS.map(level => [
78
+ level,
79
+ van.state(true)
80
+ ])
81
+ );
82
+
83
+ const query = van.state("");
84
+
85
+ const count = level =>
86
+ van.derive(() =>
87
+ feed.logs.val.filter(
88
+ entry =>
89
+ LEVEL[entry.method] === level
90
+ ).length
91
+ );
92
+
93
+ const visible = van.derive(() => {
94
+ const search =
95
+ query.val.toLowerCase();
96
+
97
+ return feed.logs.val.filter(entry => {
98
+ const level =
99
+ LEVEL[entry.method];
100
+
101
+ if (
102
+ level &&
103
+ !levels[level].val
104
+ ) {
105
+ return false;
106
+ }
107
+
108
+ if (!search) {
109
+ return true;
110
+ }
111
+
112
+ return fmt(entry.args)
113
+ .map(safe)
114
+ .join(" ")
115
+ .toLowerCase()
116
+ .includes(search);
117
+ });
118
+ });
119
+
120
+ return div(
121
+ {
122
+ class: () =>
123
+ "cf " + theme.val,
124
+
125
+ style: "flex:1"
126
+ },
127
+
128
+ ConsoleToolbar({
129
+ levels,
130
+ query,
131
+ count,
132
+ clear: feed.clear
133
+ }),
134
+
135
+ ConsoleBody(visible),
136
+
137
+ repl
138
+ ? ConsolePrompt({ feed })
139
+ : ""
140
+ );
141
+ }
@@ -0,0 +1,74 @@
1
+ import { tags } from "ziko/dom";
2
+ const { div, span, input } = tags;
3
+ export function ConsolePrompt({
4
+ feed
5
+ }) {
6
+ const history = [];
7
+ let index = 0;
8
+
9
+ const run = code => {
10
+ feed.push({
11
+ method: "command",
12
+ args: [code]
13
+ });
14
+
15
+ try {
16
+ feed.push({
17
+ method: "result",
18
+ args: [(0, eval)(code)]
19
+ });
20
+ } catch (error) {
21
+ feed.push({
22
+ method: "error",
23
+ args: [error]
24
+ });
25
+ }
26
+ };
27
+
28
+ const inp = input({
29
+ placeholder: "Run JavaScript",
30
+ "aria-label": "Run JavaScript",
31
+ spellcheck: false,
32
+ autocomplete: "off",
33
+
34
+ onKeyDown: __e__ => {
35
+ const e = __e__.event
36
+ const el = e.target;
37
+
38
+ if (
39
+ e.key === "Enter" &&
40
+ el.value.trim()
41
+ ) {
42
+ history.push(el.value);
43
+ index = history.length;
44
+
45
+ run(el.value);
46
+
47
+ el.value = "";
48
+ }
49
+
50
+ else if (
51
+ e.key === "ArrowUp" &&
52
+ index > 0
53
+ ) {
54
+ el.value = history[--index];
55
+ e.preventDefault();
56
+ }
57
+
58
+ else if (e.key === "ArrowDown") {
59
+ el.value =
60
+ index < history.length - 1
61
+ ? history[++index]
62
+ : (index = history.length, "");
63
+ }
64
+ }
65
+ })
66
+
67
+ return div(
68
+ { class: "cf-prompt" },
69
+
70
+ span("\u203A"),
71
+ inp
72
+
73
+ ).element;
74
+ }
@@ -0,0 +1,61 @@
1
+ import van from "https://cdn.jsdelivr.net/npm/vanjs-core@1.5.3/src/van.js";
2
+
3
+ const {
4
+ div,
5
+ button,
6
+ input
7
+ } = van.tags;
8
+
9
+ export function ConsoleToolbar({
10
+ levels,
11
+ query,
12
+ count,
13
+ clear
14
+ }) {
15
+ const LEVELS = [
16
+ "log",
17
+ "info",
18
+ "warn",
19
+ "error",
20
+ "debug"
21
+ ];
22
+
23
+ return div(
24
+ { class: "cf-bar" },
25
+
26
+ LEVELS.map(level =>
27
+ button(
28
+ {
29
+ class: () =>
30
+ `cf-chip ${level}` +
31
+ (levels[level].val ? " on" : ""),
32
+
33
+ "aria-pressed": () =>
34
+ levels[level].val,
35
+
36
+ onclick: () =>
37
+ levels[level].val =
38
+ !levels[level].val
39
+ },
40
+
41
+ level,
42
+ " ",
43
+ count(level)
44
+ )
45
+ ),
46
+
47
+ input({
48
+ type: "search",
49
+ placeholder: "Filter messages",
50
+ "aria-label": "Filter messages",
51
+
52
+ oninput: e =>
53
+ query.val = e.target.value
54
+ }),
55
+
56
+ button(
57
+ { onclick: clear },
58
+ "Clear"
59
+ )
60
+ );
61
+ }
@@ -0,0 +1,101 @@
1
+ import {
2
+ isObj,
3
+ prim,
4
+ primCls,
5
+ nodeLabel,
6
+ label,
7
+ short,
8
+ preview,
9
+ entriesOf,
10
+ } from "../utils/index.js";
11
+
12
+ import { tags } from "ziko/dom";
13
+ import { useState, useDerived } from "ziko/hooks";
14
+
15
+ const { div, span } = tags;
16
+
17
+ export function Inspect(v, key, seen = [], top = false) {
18
+ const k =
19
+ key === undefined
20
+ ? ""
21
+ : span({ class: "cf-k" }, key, ": ");
22
+
23
+ const leaf = (cls, t) =>
24
+ span({ class: "cf-" + cls }, k, t);
25
+
26
+ if (v instanceof Error) {
27
+ const s = v.stack?.includes(v.message)
28
+ ? v.stack
29
+ : `${v.name}: ${v.message}\n${v.stack || ""}`;
30
+
31
+ return div(
32
+ { class: "cf-err" },
33
+ k,
34
+ s,
35
+ );
36
+ }
37
+
38
+ if (top && typeof v === "string") {
39
+ return span(v);
40
+ }
41
+
42
+ if (typeof v === "function") {
43
+ return leaf("fn", short(v));
44
+ }
45
+
46
+ if (!isObj(v)) {
47
+ return leaf(primCls(v), prim(v));
48
+ }
49
+
50
+ if (v instanceof Date || v instanceof RegExp) {
51
+ return leaf("str", short(v));
52
+ }
53
+
54
+ if (typeof Node !== "undefined" && v instanceof Node) {
55
+ return leaf("nul", nodeLabel(v));
56
+ }
57
+
58
+ if (seen.includes(v)) {
59
+ return leaf("nul", "[Circular]");
60
+ }
61
+
62
+ const es = entriesOf(v);
63
+
64
+ if (!es.length) {
65
+ return leaf(
66
+ "nul",
67
+ (label(v) ? label(v) + " " : "") +
68
+ (Array.isArray(v) ? "[]" : "{}"),
69
+ );
70
+ }
71
+
72
+ const [open, setOpen] = useState(false);
73
+
74
+ const header = useDerived(
75
+ open => div(
76
+ {
77
+ class: "cf-t" + (open ? " open" : ""),
78
+ onClick: () => setOpen(old => !old),
79
+ },
80
+ k,
81
+ open
82
+ ? label(v) || "Object"
83
+ : preview(v),
84
+ ),
85
+ [open],
86
+ );
87
+
88
+ const children = useDerived(
89
+ open => {
90
+ const kids = open ? es.map(([kk, x]) => Inspect(x, kk, [...seen, v]).element) : []
91
+ return div({ class: "cf-kids" }, ...kids)
92
+ },
93
+ [open],
94
+ );
95
+
96
+ return div(
97
+ { class: "cf-node" },
98
+ header,
99
+ children
100
+ )
101
+ }
@@ -0,0 +1,64 @@
1
+ import van from "https://cdn.jsdelivr.net/npm/vanjs-core@1.5.3/src/van.js";
2
+
3
+ import {
4
+ fmt,
5
+ isObj
6
+ } from "../utils/index.js";
7
+
8
+ import { Inspect } from "./Inspect.js";
9
+ import { Table } from "./Table.js";
10
+
11
+ const { div, span } = van.tags;
12
+
13
+ const cache = new WeakMap();
14
+
15
+ const buildRow = entry => {
16
+ const [a0, ...rest] = entry.args;
17
+
18
+ const items =
19
+ entry.method === "table" && isObj(a0)
20
+ ? [
21
+ Table(a0),
22
+ ...rest.map(x =>
23
+ Inspect(x, undefined, [], true).element
24
+ )
25
+ ]
26
+ : fmt(entry.args).map(a =>
27
+ Inspect(a, undefined, [], true).element
28
+ );
29
+
30
+ return div(
31
+ {
32
+ class: `cf-row ${entry.method}`,
33
+ style: `--d:${entry.depth}`
34
+ },
35
+
36
+ () =>
37
+ entry.count.val > 1
38
+ ? span(
39
+ { class: "cf-badge" },
40
+ entry.count.val
41
+ )
42
+ : "",
43
+
44
+ span(
45
+ { class: "cf-time" },
46
+ entry.time.toLocaleTimeString([], {
47
+ hour12: false
48
+ })
49
+ ),
50
+
51
+ div(
52
+ { class: "cf-msg" },
53
+ items
54
+ )
55
+ );
56
+ };
57
+
58
+ export const Row = entry =>
59
+ cache.get(entry) ||
60
+ (() => {
61
+ const node = buildRow(entry);
62
+ cache.set(entry, node);
63
+ return node;
64
+ })();
@@ -0,0 +1,33 @@
1
+ import { isObj, prim, short } from "../utils/index.js";
2
+ import { tags } from "ziko/dom";
3
+ const { table, thead, tbody, tr, th, td } = tags;
4
+ export function Table(data) {
5
+ const rows = Array.isArray(data)
6
+ ? data.map((x, i) => [i, x])
7
+ : data instanceof Map
8
+ ? [...data].map(([a, b]) => [short(a), b])
9
+ : Object.entries(data);
10
+ const cols = [
11
+ ...new Set(rows.flatMap(([, x]) => (isObj(x) ? Object.keys(x) : []))),
12
+ ];
13
+ const hasVal = rows.some(([, x]) => !isObj(x));
14
+ return table(
15
+ { class: "cf-table" },
16
+ thead(
17
+ tr(
18
+ th("(index)"),
19
+ cols.map((c) => th(c)),
20
+ hasVal ? th("Value") : "",
21
+ ),
22
+ ),
23
+ tbody(
24
+ ...rows.map(([i, x]) =>
25
+ tr(
26
+ td(i),
27
+ cols.map((c) => td(isObj(x) && c in x ? short(x[c]) : "")),
28
+ hasVal ? td(isObj(x) ? "" : prim(x)) : "",
29
+ ),
30
+ ),
31
+ ),
32
+ ).element;
33
+ }
@@ -0,0 +1,8 @@
1
+ export * from './Inspect.js'
2
+ export * from './Table.js'
3
+ export * from './Row.js'
4
+ export * from './ConsoleToolbar.js'
5
+ export * from './ConsoleBody.js'
6
+ export * from './ConsolePrompt.js'
7
+ export * from './ConsoleFeed.js'
8
+ export * from './Console.js'
@@ -0,0 +1,10 @@
1
+ import van from "https://cdn.jsdelivr.net/npm/vanjs-core@1.5.3/src/van.js";
2
+
3
+ export const createEntry = (method, args) => ({
4
+ id: 0,
5
+ method,
6
+ args,
7
+ depth: 0,
8
+ count: van.state(1),
9
+ time: new Date()
10
+ });
@@ -0,0 +1,22 @@
1
+ import van from "https://cdn.jsdelivr.net/npm/vanjs-core@1.5.3/src/van.js";
2
+ import { createEntry } from "./createEntry.js";
3
+ import { Row } from "../components/Row.js";
4
+ const { div } = van.tags
5
+
6
+ export const nodeEntry = new WeakMap();
7
+
8
+ export const entryNode = (method, theme) => (...args) => {
9
+ const entry = createEntry(method, args);
10
+
11
+ const node = div(
12
+ {
13
+ class: () =>
14
+ "cf cf-solo " + theme.val
15
+ },
16
+ Row(entry)
17
+ );
18
+
19
+ nodeEntry.set(node, entry);
20
+
21
+ return node;
22
+ };
@@ -0,0 +1,67 @@
1
+ import van from "https://cdn.jsdelivr.net/npm/vanjs-core@1.5.3/src/van.js";
2
+ import { isObj } from "../utils/index.js";
3
+
4
+ export function createFeed(max = 1000) {
5
+ const logs = van.state([]);
6
+
7
+ let depth = 0;
8
+ let id = 0;
9
+
10
+ const same = (a, b) =>
11
+ a.method === b.method &&
12
+ a.depth === b.depth &&
13
+ a.args.length === b.args.length &&
14
+ a.args.every(
15
+ (x, i) => !isObj(x) && Object.is(x, b.args[i])
16
+ );
17
+
18
+ const push = src => {
19
+ const { method, args = [] } = src;
20
+
21
+ if (method === "clear") {
22
+ depth = 0;
23
+ logs.val = [];
24
+ return;
25
+ }
26
+
27
+ if (method === "groupEnd") {
28
+ depth = Math.max(0, depth - 1);
29
+ return;
30
+ }
31
+
32
+ const isGroup =
33
+ method === "group" ||
34
+ method === "groupCollapsed";
35
+
36
+ const entry = src.count
37
+ ? Object.assign(src, {
38
+ id: ++id,
39
+ depth
40
+ })
41
+ : {
42
+ id: ++id,
43
+ method: isGroup ? "group" : method,
44
+ args,
45
+ depth,
46
+ count: van.state(1),
47
+ time: new Date()
48
+ };
49
+
50
+ const last = logs.val.at(-1);
51
+
52
+ if (last && !isGroup && same(last, entry)) {
53
+ last.count.val++;
54
+ return;
55
+ }
56
+
57
+ logs.val = [...logs.val, entry].slice(-max);
58
+
59
+ if (isGroup) depth++;
60
+ };
61
+
62
+ return {
63
+ logs,
64
+ push,
65
+ clear: () => push({ method: "clear" })
66
+ };
67
+ }
@@ -0,0 +1,29 @@
1
+ export const METHODS = ["log","info","debug","warn","error","table","dir","assert","count","countReset",
2
+ "time","timeEnd","timeLog","group","groupCollapsed","groupEnd","clear"]
3
+
4
+ export function Hook(target, cb) {
5
+ const orig = {}, counts = {}, timers = {}
6
+ const emit = (method, args) => { try { cb({method, args}) } catch {} }
7
+ const ms = l => (performance.now() - timers[l]).toFixed(2) + "ms"
8
+ const impl = {
9
+ count: (l = "default") => emit("log", [`${l}: ${counts[l] = (counts[l] || 0) + 1}`]),
10
+ countReset: (l = "default") => { counts[l] = 0 },
11
+ time: (l = "default") => { timers[l] = performance.now() },
12
+ timeEnd: (l = "default") => { if (l in timers) { emit("log", [`${l}: ${ms(l)}`]); delete timers[l] } },
13
+ timeLog: (l = "default", ...r) => { if (l in timers) emit("log", [`${l}: ${ms(l)}`, ...r]) },
14
+ assert: (c, ...r) => { if (!c) emit("error", ["Assertion failed:", ...r]) },
15
+ }
16
+ METHODS.forEach(m => {
17
+ orig[m] = target[m]
18
+ target[m] = (...a) => { orig[m]?.apply(target, a); (impl[m] || ((...x) => emit(m, x)))(...a) }
19
+ })
20
+ const onErr = e => emit("error", [e.error || e.message])
21
+ const onRej = e => emit("error", [e.reason instanceof Error ? e.reason : new Error("Unhandled rejection: " + safe(e.reason))])
22
+ addEventListener("error", onErr)
23
+ addEventListener("unhandledrejection", onRej)
24
+ return () => {
25
+ METHODS.forEach(m => target[m] = orig[m])
26
+ removeEventListener("error", onErr)
27
+ removeEventListener("unhandledrejection", onRej)
28
+ }
29
+ }
package/src/index.css ADDED
@@ -0,0 +1,310 @@
1
+ :root {
2
+ --mono:
3
+ ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace;
4
+ --sans: system-ui, -apple-system, "Segoe UI", sans-serif;
5
+ }
6
+ * {
7
+ box-sizing: border-box;
8
+ }
9
+ body {
10
+ margin: 0;
11
+ background: #e8eaf0;
12
+ color: #232834;
13
+ font: 14px/1.5 var(--sans);
14
+ height: 100vh;
15
+ display: flex;
16
+ flex-direction: column;
17
+ }
18
+ header {
19
+ padding: 14px 20px 4px;
20
+ }
21
+ header h1 {
22
+ margin: 0;
23
+ font-size: 17px;
24
+ font-weight: 650;
25
+ }
26
+ header p {
27
+ margin: 2px 0 0;
28
+ color: #5c6578;
29
+ font-size: 13px;
30
+ }
31
+ main {
32
+ flex: 1;
33
+ min-height: 0;
34
+ display: grid;
35
+ grid-template-columns: 230px 1fr;
36
+ gap: 14px;
37
+ padding: 12px 20px 20px;
38
+ }
39
+ @media (max-width: 720px) {
40
+ main {
41
+ grid-template-columns: 1fr;
42
+ grid-template-rows: auto 1fr;
43
+ }
44
+ }
45
+ aside {
46
+ display: flex;
47
+ flex-wrap: wrap;
48
+ align-content: flex-start;
49
+ gap: 6px;
50
+ }
51
+ aside h2 {
52
+ width: 100%;
53
+ margin: 6px 0 0;
54
+ font-size: 12px;
55
+ font-weight: 600;
56
+ color: #5c6578;
57
+ }
58
+ aside button {
59
+ font: inherit;
60
+ font-size: 13px;
61
+ padding: 5px 10px;
62
+ border: 1px solid #c9cedb;
63
+ background: #f6f7fa;
64
+ color: inherit;
65
+ border-radius: 5px;
66
+ cursor: pointer;
67
+ }
68
+ aside button:hover {
69
+ background: #fff;
70
+ border-color: #8a93a8;
71
+ }
72
+ button:focus-visible,
73
+ input:focus-visible {
74
+ outline: 2px solid #3b82f6;
75
+ outline-offset: 1px;
76
+ }
77
+
78
+ /* ---------- Console component ---------- */
79
+ .cf {
80
+ --bg: #171b24;
81
+ --bar: #1e2330;
82
+ --line: #2b3244;
83
+ --fg: #d8dee9;
84
+ --dim: #7d889e;
85
+ --str: #e9b27a;
86
+ --num: #8fb8ff;
87
+ --bool: #c79bff;
88
+ --nul: #8b93a5;
89
+ --key: #7fd1c2;
90
+ --warn-bg: #2e2813;
91
+ --warn-fg: #f0d27a;
92
+ --err-bg: #331a1d;
93
+ --err-fg: #ff9b9b;
94
+ --hover: #202637;
95
+ display: flex;
96
+ flex-direction: column;
97
+ min-height: 0;
98
+ background: var(--bg);
99
+ color: var(--fg);
100
+ font: 12.5px/1.55 var(--mono);
101
+ border: 1px solid var(--line);
102
+ border-radius: 6px;
103
+ overflow: hidden;
104
+ }
105
+ .cf.light {
106
+ --bg: #fbfbfd;
107
+ --bar: #f0f2f6;
108
+ --line: #dfe3ea;
109
+ --fg: #252b37;
110
+ --dim: #7a8396;
111
+ --str: #b4531c;
112
+ --num: #1d5fd1;
113
+ --bool: #7a3fc4;
114
+ --nul: #7a8396;
115
+ --key: #0b7a6c;
116
+ --warn-bg: #fff6da;
117
+ --warn-fg: #7a5a00;
118
+ --err-bg: #ffeceb;
119
+ --err-fg: #b3261e;
120
+ --hover: #f3f5f9;
121
+ }
122
+ .cf-bar {
123
+ display: flex;
124
+ gap: 6px;
125
+ align-items: center;
126
+ padding: 6px 8px;
127
+ background: var(--bar);
128
+ border-bottom: 1px solid var(--line);
129
+ flex-wrap: wrap;
130
+ }
131
+ .cf-bar input {
132
+ flex: 1;
133
+ min-width: 120px;
134
+ font: inherit;
135
+ background: var(--bg);
136
+ color: var(--fg);
137
+ border: 1px solid var(--line);
138
+ border-radius: 4px;
139
+ padding: 3px 8px;
140
+ }
141
+ .cf-bar button {
142
+ font: inherit;
143
+ background: none;
144
+ color: var(--dim);
145
+ border: 1px solid transparent;
146
+ border-radius: 4px;
147
+ padding: 2px 8px;
148
+ cursor: pointer;
149
+ }
150
+ .cf-bar button:hover {
151
+ color: var(--fg);
152
+ border-color: var(--line);
153
+ }
154
+ .cf-bar button.cf-chip.on {
155
+ color: var(--fg);
156
+ border-color: var(--line);
157
+ background: var(--bg);
158
+ }
159
+ .cf-chip.warn.on {
160
+ color: var(--warn-fg) !important;
161
+ }
162
+ .cf-chip.error.on {
163
+ color: var(--err-fg) !important;
164
+ }
165
+ .cf-body {
166
+ flex: 1;
167
+ overflow: auto;
168
+ min-height: 0;
169
+ }
170
+ .cf-empty {
171
+ padding: 18px 12px;
172
+ color: var(--dim);
173
+ }
174
+ .cf-row {
175
+ display: flex;
176
+ gap: 8px;
177
+ align-items: flex-start;
178
+ padding: 2px 10px 2px calc(10px + var(--d, 0) * 16px);
179
+ border-bottom: 1px solid var(--line);
180
+ }
181
+ .cf-row:hover {
182
+ background: var(--hover);
183
+ }
184
+ .cf-row.warn {
185
+ background: var(--warn-bg);
186
+ color: var(--warn-fg);
187
+ }
188
+ .cf-row.error {
189
+ background: var(--err-bg);
190
+ color: var(--err-fg);
191
+ }
192
+ .cf-row.group .cf-msg {
193
+ font-weight: 650;
194
+ }
195
+ .cf-row.command .cf-msg::before,
196
+ .cf-row.result .cf-msg::before {
197
+ color: var(--dim);
198
+ margin-right: 0.6em;
199
+ }
200
+ .cf-row.command .cf-msg::before {
201
+ content: "\203A";
202
+ }
203
+ .cf-row.result .cf-msg::before {
204
+ content: "\2190";
205
+ }
206
+ .cf-badge {
207
+ background: var(--dim);
208
+ color: var(--bg);
209
+ border-radius: 9px;
210
+ padding: 0 6px;
211
+ font-size: 11px;
212
+ line-height: 17px;
213
+ margin-top: 2px;
214
+ }
215
+ .cf-time {
216
+ color: var(--dim);
217
+ font-size: 11px;
218
+ margin-top: 1px;
219
+ flex: none;
220
+ }
221
+ .cf-msg {
222
+ flex: 1;
223
+ min-width: 0;
224
+ white-space: pre-wrap;
225
+ word-break: break-word;
226
+ }
227
+ .cf-msg > * {
228
+ margin-right: 0.7em;
229
+ }
230
+ .cf-str {
231
+ color: var(--str);
232
+ }
233
+ .cf-num {
234
+ color: var(--num);
235
+ }
236
+ .cf-bool {
237
+ color: var(--bool);
238
+ }
239
+ .cf-nul {
240
+ color: var(--nul);
241
+ }
242
+ .cf-fn {
243
+ color: var(--key);
244
+ font-style: italic;
245
+ }
246
+ .cf-k {
247
+ color: var(--key);
248
+ }
249
+ .cf-node {
250
+ display: inline-block;
251
+ vertical-align: top;
252
+ max-width: 100%;
253
+ }
254
+ .cf-t {
255
+ cursor: pointer;
256
+ }
257
+ .cf-t::before {
258
+ content: "\25B8";
259
+ display: inline-block;
260
+ width: 1em;
261
+ color: var(--dim);
262
+ transition: transform 0.12s;
263
+ }
264
+ .cf-t.open::before {
265
+ transform: rotate(90deg);
266
+ }
267
+ .cf-kids {
268
+ margin-left: 0.5em;
269
+ padding-left: 0.8em;
270
+ border-left: 1px solid var(--line);
271
+ }
272
+ .cf-kids > * {
273
+ display: block;
274
+ }
275
+ .cf-err {
276
+ display: block;
277
+ }
278
+ .cf-table {
279
+ border-collapse: collapse;
280
+ margin: 3px 0;
281
+ }
282
+ .cf-table th,
283
+ .cf-table td {
284
+ border: 1px solid var(--line);
285
+ padding: 1px 10px;
286
+ text-align: left;
287
+ }
288
+ .cf-table th {
289
+ background: var(--bar);
290
+ font-weight: 600;
291
+ }
292
+ .cf-prompt {
293
+ display: flex;
294
+ align-items: center;
295
+ gap: 8px;
296
+ padding: 5px 10px;
297
+ border-top: 1px solid var(--line);
298
+ background: var(--bar);
299
+ }
300
+ .cf-prompt span {
301
+ color: var(--key);
302
+ }
303
+ .cf-prompt input {
304
+ flex: 1;
305
+ font: inherit;
306
+ background: none;
307
+ border: 0;
308
+ color: var(--fg);
309
+ outline: 0;
310
+ }
package/src/index.js ADDED
@@ -0,0 +1,51 @@
1
+ import './index.css'
2
+ import van from "https://cdn.jsdelivr.net/npm/vanjs-core@1.5.3/src/van.js"
3
+ import {
4
+ ConsoleFeed,
5
+ Console
6
+ } from './components'
7
+ import { createFeed } from './feed/createFeed'
8
+ import { Hook } from './hook/index.js'
9
+
10
+ Object.assign(window, {ConsoleFeed: {Hook, createFeed, ConsoleFeed, Console}})
11
+
12
+ /* =====================================================================
13
+ Demo
14
+ ===================================================================== */
15
+
16
+ const theme = van.state("light")
17
+
18
+ // 1) Declarative: children only, or props first then children
19
+ document.body.append(
20
+ ConsoleFeed({variant: theme, repl: false},
21
+ Console.log("Hello from VanJS", 42, true, null, undefined),
22
+ Console.info("Server listening on :3000"),
23
+ Console.group("Request"),
24
+ Console.log("parsing"),
25
+ Console.warn("token expires soon"),
26
+ Console.groupEnd(),
27
+ Console.error(new Error("Something broke")),
28
+ Console.table([{id: 1, name: "Ada"}, {id: 2, name: "Linus"}]),
29
+ )
30
+ )
31
+
32
+ // 2) Standalone: a single row, no toolbar
33
+ document.body.append(Console.log("Just one line", {a: 1, b : 1}))
34
+ document.body.append(Console.warn("Standalone warning"))
35
+ document.body.append(Console.table([1,2,3]))
36
+
37
+
38
+ // 3) Live: hook the real console into a feed
39
+ Console.theme = theme
40
+ const feed = createFeed()
41
+ Hook(console, e => feed.push(e))
42
+ globalThis.c = ConsoleFeed({feed})
43
+ document.body.append(c)
44
+
45
+ console.log("Hello from VanJS", 42, true, null, undefined)
46
+ console.log({a: 1})
47
+ console.group("Request")
48
+ console.log("parsing")
49
+ console.group("Auth")
50
+ console.warn("token expires soon")
51
+ console.groupEnd()
package/src/main.js ADDED
File without changes
@@ -0,0 +1,20 @@
1
+ /* printf-style substitutions: %s %d %i %f %o %O %j %c %% */
2
+ export function fmt(args) {
3
+ const [f, ...rest] = args
4
+ if (typeof f !== "string" || !rest.length || !/%[sdifoOjc%]/.test(f)) return args
5
+ const s = f.replace(/%([sdifoOjc%])/g, (m, c) => {
6
+ if (c === "%") return "%"
7
+ if (!rest.length) return m
8
+ const a = rest.shift()
9
+ switch (c) {
10
+ case "s": return isObj(a) ? short(a) : String(a)
11
+ case "d": return String(Number(a))
12
+ case "i": return String(parseInt(a))
13
+ case "f": return String(parseFloat(a))
14
+ case "c": return ""
15
+ case "j": try { return JSON.stringify(a) } catch { return "[Circular]" }
16
+ default: return isObj(a) ? preview(a) : prim(a)
17
+ }
18
+ })
19
+ return [s, ...rest]
20
+ }
@@ -0,0 +1,2 @@
1
+ export * from './value-formatting.js'
2
+ export * from './fmt.js'
@@ -0,0 +1,37 @@
1
+ export const isObj = v => v !== null && typeof v === "object"
2
+ export const cname = v => { try { return Object.getPrototypeOf(v)?.constructor?.name || "" } catch { return "" } }
3
+ export const prim = v => typeof v === "string" ? JSON.stringify(v) : typeof v === "bigint" ? v + "n" : String(v)
4
+ export const primCls = v => v == null ? "nul" : typeof v === "string" ? "str" : typeof v === "boolean" ? "bool" : "num"
5
+ export const nodeLabel = n => n.nodeType === 1
6
+ ? `<${n.localName}${n.id ? "#" + n.id : ""}${n.classList.length ? "." + [...n.classList].join(".") : ""}>` : String(n)
7
+
8
+ export const label = v =>
9
+ Array.isArray(v) ? `Array(${v.length})` :
10
+ v instanceof Map ? `Map(${v.size})` :
11
+ v instanceof Set ? `Set(${v.size})` :
12
+ (n => n && n !== "Object" ? n : "")(cname(v))
13
+
14
+ export const short = v =>
15
+ typeof v === "function" ? `ƒ ${v.name || ""}()` :
16
+ !isObj(v) ? prim(v) :
17
+ v instanceof Date ? v.toISOString() :
18
+ v instanceof RegExp ? String(v) :
19
+ Array.isArray(v) ? label(v) : (label(v) || "Object") + " {…}"
20
+
21
+ export const entriesOf = v => {
22
+ try {
23
+ return Array.isArray(v) ? v.map((x, i) => [i, x])
24
+ : v instanceof Map ? [...v].map(([a, b]) => [short(a), b])
25
+ : v instanceof Set ? [...v].map((x, i) => [i, x])
26
+ : Object.keys(v).map(k => [k, v[k]])
27
+ } catch { return [] }
28
+ }
29
+
30
+ export const preview = v => {
31
+ const es = entriesOf(v), list = Array.isArray(v) || v instanceof Set
32
+ const body = es.slice(0, 5).map(([k, x]) => (list ? "" : k + ": ") + short(x)).join(", ") + (es.length > 5 ? ", …" : "")
33
+ const l = label(v)
34
+ return (l ? l + " " : "") + (list ? `[${body}]` : `{${body}}`)
35
+ }
36
+
37
+ export const safe = a => a instanceof Error ? a.message : isObj(a) ? preview(a) : typeof a === "function" ? short(a) : String(a)