@lesjoursfr/edith 2.1.0 → 2.1.2

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.
@@ -0,0 +1,403 @@
1
+ import { html } from "@codemirror/lang-html";
2
+ import { EditorView, basicSetup } from "codemirror";
3
+ import {
4
+ EditorModes,
5
+ Events,
6
+ History,
7
+ cleanPastedHtml,
8
+ clearSelectionStyle,
9
+ createNodeWith,
10
+ getSelection,
11
+ hasClass,
12
+ hasTagName,
13
+ isHTMLElement,
14
+ isSelectionInsideNode,
15
+ isSelfClosing,
16
+ removeNodesRecursively,
17
+ replaceSelectionByHtml,
18
+ restoreSelection,
19
+ throttle,
20
+ unwrapNode,
21
+ wrapInsideLink,
22
+ wrapInsideTag,
23
+ } from "../core/index.js";
24
+ import { Edith } from "../edith.js";
25
+ import { EdithModal, createCheckboxModalField, createInputModalField } from "./modal.js";
26
+
27
+ export class EdithEditor {
28
+ private el!: HTMLDivElement;
29
+ private ctx: Edith;
30
+ private content: string;
31
+ private height: number;
32
+ private resizable: boolean;
33
+ private mode: EditorModes;
34
+ private visualEditor!: HTMLDivElement;
35
+ private codeEditor!: HTMLDivElement;
36
+ private codeMirror: EditorView | undefined;
37
+ private history: History;
38
+ public throttledSnapshots: ReturnType<typeof throttle>;
39
+
40
+ constructor(ctx: Edith, options: { initialContent: string; height: number; resizable: boolean }) {
41
+ this.ctx = ctx;
42
+ this.content = options.initialContent;
43
+ this.height = options.height;
44
+ this.resizable = options.resizable;
45
+ this.mode = EditorModes.Visual;
46
+ this.history = new History();
47
+ this.throttledSnapshots = throttle(() => this.takeSnapshot(), 3000, { leading: false, trailing: true });
48
+
49
+ // Replace &nbsp; by the string we use as a visual return
50
+ this.content = this.content.replace(/&nbsp;/g, '<span class="edith-nbsp" contenteditable="false">¶</span>');
51
+ }
52
+
53
+ public render(): HTMLDivElement {
54
+ // Create a wrapper for the editor
55
+ this.el = createNodeWith("div", {
56
+ attributes: {
57
+ class: "edith-editing-area",
58
+ style: this.resizable ? `min-height: ${this.height}px; resize: vertical` : `height: ${this.height}px`,
59
+ },
60
+ });
61
+
62
+ // Create the visual editor
63
+ this.visualEditor = createNodeWith("div", {
64
+ innerHTML: this.content,
65
+ attributes: {
66
+ class: "edith-visual",
67
+ contenteditable: "true",
68
+ style: this.resizable ? `min-height: ${this.height - 10}px` : `height: ${this.height - 10}px`,
69
+ },
70
+ });
71
+ this.el.append(this.visualEditor);
72
+
73
+ // Create the code editor
74
+ this.codeEditor = createNodeWith("div", {
75
+ attributes: { class: "edith-code edith-hidden" },
76
+ });
77
+ this.el.append(this.codeEditor);
78
+
79
+ // Bind events
80
+ const keyEventsListener = this.onKeyEvent.bind(this);
81
+ this.visualEditor.addEventListener("keydown", keyEventsListener);
82
+ this.visualEditor.addEventListener("keyup", keyEventsListener);
83
+ const pasteEventListener = this.onPasteEvent.bind(this);
84
+ this.visualEditor.addEventListener("paste", pasteEventListener);
85
+
86
+ // Return the wrapper
87
+ return this.el;
88
+ }
89
+
90
+ public getVisualEditorElement(): HTMLElement {
91
+ return this.visualEditor;
92
+ }
93
+
94
+ public getCodeEditorElement(): HTMLElement {
95
+ return this.codeEditor;
96
+ }
97
+
98
+ public setContent(content: string): void {
99
+ // Replace &nbsp; by the string we use as a visual return
100
+ content = content.replace(/&nbsp;/g, '<span class="edith-nbsp" contenteditable="false">¶</span>');
101
+
102
+ // Check the current mode
103
+ if (this.mode === EditorModes.Visual) {
104
+ // Update the visual editor content
105
+ this.visualEditor.innerHTML = content;
106
+ } else {
107
+ // Update the code editor content
108
+ this.codeMirror!.dispatch({
109
+ changes: { from: 0, to: this.codeMirror!.state.doc.length, insert: content },
110
+ });
111
+ }
112
+ }
113
+
114
+ public getContent(): string {
115
+ // Get the visual editor content or the code editor content
116
+ const code =
117
+ this.mode === EditorModes.Visual
118
+ ? this.visualEditor.innerHTML
119
+ : this.codeMirror!.state.doc.toJSON()
120
+ .map((line) => line.trim())
121
+ .join("\n");
122
+
123
+ // Check if there is something in the editor
124
+ if (code === "<p><br></p>") {
125
+ return "";
126
+ }
127
+
128
+ // Remove empty tags
129
+ const placeholder = createNodeWith("div", { innerHTML: code });
130
+ removeNodesRecursively(placeholder, (el) => {
131
+ return (
132
+ isHTMLElement(el) && !isSelfClosing(el.tagName) && (el.textContent === null || el.textContent.length === 0)
133
+ );
134
+ });
135
+
136
+ // Remove any style attribute
137
+ for (const el of placeholder.querySelectorAll("[style]")) {
138
+ el.removeAttribute("style");
139
+ }
140
+
141
+ // Unwrap span without attributes
142
+ for (const el of placeholder.querySelectorAll("span")) {
143
+ if (el.attributes.length === 0) {
144
+ unwrapNode(el);
145
+ }
146
+ }
147
+
148
+ // Return clean code
149
+ return placeholder.innerHTML
150
+ .replace(/\u200B/gi, "")
151
+ .replace(/<\/p>\s*<p>/gi, "<br>")
152
+ .replace(/(<p>|<\/p>)/gi, "")
153
+ .replace(/<span[^>]+class="edith-nbsp"[^>]*>[^<]*<\/span>/gi, "&nbsp;")
154
+ .replace(/(?:<br\s?\/?>)+$/gi, "");
155
+ }
156
+
157
+ public takeSnapshot(): void {
158
+ this.history.push(this.visualEditor.innerHTML);
159
+ }
160
+
161
+ public restoreSnapshot(): void {
162
+ this.visualEditor.innerHTML = this.history.pop() ?? "";
163
+ }
164
+
165
+ public wrapInsideTag<K extends keyof HTMLElementTagNameMap>(tag: K): void {
166
+ if (isSelectionInsideNode(this.visualEditor)) {
167
+ wrapInsideTag(tag);
168
+ this.takeSnapshot();
169
+ }
170
+ }
171
+
172
+ public replaceByHtml(html: string): void {
173
+ if (isSelectionInsideNode(this.visualEditor)) {
174
+ replaceSelectionByHtml(html);
175
+ this.takeSnapshot();
176
+ }
177
+ }
178
+
179
+ public clearStyle(): void {
180
+ clearSelectionStyle();
181
+ this.takeSnapshot();
182
+ }
183
+
184
+ public insertLink(): void {
185
+ // Get the caret position
186
+ const { sel, range } = getSelection();
187
+
188
+ // Check if the user has selected something
189
+ if (range === undefined) {
190
+ return;
191
+ }
192
+
193
+ // Show the modal
194
+ const modal = new EdithModal(this.ctx, {
195
+ title: "Insérer un lien",
196
+ fields: [
197
+ createInputModalField("Texte à afficher", "text", range.toString()),
198
+ createInputModalField("URL du lien", "href"),
199
+ createCheckboxModalField("Ouvrir dans une nouvelle fenêtre", "openInNewTab", true),
200
+ ],
201
+ callback: (data) => {
202
+ // Check if we have something
203
+ if (data === null) {
204
+ // Nothing to do
205
+ return;
206
+ }
207
+
208
+ // Restore the selection
209
+ restoreSelection({ sel, range });
210
+
211
+ // Insert a link
212
+ wrapInsideLink(data.text as string, data.href as string, data.openInNewTab as boolean);
213
+ },
214
+ });
215
+ modal.show();
216
+ }
217
+
218
+ public toggleCodeView(): void {
219
+ // Check the current mode
220
+ if (this.mode === EditorModes.Visual) {
221
+ // Switch mode
222
+ this.mode = EditorModes.Code;
223
+
224
+ // Hide the visual editor
225
+ this.visualEditor.classList.add("edith-hidden");
226
+
227
+ // Display the code editor
228
+ this.codeEditor.classList.remove("edith-hidden");
229
+ const codeMirrorEl = document.createElement("div");
230
+ this.codeEditor.append(codeMirrorEl);
231
+ this.codeMirror = new EditorView({
232
+ doc: this.visualEditor.innerHTML,
233
+ extensions: [basicSetup, EditorView.lineWrapping, html({ matchClosingTags: true, autoCloseTags: true })],
234
+ parent: codeMirrorEl,
235
+ });
236
+ } else {
237
+ // Switch mode
238
+ this.mode = EditorModes.Visual;
239
+
240
+ // Hide the code editor
241
+ this.codeEditor.classList.add("edith-hidden");
242
+
243
+ // Display the visual editor
244
+ this.visualEditor.classList.remove("edith-hidden");
245
+ this.visualEditor.innerHTML = this.codeMirror!.state.doc.toJSON()
246
+ .map((line) => line.trim())
247
+ .join("\n");
248
+ this.codeMirror!.destroy();
249
+ this.codeMirror = undefined;
250
+ this.codeEditor.innerHTML = "";
251
+ }
252
+
253
+ // Trigger an event with the new mode
254
+ this.ctx.trigger(Events.modeChanged, { mode: this.mode });
255
+ }
256
+
257
+ public onKeyEvent(e: KeyboardEvent): void {
258
+ // Check if a Meta key is pressed
259
+ const prevent = e.metaKey || e.ctrlKey ? this._processKeyEventWithMeta(e) : this._processKeyEvent(e);
260
+
261
+ // Check if we must stop the event here
262
+ if (prevent) {
263
+ e.preventDefault();
264
+ e.stopPropagation();
265
+ }
266
+ }
267
+
268
+ private _processKeyEvent(e: KeyboardEvent): boolean {
269
+ // Check the key code
270
+ switch (e.keyCode) {
271
+ case 13: // Enter : 13
272
+ if (e.type === "keydown") {
273
+ this.replaceByHtml("<br />"); // Insert a line break
274
+ }
275
+ return true;
276
+ }
277
+
278
+ // Save the editor content
279
+ this.throttledSnapshots();
280
+
281
+ // Return false
282
+ return false;
283
+ }
284
+
285
+ private _processKeyEventWithMeta(e: KeyboardEvent): boolean {
286
+ // Check the key code
287
+ switch (e.keyCode) {
288
+ case 13: // Enter : 13
289
+ if (e.type === "keydown") {
290
+ this.replaceByHtml("<br />"); // Insert a line break
291
+ }
292
+ return true;
293
+
294
+ case 32: // Space : 32
295
+ if (e.type === "keydown") {
296
+ this.replaceByHtml('<span class="edith-nbsp" contenteditable="false">¶</span>'); // Insert a non-breaking space
297
+ }
298
+ return true;
299
+
300
+ case 66: // b : 66
301
+ if (e.type === "keydown") {
302
+ this.wrapInsideTag("b"); // Toggle bold
303
+ }
304
+ return true;
305
+
306
+ case 73: // i : 73
307
+ if (e.type === "keydown") {
308
+ this.wrapInsideTag("i"); // Toggle italic
309
+ }
310
+ return true;
311
+
312
+ case 85: // u : 85
313
+ if (e.type === "keydown") {
314
+ this.wrapInsideTag("u"); // Toggle underline
315
+ }
316
+ return true;
317
+
318
+ case 83: // s : 83
319
+ if (e.type === "keydown") {
320
+ this.wrapInsideTag("s"); // Toggle strikethrough
321
+ }
322
+ return true;
323
+
324
+ case 90: // z : 90
325
+ if (e.type === "keydown") {
326
+ this.restoreSnapshot(); // Undo
327
+ }
328
+ return true;
329
+ }
330
+
331
+ // Return false
332
+ return false;
333
+ }
334
+
335
+ public onPasteEvent(e: ClipboardEvent): void {
336
+ // Prevent default
337
+ e.preventDefault();
338
+ e.stopPropagation();
339
+
340
+ // Get the caret position
341
+ const { sel, range } = getSelection();
342
+
343
+ // Check if the user has selected something
344
+ if (range === undefined || e.clipboardData === null) {
345
+ return;
346
+ }
347
+
348
+ // Create the fragment to insert
349
+ const frag = document.createDocumentFragment();
350
+
351
+ // Check if we try to paste HTML content
352
+ if (!e.clipboardData.types.includes("text/html")) {
353
+ // Get the content as a plain text & split it by lines
354
+ const lines = e.clipboardData.getData("text/plain").split(/[\r\n]+/g);
355
+
356
+ // Add the content as text nodes with a <br> node between each line
357
+ for (let i = 0; i < lines.length; i++) {
358
+ if (i !== 0) {
359
+ frag.append(document.createElement("br"));
360
+ }
361
+ frag.append(document.createTextNode(lines[i]));
362
+ }
363
+ } else {
364
+ // Detect style blocs in parents
365
+ let dest = sel.anchorNode as HTMLElement;
366
+ const style = { B: false, I: false, U: false, S: false, Q: false };
367
+ while (dest !== null && !hasClass(dest, "edith-visual")) {
368
+ // Check if it's a style tag
369
+ if (hasTagName(dest, ["b", "i", "u", "s", "q"])) {
370
+ // Update the style
371
+ style[(dest.tagName as "B", "I", "U", "S", "Q")] = true;
372
+ }
373
+
374
+ // Get the parent
375
+ dest = dest.parentNode as HTMLElement;
376
+ }
377
+
378
+ // We have HTML content
379
+ let html = e.clipboardData.getData("text/html").replace(/[\r\n]+/g, " ");
380
+
381
+ // Wrap the HTML content into <html><body></body></html>
382
+ if (!/^<html>\s*<body>/.test(html)) {
383
+ html = "<html><body>" + html + "</body></html>";
384
+ }
385
+
386
+ // Clean the content
387
+ const contents = cleanPastedHtml(html, style);
388
+
389
+ // Add the content to the frgament
390
+ frag.append(...contents.childNodes);
391
+ }
392
+
393
+ // Replace the current selection by the pasted content
394
+ sel.deleteFromDocument();
395
+ range.insertNode(frag);
396
+ }
397
+
398
+ public destroy(): void {
399
+ this.codeMirror?.destroy();
400
+ this.codeMirror = undefined;
401
+ this.el.remove();
402
+ }
403
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./button.js";
2
+ export * from "./editor.js";
3
+ export * from "./modal.js";
@@ -0,0 +1,180 @@
1
+ import { createNodeWith, getAttribute, hasAttribute } from "../core/index.js";
2
+ import { Edith } from "../edith.js";
3
+
4
+ export enum EdithModalFieldType {
5
+ input = 1,
6
+ checkbox = 2,
7
+ }
8
+
9
+ export type EdithModalField = {
10
+ fieldType: EdithModalFieldType;
11
+ label: string;
12
+ name: string;
13
+ initialState: string | boolean | null;
14
+ };
15
+
16
+ function renderInputModalField(field: EdithModalField) {
17
+ const el = document.createElement("div");
18
+ el.setAttribute("class", "edith-modal-input");
19
+ const label = document.createElement("label");
20
+ label.textContent = field.label;
21
+ const input = document.createElement("input");
22
+ input.setAttribute("name", field.name);
23
+ input.setAttribute("type", "text");
24
+ if (field.initialState !== null) {
25
+ input.value = field.initialState.toString();
26
+ }
27
+ el.append(label);
28
+ el.append(input);
29
+ return el;
30
+ }
31
+
32
+ function renderCheckboxModalField(field: EdithModalField) {
33
+ const el = document.createElement("div");
34
+ el.setAttribute("class", "edith-modal-checkbox");
35
+ const label = document.createElement("label");
36
+ label.textContent = field.label;
37
+ const input = document.createElement("input");
38
+ input.setAttribute("name", field.name);
39
+ input.setAttribute("type", "checkbox");
40
+ if (field.initialState) {
41
+ input.checked = true;
42
+ }
43
+ label.prepend(input);
44
+ el.append(label);
45
+ return el;
46
+ }
47
+
48
+ export function createInputModalField(
49
+ label: string,
50
+ name: string,
51
+ initialState: string | null = null
52
+ ): EdithModalField {
53
+ return {
54
+ fieldType: EdithModalFieldType.input,
55
+ label,
56
+ name,
57
+ initialState,
58
+ };
59
+ }
60
+
61
+ export function createCheckboxModalField(label: string, name: string, initialState: boolean = false): EdithModalField {
62
+ return {
63
+ fieldType: EdithModalFieldType.checkbox,
64
+ label,
65
+ name,
66
+ initialState,
67
+ };
68
+ }
69
+
70
+ export type EdithModalCallback = (payload: { [keyof: string]: string | boolean } | null) => void;
71
+
72
+ export class EdithModal {
73
+ private el!: HTMLDivElement;
74
+ private ctx: Edith;
75
+ private title: string;
76
+ private fields: EdithModalField[];
77
+ private callback: EdithModalCallback;
78
+
79
+ constructor(ctx: Edith, options: { title: string; fields?: EdithModalField[]; callback: EdithModalCallback }) {
80
+ this.ctx = ctx;
81
+ this.title = options.title;
82
+ this.fields = options.fields || [];
83
+ this.callback = options.callback;
84
+ }
85
+
86
+ public cancel(event: Event): void {
87
+ event.preventDefault();
88
+
89
+ // Call the callback with a null value
90
+ this.callback(null);
91
+
92
+ // Close the modal
93
+ this.close();
94
+ }
95
+
96
+ public submit(event: Event): void {
97
+ event.preventDefault();
98
+
99
+ // Call the callback with the input & checkboxes values
100
+ const payload: { [keyof: string]: string | boolean } = {};
101
+ for (const el of this.el.querySelectorAll("input")) {
102
+ if (hasAttribute(el, "name")) {
103
+ payload[getAttribute(el, "name")!] = getAttribute(el, "type") === "checkbox" ? el.checked : el.value;
104
+ }
105
+ }
106
+ this.callback(payload);
107
+
108
+ // Close the modal
109
+ this.close();
110
+ }
111
+
112
+ public close(): void {
113
+ // Remove the element from the dom
114
+ this.el.remove();
115
+ }
116
+
117
+ public show(): HTMLDivElement {
118
+ // Create the modal
119
+ this.el = createNodeWith("div", {
120
+ attributes: { class: "edith-modal" },
121
+ });
122
+
123
+ // Create the header
124
+ const header = createNodeWith("div", {
125
+ attributes: { class: "edith-modal-header" },
126
+ });
127
+ const title = createNodeWith("span", {
128
+ textContent: this.title,
129
+ attributes: { class: "edith-modal-title" },
130
+ });
131
+ header.append(title);
132
+
133
+ // Create the content
134
+ const content = createNodeWith("div", {
135
+ attributes: { class: "edith-modal-content" },
136
+ });
137
+ for (const field of this.fields) {
138
+ switch (field.fieldType) {
139
+ case EdithModalFieldType.input:
140
+ content.append(renderInputModalField(field));
141
+ break;
142
+ case EdithModalFieldType.checkbox:
143
+ content.append(renderCheckboxModalField(field));
144
+ break;
145
+ default:
146
+ throw new Error(`Unknown fieldType ${field.fieldType}`);
147
+ }
148
+ }
149
+
150
+ // Create the footer
151
+ const footer = createNodeWith("div", {
152
+ attributes: { class: "edith-modal-footer" },
153
+ });
154
+ const cancel = createNodeWith("button", {
155
+ textContent: "Annuler",
156
+ attributes: { class: "edith-modal-cancel", type: "button" },
157
+ });
158
+ footer.append(cancel);
159
+ const submit = createNodeWith("button", {
160
+ textContent: "Valider",
161
+ attributes: { class: "edith-modal-submit", type: "button" },
162
+ });
163
+ footer.append(submit);
164
+
165
+ // Append everything
166
+ this.el.append(header);
167
+ this.el.append(content);
168
+ this.el.append(footer);
169
+
170
+ // Add the modal to the editor
171
+ this.ctx.modals.append(this.el);
172
+
173
+ // Bind events
174
+ cancel.onclick = this.cancel.bind(this);
175
+ submit.onclick = this.submit.bind(this);
176
+
177
+ // Return the modal
178
+ return this.el;
179
+ }
180
+ }