@iquji-community/web-editor 0.0.0-stage → 0.2.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/dist/text.js ADDED
@@ -0,0 +1,451 @@
1
+ // src/editor-layout.tsx
2
+ import { jsx, jsxs } from "react/jsx-runtime";
3
+ function IqujiEditorLayout({
4
+ toolbar,
5
+ footer,
6
+ children,
7
+ className,
8
+ ...props
9
+ }) {
10
+ return /* @__PURE__ */ jsxs("div", {
11
+ ...props,
12
+ className: ["iquji-editor", className].filter(Boolean).join(" "),
13
+ children: [
14
+ toolbar && /* @__PURE__ */ jsx("div", {
15
+ className: "iquji-editor-toolbar",
16
+ children: toolbar
17
+ }),
18
+ /* @__PURE__ */ jsx("div", {
19
+ className: "iquji-editor-body",
20
+ children
21
+ }),
22
+ footer && /* @__PURE__ */ jsx("div", {
23
+ className: "iquji-editor-footer",
24
+ children: footer
25
+ })
26
+ ]
27
+ });
28
+ }
29
+ // src/editor-viewport.tsx
30
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
31
+ function IqujiEditorViewport({
32
+ toolbar,
33
+ overlay,
34
+ footer,
35
+ zoom = 100,
36
+ scrollRef,
37
+ onBodyInteract,
38
+ classes = {},
39
+ children,
40
+ className,
41
+ ...props
42
+ }) {
43
+ return /* @__PURE__ */ jsxs2("div", {
44
+ ...props,
45
+ className: ["iquji-editor-workspace", classes.workspace, className].filter(Boolean).join(" "),
46
+ children: [
47
+ toolbar,
48
+ /* @__PURE__ */ jsxs2("div", {
49
+ className: ["iquji-editor-viewport", classes.viewport].filter(Boolean).join(" "),
50
+ children: [
51
+ overlay,
52
+ /* @__PURE__ */ jsx2("div", {
53
+ className: ["iquji-editor-scroll", classes.scroll].filter(Boolean).join(" "),
54
+ ref: scrollRef,
55
+ onPointerDown: (event) => onBodyInteract?.(event.target),
56
+ onFocusCapture: (event) => onBodyInteract?.(event.target),
57
+ children: /* @__PURE__ */ jsx2("div", {
58
+ className: ["iquji-editor-page", classes.page].filter(Boolean).join(" "),
59
+ style: { zoom: zoom / 100 },
60
+ children
61
+ })
62
+ }),
63
+ footer && /* @__PURE__ */ jsx2("div", {
64
+ className: ["iquji-editor-footer", classes.footer].filter(Boolean).join(" "),
65
+ children: footer
66
+ })
67
+ ]
68
+ })
69
+ ]
70
+ });
71
+ }
72
+ // src/presets.ts
73
+ import { json, jsonParseLinter } from "@codemirror/lang-json";
74
+ import { markdown } from "@codemirror/lang-markdown";
75
+ import { yaml } from "@codemirror/lang-yaml";
76
+ import { StreamLanguage as StreamLanguage2 } from "@codemirror/language";
77
+ import { toml as tomlMode } from "@codemirror/legacy-modes/mode/toml";
78
+ import { linter } from "@codemirror/lint";
79
+ import { TomlError, parse } from "smol-toml";
80
+ import { parseDocument } from "yaml";
81
+
82
+ // src/shell.ts
83
+ import { HighlightStyle, LRLanguage, StreamLanguage, syntaxHighlighting } from "@codemirror/language";
84
+ import { shell } from "@codemirror/legacy-modes/mode/shell";
85
+ import { parser } from "@fig/lezer-bash";
86
+ import { parseMixed } from "@lezer/common";
87
+ import { styleTags, tags } from "@lezer/highlight";
88
+ var quotedShell = StreamLanguage.define(shell);
89
+ var language = LRLanguage.define({
90
+ name: "shell",
91
+ parser: parser.configure({
92
+ props: [styleTags({ "CommandName/Literal": tags.function(tags.name) })],
93
+ wrap: parseMixed((node) => node.name === "String" ? { parser: quotedShell.parser } : null)
94
+ }),
95
+ languageData: { commentTokens: { line: "#" } }
96
+ });
97
+ var colors = HighlightStyle.define([
98
+ { tag: tags.name, color: "var(--iquji-color-info-text)" },
99
+ { tag: tags.keyword, color: "var(--iquji-color-accent-strong)", fontWeight: "600" },
100
+ { tag: tags.variableName, color: "var(--iquji-color-warning-text)" },
101
+ { tag: tags.string, color: "var(--iquji-color-positive-text)" },
102
+ { tag: tags.comment, color: "var(--iquji-color-muted)", fontStyle: "italic" },
103
+ { tag: [tags.operator, tags.separator, tags.bracket], color: "var(--iquji-color-accent-strong)" }
104
+ ]);
105
+ var shellExtensions = [language, syntaxHighlighting(colors)];
106
+
107
+ // src/presets.ts
108
+ var IQUJI_EDITOR_PRESETS = [
109
+ "richText",
110
+ "markdown",
111
+ "json",
112
+ "yaml",
113
+ "toml",
114
+ "shell",
115
+ "text"
116
+ ];
117
+ var IQUJI_FORMATTABLE_PRESETS = ["json", "yaml"];
118
+ function isFormattablePreset(preset) {
119
+ return IQUJI_FORMATTABLE_PRESETS.includes(preset);
120
+ }
121
+ function textPresetExtensions(preset) {
122
+ if (preset === "shell")
123
+ return shellExtensions;
124
+ if (preset === "markdown")
125
+ return [markdown()];
126
+ if (preset === "json")
127
+ return [json(), linter(jsonParseLinter())];
128
+ if (preset === "yaml")
129
+ return [
130
+ yaml(),
131
+ linter((view) => yamlDiagnostics(view.state.doc.toString()))
132
+ ];
133
+ if (preset === "toml")
134
+ return [
135
+ StreamLanguage2.define(tomlMode),
136
+ linter((view) => tomlDiagnostics(view.state.doc.toString()))
137
+ ];
138
+ return [];
139
+ }
140
+ function yamlDiagnostics(value) {
141
+ return parseDocument(value, { uniqueKeys: true }).errors.map((error) => ({
142
+ from: Math.min(error.pos[0], value.length),
143
+ to: Math.min(Math.max(error.pos[1], error.pos[0] + 1), value.length),
144
+ severity: "error",
145
+ message: error.message
146
+ }));
147
+ }
148
+ function tomlDiagnostics(value) {
149
+ if (value.trim() === "")
150
+ return [];
151
+ try {
152
+ parse(value);
153
+ return [];
154
+ } catch (error) {
155
+ if (!(error instanceof TomlError))
156
+ throw error;
157
+ const from = offsetOfLineColumn(value, error.line, error.column);
158
+ return [
159
+ {
160
+ from,
161
+ to: Math.min(from + 1, value.length),
162
+ severity: "error",
163
+ message: error.message.split(`
164
+ `)[0]?.trim() || "TOML 语法错误"
165
+ }
166
+ ];
167
+ }
168
+ }
169
+ function offsetOfLineColumn(value, line, column) {
170
+ let offset = 0;
171
+ for (let index = 1;index < line; index += 1) {
172
+ const next = value.indexOf(`
173
+ `, offset);
174
+ if (next < 0)
175
+ return Math.min(offset, value.length);
176
+ offset = next + 1;
177
+ }
178
+ return Math.min(offset + Math.max(column - 1, 0), value.length);
179
+ }
180
+ function formatEditorText(preset, value) {
181
+ if (preset === "json")
182
+ return `${JSON.stringify(JSON.parse(value), null, 2)}
183
+ `;
184
+ if (preset === "yaml") {
185
+ const document = parseDocument(value, { uniqueKeys: true });
186
+ if (document.errors.length)
187
+ throw new Error(document.errors[0]?.message);
188
+ return document.toString();
189
+ }
190
+ return value;
191
+ }
192
+ // src/text-editor.tsx
193
+ import {
194
+ defaultKeymap,
195
+ history,
196
+ historyKeymap,
197
+ indentWithTab
198
+ } from "@codemirror/commands";
199
+ import {
200
+ bracketMatching,
201
+ defaultHighlightStyle,
202
+ indentOnInput,
203
+ syntaxHighlighting as syntaxHighlighting2
204
+ } from "@codemirror/language";
205
+ import { lintGutter } from "@codemirror/lint";
206
+ import { highlightSelectionMatches, searchKeymap } from "@codemirror/search";
207
+ import {
208
+ Annotation,
209
+ Compartment,
210
+ EditorState,
211
+ Transaction
212
+ } from "@codemirror/state";
213
+ import {
214
+ drawSelection,
215
+ EditorView,
216
+ highlightActiveLine,
217
+ keymap,
218
+ lineNumbers
219
+ } from "@codemirror/view";
220
+ import { IqujiButton } from "@iquji-community/web-component";
221
+ import { useEffect, useMemo, useRef, useState } from "react";
222
+
223
+ // src/markdown.ts
224
+ import DOMPurify from "dompurify";
225
+ import { marked, Renderer } from "marked";
226
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (character) => ({
227
+ "&": "&amp;",
228
+ "<": "&lt;",
229
+ ">": "&gt;",
230
+ '"': "&quot;",
231
+ "'": "&#39;"
232
+ })[character] ?? character);
233
+ function renderEditorMarkdown(value) {
234
+ const renderer = new Renderer;
235
+ renderer.html = ({ text }) => escapeHtml(text);
236
+ renderer.image = ({ text }) => escapeHtml(text);
237
+ renderer.link = ({ href, tokens }) => {
238
+ const label = renderer.parser.parseInline(tokens);
239
+ if (!/^(https?:\/\/|mailto:|#)/i.test(href) || [...href].some((character) => character.charCodeAt(0) <= 32))
240
+ return label;
241
+ return `<a href="${escapeHtml(href)}" rel="noopener noreferrer">${label}</a>`;
242
+ };
243
+ const html = marked.parse(value, { async: false, gfm: true, renderer });
244
+ return DOMPurify.sanitize(html, {
245
+ USE_PROFILES: { html: true },
246
+ FORBID_TAGS: [
247
+ "img",
248
+ "iframe",
249
+ "object",
250
+ "embed",
251
+ "style",
252
+ "input",
253
+ "form",
254
+ "video",
255
+ "audio"
256
+ ],
257
+ FORBID_ATTR: ["style", "src", "srcset"]
258
+ });
259
+ }
260
+
261
+ // src/text-editor.tsx
262
+ import { jsx as jsx3, jsxs as jsxs3, Fragment } from "react/jsx-runtime";
263
+ var externalUpdate = Annotation.define();
264
+ var editorAttributes = (label, documentKey) => EditorView.contentAttributes.of({
265
+ "aria-label": label,
266
+ spellcheck: "false",
267
+ "data-document-key": documentKey ?? ""
268
+ });
269
+ function IqujiTextEditor(props) {
270
+ const { preset, value, documentKey, readOnly = false, labels } = props;
271
+ const host = useRef(null);
272
+ const editor = useRef(null);
273
+ const current = useRef(props);
274
+ current.current = props;
275
+ const editable = useRef(new Compartment);
276
+ const contentAttributes = useRef(new Compartment);
277
+ const [preview, setPreview] = useState(false);
278
+ const [error, setError] = useState(false);
279
+ useEffect(() => {
280
+ if (!host.current)
281
+ return;
282
+ setPreview(false);
283
+ setError(false);
284
+ const notifySelection = (view2) => {
285
+ const range = view2.state.selection.main;
286
+ current.current.onSelectionChange?.({
287
+ from: range.from,
288
+ to: range.to,
289
+ text: view2.state.sliceDoc(range.from, range.to),
290
+ document: view2.state.doc.toString()
291
+ });
292
+ };
293
+ const view = new EditorView({
294
+ parent: host.current,
295
+ state: EditorState.create({
296
+ doc: current.current.value,
297
+ extensions: [
298
+ lineNumbers(),
299
+ history(),
300
+ drawSelection(),
301
+ highlightActiveLine(),
302
+ indentOnInput(),
303
+ bracketMatching(),
304
+ highlightSelectionMatches(),
305
+ syntaxHighlighting2(defaultHighlightStyle, { fallback: true }),
306
+ lintGutter(),
307
+ EditorView.lineWrapping,
308
+ contentAttributes.current.of(editorAttributes(current.current.ariaLabel, documentKey)),
309
+ keymap.of([
310
+ ...defaultKeymap,
311
+ ...historyKeymap,
312
+ ...searchKeymap,
313
+ indentWithTab
314
+ ]),
315
+ editable.current.of([
316
+ EditorState.readOnly.of(Boolean(current.current.readOnly)),
317
+ EditorView.editable.of(!current.current.readOnly)
318
+ ]),
319
+ ...textPresetExtensions(preset),
320
+ EditorView.updateListener.of((update) => {
321
+ if (update.docChanged) {
322
+ setError(false);
323
+ if (!update.transactions.some((transaction) => transaction.annotation(externalUpdate)))
324
+ current.current.onChange(update.state.doc.toString());
325
+ }
326
+ if (update.docChanged || update.selectionSet)
327
+ notifySelection(update.view);
328
+ })
329
+ ]
330
+ })
331
+ });
332
+ editor.current = view;
333
+ current.current.onReady?.(view);
334
+ notifySelection(view);
335
+ return () => {
336
+ current.current.onReady?.(null);
337
+ editor.current = null;
338
+ view.destroy();
339
+ };
340
+ }, [preset, documentKey]);
341
+ useEffect(() => {
342
+ editor.current?.dispatch({
343
+ effects: contentAttributes.current.reconfigure(editorAttributes(props.ariaLabel, documentKey))
344
+ });
345
+ }, [props.ariaLabel, documentKey]);
346
+ useEffect(() => {
347
+ const view = editor.current;
348
+ if (!view || view.state.doc.toString() === value)
349
+ return;
350
+ view.dispatch({
351
+ changes: { from: 0, to: view.state.doc.length, insert: value },
352
+ selection: {
353
+ anchor: Math.min(view.state.selection.main.anchor, value.length),
354
+ head: Math.min(view.state.selection.main.head, value.length)
355
+ },
356
+ annotations: [
357
+ Transaction.addToHistory.of(false),
358
+ externalUpdate.of(true)
359
+ ]
360
+ });
361
+ }, [value]);
362
+ useEffect(() => {
363
+ editor.current?.dispatch({
364
+ effects: editable.current.reconfigure([
365
+ EditorState.readOnly.of(readOnly),
366
+ EditorView.editable.of(!readOnly)
367
+ ])
368
+ });
369
+ }, [readOnly]);
370
+ const html = useMemo(() => preset === "markdown" && preview ? renderEditorMarkdown(value) : "", [preset, preview, value]);
371
+ const format = () => {
372
+ if (readOnly || !editor.current)
373
+ return;
374
+ try {
375
+ const view = editor.current;
376
+ const next = formatEditorText(preset, view.state.doc.toString());
377
+ view.dispatch({
378
+ changes: { from: 0, to: view.state.doc.length, insert: next }
379
+ });
380
+ view.focus();
381
+ } catch {
382
+ setError(true);
383
+ }
384
+ };
385
+ const showMarkdownModes = preset === "markdown";
386
+ const showFormat = !readOnly && isFormattablePreset(preset);
387
+ const toolbar = showMarkdownModes || showFormat ? /* @__PURE__ */ jsxs3(Fragment, {
388
+ children: [
389
+ showMarkdownModes && /* @__PURE__ */ jsxs3("fieldset", {
390
+ className: "iquji-editor-modes",
391
+ "aria-label": props.ariaLabel,
392
+ children: [
393
+ /* @__PURE__ */ jsx3(IqujiButton, {
394
+ compact: true,
395
+ variant: "ghost",
396
+ "aria-pressed": !preview,
397
+ onClick: () => setPreview(false),
398
+ children: labels.edit
399
+ }),
400
+ /* @__PURE__ */ jsx3(IqujiButton, {
401
+ compact: true,
402
+ variant: "ghost",
403
+ "aria-pressed": preview,
404
+ onClick: () => setPreview(true),
405
+ children: labels.preview
406
+ })
407
+ ]
408
+ }),
409
+ showFormat && /* @__PURE__ */ jsx3(IqujiButton, {
410
+ compact: true,
411
+ variant: "ghost",
412
+ onClick: format,
413
+ children: labels.format
414
+ })
415
+ ]
416
+ }) : undefined;
417
+ return /* @__PURE__ */ jsxs3(IqujiEditorLayout, {
418
+ className: props.className,
419
+ footer: props.footer,
420
+ toolbar,
421
+ children: [
422
+ error && /* @__PURE__ */ jsx3("p", {
423
+ role: "status",
424
+ className: "iquji-editor-error",
425
+ children: labels.invalid
426
+ }),
427
+ /* @__PURE__ */ jsx3("div", {
428
+ className: "iquji-text-editor",
429
+ ref: host,
430
+ hidden: preview
431
+ }),
432
+ preview && /* @__PURE__ */ jsx3("article", {
433
+ className: "iquji-editor-preview",
434
+ "aria-label": labels.preview,
435
+ dangerouslySetInnerHTML: { __html: html }
436
+ })
437
+ ]
438
+ });
439
+ }
440
+ export {
441
+ yamlDiagnostics,
442
+ tomlDiagnostics,
443
+ textPresetExtensions,
444
+ isFormattablePreset,
445
+ formatEditorText,
446
+ IqujiTextEditor,
447
+ IqujiEditorViewport,
448
+ IqujiEditorLayout,
449
+ IQUJI_FORMATTABLE_PRESETS,
450
+ IQUJI_EDITOR_PRESETS
451
+ };
package/package.json CHANGED
@@ -1,6 +1,78 @@
1
1
  {
2
2
  "name": "@iquji-community/web-editor",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "author": {
4
+ "name": "IQuji Community",
5
+ "email": "community@iqu.lol"
6
+ },
7
+ "version": "0.2.0",
8
+ "license": "MIT",
9
+ "type": "module",
10
+ "files": [
11
+ "dist",
12
+ "README.md",
13
+ "README.zh-CN.md",
14
+ "LICENSE"
15
+ ],
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js"
20
+ },
21
+ "./text": {
22
+ "types": "./dist/text.d.ts",
23
+ "import": "./dist/text.js"
24
+ },
25
+ "./styles.css": "./dist/styles.css"
26
+ },
27
+ "sideEffects": [
28
+ "./dist/styles.css"
29
+ ],
30
+ "peerDependencies": {
31
+ "@base-ui/react": "1.3.0",
32
+ "react": "19.2.4",
33
+ "@tiptap/core": "2.27.2",
34
+ "@tiptap/react": "2.27.2",
35
+ "@tiptap/pm": "2.27.2",
36
+ "react-dom": "19.2.4"
37
+ },
38
+ "dependencies": {
39
+ "@codemirror/commands": "6.11.1",
40
+ "@codemirror/lang-json": "6.0.2",
41
+ "@codemirror/lang-markdown": "6.5.2",
42
+ "@codemirror/lang-yaml": "6.1.3",
43
+ "@codemirror/language": "6.13.1",
44
+ "@codemirror/legacy-modes": "6.5.5",
45
+ "@codemirror/lint": "6.9.7",
46
+ "@codemirror/search": "6.7.2",
47
+ "@codemirror/state": "6.7.6",
48
+ "@codemirror/view": "6.43.15",
49
+ "@fig/lezer-bash": "1.2.5",
50
+ "@iquji-community/web-component": "0.2.0",
51
+ "@iquji-community/web-icons": "0.2.0",
52
+ "@iquji-community/web-theme": "0.2.0",
53
+ "@lezer/common": "1.5.4",
54
+ "@lezer/highlight": "1.2.5",
55
+ "@lezer/lr": "1.4.11",
56
+ "@tiptap/extension-text-align": "2.27.2",
57
+ "@tiptap/extension-underline": "2.27.2",
58
+ "@tiptap/starter-kit": "2.27.2",
59
+ "dompurify": "3.4.17",
60
+ "marked": "18.1.1",
61
+ "smol-toml": "1.9.1",
62
+ "yaml": "2.9.1"
63
+ },
64
+ "description": "可装配富文本与源码编辑器。",
65
+ "publishConfig": {
66
+ "access": "public",
67
+ "registry": "https://registry.npmjs.org/"
68
+ },
69
+ "repository": {
70
+ "type": "git",
71
+ "url": "git+https://github.com/haydardsx/iquji-community-web.git",
72
+ "directory": "editor"
73
+ },
74
+ "homepage": "https://haydardsx.github.io/iquji-community-web/",
75
+ "bugs": {
76
+ "url": "https://github.com/haydardsx/iquji-community-web/issues"
77
+ }
78
+ }