@mytools-all/mytools-json 0.1.0 → 0.1.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,21 +1,25 @@
1
- # JSON 编辑器
2
-
3
- JSON 编辑器
4
-
5
- 版本:0.1.0;适用于 MyTools,不能作为独立网页调用宿主能力。
6
-
7
- ## 安装
8
-
9
- 在 MyTools 插件管理的 npm 安装入口输入 `@mytools-all/mytools-json@0.1.0`。也可以下载本仓库,在开发者页面选择“安装本地目录”。
10
-
11
- ## 开发
12
-
13
- 直接编辑本目录的 HTML、JavaScript 和样式,无需依赖宿主源码或其他插件仓库。修改后重新安装本地目录。运行 `npm test` 检查包内契约和逻辑。插件 API 规范见 [mytools](https://github.com/mytools-all/mytools/tree/main/docs)。
14
-
15
- ## 权限
16
-
17
- 声明的宿主能力:clipboard.write。目录和危险操作仍需用户授权。
18
-
19
- ## 许可
20
-
21
- 项目代码使用 MIT;随附的第三方代码遵循各自随附的许可证。
1
+ # JSON 编辑器
2
+
3
+ JSON 编辑器
4
+
5
+ 版本:0.1.0;适用于 MyTools,不能作为独立网页调用宿主能力。
6
+
7
+ ## 安装
8
+
9
+ 在 MyTools 插件管理的 npm 安装入口输入 `@mytools-all/mytools-json@0.1.0`。也可以下载本仓库,在开发者页面选择“安装本地目录”。
10
+
11
+ ## 开发
12
+
13
+ 直接编辑本目录的 HTML、JavaScript 和样式,无需依赖宿主源码或其他插件仓库。修改后重新安装本地目录。运行 `npm test` 检查包内契约和逻辑。插件 API 规范见 [mytools](https://github.com/mytools-all/mytools/tree/main/docs)。
14
+
15
+ ## 权限
16
+
17
+ 声明的宿主能力:clipboard.write。目录和危险操作仍需用户授权。
18
+
19
+ ## 许可
20
+
21
+ 项目代码使用 MIT;随附的第三方代码遵循各自随附的许可证。
22
+
23
+ ## MyTools 兼容范围
24
+
25
+ 版本 0.1.1 声明支持 MyTools >=0.2.0 <0.3.0(0.2.x 稳定版),插件 API 为 v1。主程序超出范围时应更新插件或使用受支持的主程序版本。旧版主程序可能不识别此声明,请先升级到提供兼容检查的 MyTools。
package/app.mjs CHANGED
@@ -1,146 +1,146 @@
1
- import {
2
- $,
3
- $$,
4
- action,
5
- copy,
6
- status,
7
- escapeHtml,
8
- debounce,
9
- } from "./common.mjs";
10
- import { jsonPath, toXml, toTypescript } from "./utils.mjs";
11
- import { load as yamlLoad } from "./yaml.mjs";
12
- let value = null,
13
- tree = true,
14
- output = "";
15
- function xmlValue(el) {
16
- const children = [...el.children];
17
- if (!children.length) return el.textContent;
18
- const result = {};
19
- for (const child of children) {
20
- const v = xmlValue(child);
21
- if (Object.hasOwn(result, child.tagName))
22
- result[child.tagName] = Array.isArray(result[child.tagName])
23
- ? [...result[child.tagName], v]
24
- : [result[child.tagName], v];
25
- else result[child.tagName] = v;
26
- }
27
- for (const a of el.attributes) result["@" + a.name] = a.value;
28
- return result;
29
- }
30
- function parse(text) {
31
- if (text.length > 1000000) throw Error("输入超过 1 MB,请缩小内容后重试");
32
- const trimmed = text.trim();
33
- if (!trimmed) throw Error("请输入内容");
34
- try {
35
- return JSON.parse(trimmed);
36
- } catch {}
37
- if (trimmed.startsWith("<")) {
38
- const xml = new DOMParser().parseFromString(trimmed, "application/xml");
39
- if (xml.querySelector("parsererror")) throw Error("XML 格式错误");
40
- return { [xml.documentElement.tagName]: xmlValue(xml.documentElement) };
41
- }
42
- if (/^[^\s=&]+=[\s\S]+/.test(trimmed) && !trimmed.includes("\n"))
43
- return Object.fromEntries(new URLSearchParams(trimmed.replace(/^\?/, "")));
44
- const result = yamlLoad(trimmed);
45
- if (!result || typeof result !== "object")
46
- throw Error("不是有效的 JSON / YAML 对象");
47
- return result;
48
- }
49
- function node(v, key, depth = 0) {
50
- if (depth > 40) return "<span>…</span>";
51
- if (v && typeof v === "object") {
52
- const entries = Object.entries(v);
53
- return (
54
- '<details open><summary><span class="key">' +
55
- escapeHtml(key) +
56
- "</span> <small>" +
57
- (Array.isArray(v) ? "Array" : "Object") +
58
- " · " +
59
- entries.length +
60
- '</small></summary><div class="tree-children">' +
61
- entries.map(([k, x]) => node(x, k, depth + 1)).join("") +
62
- "</div></details>"
63
- );
64
- }
65
- return (
66
- '<div><span class="key">' +
67
- escapeHtml(key) +
68
- ': </span><span class="' +
69
- (typeof v === "string" ? "string" : "") +
70
- '">' +
71
- escapeHtml(JSON.stringify(v)) +
72
- "</span></div>"
73
- );
74
- }
75
- function show() {
76
- output = JSON.stringify(value, null, 2);
77
- $("#output").innerHTML = tree
78
- ? node(value, "root")
79
- : "<pre>" + escapeHtml(output) + "</pre>";
80
- status("解析成功 · " + output.length + " 字符");
81
- }
82
- function update() {
83
- value = parse($("#source").value);
84
- show();
85
- }
86
- $("#format").onclick = action(() => {
87
- update();
88
- $("#source").value = JSON.stringify(value, null, 2);
89
- });
90
- $("#minify").onclick = action(() => {
91
- update();
92
- return copy(JSON.stringify(value));
93
- });
94
- $("#escape").onclick = action(() => {
95
- update();
96
- return copy(JSON.stringify(JSON.stringify(value)));
97
- });
98
- $("#xml").onclick = action(() => {
99
- update();
100
- return copy(toXml(value));
101
- });
102
- $("#types").onclick = action(() => {
103
- update();
104
- return copy(toTypescript(value));
105
- });
106
- $("#copy").onclick = action(() => copy(output));
107
- $("#tree").onclick = () => {
108
- tree = true;
109
- show();
110
- };
111
- $("#text").onclick = () => {
112
- tree = false;
113
- show();
114
- };
115
- $("#collapse").onclick = () =>
116
- $$("#output details").forEach((d) => (d.open = false));
117
- $("#expand").onclick = () =>
118
- $$("#output details").forEach((d) => (d.open = true));
119
- $("#apply").onclick = action(() => {
120
- value = jsonPath(parse($("#source").value), $("#filter").value);
121
- show();
122
- });
123
- $("#filter").onkeydown = (e) => {
124
- if (e.key === "Enter") $("#apply").click();
125
- };
126
- $("#source").oninput = debounce(action(update), 250);
127
- $("#sample").onclick = () => {
128
- $("#source").value = JSON.stringify(
129
- { users: [{ id: 1, name: "MyTools", active: true }], version: "1.1.0" },
130
- null,
131
- 2,
132
- );
133
- update();
134
- };
135
- $("#clear").onclick = () => {
136
- $("#source").value = "";
137
- $("#output").replaceChildren();
138
- output = "";
139
- status("");
140
- };
141
- $("#source").onkeydown = (e) => {
142
- if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
143
- e.preventDefault();
144
- $("#format").click();
145
- }
146
- };
1
+ import {
2
+ $,
3
+ $$,
4
+ action,
5
+ copy,
6
+ status,
7
+ escapeHtml,
8
+ debounce,
9
+ } from "./common.mjs";
10
+ import { jsonPath, toXml, toTypescript } from "./utils.mjs";
11
+ import { load as yamlLoad } from "./yaml.mjs";
12
+ let value = null,
13
+ tree = true,
14
+ output = "";
15
+ function xmlValue(el) {
16
+ const children = [...el.children];
17
+ if (!children.length) return el.textContent;
18
+ const result = {};
19
+ for (const child of children) {
20
+ const v = xmlValue(child);
21
+ if (Object.hasOwn(result, child.tagName))
22
+ result[child.tagName] = Array.isArray(result[child.tagName])
23
+ ? [...result[child.tagName], v]
24
+ : [result[child.tagName], v];
25
+ else result[child.tagName] = v;
26
+ }
27
+ for (const a of el.attributes) result["@" + a.name] = a.value;
28
+ return result;
29
+ }
30
+ function parse(text) {
31
+ if (text.length > 1000000) throw Error("输入超过 1 MB,请缩小内容后重试");
32
+ const trimmed = text.trim();
33
+ if (!trimmed) throw Error("请输入内容");
34
+ try {
35
+ return JSON.parse(trimmed);
36
+ } catch {}
37
+ if (trimmed.startsWith("<")) {
38
+ const xml = new DOMParser().parseFromString(trimmed, "application/xml");
39
+ if (xml.querySelector("parsererror")) throw Error("XML 格式错误");
40
+ return { [xml.documentElement.tagName]: xmlValue(xml.documentElement) };
41
+ }
42
+ if (/^[^\s=&]+=[\s\S]+/.test(trimmed) && !trimmed.includes("\n"))
43
+ return Object.fromEntries(new URLSearchParams(trimmed.replace(/^\?/, "")));
44
+ const result = yamlLoad(trimmed);
45
+ if (!result || typeof result !== "object")
46
+ throw Error("不是有效的 JSON / YAML 对象");
47
+ return result;
48
+ }
49
+ function node(v, key, depth = 0) {
50
+ if (depth > 40) return "<span>…</span>";
51
+ if (v && typeof v === "object") {
52
+ const entries = Object.entries(v);
53
+ return (
54
+ '<details open><summary><span class="key">' +
55
+ escapeHtml(key) +
56
+ "</span> <small>" +
57
+ (Array.isArray(v) ? "Array" : "Object") +
58
+ " · " +
59
+ entries.length +
60
+ '</small></summary><div class="tree-children">' +
61
+ entries.map(([k, x]) => node(x, k, depth + 1)).join("") +
62
+ "</div></details>"
63
+ );
64
+ }
65
+ return (
66
+ '<div><span class="key">' +
67
+ escapeHtml(key) +
68
+ ': </span><span class="' +
69
+ (typeof v === "string" ? "string" : "") +
70
+ '">' +
71
+ escapeHtml(JSON.stringify(v)) +
72
+ "</span></div>"
73
+ );
74
+ }
75
+ function show() {
76
+ output = JSON.stringify(value, null, 2);
77
+ $("#output").innerHTML = tree
78
+ ? node(value, "root")
79
+ : "<pre>" + escapeHtml(output) + "</pre>";
80
+ status("解析成功 · " + output.length + " 字符");
81
+ }
82
+ function update() {
83
+ value = parse($("#source").value);
84
+ show();
85
+ }
86
+ $("#format").onclick = action(() => {
87
+ update();
88
+ $("#source").value = JSON.stringify(value, null, 2);
89
+ });
90
+ $("#minify").onclick = action(() => {
91
+ update();
92
+ return copy(JSON.stringify(value));
93
+ });
94
+ $("#escape").onclick = action(() => {
95
+ update();
96
+ return copy(JSON.stringify(JSON.stringify(value)));
97
+ });
98
+ $("#xml").onclick = action(() => {
99
+ update();
100
+ return copy(toXml(value));
101
+ });
102
+ $("#types").onclick = action(() => {
103
+ update();
104
+ return copy(toTypescript(value));
105
+ });
106
+ $("#copy").onclick = action(() => copy(output));
107
+ $("#tree").onclick = () => {
108
+ tree = true;
109
+ show();
110
+ };
111
+ $("#text").onclick = () => {
112
+ tree = false;
113
+ show();
114
+ };
115
+ $("#collapse").onclick = () =>
116
+ $$("#output details").forEach((d) => (d.open = false));
117
+ $("#expand").onclick = () =>
118
+ $$("#output details").forEach((d) => (d.open = true));
119
+ $("#apply").onclick = action(() => {
120
+ value = jsonPath(parse($("#source").value), $("#filter").value);
121
+ show();
122
+ });
123
+ $("#filter").onkeydown = (e) => {
124
+ if (e.key === "Enter") $("#apply").click();
125
+ };
126
+ $("#source").oninput = debounce(action(update), 250);
127
+ $("#sample").onclick = () => {
128
+ $("#source").value = JSON.stringify(
129
+ { users: [{ id: 1, name: "MyTools", active: true }], version: "1.1.0" },
130
+ null,
131
+ 2,
132
+ );
133
+ update();
134
+ };
135
+ $("#clear").onclick = () => {
136
+ $("#source").value = "";
137
+ $("#output").replaceChildren();
138
+ output = "";
139
+ status("");
140
+ };
141
+ $("#source").onkeydown = (e) => {
142
+ if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
143
+ e.preventDefault();
144
+ $("#format").click();
145
+ }
146
+ };
package/common.mjs CHANGED
@@ -1,69 +1,69 @@
1
- export const $ = (selector) => document.querySelector(selector);
2
- export const $$ = (selector) => [...document.querySelectorAll(selector)];
3
- export function status(text, error = false) {
4
- const el = $("#status");
5
- if (el) {
6
- el.textContent = text;
7
- el.dataset.error = String(error);
8
- }
9
- }
10
- export function action(fn) {
11
- return async (...args) => {
12
- try {
13
- return await fn(...args);
14
- } catch (e) {
15
- status(e.message || String(e), true);
16
- }
17
- };
18
- }
19
- export async function call(id, args = {}) {
20
- if (!window.mytools) throw Error("请从 MyTools 打开此工具");
21
- return window.mytools.call(id, args);
22
- }
23
- export const copy = async (text) => {
24
- await call("clipboard.write", { text: String(text) });
25
- status("已复制到剪贴板");
26
- };
27
- export function ready(fn) {
28
- if (window.mytools) window.mytools.onPluginReady(action(fn));
29
- else status("预览模式:系统能力需从 MyTools 使用");
30
- }
31
- export const escapeHtml = (text) =>
32
- String(text).replace(
33
- /[&<>"']/g,
34
- (c) =>
35
- ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
36
- c
37
- ],
38
- );
39
- export function download(name, text, type = "text/plain") {
40
- const url = URL.createObjectURL(new Blob([text], { type }));
41
- const a = document.createElement("a");
42
- a.href = url;
43
- a.download = name;
44
- a.click();
45
- setTimeout(() => URL.revokeObjectURL(url), 1000);
46
- }
47
- export function debounce(fn, ms = 200) {
48
- let timer;
49
- return (...args) => {
50
- clearTimeout(timer);
51
- timer = setTimeout(() => fn(...args), ms);
52
- };
53
- }
54
- export const formatBytes = (n) =>
55
- n < 1024
56
- ? n + " B"
57
- : n < 1048576
58
- ? (n / 1024).toFixed(1) + " KB"
59
- : (n / 1048576).toFixed(1) + " MB";
60
- const savedTheme = localStorage.getItem("tool-theme");
61
- document.documentElement.dataset.theme =
62
- savedTheme ||
63
- (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
64
- $("#theme")?.addEventListener("click", () => {
65
- const theme =
66
- document.documentElement.dataset.theme === "dark" ? "light" : "dark";
67
- document.documentElement.dataset.theme = theme;
68
- localStorage.setItem("tool-theme", theme);
69
- });
1
+ export const $ = (selector) => document.querySelector(selector);
2
+ export const $$ = (selector) => [...document.querySelectorAll(selector)];
3
+ export function status(text, error = false) {
4
+ const el = $("#status");
5
+ if (el) {
6
+ el.textContent = text;
7
+ el.dataset.error = String(error);
8
+ }
9
+ }
10
+ export function action(fn) {
11
+ return async (...args) => {
12
+ try {
13
+ return await fn(...args);
14
+ } catch (e) {
15
+ status(e.message || String(e), true);
16
+ }
17
+ };
18
+ }
19
+ export async function call(id, args = {}) {
20
+ if (!window.mytools) throw Error("请从 MyTools 打开此工具");
21
+ return window.mytools.call(id, args);
22
+ }
23
+ export const copy = async (text) => {
24
+ await call("clipboard.write", { text: String(text) });
25
+ status("已复制到剪贴板");
26
+ };
27
+ export function ready(fn) {
28
+ if (window.mytools) window.mytools.onPluginReady(action(fn));
29
+ else status("预览模式:系统能力需从 MyTools 使用");
30
+ }
31
+ export const escapeHtml = (text) =>
32
+ String(text).replace(
33
+ /[&<>"']/g,
34
+ (c) =>
35
+ ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
36
+ c
37
+ ],
38
+ );
39
+ export function download(name, text, type = "text/plain") {
40
+ const url = URL.createObjectURL(new Blob([text], { type }));
41
+ const a = document.createElement("a");
42
+ a.href = url;
43
+ a.download = name;
44
+ a.click();
45
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
46
+ }
47
+ export function debounce(fn, ms = 200) {
48
+ let timer;
49
+ return (...args) => {
50
+ clearTimeout(timer);
51
+ timer = setTimeout(() => fn(...args), ms);
52
+ };
53
+ }
54
+ export const formatBytes = (n) =>
55
+ n < 1024
56
+ ? n + " B"
57
+ : n < 1048576
58
+ ? (n / 1024).toFixed(1) + " KB"
59
+ : (n / 1048576).toFixed(1) + " MB";
60
+ const savedTheme = localStorage.getItem("tool-theme");
61
+ document.documentElement.dataset.theme =
62
+ savedTheme ||
63
+ (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
64
+ $("#theme")?.addEventListener("click", () => {
65
+ const theme =
66
+ document.documentElement.dataset.theme === "dark" ? "light" : "dark";
67
+ document.documentElement.dataset.theme = theme;
68
+ localStorage.setItem("tool-theme", theme);
69
+ });
package/index.html CHANGED
@@ -1,68 +1,68 @@
1
- <!doctype html>
2
- <html lang="zh-CN">
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width,initial-scale=1" />
6
- <title>JSON 编辑器</title>
7
- <link rel="stylesheet" href="tool.css" />
8
- <style>
9
- #output {
10
- font-family: Consolas, monospace;
11
- }
12
- .key {
13
- color: var(--accent);
14
- }
15
- .string {
16
- color: #389d71;
17
- }
18
- .tree-children {
19
- margin-left: 18px;
20
- }
21
- summary small {
22
- font-size: 11px;
23
- }
24
- </style>
25
- </head>
26
- <body>
27
- <main>
28
- <div class="toolbar">
29
- <strong>JSON 编辑器</strong
30
- ><button id="format" class="primary">格式化</button
31
- ><button id="minify">压缩复制</button
32
- ><button id="escape">转义复制</button><button id="xml">转 XML</button
33
- ><button id="types">转 TypeScript</button><span class="spacer"></span
34
- ><button id="sample">示例</button><button id="clear">清空</button
35
- ><button id="theme">◐</button>
36
- </div>
37
- <div class="split">
38
- <textarea
39
- id="source"
40
- class="editor"
41
- placeholder="粘贴 JSON、URL Params、XML 或 YAML…"
42
- spellcheck="false"
43
- aria-label="JSON 输入"
44
- ></textarea>
45
- <section style="display: flex; flex-direction: column">
46
- <div class="toolbar">
47
- <button id="tree">树视图</button><button id="text">文本</button
48
- ><button id="collapse">折叠</button><button id="expand">展开</button
49
- ><span class="spacer"></span><button id="copy">复制结果</button>
50
- </div>
51
- <div class="content" id="output"></div>
52
- </section>
53
- </div>
54
- <div class="toolbar">
55
- <label
56
- >过滤
57
- <input
58
- id="filter"
59
- placeholder="$.users.*.name"
60
- style="width: 240px" /></label
61
- ><button id="apply">应用</button
62
- ><span class="muted">路径过滤支持 .、[索引]、*;不执行 JavaScript</span>
63
- </div>
64
- <footer id="status" class="status" role="status"></footer>
65
- </main>
66
- <script type="module" src="app.mjs"></script>
67
- </body>
68
- </html>
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
6
+ <title>JSON 编辑器</title>
7
+ <link rel="stylesheet" href="tool.css" />
8
+ <style>
9
+ #output {
10
+ font-family: Consolas, monospace;
11
+ }
12
+ .key {
13
+ color: var(--accent);
14
+ }
15
+ .string {
16
+ color: #389d71;
17
+ }
18
+ .tree-children {
19
+ margin-left: 18px;
20
+ }
21
+ summary small {
22
+ font-size: 11px;
23
+ }
24
+ </style>
25
+ </head>
26
+ <body>
27
+ <main>
28
+ <div class="toolbar">
29
+ <strong>JSON 编辑器</strong
30
+ ><button id="format" class="primary">格式化</button
31
+ ><button id="minify">压缩复制</button
32
+ ><button id="escape">转义复制</button><button id="xml">转 XML</button
33
+ ><button id="types">转 TypeScript</button><span class="spacer"></span
34
+ ><button id="sample">示例</button><button id="clear">清空</button
35
+ ><button id="theme">◐</button>
36
+ </div>
37
+ <div class="split">
38
+ <textarea
39
+ id="source"
40
+ class="editor"
41
+ placeholder="粘贴 JSON、URL Params、XML 或 YAML…"
42
+ spellcheck="false"
43
+ aria-label="JSON 输入"
44
+ ></textarea>
45
+ <section style="display: flex; flex-direction: column">
46
+ <div class="toolbar">
47
+ <button id="tree">树视图</button><button id="text">文本</button
48
+ ><button id="collapse">折叠</button><button id="expand">展开</button
49
+ ><span class="spacer"></span><button id="copy">复制结果</button>
50
+ </div>
51
+ <div class="content" id="output"></div>
52
+ </section>
53
+ </div>
54
+ <div class="toolbar">
55
+ <label
56
+ >过滤
57
+ <input
58
+ id="filter"
59
+ placeholder="$.users.*.name"
60
+ style="width: 240px" /></label
61
+ ><button id="apply">应用</button
62
+ ><span class="muted">路径过滤支持 .、[索引]、*;不执行 JavaScript</span>
63
+ </div>
64
+ <footer id="status" class="status" role="status"></footer>
65
+ </main>
66
+ <script type="module" src="app.mjs"></script>
67
+ </body>
68
+ </html>