@iquji-community/web-editor 0.0.0-stage → 0.2.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/dist/index.js ADDED
@@ -0,0 +1,1053 @@
1
+ // src/colors.ts
2
+ var EDITOR_HIGHLIGHT_COLORS = [
3
+ "yellow",
4
+ "green",
5
+ "blue",
6
+ "purple",
7
+ "pink"
8
+ ];
9
+ var EDITOR_HIGHLIGHT_PALETTE = {
10
+ yellow: "#fef08a",
11
+ green: "#bbf7d0",
12
+ blue: "#bfdbfe",
13
+ purple: "#ddd6fe",
14
+ pink: "#fbcfe8"
15
+ };
16
+ var EDITOR_TEXT_PALETTE = [
17
+ "#171717",
18
+ "#525252",
19
+ "#b91c1c",
20
+ "#c2410c",
21
+ "#a16207",
22
+ "#15803d",
23
+ "#0e7490",
24
+ "#1d4ed8",
25
+ "#7e22ce",
26
+ "#be185d"
27
+ ];
28
+ var isEditorColor = (value) => typeof value === "string" && /^#[0-9a-f]{6}$/u.test(value);
29
+ var isEditorHighlightColor = (value) => isEditorColor(value) || EDITOR_HIGHLIGHT_COLORS.includes(value);
30
+ var editorHighlightCss = (value) => isEditorColor(value) ? value : EDITOR_HIGHLIGHT_PALETTE[value];
31
+ // src/editor-color-control.tsx
32
+ import {
33
+ IqujiColorPicker
34
+ } from "@iquji-community/web-component";
35
+ import { useEditorState } from "@tiptap/react";
36
+ import { useEffect, useRef } from "react";
37
+ import { jsx } from "react/jsx-runtime";
38
+ function IqujiEditorColorControl({
39
+ editor,
40
+ kind,
41
+ disabled = false,
42
+ selectionOnly = false,
43
+ trigger,
44
+ labels,
45
+ colorLabel
46
+ }) {
47
+ const captured = useRef(null);
48
+ const open = useRef(false);
49
+ const changed = useRef(false);
50
+ const returnFocus = useRef(false);
51
+ const state = useEditorState({
52
+ editor,
53
+ selector: ({ editor: value }) => ({
54
+ color: value?.getAttributes(kind).color,
55
+ allowed: Boolean(value?.isEditable && (!selectionOnly || !value.state.selection.empty) && value.can().setMark(kind, {
56
+ color: kind === "highlight" ? "yellow" : "#171717"
57
+ }))
58
+ })
59
+ });
60
+ const color = kind === "highlight" && isEditorHighlightColor(state?.color) ? editorHighlightCss(state.color) : isEditorColor(state?.color) ? state.color : null;
61
+ const blocked = disabled || !state?.allowed;
62
+ useEffect(() => () => {
63
+ if (editor && !editor.isDestroyed)
64
+ editor.view.dom.removeAttribute("data-editor-color-menu-open");
65
+ }, [editor]);
66
+ return /* @__PURE__ */ jsx(IqujiColorPicker, {
67
+ ...labels,
68
+ value: color,
69
+ disabled: blocked,
70
+ trigger,
71
+ presets: kind === "highlight" ? EDITOR_HIGHLIGHT_COLORS.map((name) => ({
72
+ value: EDITOR_HIGHLIGHT_PALETTE[name],
73
+ label: colorLabel(name)
74
+ })) : EDITOR_TEXT_PALETTE.map((value) => ({
75
+ value,
76
+ label: colorLabel(value)
77
+ })),
78
+ onOpenChange: (next, reason) => {
79
+ returnFocus.current = !next && ["selection", "cancel", "escape-key", "trigger-press"].includes(reason);
80
+ open.current = next;
81
+ if (!editor || editor.isDestroyed)
82
+ return;
83
+ if (next) {
84
+ changed.current = false;
85
+ captured.current = { editor, state: editor.state };
86
+ editor.view.dom.setAttribute("data-editor-color-menu-open", "");
87
+ } else
88
+ editor.view.dom.removeAttribute("data-editor-color-menu-open");
89
+ },
90
+ finalFocus: () => {
91
+ if (open.current || !returnFocus.current || !editor || editor.isDestroyed || !editor.isEditable || captured.current?.editor !== editor)
92
+ return false;
93
+ if (changed.current || captured.current.state.doc.eq(editor.state.doc)) {
94
+ editor.view.focus();
95
+ return editor.view.dom;
96
+ }
97
+ return false;
98
+ },
99
+ onChange: (value) => {
100
+ const original = captured.current;
101
+ if (!open.current || !editor || editor.isDestroyed || !editor.isEditable || blocked || original?.editor !== editor || !original.state.doc.eq(editor.state.doc) || !original.state.selection.eq(editor.state.selection))
102
+ return;
103
+ editor.view.focus();
104
+ if (!original.state.doc.eq(editor.state.doc) || !original.state.selection.eq(editor.state.selection))
105
+ return;
106
+ const selection = original.state.selection.getBookmark().resolve(editor.state.doc);
107
+ editor.view.dispatch(editor.state.tr.setSelection(selection));
108
+ const chain = editor.chain();
109
+ if (value === null)
110
+ chain.unsetMark(kind).run();
111
+ else {
112
+ const name = kind === "highlight" ? EDITOR_HIGHLIGHT_COLORS.find((entry) => EDITOR_HIGHLIGHT_PALETTE[entry] === value) : undefined;
113
+ chain.setMark(kind, { color: name ?? value }).run();
114
+ }
115
+ changed.current = true;
116
+ }
117
+ });
118
+ }
119
+ // src/editor-layout.tsx
120
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
121
+ function IqujiEditorLayout({
122
+ toolbar,
123
+ footer,
124
+ children,
125
+ className,
126
+ ...props
127
+ }) {
128
+ return /* @__PURE__ */ jsxs("div", {
129
+ ...props,
130
+ className: ["iquji-editor", className].filter(Boolean).join(" "),
131
+ children: [
132
+ toolbar && /* @__PURE__ */ jsx2("div", {
133
+ className: "iquji-editor-toolbar",
134
+ children: toolbar
135
+ }),
136
+ /* @__PURE__ */ jsx2("div", {
137
+ className: "iquji-editor-body",
138
+ children
139
+ }),
140
+ footer && /* @__PURE__ */ jsx2("div", {
141
+ className: "iquji-editor-footer",
142
+ children: footer
143
+ })
144
+ ]
145
+ });
146
+ }
147
+ // src/editor-viewport.tsx
148
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
149
+ function IqujiEditorViewport({
150
+ toolbar,
151
+ overlay,
152
+ footer,
153
+ zoom = 100,
154
+ scrollRef,
155
+ onBodyInteract,
156
+ classes = {},
157
+ children,
158
+ className,
159
+ ...props
160
+ }) {
161
+ return /* @__PURE__ */ jsxs2("div", {
162
+ ...props,
163
+ className: ["iquji-editor-workspace", classes.workspace, className].filter(Boolean).join(" "),
164
+ children: [
165
+ toolbar,
166
+ /* @__PURE__ */ jsxs2("div", {
167
+ className: ["iquji-editor-viewport", classes.viewport].filter(Boolean).join(" "),
168
+ children: [
169
+ overlay,
170
+ /* @__PURE__ */ jsx3("div", {
171
+ className: ["iquji-editor-scroll", classes.scroll].filter(Boolean).join(" "),
172
+ ref: scrollRef,
173
+ onPointerDown: (event) => onBodyInteract?.(event.target),
174
+ onFocusCapture: (event) => onBodyInteract?.(event.target),
175
+ children: /* @__PURE__ */ jsx3("div", {
176
+ className: ["iquji-editor-page", classes.page].filter(Boolean).join(" "),
177
+ style: { zoom: zoom / 100 },
178
+ children
179
+ })
180
+ }),
181
+ footer && /* @__PURE__ */ jsx3("div", {
182
+ className: ["iquji-editor-footer", classes.footer].filter(Boolean).join(" "),
183
+ children: footer
184
+ })
185
+ ]
186
+ })
187
+ ]
188
+ });
189
+ }
190
+ // src/markdown.ts
191
+ import DOMPurify from "dompurify";
192
+ import { marked, Renderer } from "marked";
193
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (character) => ({
194
+ "&": "&amp;",
195
+ "<": "&lt;",
196
+ ">": "&gt;",
197
+ '"': "&quot;",
198
+ "'": "&#39;"
199
+ })[character] ?? character);
200
+ function renderEditorMarkdown(value) {
201
+ const renderer = new Renderer;
202
+ renderer.html = ({ text }) => escapeHtml(text);
203
+ renderer.image = ({ text }) => escapeHtml(text);
204
+ renderer.link = ({ href, tokens }) => {
205
+ const label = renderer.parser.parseInline(tokens);
206
+ if (!/^(https?:\/\/|mailto:|#)/i.test(href) || [...href].some((character) => character.charCodeAt(0) <= 32))
207
+ return label;
208
+ return `<a href="${escapeHtml(href)}" rel="noopener noreferrer">${label}</a>`;
209
+ };
210
+ const html = marked.parse(value, { async: false, gfm: true, renderer });
211
+ return DOMPurify.sanitize(html, {
212
+ USE_PROFILES: { html: true },
213
+ FORBID_TAGS: [
214
+ "img",
215
+ "iframe",
216
+ "object",
217
+ "embed",
218
+ "style",
219
+ "input",
220
+ "form",
221
+ "video",
222
+ "audio"
223
+ ],
224
+ FORBID_ATTR: ["style", "src", "srcset"]
225
+ });
226
+ }
227
+ // src/presets.ts
228
+ import { json, jsonParseLinter } from "@codemirror/lang-json";
229
+ import { markdown } from "@codemirror/lang-markdown";
230
+ import { yaml } from "@codemirror/lang-yaml";
231
+ import { StreamLanguage as StreamLanguage2 } from "@codemirror/language";
232
+ import { toml as tomlMode } from "@codemirror/legacy-modes/mode/toml";
233
+ import { linter } from "@codemirror/lint";
234
+ import { TomlError, parse } from "smol-toml";
235
+ import { parseDocument } from "yaml";
236
+
237
+ // src/shell.ts
238
+ import { HighlightStyle, LRLanguage, StreamLanguage, syntaxHighlighting } from "@codemirror/language";
239
+ import { shell } from "@codemirror/legacy-modes/mode/shell";
240
+ import { parser } from "@fig/lezer-bash";
241
+ import { parseMixed } from "@lezer/common";
242
+ import { styleTags, tags } from "@lezer/highlight";
243
+ var quotedShell = StreamLanguage.define(shell);
244
+ var language = LRLanguage.define({
245
+ name: "shell",
246
+ parser: parser.configure({
247
+ props: [styleTags({ "CommandName/Literal": tags.function(tags.name) })],
248
+ wrap: parseMixed((node) => node.name === "String" ? { parser: quotedShell.parser } : null)
249
+ }),
250
+ languageData: { commentTokens: { line: "#" } }
251
+ });
252
+ var colors = HighlightStyle.define([
253
+ { tag: tags.name, color: "var(--iquji-color-info-text)" },
254
+ { tag: tags.keyword, color: "var(--iquji-color-accent-strong)", fontWeight: "600" },
255
+ { tag: tags.variableName, color: "var(--iquji-color-warning-text)" },
256
+ { tag: tags.string, color: "var(--iquji-color-positive-text)" },
257
+ { tag: tags.comment, color: "var(--iquji-color-muted)", fontStyle: "italic" },
258
+ { tag: [tags.operator, tags.separator, tags.bracket], color: "var(--iquji-color-accent-strong)" }
259
+ ]);
260
+ var shellExtensions = [language, syntaxHighlighting(colors)];
261
+
262
+ // src/presets.ts
263
+ var IQUJI_EDITOR_PRESETS = [
264
+ "richText",
265
+ "markdown",
266
+ "json",
267
+ "yaml",
268
+ "toml",
269
+ "shell",
270
+ "text"
271
+ ];
272
+ var IQUJI_FORMATTABLE_PRESETS = ["json", "yaml"];
273
+ function isFormattablePreset(preset) {
274
+ return IQUJI_FORMATTABLE_PRESETS.includes(preset);
275
+ }
276
+ function textPresetExtensions(preset) {
277
+ if (preset === "shell")
278
+ return shellExtensions;
279
+ if (preset === "markdown")
280
+ return [markdown()];
281
+ if (preset === "json")
282
+ return [json(), linter(jsonParseLinter())];
283
+ if (preset === "yaml")
284
+ return [
285
+ yaml(),
286
+ linter((view) => yamlDiagnostics(view.state.doc.toString()))
287
+ ];
288
+ if (preset === "toml")
289
+ return [
290
+ StreamLanguage2.define(tomlMode),
291
+ linter((view) => tomlDiagnostics(view.state.doc.toString()))
292
+ ];
293
+ return [];
294
+ }
295
+ function yamlDiagnostics(value) {
296
+ return parseDocument(value, { uniqueKeys: true }).errors.map((error) => ({
297
+ from: Math.min(error.pos[0], value.length),
298
+ to: Math.min(Math.max(error.pos[1], error.pos[0] + 1), value.length),
299
+ severity: "error",
300
+ message: error.message
301
+ }));
302
+ }
303
+ function tomlDiagnostics(value) {
304
+ if (value.trim() === "")
305
+ return [];
306
+ try {
307
+ parse(value);
308
+ return [];
309
+ } catch (error) {
310
+ if (!(error instanceof TomlError))
311
+ throw error;
312
+ const from = offsetOfLineColumn(value, error.line, error.column);
313
+ return [
314
+ {
315
+ from,
316
+ to: Math.min(from + 1, value.length),
317
+ severity: "error",
318
+ message: error.message.split(`
319
+ `)[0]?.trim() || "TOML 语法错误"
320
+ }
321
+ ];
322
+ }
323
+ }
324
+ function offsetOfLineColumn(value, line, column) {
325
+ let offset = 0;
326
+ for (let index = 1;index < line; index += 1) {
327
+ const next = value.indexOf(`
328
+ `, offset);
329
+ if (next < 0)
330
+ return Math.min(offset, value.length);
331
+ offset = next + 1;
332
+ }
333
+ return Math.min(offset + Math.max(column - 1, 0), value.length);
334
+ }
335
+ function formatEditorText(preset, value) {
336
+ if (preset === "json")
337
+ return `${JSON.stringify(JSON.parse(value), null, 2)}
338
+ `;
339
+ if (preset === "yaml") {
340
+ const document = parseDocument(value, { uniqueKeys: true });
341
+ if (document.errors.length)
342
+ throw new Error(document.errors[0]?.message);
343
+ return document.toString();
344
+ }
345
+ return value;
346
+ }
347
+ // src/rich-text-colors.ts
348
+ import { Mark, mergeAttributes } from "@tiptap/core";
349
+ import { Plugin } from "@tiptap/pm/state";
350
+ var colorGuard = (kind, valid) => new Plugin({
351
+ filterTransaction: (transaction) => {
352
+ if (!transaction.docChanged && !transaction.storedMarksSet)
353
+ return true;
354
+ let accepted = true;
355
+ const check = (marks) => {
356
+ if (marks.some((mark) => mark.type.name === kind && !valid(mark.attrs.color)))
357
+ accepted = false;
358
+ };
359
+ transaction.doc.descendants((node) => check(node.marks));
360
+ check(transaction.storedMarks ?? []);
361
+ return accepted;
362
+ }
363
+ });
364
+ var EditorHighlight = Mark.create({
365
+ name: "highlight",
366
+ addAttributes() {
367
+ return {
368
+ color: {
369
+ default: null,
370
+ parseHTML: (node) => node.getAttribute("data-editor-highlight")
371
+ }
372
+ };
373
+ },
374
+ parseHTML() {
375
+ return [
376
+ {
377
+ tag: "mark",
378
+ getAttrs: (node) => {
379
+ const color = node.getAttribute("data-editor-highlight");
380
+ return color === null || isEditorHighlightColor(color) ? { color } : false;
381
+ }
382
+ }
383
+ ];
384
+ },
385
+ renderHTML({ HTMLAttributes }) {
386
+ const color = HTMLAttributes.color;
387
+ const attrs = isEditorHighlightColor(color) ? {
388
+ "data-editor-highlight": color,
389
+ style: isEditorColor(color) ? `background-color: ${editorHighlightCss(color)}` : undefined
390
+ } : {};
391
+ return ["mark", attrs, 0];
392
+ },
393
+ addCommands() {
394
+ return {
395
+ setHighlight: (attrs) => ({ commands }) => attrs?.color !== undefined && !isEditorHighlightColor(attrs.color) ? false : commands.setMark(this.name, { color: attrs?.color ?? null }),
396
+ toggleHighlight: (attrs) => ({ commands }) => attrs?.color !== undefined && !isEditorHighlightColor(attrs.color) ? false : commands.toggleMark(this.name, { color: attrs?.color ?? null }),
397
+ unsetHighlight: () => ({ commands }) => commands.unsetMark(this.name)
398
+ };
399
+ },
400
+ addProseMirrorPlugins() {
401
+ return [
402
+ colorGuard(this.name, (value) => value === null || isEditorHighlightColor(value))
403
+ ];
404
+ }
405
+ });
406
+ var EditorTextColor = Mark.create({
407
+ name: "textColor",
408
+ addAttributes() {
409
+ return { color: { default: null } };
410
+ },
411
+ parseHTML() {
412
+ return [
413
+ {
414
+ tag: "span[data-editor-color]",
415
+ getAttrs: (node) => {
416
+ const color = node.getAttribute("data-editor-color");
417
+ return isEditorColor(color) ? { color } : false;
418
+ }
419
+ }
420
+ ];
421
+ },
422
+ renderHTML({ HTMLAttributes }) {
423
+ const color = HTMLAttributes.color;
424
+ return [
425
+ "span",
426
+ mergeAttributes(isEditorColor(color) ? {
427
+ "data-editor-color": color,
428
+ style: `color: ${color}`
429
+ } : {}),
430
+ 0
431
+ ];
432
+ },
433
+ addCommands() {
434
+ return {
435
+ setTextColor: (color) => ({ commands }) => isEditorColor(color) && commands.setMark(this.name, { color }),
436
+ unsetTextColor: () => ({ commands }) => commands.unsetMark(this.name)
437
+ };
438
+ },
439
+ addProseMirrorPlugins() {
440
+ return [colorGuard(this.name, isEditorColor)];
441
+ }
442
+ });
443
+ // src/rich-text-content.tsx
444
+ import { PureEditorContent } from "@tiptap/react";
445
+ import { useMemo } from "react";
446
+ import { jsx as jsx4 } from "react/jsx-runtime";
447
+
448
+ class MountedEditorContent extends PureEditorContent {
449
+ mounted = false;
450
+ pending = false;
451
+ componentDidMount() {
452
+ this.mounted = true;
453
+ this.scheduleInitialization();
454
+ }
455
+ componentDidUpdate() {
456
+ this.scheduleInitialization();
457
+ }
458
+ componentWillUnmount() {
459
+ this.mounted = false;
460
+ super.componentWillUnmount();
461
+ }
462
+ scheduleInitialization() {
463
+ if (this.pending)
464
+ return;
465
+ this.pending = true;
466
+ queueMicrotask(() => {
467
+ this.pending = false;
468
+ if (!this.mounted)
469
+ return;
470
+ const initialized = this.initialized;
471
+ this.init();
472
+ if (!initialized && this.initialized)
473
+ this.forceUpdate();
474
+ });
475
+ }
476
+ }
477
+ function IqujiRichTextContent(props) {
478
+ const key = useMemo(() => crypto.randomUUID(), [props.editor]);
479
+ return /* @__PURE__ */ jsx4(MountedEditorContent, {
480
+ ...props
481
+ }, key);
482
+ }
483
+ // src/rich-text-editor.tsx
484
+ import { useEditor } from "@tiptap/react";
485
+ import { useEffect as useEffect2, useRef as useRef2 } from "react";
486
+ import { jsx as jsx5 } from "react/jsx-runtime";
487
+ function useIqujiRichTextEditor({
488
+ assembly,
489
+ ...options
490
+ }) {
491
+ return useEditor({
492
+ ...options,
493
+ extensions: assembly.extensions,
494
+ immediatelyRender: false
495
+ });
496
+ }
497
+ function IqujiRichTextEditor(props) {
498
+ const current = useRef2(props);
499
+ current.current = props;
500
+ const editor = useIqujiRichTextEditor({
501
+ assembly: props.assembly,
502
+ content: props.value,
503
+ editable: !props.readOnly,
504
+ editorProps: {
505
+ attributes: { "aria-label": props.ariaLabel, class: "iquji-rich-editor" }
506
+ },
507
+ onUpdate: ({ editor: value }) => current.current.onChange(current.current.assembly.serialize?.(value.getJSON()) ?? value.getJSON())
508
+ });
509
+ useEffect2(() => {
510
+ current.current.onReady?.(editor);
511
+ return () => current.current.onReady?.(null);
512
+ }, [editor]);
513
+ useEffect2(() => {
514
+ if (!editor || editor.isDestroyed || JSON.stringify(editor.getJSON()) === JSON.stringify(props.value))
515
+ return;
516
+ editor.commands.setContent(props.value, false);
517
+ }, [editor, props.value]);
518
+ useEffect2(() => {
519
+ editor?.setEditable(!props.readOnly, false);
520
+ }, [editor, props.readOnly]);
521
+ return /* @__PURE__ */ jsx5(IqujiEditorLayout, {
522
+ toolbar: typeof props.toolbar === "function" ? props.toolbar(editor) : props.toolbar,
523
+ footer: props.footer,
524
+ children: /* @__PURE__ */ jsx5(IqujiRichTextContent, {
525
+ editor
526
+ })
527
+ });
528
+ }
529
+ // src/rich-text-preset.ts
530
+ import TextAlign from "@tiptap/extension-text-align";
531
+ import Underline from "@tiptap/extension-underline";
532
+ import StarterKit from "@tiptap/starter-kit";
533
+ function createRichTextPreset(extensions = []) {
534
+ return {
535
+ extensions: [
536
+ StarterKit.configure({ heading: { levels: [1, 2, 3] } }),
537
+ Underline,
538
+ EditorHighlight,
539
+ EditorTextColor,
540
+ TextAlign.configure({
541
+ types: ["heading", "paragraph"],
542
+ defaultAlignment: null
543
+ }),
544
+ ...extensions
545
+ ]
546
+ };
547
+ }
548
+ // src/rich-text-toolbar.tsx
549
+ import {
550
+ IconButton,
551
+ IqujiButton,
552
+ IqujiSelect
553
+ } from "@iquji-community/web-component";
554
+ import { useEditorState as useEditorState2 } from "@tiptap/react";
555
+
556
+ // src/editor-format-icon.tsx
557
+ import { jsx as jsx6 } from "react/jsx-runtime";
558
+ var paths = {
559
+ bold: "M6 4h7a4 4 0 0 1 0 8H6V4Zm0 8h8a4 4 0 0 1 0 8H6v-8Z",
560
+ italic: "M10 4h9M5 20h9M15 4 9 20",
561
+ underline: "M6 3v7a6 6 0 0 0 12 0V3M4 21h16",
562
+ strike: "M18 6c-1-2-3-3-6-3-4 0-6 2-6 5 0 2 2 3 6 4m-6 6c1 2 3 3 6 3 4 0 6-2 6-5 0-1-1-2-2-3M3 12h18",
563
+ code: "m8 6-6 6 6 6m8-12 6 6-6 6m-3-14-2 16",
564
+ highlight: "m9 11 6-6 5 5-6 6-5-5Zm0 0-3 3 4 4 3-3M6 14l-3 7 7-3M14 4l1-1 6 6-1 1M3 22h8",
565
+ link: "m9 15 6-6m-4-3 2-2a5 5 0 0 1 7 7l-3 3a5 5 0 0 1-7 0m3 4-2 2a5 5 0 0 1-7-7l3-3a5 5 0 0 1 7 0",
566
+ image: "M3 3h18v18H3V3Zm0 13 5-5 4 4 3-3 6 6M16 7h.01",
567
+ divider: "M3 12h18M8 5h8M8 19h8",
568
+ table: "M3 3h18v18H3V3Zm0 6h18M3 15h18M9 3v18M15 3v18",
569
+ blockquote: "M10 5H4v8h6V5Zm0 8c0 4-2 6-5 7M21 5h-6v8h6V5Zm0 8c0 4-2 6-5 7",
570
+ bulletList: "M9 5h12M9 12h12M9 19h12M3 5h.01M3 12h.01M3 19h.01",
571
+ orderedList: "M9 5h12M9 12h12M9 19h12M2 3h1v5M2 8h2M2 12c3-2 3 1 1 2l-1 2h3M2 19h2l-1 1c3 0 2 3-1 2",
572
+ taskList: "M9 5h12M9 12h12M9 19h12M2 4l2 2 3-3M2 11l2 2 3-3M2 18l2 2 3-3",
573
+ formatBrush: "M3 3h14v7H3V3Zm14 3h4v8H10v4M8 18h4v4H8v-4Z",
574
+ find: "M16 10a6 6 0 1 1-12 0 6 6 0 0 1 12 0Zm-2 4 7 7",
575
+ attachment: "m9 17 9-9a3 3 0 0 0-4-4L4 14a5 5 0 0 0 7 7L21 11M7 15l9-9",
576
+ indent: "M3 4h18M3 20h18M12 9h9M12 15h9m-18-7 4 4-4 4M7 12H2",
577
+ outdent: "M3 4h18M3 20h18M12 9h9M12 15h9m-14-7-4 4 4 4M3 12h5",
578
+ clearFormatting: "M4 4h14M11 4l-3 12m5 1 5-5 5 5-5 5h-3l-4-4 2-1Zm0 0 5 5M2 21h7",
579
+ undo: "M8 4 3 9l5 5M3 9h10a7 7 0 0 1 7 7v4",
580
+ redo: "m16 4 5 5-5 5m5-5H11a7 7 0 0 0-7 7v4",
581
+ minus: "M4 12h16",
582
+ plus: "M4 12h16M12 4v16",
583
+ "chevron-down": "m6 9 6 6 6-6"
584
+ };
585
+ function EditorFormatIcon({ name }) {
586
+ let shape;
587
+ if (name === "left" || name === "center" || name === "right" || name === "justify") {
588
+ const shortStart = name === "right" ? 9 : name === "center" ? 6 : 3;
589
+ const shortEnd = name === "left" ? 15 : name === "center" ? 18 : 21;
590
+ shape = /* @__PURE__ */ jsx6("path", {
591
+ d: `M3 4h18M3 14h18M${shortStart} 9h${shortEnd - shortStart}M${shortStart} 19h${shortEnd - shortStart}`
592
+ });
593
+ } else
594
+ shape = /* @__PURE__ */ jsx6("path", {
595
+ d: paths[name]
596
+ });
597
+ return /* @__PURE__ */ jsx6("svg", {
598
+ width: "15",
599
+ height: "15",
600
+ viewBox: "0 0 24 24",
601
+ fill: "none",
602
+ stroke: "currentColor",
603
+ strokeWidth: "1.8",
604
+ strokeLinecap: "round",
605
+ strokeLinejoin: "round",
606
+ "aria-hidden": "true",
607
+ focusable: "false",
608
+ children: shape
609
+ });
610
+ }
611
+
612
+ // src/rich-text-toolbar.tsx
613
+ import { jsx as jsx7, jsxs as jsxs3, Fragment } from "react/jsx-runtime";
614
+ var EDITOR_ALIGNMENT_TOOLS = {
615
+ left: "alignLeft",
616
+ center: "alignCenter",
617
+ right: "alignRight",
618
+ justify: "alignJustify"
619
+ };
620
+ var textFormats = ["bold", "italic", "underline", "strike"];
621
+ function IqujiRichTextToolbar({
622
+ editor,
623
+ disabled,
624
+ t,
625
+ zoom,
626
+ onZoom,
627
+ actions,
628
+ tools,
629
+ slots = {},
630
+ canClear = false,
631
+ onClear,
632
+ insertAvailable = false,
633
+ className
634
+ }) {
635
+ const has = (tool) => tools.includes(tool);
636
+ const any = (...features) => features.some(has);
637
+ const selection = useEditorState2({
638
+ editor,
639
+ selector: ({ editor: current }) => ({
640
+ heading: [1, 2, 3].find((level) => current?.isActive("heading", { level })) ?? 0,
641
+ marks: textFormats.map((name) => ({
642
+ active: current?.isActive(name),
643
+ allowed: current?.can().toggleMark(name) ?? false
644
+ })),
645
+ alignment: ["left", "center", "right", "justify"].filter((textAlign) => current?.isActive({
646
+ textAlign: textAlign === "left" ? null : textAlign
647
+ })),
648
+ canAlign: current?.can().setTextAlign("center") ?? false,
649
+ bulletList: current?.isActive("bulletList"),
650
+ canBulletList: current?.can().toggleBulletList() ?? false,
651
+ canOrderedList: current?.can().toggleOrderedList() ?? false,
652
+ canClear,
653
+ orderedList: current?.isActive("orderedList"),
654
+ table: current?.isActive("table"),
655
+ undo: current?.can().undo() ?? false,
656
+ redo: current?.can().redo() ?? false
657
+ })
658
+ });
659
+ const command = (tool, label, icon, run, active, blocked = false) => has(tool) ? /* @__PURE__ */ jsx7(IconButton, {
660
+ compact: true,
661
+ variant: "ghost",
662
+ label: t(label),
663
+ icon,
664
+ "aria-pressed": active,
665
+ disabled: disabled || !editor?.isEditable || blocked,
666
+ onClick: () => {
667
+ if (!disabled && editor?.isEditable && !editor.isDestroyed && !blocked)
668
+ run();
669
+ }
670
+ }, tool) : null;
671
+ const group = (name, children, view = false) => /* @__PURE__ */ jsx7("fieldset", {
672
+ className: `iquji-editor-tool-group${view ? " iquji-editor-view-tools" : ""}`,
673
+ "aria-label": t(name),
674
+ children
675
+ }, name);
676
+ const textGroups = [
677
+ has("textStyle") && group("toolbarStyles", /* @__PURE__ */ jsx7(IqujiSelect, {
678
+ compact: true,
679
+ "aria-label": t("textStyle"),
680
+ disabled: disabled || !editor?.isEditable,
681
+ value: String(selection?.heading ?? 0),
682
+ options: [0, 1, 2, 3].map((level) => ({
683
+ value: String(level),
684
+ label: t(level ? `heading${level}` : "paragraph")
685
+ })),
686
+ onValueChange: (value) => {
687
+ if (!value || disabled || !editor?.isEditable || editor.isDestroyed)
688
+ return;
689
+ if (value === "0")
690
+ editor.chain().focus().setParagraph().run();
691
+ else
692
+ editor.chain().focus().setHeading({ level: Number(value) }).run();
693
+ }
694
+ })),
695
+ any(...textFormats, "highlight", "textColor", "formatBrush", "clearFormatting") && group("toolbarMarks", /* @__PURE__ */ jsxs3(Fragment, {
696
+ children: [
697
+ textFormats.map((name, index) => command(name, name, /* @__PURE__ */ jsx7(EditorFormatIcon, {
698
+ name
699
+ }), () => {
700
+ editor?.chain().focus().toggleMark(name).run();
701
+ }, selection?.marks[index]?.active, !selection?.marks[index]?.allowed)),
702
+ slots.marks,
703
+ command("clearFormatting", "clearFormatting", /* @__PURE__ */ jsx7(EditorFormatIcon, {
704
+ name: "clearFormatting"
705
+ }), () => {
706
+ onClear?.();
707
+ }, undefined, !selection?.canClear)
708
+ ]
709
+ })),
710
+ any("undo", "redo", "findReplace") && group("toolbarHistory", /* @__PURE__ */ jsxs3(Fragment, {
711
+ children: [
712
+ command("undo", "undo", /* @__PURE__ */ jsx7(EditorFormatIcon, {
713
+ name: "undo"
714
+ }), () => {
715
+ editor?.chain().focus().undo().run();
716
+ }, undefined, !selection?.undo),
717
+ command("redo", "redo", /* @__PURE__ */ jsx7(EditorFormatIcon, {
718
+ name: "redo"
719
+ }), () => {
720
+ editor?.chain().focus().redo().run();
721
+ }, undefined, !selection?.redo),
722
+ slots.history
723
+ ]
724
+ }))
725
+ ].filter(Boolean);
726
+ const documentGroups = [
727
+ any("bulletList", "orderedList", "taskList", "indent") && group("toolbarParagraph", /* @__PURE__ */ jsxs3(Fragment, {
728
+ children: [
729
+ command("bulletList", "bulletList", /* @__PURE__ */ jsx7(EditorFormatIcon, {
730
+ name: "bulletList"
731
+ }), () => {
732
+ editor?.chain().focus().toggleBulletList().run();
733
+ }, selection?.bulletList, !selection?.canBulletList),
734
+ command("orderedList", "orderedList", /* @__PURE__ */ jsx7(EditorFormatIcon, {
735
+ name: "orderedList"
736
+ }), () => {
737
+ editor?.chain().focus().toggleOrderedList().run();
738
+ }, selection?.orderedList, !selection?.canOrderedList),
739
+ slots.paragraph
740
+ ]
741
+ })),
742
+ any(...Object.values(EDITOR_ALIGNMENT_TOOLS), "lineHeight") && group("toolbarAlignment", /* @__PURE__ */ jsxs3(Fragment, {
743
+ children: [
744
+ ["left", "center", "right", "justify"].map((alignment) => command(EDITOR_ALIGNMENT_TOOLS[alignment], `align.${alignment}`, /* @__PURE__ */ jsx7(EditorFormatIcon, {
745
+ name: alignment
746
+ }), () => {
747
+ if (alignment === "left")
748
+ editor?.chain().focus().unsetTextAlign().run();
749
+ else
750
+ editor?.chain().focus().setTextAlign(alignment).run();
751
+ }, selection?.alignment.includes(alignment), !selection?.canAlign)),
752
+ slots.spacing
753
+ ]
754
+ })),
755
+ (insertAvailable || has("tableEditing") && selection?.table || has("customActions") && actions) && group("toolbarInsert", /* @__PURE__ */ jsxs3(Fragment, {
756
+ children: [
757
+ slots.insert,
758
+ has("customActions") && actions
759
+ ]
760
+ })),
761
+ has("zoom") && group("toolbarView", /* @__PURE__ */ jsxs3(Fragment, {
762
+ children: [
763
+ /* @__PURE__ */ jsx7(IconButton, {
764
+ compact: true,
765
+ variant: "ghost",
766
+ label: t("zoomOut"),
767
+ icon: /* @__PURE__ */ jsx7(EditorFormatIcon, {
768
+ name: "minus"
769
+ }),
770
+ disabled: zoom <= 75,
771
+ onClick: () => onZoom(zoom - 25)
772
+ }),
773
+ /* @__PURE__ */ jsxs3(IqujiButton, {
774
+ compact: true,
775
+ variant: "ghost",
776
+ type: "button",
777
+ className: "iquji-editor-zoom",
778
+ title: t("resetZoom"),
779
+ onClick: () => onZoom(100),
780
+ children: [
781
+ zoom,
782
+ "%"
783
+ ]
784
+ }),
785
+ /* @__PURE__ */ jsx7(IconButton, {
786
+ compact: true,
787
+ variant: "ghost",
788
+ label: t("zoomIn"),
789
+ icon: /* @__PURE__ */ jsx7(EditorFormatIcon, {
790
+ name: "plus"
791
+ }),
792
+ disabled: zoom >= 150,
793
+ onClick: () => onZoom(zoom + 25)
794
+ })
795
+ ]
796
+ }), true)
797
+ ].filter(Boolean);
798
+ if (!textGroups.length && !documentGroups.length)
799
+ return null;
800
+ return /* @__PURE__ */ jsxs3("div", {
801
+ className: ["iquji-editor-format-toolbar", className].filter(Boolean).join(" "),
802
+ role: "toolbar",
803
+ "aria-label": t("toolbar"),
804
+ children: [
805
+ textGroups.length > 0 && /* @__PURE__ */ jsx7("fieldset", {
806
+ className: "iquji-editor-tool-row",
807
+ "aria-label": t("toolbarText"),
808
+ children: textGroups
809
+ }),
810
+ documentGroups.length > 0 && /* @__PURE__ */ jsx7("fieldset", {
811
+ className: "iquji-editor-tool-row",
812
+ "aria-label": t("toolbarDocument"),
813
+ children: documentGroups
814
+ })
815
+ ]
816
+ });
817
+ }
818
+ // src/text-editor.tsx
819
+ import {
820
+ defaultKeymap,
821
+ history,
822
+ historyKeymap,
823
+ indentWithTab
824
+ } from "@codemirror/commands";
825
+ import {
826
+ bracketMatching,
827
+ defaultHighlightStyle,
828
+ indentOnInput,
829
+ syntaxHighlighting as syntaxHighlighting2
830
+ } from "@codemirror/language";
831
+ import { lintGutter } from "@codemirror/lint";
832
+ import { highlightSelectionMatches, searchKeymap } from "@codemirror/search";
833
+ import {
834
+ Annotation,
835
+ Compartment,
836
+ EditorState,
837
+ Transaction
838
+ } from "@codemirror/state";
839
+ import {
840
+ drawSelection,
841
+ EditorView,
842
+ highlightActiveLine,
843
+ keymap,
844
+ lineNumbers
845
+ } from "@codemirror/view";
846
+ import { IqujiButton as IqujiButton2 } from "@iquji-community/web-component";
847
+ import { useEffect as useEffect3, useMemo as useMemo2, useRef as useRef3, useState } from "react";
848
+ import { jsx as jsx8, jsxs as jsxs4, Fragment as Fragment2 } from "react/jsx-runtime";
849
+ var externalUpdate = Annotation.define();
850
+ var editorAttributes = (label, documentKey) => EditorView.contentAttributes.of({
851
+ "aria-label": label,
852
+ spellcheck: "false",
853
+ "data-document-key": documentKey ?? ""
854
+ });
855
+ function IqujiTextEditor(props) {
856
+ const { preset, value, documentKey, readOnly = false, labels } = props;
857
+ const host = useRef3(null);
858
+ const editor = useRef3(null);
859
+ const current = useRef3(props);
860
+ current.current = props;
861
+ const editable = useRef3(new Compartment);
862
+ const contentAttributes = useRef3(new Compartment);
863
+ const [preview, setPreview] = useState(false);
864
+ const [error, setError] = useState(false);
865
+ useEffect3(() => {
866
+ if (!host.current)
867
+ return;
868
+ setPreview(false);
869
+ setError(false);
870
+ const notifySelection = (view2) => {
871
+ const range = view2.state.selection.main;
872
+ current.current.onSelectionChange?.({
873
+ from: range.from,
874
+ to: range.to,
875
+ text: view2.state.sliceDoc(range.from, range.to),
876
+ document: view2.state.doc.toString()
877
+ });
878
+ };
879
+ const view = new EditorView({
880
+ parent: host.current,
881
+ state: EditorState.create({
882
+ doc: current.current.value,
883
+ extensions: [
884
+ lineNumbers(),
885
+ history(),
886
+ drawSelection(),
887
+ highlightActiveLine(),
888
+ indentOnInput(),
889
+ bracketMatching(),
890
+ highlightSelectionMatches(),
891
+ syntaxHighlighting2(defaultHighlightStyle, { fallback: true }),
892
+ lintGutter(),
893
+ EditorView.lineWrapping,
894
+ contentAttributes.current.of(editorAttributes(current.current.ariaLabel, documentKey)),
895
+ keymap.of([
896
+ ...defaultKeymap,
897
+ ...historyKeymap,
898
+ ...searchKeymap,
899
+ indentWithTab
900
+ ]),
901
+ editable.current.of([
902
+ EditorState.readOnly.of(Boolean(current.current.readOnly)),
903
+ EditorView.editable.of(!current.current.readOnly)
904
+ ]),
905
+ ...textPresetExtensions(preset),
906
+ EditorView.updateListener.of((update) => {
907
+ if (update.docChanged) {
908
+ setError(false);
909
+ if (!update.transactions.some((transaction) => transaction.annotation(externalUpdate)))
910
+ current.current.onChange(update.state.doc.toString());
911
+ }
912
+ if (update.docChanged || update.selectionSet)
913
+ notifySelection(update.view);
914
+ })
915
+ ]
916
+ })
917
+ });
918
+ editor.current = view;
919
+ current.current.onReady?.(view);
920
+ notifySelection(view);
921
+ return () => {
922
+ current.current.onReady?.(null);
923
+ editor.current = null;
924
+ view.destroy();
925
+ };
926
+ }, [preset, documentKey]);
927
+ useEffect3(() => {
928
+ editor.current?.dispatch({
929
+ effects: contentAttributes.current.reconfigure(editorAttributes(props.ariaLabel, documentKey))
930
+ });
931
+ }, [props.ariaLabel, documentKey]);
932
+ useEffect3(() => {
933
+ const view = editor.current;
934
+ if (!view || view.state.doc.toString() === value)
935
+ return;
936
+ view.dispatch({
937
+ changes: { from: 0, to: view.state.doc.length, insert: value },
938
+ selection: {
939
+ anchor: Math.min(view.state.selection.main.anchor, value.length),
940
+ head: Math.min(view.state.selection.main.head, value.length)
941
+ },
942
+ annotations: [
943
+ Transaction.addToHistory.of(false),
944
+ externalUpdate.of(true)
945
+ ]
946
+ });
947
+ }, [value]);
948
+ useEffect3(() => {
949
+ editor.current?.dispatch({
950
+ effects: editable.current.reconfigure([
951
+ EditorState.readOnly.of(readOnly),
952
+ EditorView.editable.of(!readOnly)
953
+ ])
954
+ });
955
+ }, [readOnly]);
956
+ const html = useMemo2(() => preset === "markdown" && preview ? renderEditorMarkdown(value) : "", [preset, preview, value]);
957
+ const format = () => {
958
+ if (readOnly || !editor.current)
959
+ return;
960
+ try {
961
+ const view = editor.current;
962
+ const next = formatEditorText(preset, view.state.doc.toString());
963
+ view.dispatch({
964
+ changes: { from: 0, to: view.state.doc.length, insert: next }
965
+ });
966
+ view.focus();
967
+ } catch {
968
+ setError(true);
969
+ }
970
+ };
971
+ const showMarkdownModes = preset === "markdown";
972
+ const showFormat = !readOnly && isFormattablePreset(preset);
973
+ const toolbar = showMarkdownModes || showFormat ? /* @__PURE__ */ jsxs4(Fragment2, {
974
+ children: [
975
+ showMarkdownModes && /* @__PURE__ */ jsxs4("fieldset", {
976
+ className: "iquji-editor-modes",
977
+ "aria-label": props.ariaLabel,
978
+ children: [
979
+ /* @__PURE__ */ jsx8(IqujiButton2, {
980
+ compact: true,
981
+ variant: "ghost",
982
+ "aria-pressed": !preview,
983
+ onClick: () => setPreview(false),
984
+ children: labels.edit
985
+ }),
986
+ /* @__PURE__ */ jsx8(IqujiButton2, {
987
+ compact: true,
988
+ variant: "ghost",
989
+ "aria-pressed": preview,
990
+ onClick: () => setPreview(true),
991
+ children: labels.preview
992
+ })
993
+ ]
994
+ }),
995
+ showFormat && /* @__PURE__ */ jsx8(IqujiButton2, {
996
+ compact: true,
997
+ variant: "ghost",
998
+ onClick: format,
999
+ children: labels.format
1000
+ })
1001
+ ]
1002
+ }) : undefined;
1003
+ return /* @__PURE__ */ jsxs4(IqujiEditorLayout, {
1004
+ className: props.className,
1005
+ footer: props.footer,
1006
+ toolbar,
1007
+ children: [
1008
+ error && /* @__PURE__ */ jsx8("p", {
1009
+ role: "status",
1010
+ className: "iquji-editor-error",
1011
+ children: labels.invalid
1012
+ }),
1013
+ /* @__PURE__ */ jsx8("div", {
1014
+ className: "iquji-text-editor",
1015
+ ref: host,
1016
+ hidden: preview
1017
+ }),
1018
+ preview && /* @__PURE__ */ jsx8("article", {
1019
+ className: "iquji-editor-preview",
1020
+ "aria-label": labels.preview,
1021
+ dangerouslySetInnerHTML: { __html: html }
1022
+ })
1023
+ ]
1024
+ });
1025
+ }
1026
+ export {
1027
+ yamlDiagnostics,
1028
+ useIqujiRichTextEditor,
1029
+ tomlDiagnostics,
1030
+ textPresetExtensions,
1031
+ renderEditorMarkdown,
1032
+ isFormattablePreset,
1033
+ isEditorHighlightColor,
1034
+ isEditorColor,
1035
+ formatEditorText,
1036
+ editorHighlightCss,
1037
+ createRichTextPreset,
1038
+ IqujiTextEditor,
1039
+ IqujiRichTextToolbar,
1040
+ IqujiRichTextEditor,
1041
+ IqujiRichTextContent,
1042
+ IqujiEditorViewport,
1043
+ IqujiEditorLayout,
1044
+ IqujiEditorColorControl,
1045
+ IQUJI_FORMATTABLE_PRESETS,
1046
+ IQUJI_EDITOR_PRESETS,
1047
+ EditorTextColor,
1048
+ EditorHighlight,
1049
+ EDITOR_TEXT_PALETTE,
1050
+ EDITOR_HIGHLIGHT_PALETTE,
1051
+ EDITOR_HIGHLIGHT_COLORS,
1052
+ EDITOR_ALIGNMENT_TOOLS
1053
+ };