@remit/ui 0.0.214 → 0.0.216
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 +1 -1
- package/src/components/calendar-suggestion-deck.pointer.test.ts +98 -0
- package/src/components/calendar-suggestion-deck.tsx +8 -2
- package/src/components/compose-body.tsx +4 -0
- package/src/components/compose-form-shell.tsx +42 -2
- package/src/components/rich-text-document.ts +11 -4
- package/src/components/rich-text-editor.stories.tsx +81 -0
- package/src/components/rich-text-editor.tsx +43 -10
- package/src/components/rich-text-image-node.ts +20 -5
- package/src/components/rich-text-inline-images.tsx +222 -0
- package/src/lib/adopted-html.test.ts +13 -0
- package/src/lib/adopted-html.ts +24 -3
- package/src/rich-text.ts +4 -0
package/package.json
CHANGED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import "@remit/test-dom";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { afterEach, beforeEach, describe, it } from "node:test";
|
|
4
|
+
import { act, createElement } from "react";
|
|
5
|
+
import { createRoot, type Root } from "react-dom/client";
|
|
6
|
+
import {
|
|
7
|
+
CalendarSuggestionDeck,
|
|
8
|
+
type CalendarSuggestionDeckProps,
|
|
9
|
+
} from "./calendar-suggestion-deck.js";
|
|
10
|
+
|
|
11
|
+
let container: HTMLElement;
|
|
12
|
+
let root: Root;
|
|
13
|
+
let captured: number[];
|
|
14
|
+
let confirmed: number;
|
|
15
|
+
let pressed: number;
|
|
16
|
+
|
|
17
|
+
const originalSet = HTMLElement.prototype.setPointerCapture;
|
|
18
|
+
const originalHas = HTMLElement.prototype.hasPointerCapture;
|
|
19
|
+
|
|
20
|
+
beforeEach(() => {
|
|
21
|
+
captured = [];
|
|
22
|
+
confirmed = 0;
|
|
23
|
+
pressed = 0;
|
|
24
|
+
HTMLElement.prototype.setPointerCapture = (pointerId: number) => {
|
|
25
|
+
captured.push(pointerId);
|
|
26
|
+
};
|
|
27
|
+
HTMLElement.prototype.hasPointerCapture = (pointerId: number) =>
|
|
28
|
+
captured.includes(pointerId);
|
|
29
|
+
const deckProps: CalendarSuggestionDeckProps = {
|
|
30
|
+
hasCard: true,
|
|
31
|
+
remaining: 1,
|
|
32
|
+
blocked: false,
|
|
33
|
+
blockedReason: "",
|
|
34
|
+
onConfirm: () => {
|
|
35
|
+
confirmed += 1;
|
|
36
|
+
},
|
|
37
|
+
onReject: () => undefined,
|
|
38
|
+
children: createElement(
|
|
39
|
+
"button",
|
|
40
|
+
{
|
|
41
|
+
type: "button",
|
|
42
|
+
onClick: () => {
|
|
43
|
+
pressed += 1;
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
"Change first",
|
|
47
|
+
),
|
|
48
|
+
};
|
|
49
|
+
container = document.createElement("div");
|
|
50
|
+
document.body.append(container);
|
|
51
|
+
root = createRoot(container);
|
|
52
|
+
act(() => {
|
|
53
|
+
root.render(createElement(CalendarSuggestionDeck, deckProps));
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
afterEach(() => {
|
|
58
|
+
act(() => root.unmount());
|
|
59
|
+
container.remove();
|
|
60
|
+
HTMLElement.prototype.setPointerCapture = originalSet;
|
|
61
|
+
HTMLElement.prototype.hasPointerCapture = originalHas;
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
const pointer = (target: Element, type: string, clientX: number) => {
|
|
65
|
+
act(() => {
|
|
66
|
+
target.dispatchEvent(
|
|
67
|
+
new PointerEvent(type, { bubbles: true, clientX, pointerId: 1 }),
|
|
68
|
+
);
|
|
69
|
+
});
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const button = (): HTMLButtonElement => {
|
|
73
|
+
const found = container.querySelector("button");
|
|
74
|
+
if (!found) throw new Error("the card's button is not drawn");
|
|
75
|
+
return found;
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
describe("pressing a button on the top card", () => {
|
|
79
|
+
it("leaves the pointer to the button, so the press reaches it", () => {
|
|
80
|
+
pointer(button(), "pointerdown", 100);
|
|
81
|
+
pointer(button(), "pointerup", 100);
|
|
82
|
+
act(() => button().click());
|
|
83
|
+
|
|
84
|
+
assert.deepEqual(captured, []);
|
|
85
|
+
assert.equal(pressed, 1);
|
|
86
|
+
assert.equal(confirmed, 0);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("still takes the pointer once the card is dragged, and a long drag confirms", () => {
|
|
90
|
+
pointer(button(), "pointerdown", 100);
|
|
91
|
+
pointer(button(), "pointermove", 150);
|
|
92
|
+
pointer(button(), "pointermove", 220);
|
|
93
|
+
pointer(button(), "pointerup", 220);
|
|
94
|
+
|
|
95
|
+
assert.deepEqual(captured, [1]);
|
|
96
|
+
assert.equal(confirmed, 1);
|
|
97
|
+
});
|
|
98
|
+
});
|
|
@@ -9,6 +9,7 @@ import { cn } from "../lib/cn.js";
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
const COMMIT_DISTANCE = 96;
|
|
12
|
+
const DRAG_SLOP = 6;
|
|
12
13
|
|
|
13
14
|
export interface CalendarSuggestionDeckProps {
|
|
14
15
|
children: ReactNode;
|
|
@@ -68,12 +69,17 @@ export function CalendarSuggestionDeck({
|
|
|
68
69
|
transition: from === null ? "transform 180ms ease-out" : "none",
|
|
69
70
|
}}
|
|
70
71
|
onPointerDown={(e) => {
|
|
71
|
-
e.currentTarget.setPointerCapture(e.pointerId);
|
|
72
72
|
setFrom(e.clientX);
|
|
73
73
|
}}
|
|
74
74
|
onPointerMove={(e) => {
|
|
75
75
|
if (from === null) return;
|
|
76
|
-
|
|
76
|
+
const moved = e.clientX - from;
|
|
77
|
+
if (
|
|
78
|
+
Math.abs(moved) > DRAG_SLOP &&
|
|
79
|
+
!e.currentTarget.hasPointerCapture(e.pointerId)
|
|
80
|
+
)
|
|
81
|
+
e.currentTarget.setPointerCapture(e.pointerId);
|
|
82
|
+
setDrag(moved);
|
|
77
83
|
}}
|
|
78
84
|
onPointerUp={() => {
|
|
79
85
|
if (Math.abs(drag) > COMMIT_DISTANCE) {
|
|
@@ -9,6 +9,7 @@ import { ConfirmDialog } from "./confirm-dialog.js";
|
|
|
9
9
|
import { PlainTextEditor } from "./plain-text-editor.js";
|
|
10
10
|
import { markdownToHtml } from "./rich-text-document.js";
|
|
11
11
|
import { RichTextEditor } from "./rich-text-editor.js";
|
|
12
|
+
import type { InlineImages } from "./rich-text-inline-images.js";
|
|
12
13
|
import type { SpellcheckOptions } from "./rich-text-spellcheck.js";
|
|
13
14
|
import type {
|
|
14
15
|
ComposeCaret,
|
|
@@ -75,6 +76,7 @@ export interface ComposeBodyProps {
|
|
|
75
76
|
spellcheck?: SpellcheckOptions;
|
|
76
77
|
insertion?: ComposeInsertion;
|
|
77
78
|
onInserted?: (version: number) => void;
|
|
79
|
+
inlineImages?: InlineImages;
|
|
78
80
|
}
|
|
79
81
|
|
|
80
82
|
/**
|
|
@@ -99,6 +101,7 @@ export const ComposeBody = ({
|
|
|
99
101
|
spellcheck,
|
|
100
102
|
insertion,
|
|
101
103
|
onInserted,
|
|
104
|
+
inlineImages,
|
|
102
105
|
}: ComposeBodyProps) => {
|
|
103
106
|
const [richHtml, setRichHtml] = useState(initialHtml);
|
|
104
107
|
const [richGeneration, setRichGeneration] = useState(0);
|
|
@@ -218,6 +221,7 @@ export const ComposeBody = ({
|
|
|
218
221
|
spellcheck={spellcheck}
|
|
219
222
|
insertion={insertion}
|
|
220
223
|
onInserted={onInserted}
|
|
224
|
+
inlineImages={inlineImages}
|
|
221
225
|
/>
|
|
222
226
|
)}
|
|
223
227
|
<ConfirmDialog
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type DragEvent, type ReactNode, useState } from "react";
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* How the surface gets its height. `fill` takes the one its container hands it
|
|
@@ -23,8 +23,12 @@ export interface ComposeFormShellProps {
|
|
|
23
23
|
/** The ComposeActionBar. */
|
|
24
24
|
actionBar: ReactNode;
|
|
25
25
|
layout?: ComposeShellLayout;
|
|
26
|
+
onDropFiles?: (files: File[]) => void;
|
|
26
27
|
}
|
|
27
28
|
|
|
29
|
+
const carriesFiles = (event: DragEvent): boolean =>
|
|
30
|
+
Array.from(event.dataTransfer?.types ?? []).includes("Files");
|
|
31
|
+
|
|
28
32
|
/**
|
|
29
33
|
* Presentational compose layout: banner / header / body+quote / action bar.
|
|
30
34
|
*
|
|
@@ -51,10 +55,46 @@ export function ComposeFormShell({
|
|
|
51
55
|
attachments,
|
|
52
56
|
actionBar,
|
|
53
57
|
layout = "fill",
|
|
58
|
+
onDropFiles,
|
|
54
59
|
}: ComposeFormShellProps) {
|
|
55
60
|
const fills = layout === "fill";
|
|
61
|
+
const [dropping, setDropping] = useState(false);
|
|
62
|
+
const dropTarget = onDropFiles
|
|
63
|
+
? {
|
|
64
|
+
onDragOver: (event: DragEvent<HTMLDivElement>) => {
|
|
65
|
+
if (!carriesFiles(event)) return;
|
|
66
|
+
event.preventDefault();
|
|
67
|
+
setDropping(true);
|
|
68
|
+
},
|
|
69
|
+
onDragLeave: (event: DragEvent<HTMLDivElement>) => {
|
|
70
|
+
if (
|
|
71
|
+
event.relatedTarget instanceof Node &&
|
|
72
|
+
event.currentTarget.contains(event.relatedTarget)
|
|
73
|
+
)
|
|
74
|
+
return;
|
|
75
|
+
setDropping(false);
|
|
76
|
+
},
|
|
77
|
+
onDrop: (event: DragEvent<HTMLDivElement>) => {
|
|
78
|
+
setDropping(false);
|
|
79
|
+
const files = Array.from(event.dataTransfer?.files ?? []);
|
|
80
|
+
if (files.length === 0) return;
|
|
81
|
+
event.preventDefault();
|
|
82
|
+
onDropFiles(files);
|
|
83
|
+
},
|
|
84
|
+
}
|
|
85
|
+
: {};
|
|
56
86
|
return (
|
|
57
|
-
<div
|
|
87
|
+
<div
|
|
88
|
+
className={[
|
|
89
|
+
fills ? "flex h-full min-h-0 flex-col" : "flex flex-col",
|
|
90
|
+
dropping && "outline-2 -outline-offset-2 outline-dashed outline-accent",
|
|
91
|
+
]
|
|
92
|
+
.filter(Boolean)
|
|
93
|
+
.join(" ")}
|
|
94
|
+
data-testid="compose-drop-target"
|
|
95
|
+
data-dropping={dropping || undefined}
|
|
96
|
+
{...dropTarget}
|
|
97
|
+
>
|
|
58
98
|
{banner}
|
|
59
99
|
{header}
|
|
60
100
|
<div
|
|
@@ -13,7 +13,10 @@ import {
|
|
|
13
13
|
type LexicalNode,
|
|
14
14
|
type TextFormatType,
|
|
15
15
|
} from "lexical";
|
|
16
|
-
import {
|
|
16
|
+
import {
|
|
17
|
+
type ContentIdOwner,
|
|
18
|
+
sanitizeAdoptedHtml,
|
|
19
|
+
} from "../lib/adopted-html.js";
|
|
17
20
|
import { COMPOSE_TRANSFORMERS } from "./rich-text-markdown.js";
|
|
18
21
|
import { RICH_TEXT_NODES } from "./rich-text-nodes.js";
|
|
19
22
|
import type { RichTextValue } from "./rich-text-value.js";
|
|
@@ -21,9 +24,10 @@ import type { RichTextValue } from "./rich-text-value.js";
|
|
|
21
24
|
export const $adoptHtml = (
|
|
22
25
|
editor: LexicalEditor,
|
|
23
26
|
html: string,
|
|
27
|
+
owns?: ContentIdOwner,
|
|
24
28
|
): LexicalNode[] => {
|
|
25
29
|
const document = new DOMParser().parseFromString(
|
|
26
|
-
sanitizeAdoptedHtml(html),
|
|
30
|
+
sanitizeAdoptedHtml(html, owns),
|
|
27
31
|
"text/html",
|
|
28
32
|
);
|
|
29
33
|
return $generateNodesFromDOM(editor, document);
|
|
@@ -85,8 +89,11 @@ export const $documentFormatting = (): string[] => {
|
|
|
85
89
|
* outgoing document goes back through the same profile a paste comes in
|
|
86
90
|
* through.
|
|
87
91
|
*/
|
|
88
|
-
export const $readRichText = (
|
|
89
|
-
|
|
92
|
+
export const $readRichText = (
|
|
93
|
+
editor: LexicalEditor,
|
|
94
|
+
owns?: ContentIdOwner,
|
|
95
|
+
): RichTextValue => ({
|
|
96
|
+
html: sanitizeAdoptedHtml($generateHtmlFromNodes(editor, null), owns),
|
|
90
97
|
text: $convertToMarkdownString(COMPOSE_TRANSFORMERS),
|
|
91
98
|
formatting: $documentFormatting(),
|
|
92
99
|
});
|
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
ComposeModeToggle,
|
|
9
9
|
} from "./compose-mode-toggle.js";
|
|
10
10
|
import { RichTextEditor } from "./rich-text-editor.js";
|
|
11
|
+
import type { InlineImages } from "./rich-text-inline-images.js";
|
|
11
12
|
import type {
|
|
12
13
|
CheckRequest,
|
|
13
14
|
Finding,
|
|
@@ -1110,3 +1111,83 @@ export const StickyToolbar: Story = {
|
|
|
1110
1111
|
).toBeLessThan(60);
|
|
1111
1112
|
},
|
|
1112
1113
|
};
|
|
1114
|
+
|
|
1115
|
+
const pasteScreenshot = async (editable: HTMLElement): Promise<void> => {
|
|
1116
|
+
const canvas = document.createElement("canvas");
|
|
1117
|
+
canvas.width = 480;
|
|
1118
|
+
canvas.height = 200;
|
|
1119
|
+
const context = canvas.getContext("2d");
|
|
1120
|
+
if (!context) throw new Error("no 2d canvas to draw the screenshot on");
|
|
1121
|
+
context.fillStyle = "#e2e8f0";
|
|
1122
|
+
context.fillRect(0, 0, 480, 200);
|
|
1123
|
+
context.fillStyle = "#3780f6";
|
|
1124
|
+
for (const [index, height] of [60, 120, 90, 160].entries()) {
|
|
1125
|
+
context.fillRect(40 + index * 110, 180 - height, 70, height);
|
|
1126
|
+
}
|
|
1127
|
+
const blob = await new Promise<Blob | null>((resolve) =>
|
|
1128
|
+
canvas.toBlob(resolve, "image/png"),
|
|
1129
|
+
);
|
|
1130
|
+
if (!blob) throw new Error("the screenshot could not be encoded");
|
|
1131
|
+
const clipboard = new DataTransfer();
|
|
1132
|
+
clipboard.items.add(new File([blob], "chart.png", { type: "image/png" }));
|
|
1133
|
+
editable.dispatchEvent(
|
|
1134
|
+
new ClipboardEvent("paste", {
|
|
1135
|
+
clipboardData: clipboard,
|
|
1136
|
+
bubbles: true,
|
|
1137
|
+
cancelable: true,
|
|
1138
|
+
}),
|
|
1139
|
+
);
|
|
1140
|
+
};
|
|
1141
|
+
|
|
1142
|
+
const storyInlineImages: InlineImages = {
|
|
1143
|
+
attach: (files, placement) => {
|
|
1144
|
+
for (const file of files) placement?.stored(file, `${file.name}@remit`);
|
|
1145
|
+
},
|
|
1146
|
+
owns: (contentId) => contentId.endsWith("@remit"),
|
|
1147
|
+
resolve: async () => null,
|
|
1148
|
+
onRemoved: () => () => {},
|
|
1149
|
+
};
|
|
1150
|
+
|
|
1151
|
+
const InlineImageComposer = () => {
|
|
1152
|
+
const [outgoing, setOutgoing] = useState("");
|
|
1153
|
+
return (
|
|
1154
|
+
<>
|
|
1155
|
+
<RichTextEditor
|
|
1156
|
+
initialHtml="<p>This week's numbers:</p>"
|
|
1157
|
+
onChange={(value) => setOutgoing(value.html)}
|
|
1158
|
+
inlineImages={storyInlineImages}
|
|
1159
|
+
/>
|
|
1160
|
+
<output data-testid="outgoing-html" className="sr-only">
|
|
1161
|
+
{outgoing}
|
|
1162
|
+
</output>
|
|
1163
|
+
</>
|
|
1164
|
+
);
|
|
1165
|
+
};
|
|
1166
|
+
|
|
1167
|
+
export const PastedInlineImage: Story = {
|
|
1168
|
+
name: "Pasting a screenshot inline",
|
|
1169
|
+
render: () => <InlineImageComposer />,
|
|
1170
|
+
play: async ({ canvasElement }) => {
|
|
1171
|
+
const editable = canvasElement.querySelector<HTMLElement>(
|
|
1172
|
+
"[data-testid=compose-body]",
|
|
1173
|
+
);
|
|
1174
|
+
const outgoing = canvasElement.querySelector<HTMLElement>(
|
|
1175
|
+
"[data-testid=outgoing-html]",
|
|
1176
|
+
);
|
|
1177
|
+
if (!editable || !outgoing) throw new Error("the editor is not mounted");
|
|
1178
|
+
|
|
1179
|
+
await userEvent.click(editable);
|
|
1180
|
+
await pasteScreenshot(editable);
|
|
1181
|
+
|
|
1182
|
+
const image = await waitFor(() => {
|
|
1183
|
+
const shown = editable.querySelector("img");
|
|
1184
|
+
if (!shown) throw new Error("the screenshot is not in the body");
|
|
1185
|
+
return shown;
|
|
1186
|
+
});
|
|
1187
|
+
await expect(image).toHaveAttribute("alt", "chart.png");
|
|
1188
|
+
await waitFor(() => expect(image.naturalWidth).toBe(480));
|
|
1189
|
+
await waitFor(() =>
|
|
1190
|
+
expect(outgoing.textContent).toContain('src="cid:chart.png@remit"'),
|
|
1191
|
+
);
|
|
1192
|
+
},
|
|
1193
|
+
};
|
|
@@ -30,9 +30,16 @@ import {
|
|
|
30
30
|
useRef,
|
|
31
31
|
useState,
|
|
32
32
|
} from "react";
|
|
33
|
+
import type { ContentIdOwner } from "../lib/adopted-html.js";
|
|
33
34
|
import { isWritingElsewhere } from "./editor-focus.js";
|
|
34
35
|
import { RichTextCorrectionMenu } from "./rich-text-correction-menu.js";
|
|
35
36
|
import { $adoptHtml, $readRichText } from "./rich-text-document.js";
|
|
37
|
+
import {
|
|
38
|
+
$pasteFiles,
|
|
39
|
+
InlineImagePlugin,
|
|
40
|
+
type InlineImages,
|
|
41
|
+
pastedFiles,
|
|
42
|
+
} from "./rich-text-inline-images.js";
|
|
36
43
|
import { RICH_TEXT_NODES, richTextTheme } from "./rich-text-nodes.js";
|
|
37
44
|
import type {
|
|
38
45
|
CheckSpan,
|
|
@@ -87,6 +94,7 @@ export interface RichTextEditorProps {
|
|
|
87
94
|
spellcheck?: SpellcheckOptions;
|
|
88
95
|
insertion?: ComposeInsertion;
|
|
89
96
|
onInserted?: (version: number) => void;
|
|
97
|
+
inlineImages?: InlineImages;
|
|
90
98
|
}
|
|
91
99
|
|
|
92
100
|
/**
|
|
@@ -98,7 +106,13 @@ export interface RichTextEditorProps {
|
|
|
98
106
|
* Apple Mail. The clipboard event carries no modifier state, so the keystroke
|
|
99
107
|
* that triggered it is what records the intent.
|
|
100
108
|
*/
|
|
101
|
-
const PastePlugin = (
|
|
109
|
+
const PastePlugin = ({
|
|
110
|
+
inlineImages,
|
|
111
|
+
owns,
|
|
112
|
+
}: {
|
|
113
|
+
inlineImages: RefObject<InlineImages | undefined>;
|
|
114
|
+
owns: ContentIdOwner;
|
|
115
|
+
}) => {
|
|
102
116
|
const [editor] = useLexicalComposerContext();
|
|
103
117
|
const plainRequested = useRef(false);
|
|
104
118
|
|
|
@@ -130,6 +144,14 @@ const PastePlugin = () => {
|
|
|
130
144
|
const wasPlainRequested = plainRequested.current;
|
|
131
145
|
plainRequested.current = false;
|
|
132
146
|
|
|
147
|
+
const images = inlineImages.current;
|
|
148
|
+
const files = images ? pastedFiles(clipboard) : [];
|
|
149
|
+
if (images && files.length > 0) {
|
|
150
|
+
event.preventDefault();
|
|
151
|
+
$pasteFiles(editor, files, images);
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
|
|
133
155
|
if (wasPlainRequested) {
|
|
134
156
|
const selection = $getSelection();
|
|
135
157
|
if (!$isRangeSelection(selection)) return false;
|
|
@@ -142,13 +164,13 @@ const PastePlugin = () => {
|
|
|
142
164
|
if (!html) return false;
|
|
143
165
|
|
|
144
166
|
event.preventDefault();
|
|
145
|
-
$insertNodes($adoptHtml(editor, html));
|
|
167
|
+
$insertNodes($adoptHtml(editor, html, owns));
|
|
146
168
|
return true;
|
|
147
169
|
},
|
|
148
170
|
COMMAND_PRIORITY_CRITICAL,
|
|
149
171
|
),
|
|
150
172
|
),
|
|
151
|
-
[editor],
|
|
173
|
+
[editor, inlineImages, owns],
|
|
152
174
|
);
|
|
153
175
|
|
|
154
176
|
return null;
|
|
@@ -162,8 +184,10 @@ const PastePlugin = () => {
|
|
|
162
184
|
*/
|
|
163
185
|
const ChangePlugin = ({
|
|
164
186
|
onChange,
|
|
187
|
+
owns,
|
|
165
188
|
}: {
|
|
166
189
|
onChange: (value: RichTextValue) => void;
|
|
190
|
+
owns: ContentIdOwner;
|
|
167
191
|
}) => {
|
|
168
192
|
const [editor] = useLexicalComposerContext();
|
|
169
193
|
const report = useRef(onChange);
|
|
@@ -173,13 +197,14 @@ const ChangePlugin = ({
|
|
|
173
197
|
}, [onChange]);
|
|
174
198
|
|
|
175
199
|
useEffect(() => {
|
|
176
|
-
const emit = () =>
|
|
200
|
+
const emit = () =>
|
|
201
|
+
report.current(editor.read(() => $readRichText(editor, owns)));
|
|
177
202
|
emit();
|
|
178
203
|
return editor.registerUpdateListener(({ dirtyElements, dirtyLeaves }) => {
|
|
179
204
|
if (dirtyElements.size === 0 && dirtyLeaves.size === 0) return;
|
|
180
205
|
emit();
|
|
181
206
|
});
|
|
182
|
-
}, [editor]);
|
|
207
|
+
}, [editor, owns]);
|
|
183
208
|
|
|
184
209
|
return null;
|
|
185
210
|
};
|
|
@@ -939,9 +964,9 @@ const InsertionPlugin = ({
|
|
|
939
964
|
};
|
|
940
965
|
|
|
941
966
|
const seedDocument =
|
|
942
|
-
(html: string) =>
|
|
967
|
+
(html: string, owns: ContentIdOwner) =>
|
|
943
968
|
(editor: LexicalEditor): void => {
|
|
944
|
-
const nodes = $adoptHtml(editor, html);
|
|
969
|
+
const nodes = $adoptHtml(editor, html, owns);
|
|
945
970
|
if (nodes.length === 0) return;
|
|
946
971
|
$getRoot().select();
|
|
947
972
|
$insertNodes(nodes);
|
|
@@ -959,9 +984,16 @@ export const RichTextEditor = ({
|
|
|
959
984
|
spellcheck,
|
|
960
985
|
insertion,
|
|
961
986
|
onInserted,
|
|
987
|
+
inlineImages,
|
|
962
988
|
}: RichTextEditorProps) => {
|
|
963
989
|
const [checkedHere, setCheckedHere] = useState(false);
|
|
964
990
|
const bodyRef = useRef<HTMLDivElement>(null);
|
|
991
|
+
const inlineRef = useRef(inlineImages);
|
|
992
|
+
inlineRef.current = inlineImages;
|
|
993
|
+
const owns = useCallback(
|
|
994
|
+
(contentId: string) => inlineRef.current?.owns(contentId) ?? false,
|
|
995
|
+
[],
|
|
996
|
+
);
|
|
965
997
|
|
|
966
998
|
return (
|
|
967
999
|
<LexicalComposer
|
|
@@ -969,7 +1001,7 @@ export const RichTextEditor = ({
|
|
|
969
1001
|
namespace: "compose",
|
|
970
1002
|
nodes: RICH_TEXT_NODES,
|
|
971
1003
|
theme: richTextTheme,
|
|
972
|
-
editorState: initialHtml ? seedDocument(initialHtml) : undefined,
|
|
1004
|
+
editorState: initialHtml ? seedDocument(initialHtml, owns) : undefined,
|
|
973
1005
|
onError: (error) => {
|
|
974
1006
|
throw error;
|
|
975
1007
|
},
|
|
@@ -1029,10 +1061,11 @@ export const RichTextEditor = ({
|
|
|
1029
1061
|
<ListPlugin />
|
|
1030
1062
|
<LinkPlugin />
|
|
1031
1063
|
<TablePlugin />
|
|
1032
|
-
<PastePlugin />
|
|
1064
|
+
<PastePlugin inlineImages={inlineRef} owns={owns} />
|
|
1065
|
+
<InlineImagePlugin inlineImages={inlineRef} />
|
|
1033
1066
|
<AutoFocus caret={initialCaret} />
|
|
1034
1067
|
<InsertionPlugin insertion={insertion} onInserted={onInserted} />
|
|
1035
|
-
{onChange && <ChangePlugin onChange={onChange} />}
|
|
1068
|
+
{onChange && <ChangePlugin onChange={onChange} owns={owns} />}
|
|
1036
1069
|
</LexicalComposer>
|
|
1037
1070
|
);
|
|
1038
1071
|
};
|
|
@@ -29,6 +29,8 @@ export class ImageNode extends DecoratorNode<null> {
|
|
|
29
29
|
__src: string;
|
|
30
30
|
/** @internal */
|
|
31
31
|
__alt: string;
|
|
32
|
+
/** @internal */
|
|
33
|
+
__preview = "";
|
|
32
34
|
|
|
33
35
|
$config() {
|
|
34
36
|
return this.config("image", {
|
|
@@ -48,22 +50,25 @@ export class ImageNode extends DecoratorNode<null> {
|
|
|
48
50
|
super.afterCloneFrom(prevNode);
|
|
49
51
|
this.__src = prevNode.__src;
|
|
50
52
|
this.__alt = prevNode.__alt;
|
|
53
|
+
this.__preview = prevNode.__preview;
|
|
51
54
|
}
|
|
52
55
|
|
|
53
56
|
createDOM(config: EditorConfig): HTMLImageElement {
|
|
54
|
-
const element = this.buildImage();
|
|
57
|
+
const element = this.buildImage(this.__preview || this.__src);
|
|
55
58
|
addClassNamesToElement(element, config.theme.image);
|
|
56
59
|
return element;
|
|
57
60
|
}
|
|
58
61
|
|
|
59
62
|
updateDOM(prevNode: this, element: HTMLImageElement): boolean {
|
|
60
|
-
|
|
63
|
+
const shown = this.__preview || this.__src;
|
|
64
|
+
if ((prevNode.__preview || prevNode.__src) !== shown)
|
|
65
|
+
element.setAttribute("src", shown);
|
|
61
66
|
if (prevNode.__alt !== this.__alt) element.setAttribute("alt", this.__alt);
|
|
62
67
|
return false;
|
|
63
68
|
}
|
|
64
69
|
|
|
65
70
|
exportDOM(): DOMExportOutput {
|
|
66
|
-
return { element: this.buildImage() };
|
|
71
|
+
return { element: this.buildImage(this.__src) };
|
|
67
72
|
}
|
|
68
73
|
|
|
69
74
|
exportJSON(): SerializedImageNode {
|
|
@@ -87,6 +92,16 @@ export class ImageNode extends DecoratorNode<null> {
|
|
|
87
92
|
return writable;
|
|
88
93
|
}
|
|
89
94
|
|
|
95
|
+
getPreview(): string {
|
|
96
|
+
return this.getLatest().__preview;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
setPreview(preview: string): this {
|
|
100
|
+
const writable = this.getWritable();
|
|
101
|
+
writable.__preview = preview;
|
|
102
|
+
return writable;
|
|
103
|
+
}
|
|
104
|
+
|
|
90
105
|
getAlt(): string {
|
|
91
106
|
return this.getLatest().__alt;
|
|
92
107
|
}
|
|
@@ -106,9 +121,9 @@ export class ImageNode extends DecoratorNode<null> {
|
|
|
106
121
|
return true;
|
|
107
122
|
}
|
|
108
123
|
|
|
109
|
-
private buildImage(): HTMLImageElement {
|
|
124
|
+
private buildImage(src: string): HTMLImageElement {
|
|
110
125
|
const element = $getDocument().createElement("img");
|
|
111
|
-
element.setAttribute("src",
|
|
126
|
+
element.setAttribute("src", src);
|
|
112
127
|
element.setAttribute("alt", this.__alt);
|
|
113
128
|
return element;
|
|
114
129
|
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
|
|
2
|
+
import { $dfs, mergeRegister } from "@lexical/utils";
|
|
3
|
+
import {
|
|
4
|
+
$applyNodeReplacement,
|
|
5
|
+
$createParagraphNode,
|
|
6
|
+
$getNodeByKey,
|
|
7
|
+
$getRoot,
|
|
8
|
+
$insertNodes,
|
|
9
|
+
$isElementNode,
|
|
10
|
+
HISTORY_MERGE_TAG,
|
|
11
|
+
HISTORY_PUSH_TAG,
|
|
12
|
+
type LexicalEditor,
|
|
13
|
+
type NodeKey,
|
|
14
|
+
} from "lexical";
|
|
15
|
+
import { type RefObject, useEffect } from "react";
|
|
16
|
+
import { ImageNode } from "./rich-text-image-node.js";
|
|
17
|
+
|
|
18
|
+
export interface InlineImagePlacement {
|
|
19
|
+
stored: (file: File, contentId: string) => void;
|
|
20
|
+
failed: (file: File) => void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface InlineImages {
|
|
24
|
+
attach: (files: File[], placement?: InlineImagePlacement) => void;
|
|
25
|
+
owns: (contentId: string) => boolean;
|
|
26
|
+
resolve: (contentId: string) => Promise<string | null>;
|
|
27
|
+
onRemoved: (listener: (contentId: string) => void) => () => void;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const CONTENT_ID_SOURCE = /^cid:(.+)$/i;
|
|
31
|
+
|
|
32
|
+
const contentIdOf = (src: string): string | null =>
|
|
33
|
+
CONTENT_ID_SOURCE.exec(src)?.[1] ?? null;
|
|
34
|
+
|
|
35
|
+
export const pastedFiles = (clipboard: DataTransfer): File[] => {
|
|
36
|
+
if (clipboard.getData("text/plain")) return [];
|
|
37
|
+
return Array.from(clipboard.files ?? []);
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const isImage = (file: File): boolean => file.type.startsWith("image/");
|
|
41
|
+
|
|
42
|
+
const merged = { tag: HISTORY_MERGE_TAG };
|
|
43
|
+
|
|
44
|
+
export const $pasteFiles = (
|
|
45
|
+
editor: LexicalEditor,
|
|
46
|
+
files: File[],
|
|
47
|
+
inlineImages: InlineImages,
|
|
48
|
+
): void => {
|
|
49
|
+
const images = files.filter(isImage);
|
|
50
|
+
const others = files.filter((file) => !isImage(file));
|
|
51
|
+
const placed = new Map<File, NodeKey>();
|
|
52
|
+
const taken = new Map<File, { parentKey: NodeKey; index: number }>();
|
|
53
|
+
const $createImage = (file: File, src: string): ImageNode => {
|
|
54
|
+
const node = $applyNodeReplacement(
|
|
55
|
+
new ImageNode(src, file.name),
|
|
56
|
+
).setPreview(URL.createObjectURL(file));
|
|
57
|
+
placed.set(file, node.getKey());
|
|
58
|
+
return node;
|
|
59
|
+
};
|
|
60
|
+
const nodes = images.map((file) => $createImage(file, ""));
|
|
61
|
+
if (nodes.length > 0) $insertNodes(nodes);
|
|
62
|
+
const placedImage = (file: File): ImageNode | null => {
|
|
63
|
+
const key = placed.get(file);
|
|
64
|
+
const node = key === undefined ? null : $getNodeByKey(key);
|
|
65
|
+
return node instanceof ImageNode ? node : null;
|
|
66
|
+
};
|
|
67
|
+
queueMicrotask(() => {
|
|
68
|
+
if (others.length > 0) inlineImages.attach(others);
|
|
69
|
+
if (images.length === 0) return;
|
|
70
|
+
inlineImages.attach(images, {
|
|
71
|
+
stored: (file, contentId) => {
|
|
72
|
+
const src = `cid:${contentId}`;
|
|
73
|
+
const node = editor.read(() => placedImage(file));
|
|
74
|
+
if (node) {
|
|
75
|
+
editor.update(() => {
|
|
76
|
+
placedImage(file)?.setSrc(src);
|
|
77
|
+
}, merged);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const spot = taken.get(file);
|
|
81
|
+
if (!spot) return;
|
|
82
|
+
editor.update(
|
|
83
|
+
() => {
|
|
84
|
+
const image = $createImage(file, src);
|
|
85
|
+
const parent = $getNodeByKey(spot.parentKey);
|
|
86
|
+
if ($isElementNode(parent) && parent.isAttached()) {
|
|
87
|
+
parent.splice(Math.min(spot.index, parent.getChildrenSize()), 0, [
|
|
88
|
+
image,
|
|
89
|
+
]);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
$getRoot().append($createParagraphNode().append(image));
|
|
93
|
+
},
|
|
94
|
+
{ tag: HISTORY_PUSH_TAG },
|
|
95
|
+
);
|
|
96
|
+
},
|
|
97
|
+
failed: (file) => {
|
|
98
|
+
editor.update(() => {
|
|
99
|
+
const node = placedImage(file);
|
|
100
|
+
if (!node) return;
|
|
101
|
+
taken.set(file, {
|
|
102
|
+
parentKey: node.getParentOrThrow().getKey(),
|
|
103
|
+
index: node.getIndexWithinParent(),
|
|
104
|
+
});
|
|
105
|
+
node.remove();
|
|
106
|
+
}, merged);
|
|
107
|
+
},
|
|
108
|
+
});
|
|
109
|
+
});
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const isBlobUrl = (url: string): boolean => url.startsWith("blob:");
|
|
113
|
+
|
|
114
|
+
export const InlineImagePlugin = ({
|
|
115
|
+
inlineImages,
|
|
116
|
+
}: {
|
|
117
|
+
inlineImages: RefObject<InlineImages | undefined>;
|
|
118
|
+
}) => {
|
|
119
|
+
const [editor] = useLexicalComposerContext();
|
|
120
|
+
|
|
121
|
+
useEffect(() => {
|
|
122
|
+
const owned = new Map<NodeKey, string>();
|
|
123
|
+
const revoked = new Set<string>();
|
|
124
|
+
const resolving = new Set<NodeKey>();
|
|
125
|
+
let live = true;
|
|
126
|
+
|
|
127
|
+
const release = (url: string): void => {
|
|
128
|
+
URL.revokeObjectURL(url);
|
|
129
|
+
revoked.add(url);
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const adopt = (key: NodeKey, preview: string): void => {
|
|
133
|
+
const previous = owned.get(key);
|
|
134
|
+
if (previous === preview) return;
|
|
135
|
+
if (previous) release(previous);
|
|
136
|
+
owned.set(key, preview);
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
const resolve = (key: NodeKey, src: string, contentId: string): void => {
|
|
140
|
+
const images = inlineImages.current;
|
|
141
|
+
if (!images?.owns(contentId) || resolving.has(key)) return;
|
|
142
|
+
resolving.add(key);
|
|
143
|
+
void images.resolve(contentId).then((url) => {
|
|
144
|
+
resolving.delete(key);
|
|
145
|
+
if (url === null) return;
|
|
146
|
+
if (!live) {
|
|
147
|
+
URL.revokeObjectURL(url);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
editor.update(() => {
|
|
151
|
+
const node = $getNodeByKey(key);
|
|
152
|
+
if (!(node instanceof ImageNode) || node.getSrc() !== src) {
|
|
153
|
+
URL.revokeObjectURL(url);
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
node.setPreview(url);
|
|
157
|
+
}, merged);
|
|
158
|
+
});
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
const visit = (key: NodeKey, orphans: NodeKey[]): void => {
|
|
162
|
+
const node = $getNodeByKey(key);
|
|
163
|
+
if (!(node instanceof ImageNode)) return;
|
|
164
|
+
const referenced = contentIdOf(node.getSrc());
|
|
165
|
+
if (referenced !== null && !inlineImages.current?.owns(referenced)) {
|
|
166
|
+
orphans.push(key);
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
const preview = node.getPreview();
|
|
170
|
+
if (preview && !revoked.has(preview)) {
|
|
171
|
+
if (isBlobUrl(preview)) adopt(key, preview);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
const src = node.getSrc();
|
|
175
|
+
const contentId = contentIdOf(src);
|
|
176
|
+
if (contentId !== null) resolve(key, src, contentId);
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
const removeReferences = (contentId: string): void => {
|
|
180
|
+
editor.update(() => {
|
|
181
|
+
for (const { node } of $dfs()) {
|
|
182
|
+
if (node instanceof ImageNode && node.getSrc() === `cid:${contentId}`)
|
|
183
|
+
node.remove();
|
|
184
|
+
}
|
|
185
|
+
}, merged);
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
const unsubscribe =
|
|
189
|
+
inlineImages.current?.onRemoved(removeReferences) ?? (() => {});
|
|
190
|
+
|
|
191
|
+
const unregister = editor.registerMutationListener(
|
|
192
|
+
ImageNode,
|
|
193
|
+
(mutations) => {
|
|
194
|
+
const orphans: NodeKey[] = [];
|
|
195
|
+
editor.read(() => {
|
|
196
|
+
for (const [key, mutation] of mutations) {
|
|
197
|
+
if (mutation !== "destroyed") {
|
|
198
|
+
visit(key, orphans);
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
const url = owned.get(key);
|
|
202
|
+
owned.delete(key);
|
|
203
|
+
if (url) release(url);
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
if (orphans.length === 0) return;
|
|
207
|
+
editor.update(() => {
|
|
208
|
+
for (const key of orphans) $getNodeByKey(key)?.remove();
|
|
209
|
+
}, merged);
|
|
210
|
+
},
|
|
211
|
+
);
|
|
212
|
+
|
|
213
|
+
return () => {
|
|
214
|
+
live = false;
|
|
215
|
+
mergeRegister(unregister, unsubscribe)();
|
|
216
|
+
for (const url of owned.values()) URL.revokeObjectURL(url);
|
|
217
|
+
owned.clear();
|
|
218
|
+
};
|
|
219
|
+
}, [editor, inlineImages]);
|
|
220
|
+
|
|
221
|
+
return null;
|
|
222
|
+
};
|
|
@@ -106,6 +106,19 @@ describe("sanitizeAdoptedHtml", () => {
|
|
|
106
106
|
assert.equal(result.includes("cid:part1"), false);
|
|
107
107
|
});
|
|
108
108
|
|
|
109
|
+
it("keeps a cid: image only when it names one of the draft's own files", () => {
|
|
110
|
+
const result = sanitizeAdoptedHtml(
|
|
111
|
+
[
|
|
112
|
+
'<img src="cid:att-1@remit" alt="Ours">',
|
|
113
|
+
'<img src="cid:part1" alt="Another message">',
|
|
114
|
+
].join(""),
|
|
115
|
+
(contentId) => contentId === "att-1@remit",
|
|
116
|
+
);
|
|
117
|
+
|
|
118
|
+
assert.match(result, /src="cid:att-1@remit"/);
|
|
119
|
+
assert.equal(result.includes("cid:part1"), false);
|
|
120
|
+
});
|
|
121
|
+
|
|
109
122
|
it("caps an image at the width the recipient has for it", () => {
|
|
110
123
|
const result = sanitizeAdoptedHtml(
|
|
111
124
|
'<img src="https://example.com/screenshot.png" width="1600">',
|
package/src/lib/adopted-html.ts
CHANGED
|
@@ -62,6 +62,18 @@ const ADOPTED_ATTR = [
|
|
|
62
62
|
|
|
63
63
|
const LINK_SCHEMES = /^(?:https?:|mailto:)/i;
|
|
64
64
|
const IMAGE_SCHEMES = /^(?:https:|data:image\/)/i;
|
|
65
|
+
const CONTENT_ID_SOURCE = /^cid:(.+)$/i;
|
|
66
|
+
|
|
67
|
+
export type ContentIdOwner = (contentId: string) => boolean;
|
|
68
|
+
|
|
69
|
+
const ownsNone: ContentIdOwner = () => false;
|
|
70
|
+
let ownsContentId: ContentIdOwner = ownsNone;
|
|
71
|
+
|
|
72
|
+
const keepsImage = (src: string): boolean => {
|
|
73
|
+
const reference = CONTENT_ID_SOURCE.exec(src);
|
|
74
|
+
if (reference) return ownsContentId(reference[1]);
|
|
75
|
+
return IMAGE_SCHEMES.test(src);
|
|
76
|
+
};
|
|
65
77
|
|
|
66
78
|
/**
|
|
67
79
|
* A pasted screenshot is as wide as the screen it came off, and the class the
|
|
@@ -107,7 +119,7 @@ const createPurifier = (profile: Profile): ReturnType<typeof DOMPurify> => {
|
|
|
107
119
|
node.remove();
|
|
108
120
|
return;
|
|
109
121
|
}
|
|
110
|
-
if (!
|
|
122
|
+
if (!keepsImage(node.getAttribute("src") ?? "")) {
|
|
111
123
|
node.remove();
|
|
112
124
|
return;
|
|
113
125
|
}
|
|
@@ -142,8 +154,17 @@ const sanitize = (html: string, profile: Profile): string =>
|
|
|
142
154
|
* It runs on the way in over a clipboard, and again on the way out over the
|
|
143
155
|
* editor's own serialization, which carries the app's stylesheet with it.
|
|
144
156
|
*/
|
|
145
|
-
export const sanitizeAdoptedHtml = (
|
|
146
|
-
|
|
157
|
+
export const sanitizeAdoptedHtml = (
|
|
158
|
+
html: string,
|
|
159
|
+
owns: ContentIdOwner = ownsNone,
|
|
160
|
+
): string => {
|
|
161
|
+
ownsContentId = owns;
|
|
162
|
+
try {
|
|
163
|
+
return sanitize(html, "outgoing");
|
|
164
|
+
} finally {
|
|
165
|
+
ownsContentId = ownsNone;
|
|
166
|
+
}
|
|
167
|
+
};
|
|
147
168
|
|
|
148
169
|
/** The same profile for mail quoted back at its sender, links and images defanged. */
|
|
149
170
|
export const sanitizeQuotedHtml = (html: string): string =>
|
package/src/rich-text.ts
CHANGED
|
@@ -37,6 +37,10 @@ export {
|
|
|
37
37
|
RichTextEditor,
|
|
38
38
|
type RichTextEditorProps,
|
|
39
39
|
} from "./components/rich-text-editor.js";
|
|
40
|
+
export type {
|
|
41
|
+
InlineImagePlacement,
|
|
42
|
+
InlineImages,
|
|
43
|
+
} from "./components/rich-text-inline-images.js";
|
|
40
44
|
export { COMPOSE_TRANSFORMERS } from "./components/rich-text-markdown.js";
|
|
41
45
|
export type {
|
|
42
46
|
CheckRequest,
|