@griddo/ax 12.14.0 → 12.14.2-beta.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@griddo/ax",
3
3
  "description": "Griddo Author Experience",
4
- "version": "12.14.0",
4
+ "version": "12.14.2-beta.0",
5
5
  "homepage": "https://griddo.io",
6
6
  "repository": {
7
7
  "type": "git",
@@ -127,7 +127,7 @@
127
127
  },
128
128
  "devDependencies": {
129
129
  "@biomejs/biome": "2.5.15",
130
- "@griddo/core": "12.14.0",
130
+ "@griddo/core": "12.14.2-beta.0",
131
131
  "@types/redux-mock-store": "1.5.0",
132
132
  "@vitest/coverage-v8": "4.1.11",
133
133
  "axios-mock-adapter": "1.22.0",
@@ -138,7 +138,7 @@
138
138
  "vitest-styled-components": "1.0.0"
139
139
  },
140
140
  "peerDependencies": {
141
- "@griddo/core": "12.14.0"
141
+ "@griddo/core": "12.14.2-beta.0"
142
142
  },
143
143
  "babel": {
144
144
  "presets": [
@@ -171,5 +171,5 @@
171
171
  "publishConfig": {
172
172
  "access": "public"
173
173
  },
174
- "gitHead": "ca40c989e144a41723af744eeceb4e0ea26a07b5"
174
+ "gitHead": "0b8a3e6b9d014d3329b0760e44e1e8674633a656"
175
175
  }
@@ -14,11 +14,13 @@ import { cleanup, render, waitFor } from "../../../../../config/tests/test-utils
14
14
 
15
15
  const schemasConfig = config.schemas.config;
16
16
  const store = configureStore()({ app: { token: "token" } });
17
+ // What AX keeps of the content: the editor's HTML only reaches it through here
18
+ const onChange = vi.fn();
17
19
 
18
20
  const mountEditor = async (value: string) => {
19
21
  const { container } = render(
20
22
  <ThemeProvider theme={parseTheme(globalTheme)}>
21
- <Wysiwyg value={value} onChange={vi.fn()} site={null} />
23
+ <Wysiwyg value={value} onChange={onChange} site={null} />
22
24
  </ThemeProvider>,
23
25
  { store },
24
26
  );
@@ -42,6 +44,20 @@ const rect = (width: number) =>
42
44
 
43
45
  const caption = (editor: any): HTMLElement | null => editor.el.querySelector(".fr-img-caption");
44
46
 
47
+ // The editor's top level: each paragraph by its text, anything else by its class
48
+ const outline = (editor: any) =>
49
+ [...editor.el.children].map((el: HTMLElement) => (el.tagName === "P" ? `p: ${el.textContent}` : el.className));
50
+
51
+ const caretAt = (node: Node, offset: number) => {
52
+ const range = document.createRange();
53
+ range.setStart(node, offset);
54
+ getSelection()?.removeAllRanges();
55
+ getSelection()?.addRange(range);
56
+ };
57
+
58
+ const press = (editor: any, key: string) =>
59
+ editor.el.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));
60
+
45
61
  describe("Wysiwyg image caption", () => {
46
62
  beforeAll(() => {
47
63
  // Froala's licence check splits document.domain, which jsdom leaves undefined
@@ -72,32 +88,39 @@ describe("Wysiwyg image caption", () => {
72
88
  expect(inner?.getAttribute("contenteditable")).toBe("true");
73
89
  });
74
90
 
75
- it("should give the caption the width the image is showing at", async () => {
91
+ // The site sizes an image that has no width of its own: a width taken from
92
+ // how it shows in the editor would override that
93
+ it("should give no width to a never resized image, or to its caption", async () => {
76
94
  const editor = await mountEditor('<p><img src="http://x/a.png" alt="" class="fr-dib"></p>');
77
- vi.spyOn(editor.el.querySelector("img"), "getBoundingClientRect").mockReturnValue(rect(300));
95
+ const img = editor.el.querySelector("img");
96
+ vi.spyOn(img, "getBoundingClientRect").mockReturnValue(rect(300));
78
97
  vi.spyOn(editor.el.querySelector("p"), "getBoundingClientRect").mockReturnValue(rect(600));
79
98
 
80
99
  toggleCaption(editor);
81
100
 
82
- expect(caption(editor)?.style.width).toBe("50%");
101
+ expect(caption(editor)?.hasAttribute("style")).toBe(false);
102
+ expect(img.hasAttribute("style")).toBe(false);
83
103
  });
84
104
 
85
- it("should fall back to the full width when the image cannot be measured", async () => {
86
- const editor = await mountEditor('<p><img src="http://x/a.png" alt="" class="fr-dib"></p>');
105
+ it("should keep a never resized image's other styles when it is captioned", async () => {
106
+ const editor = await mountEditor(
107
+ '<p><img src="http://x/a.png" alt="" class="fr-dib" style="height: 200px;"></p>',
108
+ );
109
+ const img = editor.el.querySelector("img");
87
110
 
88
111
  toggleCaption(editor);
89
112
 
90
- expect(caption(editor)?.style.width).toBe("100%");
113
+ expect(img.getAttribute("style")).toBe("height: 200px;");
91
114
  });
92
115
 
93
- it("should move a resized image's width to its caption and back", async () => {
116
+ it("should give a resized image's width to its caption, and keep it on the image", async () => {
94
117
  const editor = await mountEditor('<p><img src="http://x/a.png" alt="" class="fr-dib" style="width: 40%;"></p>');
95
118
  const img = editor.el.querySelector("img");
96
119
 
97
120
  toggleCaption(editor);
98
121
 
99
122
  expect(caption(editor)?.style.width).toBe("40%");
100
- expect(img.style.width).toBe("");
123
+ expect(img.style.width).toBe("40%");
101
124
 
102
125
  toggleCaption(editor);
103
126
 
@@ -111,7 +134,6 @@ describe("Wysiwyg image caption", () => {
111
134
  toggleCaption(editor);
112
135
 
113
136
  expect(editor.el.querySelector("[width]")).toBeNull();
114
- expect(editor.el.querySelector("img").hasAttribute("style")).toBe(false);
115
137
  });
116
138
 
117
139
  it("should turn a pixel width from before percentages into the caption's share", async () => {
@@ -125,7 +147,7 @@ describe("Wysiwyg image caption", () => {
125
147
  toggleCaption(editor);
126
148
 
127
149
  expect(caption(editor)?.style.width).toBe("50%");
128
- expect(img.style.width).toBe("");
150
+ expect(img.style.width).toBe("50%");
129
151
  });
130
152
 
131
153
  it("should keep a resized image's size when its caption is put back", async () => {
@@ -137,28 +159,10 @@ describe("Wysiwyg image caption", () => {
137
159
  toggleCaption(editor);
138
160
 
139
161
  expect(caption(editor)?.style.width).toBe("40%");
140
- expect(img.style.width).toBe("");
162
+ expect(img.style.width).toBe("40%");
141
163
  expect(editor.el.querySelectorAll(".fr-img-space-wrap")).toHaveLength(1);
142
164
  });
143
165
 
144
- it("should leave the other captions alone when an image is captioned again", async () => {
145
- const editor = await mountEditor(
146
- '<p><img id="first" src="http://x/a.png" alt="" class="fr-dib"></p><p><img id="second" src="http://x/b.png" alt="" class="fr-dib"></p>',
147
- );
148
- const first = editor.el.querySelector("#first");
149
- const second = editor.el.querySelector("#second");
150
-
151
- toggleCaption(editor, first);
152
- toggleCaption(editor, second);
153
- toggleCaption(editor, second);
154
- toggleCaption(editor, second);
155
-
156
- expect(first.closest(".fr-img-space-wrap")).not.toBeNull();
157
- expect(first.closest(".fr-img-caption")).not.toBeNull();
158
- expect(second.closest(".fr-img-caption")).not.toBeNull();
159
- expect(editor.el.querySelectorAll(".fr-img-space-wrap")).toHaveLength(2);
160
- });
161
-
162
166
  describe("with the size popup", () => {
163
167
  const widthInput = (editor: any) => editor.popups.get("image.size").find('input[name="width"]');
164
168
 
@@ -177,14 +181,14 @@ describe("Wysiwyg image caption", () => {
177
181
  expect(widthInput(editor).val()).toBe("40%");
178
182
  });
179
183
 
180
- it("should size a captioned image through its caption only", async () => {
184
+ it("should size a captioned image and its caption alike", async () => {
181
185
  const { editor, img } = await captionedAt40();
182
186
 
183
187
  widthInput(editor).val("30%");
184
188
  editor.commands.exec("imageSetSize");
185
189
 
186
190
  expect(caption(editor)?.style.width).toBe("30%");
187
- expect(img.style.width).toBe("");
191
+ expect(img.style.width).toBe("30%");
188
192
  });
189
193
 
190
194
  it("should keep a captioned image's height on the image", async () => {
@@ -219,14 +223,14 @@ describe("Wysiwyg image caption", () => {
219
223
  });
220
224
 
221
225
  describe("when resizing a captioned image", () => {
222
- // jsdom has no layout: the column is 600px, and the caption, with the
223
- // paragraph and image inside it, takes the share its style asks for
226
+ // jsdom has no layout: the column is 600px, and the caption, with
227
+ // everything inside it, takes the share its style asks for
224
228
  const COLUMN = 600;
225
229
 
226
230
  beforeEach(() => {
227
231
  vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockImplementation(function (this: HTMLElement) {
228
232
  const box = this.closest(".fr-img-caption") as HTMLElement | null;
229
- return box ? (Number.parseFloat(box.style.width) / 100) * COLUMN : COLUMN;
233
+ return box?.style.width ? (Number.parseFloat(box.style.width) / 100) * COLUMN : COLUMN;
230
234
  });
231
235
  });
232
236
 
@@ -238,6 +242,16 @@ describe("Wysiwyg image caption", () => {
238
242
  return { editor, img };
239
243
  };
240
244
 
245
+ // As captions were saved before the paragraph inside them was dropped
246
+ const captionedWithParagraph = async () => {
247
+ const editor = await mountEditor(
248
+ '<div class="fr-img-space-wrap"><span contenteditable="false" class="fr-img-caption fr-dib" draggable="false" style="width: 50%;"><span class="fr-img-wrap"><p><img src="http://x/a.png" alt="" class="fr-dib"><span class="fr-inner" contenteditable="true">Image Caption</span></p></span></span></div>',
249
+ );
250
+ const img = editor.el.querySelector("img");
251
+ editor.image.edit(editor.$(img));
252
+ return { editor, img };
253
+ };
254
+
241
255
  // Froala reads pageX, which jsdom does not derive from clientX
242
256
  const mouse = (type: string, pageX = 0) =>
243
257
  Object.defineProperty(new MouseEvent(type, { bubbles: true }), "pageX", { value: pageX });
@@ -251,14 +265,41 @@ describe("Wysiwyg image caption", () => {
251
265
  });
252
266
  };
253
267
 
254
- it("should follow the pointer without bouncing", async () => {
255
- await captioned();
268
+ it.each([
269
+ ["a new caption", captioned],
270
+ ["a caption saved with a paragraph in it", captionedWithParagraph],
271
+ ])("should follow the pointer without bouncing, with %s", async (_, setup) => {
272
+ await setup();
256
273
 
257
274
  expect(dragHandle([160, 160, 160, 130])).toEqual(["60%", "60%", "60%", "55%"]);
258
275
  });
259
276
 
260
- it("should put the caption back in its paragraph when the drag ends", async () => {
261
- const { img } = await captioned();
277
+ it("should give the image the width the drag leaves on its caption", async () => {
278
+ const { editor, img } = await captioned();
279
+
280
+ dragHandle([160]);
281
+ document.body.dispatchEvent(mouse("mouseup"));
282
+
283
+ expect(img.style.width).toBe("60%");
284
+ expect(onChange).toHaveBeenLastCalledWith(editor.html.get());
285
+ });
286
+
287
+ it("should size a never resized image and its caption alike", async () => {
288
+ const editor = await mountEditor('<p><img src="http://x/a.png" alt="" class="fr-dib"></p>');
289
+ const img = editor.el.querySelector("img");
290
+ toggleCaption(editor);
291
+ editor.image.edit(editor.$(img));
292
+
293
+ dragHandle([40]);
294
+ document.body.dispatchEvent(mouse("mouseup"));
295
+
296
+ expect(caption(editor)?.style.width).toBe("90%");
297
+ expect(img.style.width).toBe("90%");
298
+ expect(onChange).toHaveBeenLastCalledWith(editor.html.get());
299
+ });
300
+
301
+ it("should put a caption saved with a paragraph in it back in its paragraph when the drag ends", async () => {
302
+ const { editor, img } = await captionedWithParagraph();
262
303
 
263
304
  dragHandle([160]);
264
305
  document.body.dispatchEvent(mouse("mouseup"));
@@ -266,6 +307,7 @@ describe("Wysiwyg image caption", () => {
266
307
  const paragraph = img.closest(".fr-img-wrap > p");
267
308
  expect(paragraph).not.toBeNull();
268
309
  expect(paragraph.querySelector(".fr-inner")?.textContent).toBe("Image Caption");
310
+ expect(onChange).toHaveBeenLastCalledWith(editor.html.get());
269
311
  });
270
312
  });
271
313
 
@@ -281,6 +323,253 @@ describe("Wysiwyg image caption", () => {
281
323
  });
282
324
  });
283
325
 
326
+ describe.each([
327
+ ["on", { imageResize: true }],
328
+ ["off", undefined],
329
+ ])("with image resizing %s", (_, richTextConfig) => {
330
+ beforeEach(() => {
331
+ if (richTextConfig) schemasConfig.richTextConfig = richTextConfig;
332
+ });
333
+
334
+ it("should put the caption's text right after the image, with no paragraph around them", async () => {
335
+ const editor = await mountEditor('<p><img src="http://x/a.png" alt="" class="fr-dib"></p>');
336
+
337
+ toggleCaption(editor);
338
+
339
+ expect(caption(editor)?.querySelector("p")).toBeNull();
340
+ expect(caption(editor)?.querySelector(".fr-img-wrap > img + .fr-inner")?.textContent).toBe("Image Caption");
341
+ });
342
+
343
+ it("should leave the caption's placeholder selected, to type over it", async () => {
344
+ const editor = await mountEditor('<p><img src="http://x/a.png" alt="" class="fr-dib"></p>');
345
+
346
+ toggleCaption(editor);
347
+
348
+ expect(getSelection()?.toString()).toBe("Image Caption");
349
+ expect(getSelection()?.anchorNode?.parentElement?.closest(".fr-inner")).not.toBeNull();
350
+ });
351
+
352
+ it("should leave the text sharing the image's paragraph out of the caption", async () => {
353
+ const editor = await mountEditor('<p>Above<img src="http://x/a.png" alt="" class="fr-dib">Below</p>');
354
+
355
+ toggleCaption(editor);
356
+
357
+ expect(outline(editor)).toEqual(["p: Above", "fr-img-space-wrap", "p: Below"]);
358
+ expect(caption(editor)?.textContent).toBe("Image Caption");
359
+ });
360
+
361
+ it("should keep the text around the image when its caption is removed", async () => {
362
+ const editor = await mountEditor('<p>Above<img src="http://x/a.png" alt="" class="fr-dib">Below</p>');
363
+
364
+ toggleCaption(editor);
365
+ toggleCaption(editor);
366
+
367
+ expect(caption(editor)).toBeNull();
368
+ expect(outline(editor)).toEqual(["p: Above", "fr-img-space-wrap", "p: Below"]);
369
+ });
370
+
371
+ it("should give back the text an earlier caption took in, when that caption is removed", async () => {
372
+ const editor = await mountEditor(
373
+ '<div class="fr-img-space-wrap"><span contenteditable="false" class="fr-img-caption fr-dib" draggable="false"><span class="fr-img-wrap"><p>Above<img src="http://x/a.png" alt="" class="fr-dib"><span class="fr-inner" contenteditable="true">Caption</span>Below</p></span></span></div>',
374
+ );
375
+
376
+ toggleCaption(editor);
377
+
378
+ expect(caption(editor)).toBeNull();
379
+ expect(outline(editor)).toEqual(["p: Above", "fr-img-space-wrap", "p: Below"]);
380
+ });
381
+
382
+ it("should not put a linked image's caption inside a paragraph", async () => {
383
+ const editor = await mountEditor(
384
+ '<p><a href="http://x"><img src="http://x/a.png" alt="" class="fr-dib"></a>Below</p>',
385
+ );
386
+
387
+ toggleCaption(editor);
388
+
389
+ expect(outline(editor)).toEqual(["fr-img-space-wrap", "p: Below"]);
390
+ expect(caption(editor)?.querySelector("a > img")).not.toBeNull();
391
+ });
392
+
393
+ // As when the image goes in with the caret inside a link
394
+ it("should leave out of the caption, still linked, the text of a link the image is in", async () => {
395
+ const editor = await mountEditor(
396
+ '<p>Above <a href="http://x">link<img src="http://x/a.png" alt="" class="fr-dib">more</a> below</p>',
397
+ );
398
+ const links = () => [...editor.el.querySelectorAll(":scope > p > a")].map((a: HTMLElement) => a.textContent);
399
+
400
+ toggleCaption(editor);
401
+
402
+ expect(outline(editor)).toEqual(["p: Above link", "fr-img-space-wrap", "p: more below"]);
403
+ expect(links()).toEqual(["link", "more"]);
404
+ expect(caption(editor)?.querySelector("a > img + .fr-inner")?.textContent).toBe("Image Caption");
405
+
406
+ toggleCaption(editor);
407
+
408
+ expect(outline(editor)).toEqual(["p: Above link", "fr-img-space-wrap", "p: more below"]);
409
+ expect(links()).toEqual(["link", "more"]);
410
+ });
411
+
412
+ // As when the image goes in with the caret inside bold text
413
+ it("should leave out of the caption, still bold, the text around an image in bold", async () => {
414
+ const editor = await mountEditor(
415
+ '<p><strong>Above<img src="http://x/a.png" alt="" class="fr-dib">Below</strong></p>',
416
+ );
417
+
418
+ toggleCaption(editor);
419
+
420
+ expect(outline(editor)).toEqual(["p: Above", "fr-img-space-wrap", "p: Below"]);
421
+ const bold = [...editor.el.querySelectorAll(":scope > p > strong")].map((b: HTMLElement) => b.textContent);
422
+ expect(bold).toEqual(["Above", "Below"]);
423
+ expect(caption(editor)?.querySelector("strong")).toBeNull();
424
+ });
425
+
426
+ it("should leave the other captions alone when an image is captioned again", async () => {
427
+ const editor = await mountEditor(
428
+ '<p><img id="first" src="http://x/a.png" alt="" class="fr-dib"></p><p><img id="second" src="http://x/b.png" alt="" class="fr-dib"></p>',
429
+ );
430
+ const first = editor.el.querySelector("#first");
431
+ const second = editor.el.querySelector("#second");
432
+
433
+ toggleCaption(editor, first);
434
+ toggleCaption(editor, second);
435
+ toggleCaption(editor, second);
436
+ toggleCaption(editor, second);
437
+
438
+ expect(first.closest(".fr-img-space-wrap")).not.toBeNull();
439
+ expect(first.closest(".fr-img-caption")).not.toBeNull();
440
+ expect(second.closest(".fr-img-caption")).not.toBeNull();
441
+ expect(editor.el.querySelectorAll(".fr-img-space-wrap")).toHaveLength(2);
442
+ });
443
+ });
444
+
445
+ describe("with the keyboard around a captioned image", () => {
446
+ const captioned = async (
447
+ html = '<p>Above</p><p><img src="http://x/a.png" alt="" class="fr-dib"></p><p>Below</p>',
448
+ ) => {
449
+ const editor = await mountEditor(html);
450
+ const img = editor.el.querySelector("img");
451
+ toggleCaption(editor, img);
452
+ return { editor, img };
453
+ };
454
+
455
+ const paragraph = (editor: any, text: string) =>
456
+ [...editor.el.querySelectorAll(":scope > p")].find((p: HTMLElement) => p.textContent === text);
457
+
458
+ const caretBlock = () => {
459
+ const node = getSelection()?.anchorNode;
460
+ return (node instanceof Element ? node : node?.parentElement)?.closest("p");
461
+ };
462
+
463
+ it("should select the image instead of merging the block after it into its wrapper", async () => {
464
+ const { editor, img } = await captioned();
465
+ caretAt(paragraph(editor, "Below").firstChild, 0);
466
+
467
+ press(editor, "Backspace");
468
+
469
+ expect(outline(editor)).toEqual(["p: Above", "fr-img-space-wrap", "p: Below"]);
470
+ expect(editor.image.get()?.get(0)).toBe(img);
471
+ });
472
+
473
+ it("should select the image instead of merging its caption into the block before it", async () => {
474
+ const { editor, img } = await captioned();
475
+ caretAt(paragraph(editor, "Above").firstChild, "Above".length);
476
+
477
+ press(editor, "Delete");
478
+
479
+ expect(outline(editor)).toEqual(["p: Above", "fr-img-space-wrap", "p: Below"]);
480
+ expect(editor.image.get()?.get(0)).toBe(img);
481
+ });
482
+
483
+ it.each([
484
+ [
485
+ "Backspace",
486
+ "after",
487
+ '<p><img src="http://x/a.png" alt="" class="fr-dib"></p><p><br></p><p>Below</p>',
488
+ ["fr-img-space-wrap", "p: Below"],
489
+ ],
490
+ [
491
+ "Delete",
492
+ "before",
493
+ '<p>Above</p><p><br></p><p><img src="http://x/a.png" alt="" class="fr-dib"></p>',
494
+ ["p: Above", "fr-img-space-wrap"],
495
+ ],
496
+ ])("should drop an empty block on %s %s the image, and select it", async (key, _, html, expected) => {
497
+ const { editor, img } = await captioned(html);
498
+ caretAt(paragraph(editor, ""), 0);
499
+
500
+ press(editor, key);
501
+
502
+ expect(outline(editor)).toEqual(expected);
503
+ expect(editor.image.get()?.get(0)).toBe(img);
504
+ expect(onChange).toHaveBeenLastCalledWith(editor.html.get());
505
+ });
506
+
507
+ it("should leave Backspace alone away from the start of the block", async () => {
508
+ const { editor } = await captioned();
509
+ caretAt(paragraph(editor, "Below").firstChild, 2);
510
+
511
+ press(editor, "Backspace");
512
+
513
+ expect(editor.image.get()).toBeFalsy();
514
+ });
515
+
516
+ it.each([
517
+ ["ArrowRight", "Below"],
518
+ ["ArrowDown", "Below"],
519
+ ["Escape", "Below"],
520
+ ["ArrowLeft", "Above"],
521
+ ["ArrowUp", "Above"],
522
+ ])("should take the caret out of the image's wrapper on %s", async (key, text) => {
523
+ const { editor, img } = await captioned();
524
+ editor.image.edit(editor.$(img));
525
+
526
+ press(editor, key);
527
+
528
+ expect(editor.image.get()).toBeFalsy();
529
+ expect(caretBlock()?.textContent).toBe(text);
530
+ expect(outline(editor)).toEqual(["p: Above", "fr-img-space-wrap", "p: Below"]);
531
+ });
532
+
533
+ it("should start a paragraph to take the caret to when there is none", async () => {
534
+ const { editor, img } = await captioned('<p>Above</p><p><img src="http://x/a.png" alt="" class="fr-dib"></p>');
535
+ editor.image.edit(editor.$(img));
536
+
537
+ press(editor, "ArrowRight");
538
+
539
+ expect(outline(editor)).toEqual(["p: Above", "fr-img-space-wrap", "p: "]);
540
+ expect(caretBlock()).toBe(editor.el.lastElementChild);
541
+ });
542
+
543
+ it("should hand AX the paragraph it starts between two images", async () => {
544
+ const { editor, img } = await captioned(
545
+ '<p><img src="http://x/a.png" alt="" class="fr-dib"></p><p><img id="second" src="http://x/b.png" alt="" class="fr-dib"></p>',
546
+ );
547
+ toggleCaption(editor, editor.el.querySelector("#second"));
548
+ editor.image.edit(editor.$(img));
549
+
550
+ press(editor, "ArrowRight");
551
+
552
+ expect(outline(editor)).toEqual(["fr-img-space-wrap", "p: ", "fr-img-space-wrap"]);
553
+ expect(onChange).toHaveBeenLastCalledWith(editor.html.get());
554
+ });
555
+
556
+ it.each([
557
+ ["with Backspace", (editor: any) => press(editor, "Backspace")],
558
+ ["with Delete", (editor: any) => press(editor, "Delete")],
559
+ ["from its popup", (editor: any) => editor.commands.exec("imageRemove")],
560
+ ])("should leave a paragraph where the image was when it is removed %s", async (_, remove) => {
561
+ const { editor, img } = await captioned();
562
+ editor.image.edit(editor.$(img));
563
+
564
+ remove(editor);
565
+
566
+ expect(editor.el.querySelector("img")).toBeNull();
567
+ expect(outline(editor)).toEqual(["p: Above", "p: ", "p: Below"]);
568
+ expect(caretBlock()).toBe(editor.el.children[1]);
569
+ expect(onChange).toHaveBeenLastCalledWith(editor.html.get());
570
+ });
571
+ });
572
+
284
573
  it("should leave Froala's pixel caption alone when resizing is off", async () => {
285
574
  const editor = await mountEditor('<p><img src="http://x/a.png" alt="" class="fr-dib"></p>');
286
575
 
@@ -19,6 +19,7 @@ vi.mock("react-froala-wysiwyg", () => ({
19
19
  $el: { get: vi.fn(() => editorElRef.current!) },
20
20
  el: editorElRef.current,
21
21
  edit: { on: vi.fn(), off: vi.fn() },
22
+ events: { on: vi.fn() },
22
23
  commands: { exec: vi.fn() },
23
24
  opts: { zIndex: 1 },
24
25
  $tb: { css: vi.fn() },
@@ -152,13 +152,201 @@ const getImagePercentWidth = (editor: any, $img: any) => {
152
152
  return percent > 0 && percent < 100 ? `${percent}%` : "100%";
153
153
  };
154
154
 
155
+ // Nothing but blank text, Froala's invisible spaces and its selection markers.
156
+ const isBlank = (fragment: DocumentFragment) => {
157
+ for (const marker of fragment.querySelectorAll(".fr-marker")) marker.remove();
158
+ return !fragment.textContent?.replace(/\u200B/g, "").trim() && !fragment.querySelector("img, iframe, video");
159
+ };
160
+
161
+ // Moves what `paragraph` holds before `first` and after `last` out to
162
+ // paragraphs of their own, around `anchor`, unless it is blank.
163
+ const splitAround = (paragraph: HTMLElement, first: Node, last: Node, anchor: Element) => {
164
+ const before = document.createRange();
165
+ before.setStart(paragraph, 0);
166
+ before.setEndBefore(first);
167
+ const after = document.createRange();
168
+ after.setStartAfter(last);
169
+ after.setEnd(paragraph, paragraph.childNodes.length);
170
+ for (const [range, side] of [
171
+ [before, "before"],
172
+ [after, "after"],
173
+ ] as const) {
174
+ if (isBlank(range.cloneContents())) continue;
175
+ const part = paragraph.cloneNode(false) as HTMLElement;
176
+ part.append(range.extractContents());
177
+ anchor[side](part);
178
+ }
179
+ };
180
+
181
+ // The outermost element around `img`, inside `paragraph`, with nothing but
182
+ // blank on that `side` of it: splitting the paragraph there leaves no empty
183
+ // copy of a link or a bold on that side.
184
+ const edgeAround = (img: Element, paragraph: Element, side: "before" | "after") => {
185
+ let edge = img;
186
+ while (edge.parentElement && edge.parentElement !== paragraph) {
187
+ const rest = document.createRange();
188
+ rest.selectNodeContents(edge.parentElement);
189
+ if (side === "before") rest.setEndBefore(edge);
190
+ else rest.setStartAfter(edge);
191
+ if (!isBlank(rest.cloneContents())) break;
192
+ edge = edge.parentElement;
193
+ }
194
+ return edge;
195
+ };
196
+
197
+ // Froala captions an image by wrapping the whole paragraph it is in, so any
198
+ // text sharing it ends up inside the caption, where it can't be edited, and
199
+ // goes away with the caption. Leave the image alone in its paragraph first,
200
+ // out of the bold or the link it may be in too: their text stays around it,
201
+ // still bold or linked. A linked image leaves the paragraph, in its link alone:
202
+ // Froala wraps just the link, and the wrapper div it adds can't sit inside a <p>.
203
+ //
204
+ // Removing a caption leaves the image in that wrapper div, out of any
205
+ // paragraph, and captioning it there nests a second wrapper that Froala then
206
+ // fails to unwrap: it throws, and unwraps another image's. Put the image back
207
+ // in a paragraph before anything else.
208
+ const isolateImage = (img: HTMLElement) => {
209
+ const unit = img.parentElement?.tagName === "A" ? img.parentElement : img;
210
+ const leftoverWrap = unit.parentElement;
211
+ if (leftoverWrap?.classList.contains("fr-img-space-wrap")) {
212
+ const p = document.createElement("p");
213
+ p.append(...leftoverWrap.childNodes);
214
+ leftoverWrap.replaceWith(p);
215
+ }
216
+ const paragraph = img.closest("p");
217
+ if (!paragraph) return;
218
+ splitAround(paragraph, edgeAround(img, paragraph, "before"), edgeAround(img, paragraph, "after"), paragraph);
219
+ const link = img.closest("a");
220
+ if (link && paragraph.contains(link)) {
221
+ link.replaceChildren(img);
222
+ paragraph.replaceWith(link);
223
+ } else {
224
+ paragraph.replaceChildren(img);
225
+ }
226
+ };
227
+
228
+ // Froala keeps the paragraph it wrapped inside the caption, so the caption's
229
+ // text sits in a <p> inside a <span>: it takes the paragraph style of the page,
230
+ // Froala's caption style misses it, and resizing measures the image against the
231
+ // caption itself. Leave the image and its caption text straight in the wrapper.
232
+ const dropCaptionParagraph = (editor: any, img: HTMLElement) => {
233
+ const paragraph = img.parentElement;
234
+ if (!paragraph?.matches(".fr-img-wrap > p")) return;
235
+ // Moving the caption's text drops the selection Froala leaves on it, to type over
236
+ editor.selection.save();
237
+ paragraph.replaceWith(...paragraph.childNodes);
238
+ editor.selection.restore();
239
+ };
240
+
241
+ // The div Froala keeps a captioned image in, and leaves it in once the caption
242
+ // goes. It should hold nothing but the image.
243
+ const imageWrapOf = (img: Element) => img.closest(".fr-img-space-wrap") || img.closest(".fr-img-caption");
244
+
245
+ // Captions put on before isolateImage still hold the text of the paragraph
246
+ // they wrapped, and Froala deletes it along with the caption: take it out to
247
+ // paragraphs around the image first.
248
+ const takeTextOutOfCaption = (img: HTMLElement) => {
249
+ const paragraph = img.parentElement;
250
+ const wrap = imageWrapOf(img);
251
+ if (!paragraph?.matches(".fr-img-wrap > p") || !wrap) return;
252
+ splitAround(paragraph, img, paragraph.querySelector(":scope > .fr-inner") || img, wrap);
253
+ };
254
+
255
+ // Removing an image leaves its wrapper div empty, with the caret in it, so what
256
+ // is typed next would not be in a paragraph: make the div one. Froala hands AX
257
+ // the content only when it saves an undo step, and it saved the removal with
258
+ // the div still there: save the paragraph as well.
259
+ const removeImage = (editor: any) => {
260
+ const wrap = imageWrapOf(editor.image.get().get(0));
261
+ editor.image.remove();
262
+ if (!wrap?.isConnected || wrap.querySelector("img")) return;
263
+ const p = document.createElement("p");
264
+ p.append(...wrap.childNodes);
265
+ wrap.replaceWith(p);
266
+ editor.selection.setAtStart(p);
267
+ editor.selection.restore();
268
+ editor.undo.saveStep();
269
+ };
270
+
271
+ // Leaving a selected image in a wrapper div with the arrows or Esc puts the
272
+ // caret inside the div, after the caption, and what is typed there is not in a
273
+ // paragraph: take the caret to the block next to the image, or to a new one.
274
+ const leaveWrappedImage = (editor: any, wrap: Element, key: string) => {
275
+ if (!["ArrowLeft", "ArrowUp", "ArrowRight", "ArrowDown", "Escape"].includes(key)) return false;
276
+ const forward = key !== "ArrowLeft" && key !== "ArrowUp";
277
+ let block = forward ? wrap.nextElementSibling : wrap.previousElementSibling;
278
+ if (!block?.matches("p, h1, h2, h3, h4, h5, h6, ul, ol, blockquote, pre, table")) {
279
+ block = document.createElement("p");
280
+ block.innerHTML = "<br>";
281
+ wrap[forward ? "after" : "before"](block);
282
+ }
283
+ editor.image.exitEdit(true);
284
+ if (forward) editor.selection.setAtStart(block);
285
+ else editor.selection.setAtEnd(block);
286
+ editor.selection.restore();
287
+ // A new paragraph has to reach AX too (see removeImage). With none, nothing is saved.
288
+ editor.undo.saveStep();
289
+ return true;
290
+ };
291
+
292
+ // Backspace at the start of the block after an image in a wrapper div merges
293
+ // that block into the div, and Delete at the end of the block before merges
294
+ // the caption out into that block. Select the image instead, dropping the
295
+ // block if it is empty: a second press removes the image.
296
+ const selectNeighbourImage = (editor: any, key: string) => {
297
+ const selection = editor.selection.get();
298
+ if ((key !== "Backspace" && key !== "Delete") || !selection.rangeCount || !selection.isCollapsed) return false;
299
+ const forward = key === "Delete";
300
+ const block: Element | undefined = editor.selection.blocks()[0];
301
+ const neighbour = forward ? block?.nextElementSibling : block?.previousElementSibling;
302
+ const img = neighbour?.matches(".fr-img-space-wrap") ? neighbour.querySelector("img") : null;
303
+ if (!block || !img) return false;
304
+ const toEdge = selection.getRangeAt(0).cloneRange();
305
+ if (forward) toEdge.setEnd(block, block.childNodes.length);
306
+ else toEdge.setStart(block, 0);
307
+ if (!isBlank(toEdge.cloneContents())) return false;
308
+ toEdge.selectNodeContents(block);
309
+ // Dropping the block has to reach AX too: see removeImage
310
+ if (isBlank(toEdge.cloneContents())) {
311
+ block.remove();
312
+ editor.undo.saveStep();
313
+ }
314
+ editor.image.edit(editor.$(img));
315
+ return true;
316
+ };
317
+
318
+ // Keeps text out of the div Froala wraps a captioned image in, which the keys
319
+ // around it move text into and the caption out of.
320
+ const handleImageWrapKeys = (editor: any, e: KeyboardEvent) => {
321
+ if (e.isComposing) return;
322
+ const img = editor.image.get()?.get(0);
323
+ const wrap = img && imageWrapOf(img);
324
+ if (!img) {
325
+ if (!selectNeighbourImage(editor, e.key)) return;
326
+ } else if (!wrap) {
327
+ return;
328
+ } else if (e.key === "Backspace" || e.key === "Delete") {
329
+ removeImage(editor);
330
+ } else if (!leaveWrappedImage(editor, wrap, e.key)) {
331
+ return;
332
+ }
333
+ e.preventDefault();
334
+ e.stopPropagation();
335
+ return false;
336
+ };
337
+
155
338
  export {
156
339
  createPopupFunctions,
340
+ dropCaptionParagraph,
157
341
  getImagePercentWidth,
158
342
  getLanguageMenuHtml,
159
343
  getPopupPosition,
160
344
  getRichTextConfig,
345
+ handleImageWrapKeys,
161
346
  type IRichTextConfig,
347
+ isolateImage,
162
348
  parseClassNames,
349
+ removeImage,
163
350
  setLinkAttributes,
351
+ takeTextOutOfCaption,
164
352
  };
@@ -11,7 +11,17 @@ import FroalaEditor from "froala-editor";
11
11
 
12
12
  import { LinkPopover } from "./atoms";
13
13
  import { buttons, buttonsFull, inlineToolbar, wysiwygConfig } from "./config";
14
- import { createPopupFunctions, getImagePercentWidth, getPopupPosition, setLinkAttributes } from "./helpers";
14
+ import {
15
+ createPopupFunctions,
16
+ dropCaptionParagraph,
17
+ getImagePercentWidth,
18
+ getPopupPosition,
19
+ handleImageWrapKeys,
20
+ isolateImage,
21
+ removeImage,
22
+ setLinkAttributes,
23
+ takeTextOutOfCaption,
24
+ } from "./helpers";
15
25
  import "./vendors";
16
26
 
17
27
  import { useModals } from "@ax/hooks";
@@ -51,6 +61,7 @@ const Wysiwyg = (props: IWysiwygProps) => {
51
61
  isImageLink?: boolean;
52
62
  } | null>(null);
53
63
  const replaceImgRef = useRef<any>(null);
64
+ const captioningImgRef = useRef<HTMLElement | null>(null);
54
65
  const captionWidthRef = useRef<any>(null);
55
66
  const uncaptionedHeightRef = useRef<{ img: HTMLElement; height: string } | null>(null);
56
67
  const liftedCaptionRef = useRef<{ paragraph: HTMLElement; nodes: ChildNode[] } | null>(null);
@@ -213,12 +224,12 @@ const Wysiwyg = (props: IWysiwygProps) => {
213
224
  if (!editorEl) return;
214
225
 
215
226
  // Froala resizes a percentage image against the nearest block around
216
- // it, and with a caption on that is the <p> the caption keeps inside:
217
- // every step of the drag measures against the width the step before
218
- // just set, and the image bounces. Lift the caption's content out of
219
- // that paragraph while dragging, so it measures against the column,
220
- // and put it back in "image.resizeEnd". Capturing runs it before
221
- // Froala's own mousedown on the handle.
227
+ // it, and in captions saved with a <p> inside (see dropCaptionParagraph)
228
+ // that is the <p>: every step of the drag measures against the width
229
+ // the step before just set, and the image bounces. Lift the caption's
230
+ // content out of that paragraph while dragging, so it measures against
231
+ // the column, and put it back in "image.resizeEnd". Capturing runs it
232
+ // before Froala's own mousedown on the handle.
222
233
  if (this.opts.imageResizeWithPercent) {
223
234
  this.$box?.get?.(0)?.addEventListener(
224
235
  "mousedown",
@@ -233,8 +244,9 @@ const Wysiwyg = (props: IWysiwygProps) => {
233
244
  true,
234
245
  );
235
246
 
236
- // A captioned image keeps its width on the caption, but Froala's size
237
- // popup only reads the image's own: show the caption's instead of auto.
247
+ // Captions saved before the image kept its width too have it on the
248
+ // caption alone, but Froala's size popup only reads the image's own:
249
+ // show the caption's instead of auto.
238
250
  this.popups.onRefresh("image.size", () => {
239
251
  const caption = this.image.get()?.get(0)?.closest(".fr-img-caption");
240
252
  if (!caption?.style.width) return;
@@ -242,6 +254,9 @@ const Wysiwyg = (props: IWysiwygProps) => {
242
254
  });
243
255
  }
244
256
 
257
+ // First, so it runs before Froala's own handling of these keys
258
+ this.events.on("keydown", (e: KeyboardEvent) => handleImageWrapKeys(this, e), true);
259
+
245
260
  editorEl.addEventListener("griddo:openLinkPopover", (e: Event) => {
246
261
  const detail = (e as CustomEvent).detail;
247
262
  setLinkPopoverOpen(true);
@@ -331,30 +346,40 @@ const Wysiwyg = (props: IWysiwygProps) => {
331
346
  // checking there is one: on an image inside a paragraph, or never resized,
332
347
  // it throws and no caption appears. Hand it the image's own width, and
333
348
  // once the caption is in, give that width to the caption, as Froala's
334
- // resizing expects, and take it off the image so it is not applied twice.
335
- // Removing the caption gives it back to the image.
349
+ // resizing expects, and keep it on the image: out of the editor nothing
350
+ // sizes the caption. In here the image fills its caption (see style.tsx),
351
+ // so the width is not applied twice. An image never resized has no width
352
+ // to keep: it leaves with none, so the site's default size still applies.
336
353
  //
337
- // Removing a caption also leaves the image in Froala's wrapper div, out
338
- // of its paragraph. Captioning it again there nests a second wrapper that
339
- // Froala then fails to unwrap, so put the image back in a paragraph first.
354
+ // In any mode, Froala's caption swallows the paragraph the image is in,
355
+ // and removing it deletes whatever it holds: see isolateImage,
356
+ // dropCaptionParagraph and takeTextOutOfCaption. Removing the image is
357
+ // ours too: see removeImage.
340
358
  "commands.before": function (this: any, cmd: string) {
341
359
  if (cmd === "fullscreen" && !this.fullscreen.isActive()) {
342
360
  this.opts.z_index = this.opts.zIndex;
343
361
  }
362
+ if (cmd === "imageRemove" && this.image.get()) {
363
+ removeImage(this);
364
+ return false;
365
+ }
366
+ if (cmd === "imageCaption" && this.image.get()) {
367
+ const img = this.image.get().get(0);
368
+ if (this.image.hasCaption()) {
369
+ takeTextOutOfCaption(img);
370
+ } else {
371
+ isolateImage(img);
372
+ captioningImgRef.current = img;
373
+ }
374
+ }
344
375
  if (cmd === "imageCaption" && this.opts.imageResizeWithPercent && !this.image.hasCaption()) {
345
376
  const $img = this.image.get();
346
377
  if (!$img) return;
347
378
  const img = $img.get(0);
348
- const leftoverWrap = img.closest(".fr-img-space-wrap");
349
- if (leftoverWrap) {
350
- const p = document.createElement("p");
351
- p.append(...leftoverWrap.childNodes);
352
- leftoverWrap.replaceWith(p);
353
- }
354
- const width = getImagePercentWidth(this, $img);
379
+ const width = img.style.width ? getImagePercentWidth(this, $img) : null;
355
380
  const $sized = $img.parent().is("a") || $img.parent().is("p") ? $img.parent() : $img;
356
381
  const seeded = !$sized.attr("style") && !$sized.attr("width");
357
- if (seeded) $sized.attr("width", width);
382
+ if (seeded) $sized.attr("width", width ?? "100%");
358
383
  captionWidthRef.current = { img, width, $seeded: seeded ? $sized : null };
359
384
  }
360
385
  // Removing the caption hands the image the caption's style in place of
@@ -368,13 +393,20 @@ const Wysiwyg = (props: IWysiwygProps) => {
368
393
  if (cmd === "fullscreen" && !this.fullscreen.isActive()) {
369
394
  this.$tb.css("z-index", "");
370
395
  }
396
+ if (cmd === "imageCaption" && captioningImgRef.current) {
397
+ dropCaptionParagraph(this, captioningImgRef.current);
398
+ captioningImgRef.current = null;
399
+ }
371
400
  if (cmd === "imageCaption" && captionWidthRef.current) {
372
401
  const { img, width, $seeded } = captionWidthRef.current;
373
402
  $seeded?.removeAttr("width");
374
403
  const caption = img.closest(".fr-img-caption");
375
- if (caption) caption.style.width = width;
376
- img.style.removeProperty("width");
377
- if (!img.getAttribute("style")) img.removeAttribute("style");
404
+ for (const el of [caption, img]) {
405
+ if (!el) continue;
406
+ if (width) el.style.width = width;
407
+ else el.style.removeProperty("width");
408
+ if (!el.getAttribute("style")) el.removeAttribute("style");
409
+ }
378
410
  captionWidthRef.current = null;
379
411
  }
380
412
  if (cmd === "imageCaption" && uncaptionedHeightRef.current) {
@@ -383,25 +415,29 @@ const Wysiwyg = (props: IWysiwygProps) => {
383
415
  uncaptionedHeightRef.current = null;
384
416
  }
385
417
  // The size popup sets the width and height on the caption and on the
386
- // image inside it, so the size is applied twice: in percent the widths
387
- // multiply, and a fixed height on the caption leaves no room for its
388
- // text. Keep the width on the caption and the height on the image.
418
+ // image inside it. The width belongs on both, but a fixed height on the
419
+ // caption leaves no room for its text: the height is the image's alone.
389
420
  if (cmd === "imageSetSize" && this.opts.imageResizeWithPercent && this.image.hasCaption()) {
390
- const img = this.image.get()?.get(0);
391
- const caption = img?.closest(".fr-img-caption");
392
- img?.style.removeProperty("width");
421
+ const caption = this.image.get()?.get(0)?.closest(".fr-img-caption");
393
422
  caption?.style.removeProperty("height");
394
- for (const el of [img, caption]) {
395
- if (el && !el.getAttribute("style")) el.removeAttribute("style");
396
- }
423
+ if (caption && !caption.getAttribute("style")) caption.removeAttribute("style");
397
424
  }
398
425
  },
399
- "image.resizeEnd": () => {
426
+ // Froala's resizing sizes a captioned image's caption alone: the image
427
+ // takes the same width, for outside the editor. Froala hands AX the
428
+ // content when it saves an undo step, and it saved the drag's before
429
+ // this: save again, or AX keeps the width the image had before.
430
+ "image.resizeEnd": function (this: any, $img: any) {
431
+ const img = $img?.get?.(0);
432
+ const caption = img?.closest(".fr-img-caption");
433
+ if (caption) img.style.width = caption.style.width;
400
434
  const lifted = liftedCaptionRef.current;
401
- if (!lifted) return;
402
- lifted.nodes[0].before(lifted.paragraph);
403
- lifted.paragraph.append(...lifted.nodes);
404
- liftedCaptionRef.current = null;
435
+ if (lifted) {
436
+ lifted.nodes[0].before(lifted.paragraph);
437
+ lifted.paragraph.append(...lifted.nodes);
438
+ liftedCaptionRef.current = null;
439
+ }
440
+ this.undo.saveStep();
405
441
  },
406
442
  // Froala's shortcut dispatcher calls plugin commands unbound, so its own
407
443
  // Ctrl/Cmd+K throws instead of opening anything. Returning false cancels
@@ -81,6 +81,11 @@ export const EditorWrapper = styled.div<{ error: boolean | undefined; disabled?:
81
81
  font-size: 17px;
82
82
  font-weight: 600;
83
83
  }
84
+ /* A captioned image carries its width for outside the editor, where nothing
85
+ sizes the caption. In here the caption has that width, and the image fills it. */
86
+ .fr-img-caption img {
87
+ width: 100% !important;
88
+ }
84
89
  .fr-toolbar {
85
90
  border-color: ${(p) =>
86
91
  p.error === true ? p.theme.color.error : p.disabled ? p.theme.color.interactiveDisabled : p.theme.color.uiLine};