@sincpro/web-ui 2.14.2 → 2.15.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/README.md +53 -3
- package/dist/foundations/copy.es.js +8 -0
- package/dist/foundations/uiCopy.d.ts +14 -0
- package/dist/foundations/uiCopy.js +8 -0
- package/dist/primitives/field/RichTextEditor.d.ts +13 -1
- package/dist/primitives/field/RichTextEditor.js +152 -8
- package/dist/primitives/field/RichTextInput.d.ts +14 -3
- package/dist/primitives/field/RichTextInput.js +9 -3
- package/dist/primitives/field/index.d.ts +1 -1
- package/dist/primitives/value/RichText.d.ts +15 -3
- package/dist/primitives/value/RichText.js +26 -73
- package/dist/primitives/value/index.d.ts +1 -0
- package/dist/primitives/value/index.js +2 -0
- package/dist/primitives/value/richTextPlain.d.ts +1 -1
- package/dist/primitives/value/richTextPlain.js +2 -2
- package/dist/primitives/value/richTextPolicy.d.ts +39 -0
- package/dist/primitives/value/richTextPolicy.js +195 -0
- package/dist/tokens.css +22 -0
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -130,9 +130,10 @@ export default { plugins: { "@tailwindcss/postcss": {} } };
|
|
|
130
130
|
`formatNumber`, `formatWith`, `formatDateTime`, `formatRelative`, `countText`), the words
|
|
131
131
|
(`installCopy`, `currentCopy`, `fillCopy`, `ENGLISH_COPY`), the theme's names
|
|
132
132
|
(`THEME_ATTRIBUTE`, `isTheme`), `writeXlsx`, the calendar, the pivot, the criteria and the
|
|
133
|
-
filter's tree (`describeFilter`, `treeFromFilter`)
|
|
134
|
-
|
|
135
|
-
`
|
|
133
|
+
filter's tree (`describeFilter`, `treeFromFilter`), the rich text's policy
|
|
134
|
+
(`sanitizeRichTextWith`, `embedOf`, `isRichTextUri`, `RICH_TEXT_ALLOWED_TAGS`) —
|
|
135
|
+
`tests/serverBoundary.test.ts` holds it. What needs a browser stays client: `downloadFile`,
|
|
136
|
+
`downloadXlsx`, `applyTheme`, `sanitizeRichText`. The views are client components: compose `Record` or `List` inside a
|
|
136
137
|
client component of your own.
|
|
137
138
|
|
|
138
139
|
```tsx
|
|
@@ -186,6 +187,55 @@ export default { plugins: { "@tailwindcss/postcss": {} } };
|
|
|
186
187
|
- What only a browser can draw is drawn there: the Gantt (SVAR paints its grid on a canvas)
|
|
187
188
|
renders its skeleton on the server and the chart after hydration.
|
|
188
189
|
|
|
190
|
+
- **Rich text on the server.** DOMPurify needs a DOM, so on the server `RichTextValue` writes
|
|
191
|
+
a note's plain words and the browser upgrades them to the cleaned HTML. A page that must
|
|
192
|
+
carry its formatting in the server's HTML (an article, read by a search engine or before the
|
|
193
|
+
scripts arrive) cleans the HTML ON THE SERVER and says so with `sanitized`:
|
|
194
|
+
|
|
195
|
+
```tsx
|
|
196
|
+
// app/noticias/[slug]/page.tsx — a Server Component
|
|
197
|
+
import { RichTextValue, sanitizeRichTextWith } from "@sincpro/web-ui";
|
|
198
|
+
import DOMPurify from "dompurify";
|
|
199
|
+
import { JSDOM } from "jsdom";
|
|
200
|
+
|
|
201
|
+
const purify = DOMPurify(new JSDOM("").window);
|
|
202
|
+
|
|
203
|
+
export default async function Noticia({ params }: { params: Promise<{ slug: string }> }) {
|
|
204
|
+
const { body } = await article((await params).slug);
|
|
205
|
+
const html = sanitizeRichTextWith(purify, body, { embeds: ["youtube", "vimeo"] });
|
|
206
|
+
return <RichTextValue value={html} embeds={["youtube", "vimeo"]} sanitized />;
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
**The contract.** `sanitized` is the application's word, not a check: on the server the
|
|
211
|
+
value is written as it comes. The browser still cleans it again with DOMPurify after
|
|
212
|
+
hydration (and on every client render), so a mistake is caught there — but by then the
|
|
213
|
+
server's HTML has already been parsed. Whatever produces the value — this package's
|
|
214
|
+
`sanitizeRichTextWith`, or a backend's own sanitizer — must keep ONLY:
|
|
215
|
+
- **tags** in `RICH_TEXT_ALLOWED_TAGS`: `p`, `br`, `strong`, `b`, `em`, `i`, `u`, `s`,
|
|
216
|
+
`strike`, `del`, `code`, `pre`, `h1`–`h4`, `ul`, `ol`, `li`, `blockquote`, `hr`, `a`,
|
|
217
|
+
`span`, `table`, `thead`, `tbody`, `tr`, `th`, `td`, `colgroup`, `col`, `img` — plus
|
|
218
|
+
`div` and `iframe` when embeds are allowed;
|
|
219
|
+
- **attributes** in `RICH_TEXT_ALLOWED_ATTR`: `href`, `title`, `colspan`, `rowspan`, `src`,
|
|
220
|
+
`alt`, `data-type`, `data-id`, `data-label` — plus `data-embed` with embeds; no `on*`, no
|
|
221
|
+
`style`, no `srcdoc`;
|
|
222
|
+
- **addresses** (`href`, `src`) matching `RICH_TEXT_URI`: `https:`, `http:`, `mailto:`,
|
|
223
|
+
`tel:`, `data:image/(png|jpeg|gif|webp);`, or relative (`/v1/media/12`, `#a`, `?b`) —
|
|
224
|
+
never `javascript:`, `vbscript:`, `data:text/html`, `data:image/svg+xml` or any other
|
|
225
|
+
scheme, with whitespace and control characters stripped before testing;
|
|
226
|
+
- **iframes** only with a `src` that is exactly a YouTube player without cookies,
|
|
227
|
+
`https://www.youtube-nocookie.com/embed/<id>` (11 of `[A-Za-z0-9_-]`, optionally
|
|
228
|
+
`?start=<digits>`), or a Vimeo player, `https://player.vimeo.com/video/<digits>`
|
|
229
|
+
(optionally `?h=<hex>`) — `embedProviderOf` — carrying the attributes of
|
|
230
|
+
`EMBED_IFRAME_ATTRIBUTES` (`sandbox`, `allow`, `loading`, `referrerpolicy`) written by
|
|
231
|
+
the sanitizer, never taken from the input. The sandbox allows scripts, same origin,
|
|
232
|
+
presentation and popups, nothing else.
|
|
233
|
+
|
|
234
|
+
Cleaned by `sanitizeRichTextWith` with the same options, the browser's cleaning yields the
|
|
235
|
+
same string and nothing moves after hydration; another sanitizer's output may be rewritten
|
|
236
|
+
once (links get `target="_blank" rel="noopener noreferrer"`), which reloads a player.
|
|
237
|
+
`jsdom` is the application's dependency, on the server only — the package does not pull it.
|
|
238
|
+
|
|
189
239
|
### Theming (light / dark)
|
|
190
240
|
|
|
191
241
|
The palettes live in `tokens.css`: the same `--color-*` names, redefined for dark. Components
|
|
@@ -343,6 +343,14 @@ export const SPANISH_COPY = {
|
|
|
343
343
|
clear: "Quitar formato",
|
|
344
344
|
mentions: "Personas",
|
|
345
345
|
noMatches: "No coincide nadie",
|
|
346
|
+
image: "Insertar imagen",
|
|
347
|
+
imageUploading: "Subiendo la imagen…",
|
|
348
|
+
imageFailed: "No se pudo subir la imagen.",
|
|
349
|
+
video: "Insertar video",
|
|
350
|
+
videoUrl: "Dirección del video",
|
|
351
|
+
insertVideo: "Insertar",
|
|
352
|
+
badVideo: "Pegá el enlace de un video de {providers}.",
|
|
353
|
+
videoTitle: "Video de {provider}",
|
|
346
354
|
},
|
|
347
355
|
sorting: {
|
|
348
356
|
label: "Ordenar",
|
|
@@ -478,6 +478,20 @@ export type UiCopy = {
|
|
|
478
478
|
/** The list that opens on «@»: people to mention. */
|
|
479
479
|
mentions: string;
|
|
480
480
|
noMatches: string;
|
|
481
|
+
/** The button that adds a picture (`images`): chosen, pasted or dropped. */
|
|
482
|
+
image: string;
|
|
483
|
+
/** Said while the application stores the picture. */
|
|
484
|
+
imageUploading: string;
|
|
485
|
+
/** A failed upload, when the application did not say why. */
|
|
486
|
+
imageFailed: string;
|
|
487
|
+
/** The button and the form that add a video (`embeds`). */
|
|
488
|
+
video: string;
|
|
489
|
+
videoUrl: string;
|
|
490
|
+
insertVideo: string;
|
|
491
|
+
/** Said when the address is not a video of an allowed host. `{providers}` lists them. */
|
|
492
|
+
badVideo: string;
|
|
493
|
+
/** The player's name, for whoever cannot see it. `{provider}` is the host. */
|
|
494
|
+
videoTitle: string;
|
|
481
495
|
};
|
|
482
496
|
/** Sorting, when the presentation has no headers to click on. */
|
|
483
497
|
sorting: {
|
|
@@ -290,6 +290,14 @@ export const ENGLISH_COPY = {
|
|
|
290
290
|
clear: "Clear formatting",
|
|
291
291
|
mentions: "People",
|
|
292
292
|
noMatches: "Nobody matches",
|
|
293
|
+
image: "Insert image",
|
|
294
|
+
imageUploading: "Uploading the image…",
|
|
295
|
+
imageFailed: "The image could not be uploaded.",
|
|
296
|
+
video: "Insert video",
|
|
297
|
+
videoUrl: "Video address",
|
|
298
|
+
insertVideo: "Insert",
|
|
299
|
+
badVideo: "Paste the link of a video from {providers}.",
|
|
300
|
+
videoTitle: "{provider} video",
|
|
293
301
|
},
|
|
294
302
|
sorting: {
|
|
295
303
|
label: "Sort",
|
|
@@ -1,7 +1,17 @@
|
|
|
1
|
+
import { type EmbedProvider } from "../value/richTextPolicy.js";
|
|
1
2
|
export type MentionItem = {
|
|
2
3
|
id: string;
|
|
3
4
|
label: string;
|
|
4
5
|
};
|
|
6
|
+
/** Pictures in the text: the application stores each file and answers where it lives. */
|
|
7
|
+
export type RichTextImages = {
|
|
8
|
+
/** Store the picture; answer its address (relative is fine: `/v1/media/12`) and,
|
|
9
|
+
* if it has one, its description. A thrown `Error`'s message is shown as the failure. */
|
|
10
|
+
upload: (file: File) => Promise<{
|
|
11
|
+
src: string;
|
|
12
|
+
alt?: string;
|
|
13
|
+
}>;
|
|
14
|
+
};
|
|
5
15
|
export type RichTextEditorProps = {
|
|
6
16
|
id: string | undefined;
|
|
7
17
|
labelledBy: string | undefined;
|
|
@@ -14,5 +24,7 @@ export type RichTextEditorProps = {
|
|
|
14
24
|
disabled: boolean;
|
|
15
25
|
toolbar: "full" | "basic" | "none";
|
|
16
26
|
mentions: ((query: string) => readonly MentionItem[] | Promise<readonly MentionItem[]>) | undefined;
|
|
27
|
+
images?: RichTextImages | undefined;
|
|
28
|
+
embeds?: readonly EmbedProvider[] | undefined;
|
|
17
29
|
};
|
|
18
|
-
export declare function RichTextEditor({ id, labelledBy, describedBy, invalid, ariaLabel, value, onChange, placeholder, disabled, toolbar, mentions, }: RichTextEditorProps): import("react").JSX.Element;
|
|
30
|
+
export declare function RichTextEditor({ id, labelledBy, describedBy, invalid, ariaLabel, value, onChange, placeholder, disabled, toolbar, mentions, images, embeds, }: RichTextEditorProps): import("react").JSX.Element;
|
|
@@ -1,17 +1,59 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
3
|
-
import { useUiCopy } from "../../foundations/copy.js";
|
|
3
|
+
import { fillCopy, useUiCopy } from "../../foundations/copy.js";
|
|
4
4
|
import { Button, IconButton } from "../button/Button.js";
|
|
5
5
|
import { emailHref, telHref, urlHref } from "./contact.js";
|
|
6
6
|
import { PopoverTrigger } from "../overlay/PopoverTrigger.js";
|
|
7
7
|
import { Toolbar, ToolbarSeparator } from "../toolbar/Toolbar.js";
|
|
8
|
+
import { EMBED_IFRAME_ATTRIBUTES, embedOf, isRichTextUri, } from "../value/richTextPolicy.js";
|
|
9
|
+
import Image from "@tiptap/extension-image";
|
|
8
10
|
import Mention from "@tiptap/extension-mention";
|
|
9
11
|
import { TableKit } from "@tiptap/extension-table";
|
|
10
12
|
import { Placeholder } from "@tiptap/extensions";
|
|
11
|
-
import { EditorContent, useEditor, useEditorState } from "@tiptap/react";
|
|
13
|
+
import { EditorContent, Node, useEditor, useEditorState } from "@tiptap/react";
|
|
12
14
|
import StarterKit from "@tiptap/starter-kit";
|
|
13
|
-
import { Bold, Heading2, Heading3, Italic, Link as LinkIcon, List, ListOrdered, Redo2, RemoveFormatting, Strikethrough, Table, TextQuote, Underline, Undo2, } from "lucide-react";
|
|
15
|
+
import { Bold, Heading2, Heading3, ImagePlus, Italic, Link as LinkIcon, List, ListOrdered, Redo2, RemoveFormatting, Strikethrough, Table, TextQuote, Underline, Undo2, Video, } from "lucide-react";
|
|
14
16
|
import { useEffect, useId, useRef, useState } from "react";
|
|
17
|
+
const PROVIDER_NAME = { youtube: "YouTube", vimeo: "Vimeo" };
|
|
18
|
+
/** A video's player as one block: drawn as `<div data-embed><iframe></div>`, read back only
|
|
19
|
+
* from an address the policy turns into an allowed player. */
|
|
20
|
+
function embedNode(providers, title) {
|
|
21
|
+
const read = (element) => {
|
|
22
|
+
const frame = element.tagName === "IFRAME" ? element : element.querySelector("iframe");
|
|
23
|
+
const found = embedOf(frame?.getAttribute("src") ?? "", providers);
|
|
24
|
+
return found === null ? false : { src: found.src, provider: found.provider };
|
|
25
|
+
};
|
|
26
|
+
return Node.create({
|
|
27
|
+
name: "embed",
|
|
28
|
+
group: "block",
|
|
29
|
+
atom: true,
|
|
30
|
+
draggable: true,
|
|
31
|
+
addAttributes: () => ({ src: { default: null }, provider: { default: null } }),
|
|
32
|
+
parseHTML: () => [
|
|
33
|
+
{ tag: "div[data-embed]", getAttrs: read },
|
|
34
|
+
{ tag: "iframe[src]", getAttrs: read },
|
|
35
|
+
],
|
|
36
|
+
renderHTML: ({ node }) => {
|
|
37
|
+
const provider = String(node.attrs["provider"]);
|
|
38
|
+
return [
|
|
39
|
+
"div",
|
|
40
|
+
{ "data-embed": provider },
|
|
41
|
+
[
|
|
42
|
+
"iframe",
|
|
43
|
+
{
|
|
44
|
+
src: node.attrs["src"],
|
|
45
|
+
title: title(PROVIDER_NAME[provider] ?? provider),
|
|
46
|
+
...EMBED_IFRAME_ATTRIBUTES,
|
|
47
|
+
},
|
|
48
|
+
],
|
|
49
|
+
];
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
/** The pictures among some files — what a paste or a drop hands over. */
|
|
54
|
+
function imagesIn(files) {
|
|
55
|
+
return [...(files ?? [])].filter((file) => file.type.startsWith("image/"));
|
|
56
|
+
}
|
|
15
57
|
/** A link address as people write it: a website, an email, a phone — or nothing valid. */
|
|
16
58
|
function linkHref(text) {
|
|
17
59
|
const clean = text.trim();
|
|
@@ -45,7 +87,27 @@ function LinkForm({ editor, close }) {
|
|
|
45
87
|
close();
|
|
46
88
|
}, children: copy.removeLink })), _jsx(Button, { role: "secondary", size: "sm", type: "submit", children: copy.applyLink })] })] }));
|
|
47
89
|
}
|
|
48
|
-
function
|
|
90
|
+
function VideoForm({ editor, providers, close, }) {
|
|
91
|
+
const copy = useUiCopy().richText;
|
|
92
|
+
const [text, setText] = useState("");
|
|
93
|
+
const [tried, setTried] = useState(false);
|
|
94
|
+
const inputId = useId();
|
|
95
|
+
const found = embedOf(text, providers);
|
|
96
|
+
const apply = () => {
|
|
97
|
+
setTried(true);
|
|
98
|
+
if (found === null)
|
|
99
|
+
return;
|
|
100
|
+
editor.chain().focus().insertContent({ type: "embed", attrs: found }).run();
|
|
101
|
+
close();
|
|
102
|
+
};
|
|
103
|
+
return (_jsxs("form", { className: "flex w-72 max-w-full flex-col gap-2", onSubmit: (event) => {
|
|
104
|
+
event.preventDefault();
|
|
105
|
+
apply();
|
|
106
|
+
}, children: [_jsx("label", { htmlFor: inputId, className: "text-micro font-medium text-muted", children: copy.videoUrl }), _jsx("input", { id: inputId, value: text, autoFocus: true, inputMode: "url", spellCheck: false, "aria-invalid": tried && found === null, ...(tried && found === null ? { "aria-describedby": `${inputId}-error` } : {}), onChange: (event) => setText(event.target.value), className: "h-(--size-control-md) w-full min-w-0 rounded-control border border-line-strong bg-surface px-2.5 text-meta text-ink outline-0 focus-visible:border-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary" }), tried && found === null ? (_jsx("p", { id: `${inputId}-error`, role: "alert", className: "text-micro text-danger", children: fillCopy(copy.badVideo, {
|
|
107
|
+
providers: providers.map((one) => PROVIDER_NAME[one]).join(", "),
|
|
108
|
+
}) })) : null, _jsx("div", { className: "flex items-center justify-end gap-2", children: _jsx(Button, { role: "secondary", size: "sm", type: "submit", children: copy.insertVideo }) })] }));
|
|
109
|
+
}
|
|
110
|
+
function Bar({ editor, full, media }) {
|
|
49
111
|
const copy = useUiCopy().richText;
|
|
50
112
|
const on = useEditorState({
|
|
51
113
|
editor,
|
|
@@ -78,7 +140,7 @@ function Bar({ editor, full }) {
|
|
|
78
140
|
? toggle(copy.subheading, Heading3, on.h3, () => chain().toggleHeading({ level: 3 }).run())
|
|
79
141
|
: null, toggle(copy.bulletList, List, on.bullet, () => chain().toggleBulletList().run()), toggle(copy.orderedList, ListOrdered, on.ordered, () => chain().toggleOrderedList().run()), full
|
|
80
142
|
? toggle(copy.quote, TextQuote, on.quote, () => chain().toggleBlockquote().run())
|
|
81
|
-
: null, _jsx(ToolbarSeparator, {}), _jsx(PopoverTrigger, { title: copy.link, trigger: _jsx(IconButton, { icon: LinkIcon, label: copy.link, "aria-pressed": on.link, disabled: !editor.isEditable }), children: (close) => _jsx(LinkForm, { editor: editor, close: close }) }), full ? (_jsx(IconButton, { icon: Table, label: copy.table, disabled: !editor.isEditable, onMouseDown: (event) => event.preventDefault(), onClick: () => chain().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run() })) : null, full ? (_jsxs(_Fragment, { children: [_jsx(ToolbarSeparator, {}), _jsx(IconButton, { icon: Undo2, label: copy.undo, disabled: !on.undo, onMouseDown: (event) => event.preventDefault(), onClick: () => chain().undo().run() }), _jsx(IconButton, { icon: Redo2, label: copy.redo, disabled: !on.redo, onMouseDown: (event) => event.preventDefault(), onClick: () => chain().redo().run() }), _jsx(IconButton, { icon: RemoveFormatting, label: copy.clear, disabled: !editor.isEditable, onMouseDown: (event) => event.preventDefault(), onClick: () => chain().unsetAllMarks().clearNodes().run() })] })) : null] }) }));
|
|
143
|
+
: null, _jsx(ToolbarSeparator, {}), _jsx(PopoverTrigger, { title: copy.link, trigger: _jsx(IconButton, { icon: LinkIcon, label: copy.link, "aria-pressed": on.link, disabled: !editor.isEditable }), children: (close) => _jsx(LinkForm, { editor: editor, close: close }) }), media.pickImage === undefined ? null : (_jsx(IconButton, { icon: ImagePlus, label: copy.image, busy: media.uploading, disabled: !editor.isEditable, onMouseDown: (event) => event.preventDefault(), onClick: media.pickImage })), media.embeds === undefined || media.embeds.length === 0 ? null : (_jsx(PopoverTrigger, { title: copy.video, trigger: _jsx(IconButton, { icon: Video, label: copy.video, disabled: !editor.isEditable }), children: (close) => (_jsx(VideoForm, { editor: editor, providers: media.embeds ?? [], close: close })) })), full ? (_jsx(IconButton, { icon: Table, label: copy.table, disabled: !editor.isEditable, onMouseDown: (event) => event.preventDefault(), onClick: () => chain().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run() })) : null, full ? (_jsxs(_Fragment, { children: [_jsx(ToolbarSeparator, {}), _jsx(IconButton, { icon: Undo2, label: copy.undo, disabled: !on.undo, onMouseDown: (event) => event.preventDefault(), onClick: () => chain().undo().run() }), _jsx(IconButton, { icon: Redo2, label: copy.redo, disabled: !on.redo, onMouseDown: (event) => event.preventDefault(), onClick: () => chain().redo().run() }), _jsx(IconButton, { icon: RemoveFormatting, label: copy.clear, disabled: !editor.isEditable, onMouseDown: (event) => event.preventDefault(), onClick: () => chain().unsetAllMarks().clearNodes().run() })] })) : null] }) }));
|
|
82
144
|
}
|
|
83
145
|
/** The list that opens on «@»: fixed under the caret, moved through from the editor. */
|
|
84
146
|
function MentionList({ asking, active, listId, }) {
|
|
@@ -91,11 +153,18 @@ function MentionList({ asking, active, listId, }) {
|
|
|
91
153
|
asking.pick(item);
|
|
92
154
|
}, className: `cursor-default rounded-control px-2 py-1 text-meta text-ink ${index === active ? "bg-ui-option-active" : ""}`, children: item.label }, item.id)))) }));
|
|
93
155
|
}
|
|
94
|
-
export function RichTextEditor({ id, labelledBy, describedBy, invalid, ariaLabel, value, onChange, placeholder, disabled, toolbar, mentions, }) {
|
|
156
|
+
export function RichTextEditor({ id, labelledBy, describedBy, invalid, ariaLabel, value, onChange, placeholder, disabled, toolbar, mentions, images, embeds, }) {
|
|
157
|
+
const copy = useUiCopy().richText;
|
|
95
158
|
const changed = useRef(onChange);
|
|
96
159
|
changed.current = onChange;
|
|
97
160
|
const searching = useRef(mentions);
|
|
98
161
|
searching.current = mentions;
|
|
162
|
+
/* Pictures on their way to the application: how many, and the last failure. */
|
|
163
|
+
const [uploading, setUploading] = useState(0);
|
|
164
|
+
const [failure, setFailure] = useState(null);
|
|
165
|
+
const fileInput = useRef(null);
|
|
166
|
+
/* Set below once the editor exists; the paste and drop handlers are fixed at creation. */
|
|
167
|
+
const uploadRef = useRef(null);
|
|
99
168
|
const [asking, setAsking] = useState(null);
|
|
100
169
|
const [active, setActive] = useState(0);
|
|
101
170
|
const activeRef = useRef(0);
|
|
@@ -118,6 +187,10 @@ export function RichTextEditor({ id, labelledBy, describedBy, invalid, ariaLabel
|
|
|
118
187
|
}),
|
|
119
188
|
TableKit.configure({ table: { resizable: false } }),
|
|
120
189
|
...(placeholder === undefined ? [] : [Placeholder.configure({ placeholder })]),
|
|
190
|
+
...(images === undefined ? [] : [Image.configure({ allowBase64: false })]),
|
|
191
|
+
...(embeds === undefined || embeds.length === 0
|
|
192
|
+
? []
|
|
193
|
+
: [embedNode(embeds, (provider) => fillCopy(copy.videoTitle, { provider }))]),
|
|
121
194
|
...(mentions === undefined
|
|
122
195
|
? []
|
|
123
196
|
: [
|
|
@@ -174,6 +247,23 @@ export function RichTextEditor({ id, labelledBy, describedBy, invalid, ariaLabel
|
|
|
174
247
|
]),
|
|
175
248
|
],
|
|
176
249
|
editorProps: {
|
|
250
|
+
handlePaste: (_view, event) => {
|
|
251
|
+
const files = imagesIn(event.clipboardData?.files);
|
|
252
|
+
if (files.length === 0 || uploadRef.current === null)
|
|
253
|
+
return false;
|
|
254
|
+
event.preventDefault();
|
|
255
|
+
uploadRef.current(files, null);
|
|
256
|
+
return true;
|
|
257
|
+
},
|
|
258
|
+
handleDrop: (view, event, _slice, moved) => {
|
|
259
|
+
const files = imagesIn(event.dataTransfer?.files);
|
|
260
|
+
if (moved || files.length === 0 || uploadRef.current === null)
|
|
261
|
+
return false;
|
|
262
|
+
event.preventDefault();
|
|
263
|
+
const at = view.posAtCoords({ left: event.clientX, top: event.clientY });
|
|
264
|
+
uploadRef.current(files, at?.pos ?? null);
|
|
265
|
+
return true;
|
|
266
|
+
},
|
|
177
267
|
attributes: {
|
|
178
268
|
class: "rich-text min-h-24 max-h-96 overflow-y-auto px-2.5 py-2 outline-0",
|
|
179
269
|
role: "textbox",
|
|
@@ -209,6 +299,48 @@ export function RichTextEditor({ id, labelledBy, describedBy, invalid, ariaLabel
|
|
|
209
299
|
listId,
|
|
210
300
|
]);
|
|
211
301
|
useEffect(() => editor?.setEditable(!disabled), [editor, disabled]);
|
|
302
|
+
/* One picture after another, in the order given; each goes in where the caret is when it
|
|
303
|
+
arrives (or where it was dropped), so typing meanwhile is not lost. */
|
|
304
|
+
uploadRef.current =
|
|
305
|
+
editor === null || images === undefined
|
|
306
|
+
? null
|
|
307
|
+
: (files, at) => {
|
|
308
|
+
if (!editor.isEditable)
|
|
309
|
+
return;
|
|
310
|
+
setFailure(null);
|
|
311
|
+
setUploading((count) => count + 1);
|
|
312
|
+
void (async () => {
|
|
313
|
+
let place = at;
|
|
314
|
+
try {
|
|
315
|
+
for (const file of files) {
|
|
316
|
+
const stored = await images.upload(file);
|
|
317
|
+
if (!isRichTextUri(stored.src))
|
|
318
|
+
throw new Error(copy.imageFailed);
|
|
319
|
+
const node = {
|
|
320
|
+
type: "image",
|
|
321
|
+
attrs: { src: stored.src, alt: stored.alt ?? "" },
|
|
322
|
+
};
|
|
323
|
+
if (editor.isDestroyed)
|
|
324
|
+
return;
|
|
325
|
+
if (place === null)
|
|
326
|
+
editor.chain().focus().insertContent(node).run();
|
|
327
|
+
else {
|
|
328
|
+
const inside = Math.min(place, editor.state.doc.content.size);
|
|
329
|
+
editor.chain().insertContentAt(inside, node).run();
|
|
330
|
+
place = editor.state.selection.to;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
catch (error) {
|
|
335
|
+
setFailure(error instanceof Error && error.message !== ""
|
|
336
|
+
? error.message
|
|
337
|
+
: copy.imageFailed);
|
|
338
|
+
}
|
|
339
|
+
finally {
|
|
340
|
+
setUploading((count) => count - 1);
|
|
341
|
+
}
|
|
342
|
+
})();
|
|
343
|
+
};
|
|
212
344
|
/* A value written from outside (a reset, a suggestion applied) replaces the content — but
|
|
213
345
|
never while the person is typing, which would move their caret. */
|
|
214
346
|
useEffect(() => {
|
|
@@ -218,7 +350,19 @@ export function RichTextEditor({ id, labelledBy, describedBy, invalid, ariaLabel
|
|
|
218
350
|
if (current !== value)
|
|
219
351
|
editor.commands.setContent(value === "" ? "" : value, { emitUpdate: false });
|
|
220
352
|
}, [editor, value]);
|
|
221
|
-
|
|
353
|
+
const media = {
|
|
354
|
+
pickImage: images === undefined ? undefined : () => fileInput.current?.click(),
|
|
355
|
+
uploading: uploading > 0,
|
|
356
|
+
embeds,
|
|
357
|
+
};
|
|
358
|
+
return (_jsxs("div", { ...(uploading > 0 ? { "aria-busy": true } : {}), className: `w-full min-w-0 overflow-clip rounded-control border bg-surface transition-colors duration-(--duration-instant) focus-within:outline-2 focus-within:outline-offset-2 ${invalid
|
|
222
359
|
? "border-danger focus-within:outline-danger"
|
|
223
|
-
: "border-line-strong focus-within:border-primary focus-within:outline-primary"} ${disabled ? "bg-ground text-muted" : ""}`, children: [editor === null || toolbar === "none" ? null : (_jsx(Bar, { editor: editor, full: toolbar === "full"
|
|
360
|
+
: "border-line-strong focus-within:border-primary focus-within:outline-primary"} ${disabled ? "bg-ground text-muted" : ""}`, children: [editor === null || toolbar === "none" ? null : (_jsx(Bar, { editor: editor, full: toolbar === "full", media: media })), images === undefined ? null : (_jsx("input", { ref: fileInput, type: "file", accept: "image/*", multiple: true, hidden: true, tabIndex: -1, "aria-hidden": true, onChange: (event) => {
|
|
361
|
+
const files = imagesIn(event.target.files);
|
|
362
|
+
event.target.value = "";
|
|
363
|
+
if (files.length > 0)
|
|
364
|
+
uploadRef.current?.(files, null);
|
|
365
|
+
} })), _jsx(EditorContent, { editor: editor }), images === undefined ? null : (_jsx("p", { role: "status", className: uploading > 0
|
|
366
|
+
? "border-t border-line px-2.5 py-1 text-micro text-muted"
|
|
367
|
+
: "sr-only", children: uploading > 0 ? copy.imageUploading : "" })), failure === null ? null : (_jsx("p", { role: "alert", className: "border-t border-line px-2.5 py-1 text-micro text-danger", children: failure })), asking === null ? null : (_jsx(MentionList, { asking: asking, active: active, listId: listId }))] }));
|
|
224
368
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ControlProps } from "./Field.js";
|
|
2
|
-
import type { MentionItem } from "./RichTextEditor.js";
|
|
2
|
+
import type { MentionItem, RichTextImages } from "./RichTextEditor.js";
|
|
3
|
+
import type { EmbedProvider } from "../value/richTextPolicy.js";
|
|
3
4
|
/**
|
|
4
5
|
* Formatted text — a description, the notes of an order, the body of an email: an Odoo `html`
|
|
5
6
|
* field. The value is HTML in and HTML out.
|
|
@@ -17,8 +18,14 @@ import type { MentionItem } from "./RichTextEditor.js";
|
|
|
17
18
|
* `toolbar` picks how much to offer: `full` (headings, quote, table, undo), `basic` (bold,
|
|
18
19
|
* italic, lists, link — a comment), `none` (only the keyboard shortcuts). `mentions` turns on
|
|
19
20
|
* «@»: the application answers who matches what was typed.
|
|
21
|
+
*
|
|
22
|
+
* An article needs more, and asks for it: `images` adds pictures — the toolbar's button, a
|
|
23
|
+
* paste, a drop — each handed to the application's `upload`, which stores it and answers its
|
|
24
|
+
* address; `embeds` adds the player of a YouTube (`youtube-nocookie.com`) or Vimeo video by
|
|
25
|
+
* its address. Without them, the field is what it was. Read mode draws the players of the
|
|
26
|
+
* same `embeds`.
|
|
20
27
|
*/
|
|
21
|
-
export declare function RichTextInput({ id: ownId, value, onChange, placeholder, describedBy: ownDescribedBy, invalid: ownInvalid, disabled, mode, toolbar, mentions, "aria-label": ariaLabel, }: ControlProps & {
|
|
28
|
+
export declare function RichTextInput({ id: ownId, value, onChange, placeholder, describedBy: ownDescribedBy, invalid: ownInvalid, disabled, mode, toolbar, mentions, images, embeds, "aria-label": ariaLabel, }: ControlProps & {
|
|
22
29
|
/** HTML. `""` is empty. */
|
|
23
30
|
value: string;
|
|
24
31
|
onChange?: (html: string) => void;
|
|
@@ -26,5 +33,9 @@ export declare function RichTextInput({ id: ownId, value, onChange, placeholder,
|
|
|
26
33
|
toolbar?: "full" | "basic" | "none";
|
|
27
34
|
/** Who can be mentioned with «@», for what was typed after it. */
|
|
28
35
|
mentions?: (query: string) => readonly MentionItem[] | Promise<readonly MentionItem[]>;
|
|
36
|
+
/** Pictures in the text: the application stores each one (`upload`) and answers where. */
|
|
37
|
+
images?: RichTextImages;
|
|
38
|
+
/** The video hosts whose players may be added by address, e.g. `["youtube", "vimeo"]`. */
|
|
39
|
+
embeds?: readonly EmbedProvider[];
|
|
29
40
|
}): import("react").JSX.Element;
|
|
30
|
-
export type { MentionItem };
|
|
41
|
+
export type { EmbedProvider, MentionItem, RichTextImages };
|
|
@@ -25,14 +25,20 @@ const RichTextEditor = lazy(() => import("./RichTextEditor.js").then((module) =>
|
|
|
25
25
|
* `toolbar` picks how much to offer: `full` (headings, quote, table, undo), `basic` (bold,
|
|
26
26
|
* italic, lists, link — a comment), `none` (only the keyboard shortcuts). `mentions` turns on
|
|
27
27
|
* «@»: the application answers who matches what was typed.
|
|
28
|
+
*
|
|
29
|
+
* An article needs more, and asks for it: `images` adds pictures — the toolbar's button, a
|
|
30
|
+
* paste, a drop — each handed to the application's `upload`, which stores it and answers its
|
|
31
|
+
* address; `embeds` adds the player of a YouTube (`youtube-nocookie.com`) or Vimeo video by
|
|
32
|
+
* its address. Without them, the field is what it was. Read mode draws the players of the
|
|
33
|
+
* same `embeds`.
|
|
28
34
|
*/
|
|
29
|
-
export function RichTextInput({ id: ownId, value, onChange, placeholder, describedBy: ownDescribedBy, invalid: ownInvalid, disabled = false, mode, toolbar = "full", mentions, "aria-label": ariaLabel, }) {
|
|
35
|
+
export function RichTextInput({ id: ownId, value, onChange, placeholder, describedBy: ownDescribedBy, invalid: ownInvalid, disabled = false, mode, toolbar = "full", mentions, images, embeds, "aria-label": ariaLabel, }) {
|
|
30
36
|
const { id, labelledBy, describedBy, invalid } = useFieldIds({
|
|
31
37
|
id: ownId,
|
|
32
38
|
describedBy: ownDescribedBy,
|
|
33
39
|
invalid: ownInvalid,
|
|
34
40
|
});
|
|
35
41
|
if (useFormMode(mode) === "read")
|
|
36
|
-
return _jsx(RichTextValue, { value: value });
|
|
37
|
-
return (_jsx(Suspense, { fallback: _jsx("div", { "aria-busy": "true", className: "h-32 w-full min-w-0 animate-reveal-late rounded-control border border-line-strong bg-ground" }), children: _jsx(RichTextEditor, { id: id, labelledBy: labelledBy, describedBy: describedBy, invalid: invalid, ariaLabel: ariaLabel, value: value, onChange: onChange, placeholder: placeholder, disabled: disabled, toolbar: toolbar, mentions: mentions }) }));
|
|
42
|
+
return _jsx(RichTextValue, { value: value, embeds: embeds });
|
|
43
|
+
return (_jsx(Suspense, { fallback: _jsx("div", { "aria-busy": "true", className: "h-32 w-full min-w-0 animate-reveal-late rounded-control border border-line-strong bg-ground" }), children: _jsx(RichTextEditor, { id: id, labelledBy: labelledBy, describedBy: describedBy, invalid: invalid, ariaLabel: ariaLabel, value: value, onChange: onChange, placeholder: placeholder, disabled: disabled, toolbar: toolbar, mentions: mentions, images: images, embeds: embeds }) }));
|
|
38
44
|
}
|
|
@@ -17,7 +17,7 @@ export { DataField, Field, NumberInput, ReadValue, Select, type SelectOption, Te
|
|
|
17
17
|
export { type ImageChange, ImageInput } from "./ImageInput.js";
|
|
18
18
|
export { type FieldLayout, FieldLayoutProvider, useSheetLayout, } from "./layout.js";
|
|
19
19
|
export { PasswordInput } from "./PasswordInput.js";
|
|
20
|
-
export { type MentionItem, RichTextInput, } from "./RichTextInput.js";
|
|
20
|
+
export { type MentionItem, type RichTextImages, RichTextInput, } from "./RichTextInput.js";
|
|
21
21
|
export { formatPattern, isPatternComplete, patternLength, patternValue, } from "./pattern.js";
|
|
22
22
|
export { PatternInput } from "./PatternInput.js";
|
|
23
23
|
export { SignatureInput } from "./SignatureInput.js";
|
|
@@ -1,8 +1,20 @@
|
|
|
1
1
|
import { isRichTextEmpty, richTextPlain } from "./richTextPlain.js";
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
import { type EmbedProvider, type RichTextPolicyOptions } from "./richTextPolicy.js";
|
|
3
|
+
/** The HTML with everything that runs taken out, or `null` where there is no DOM to do it.
|
|
4
|
+
* `embeds` lets the players of those video hosts through (`richTextPolicy.ts`). */
|
|
5
|
+
export declare function sanitizeRichText(html: string, options?: RichTextPolicyOptions): string | null;
|
|
4
6
|
export { isRichTextEmpty, richTextPlain };
|
|
5
7
|
/** The HTML of a note, read: cleaned, in the system's text style (`rich-text` in tokens.css). */
|
|
6
|
-
export declare function RichTextValue({ value }: {
|
|
8
|
+
export declare function RichTextValue({ value, embeds, sanitized, }: {
|
|
7
9
|
value: string | null | undefined;
|
|
10
|
+
/** The video hosts whose players are drawn (`RichTextInput embeds`). Without it, no iframe. */
|
|
11
|
+
embeds?: readonly EmbedProvider[];
|
|
12
|
+
/**
|
|
13
|
+
* The HTML was ALREADY cleaned by a trusted server under the rich text's policy
|
|
14
|
+
* (`sanitizeRichTextWith`, or the same allow-list in the backend): draw it as HTML on the
|
|
15
|
+
* server render too, instead of its plain words. The browser cleans it again anyway. Never
|
|
16
|
+
* set it for HTML that reaches the page without that cleaning — on the server it is drawn
|
|
17
|
+
* as it comes.
|
|
18
|
+
*/
|
|
19
|
+
sanitized?: boolean;
|
|
8
20
|
}): import("react").JSX.Element;
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
3
3
|
import { useUiCopy } from "../../foundations/copy.js";
|
|
4
4
|
import { isRichTextEmpty, richTextPlain, } from "./richTextPlain.js";
|
|
5
|
+
import { sanitizeRichTextWith, } from "./richTextPolicy.js";
|
|
5
6
|
import DOMPurify from "dompurify";
|
|
6
7
|
import { useSyncExternalStore } from "react";
|
|
7
8
|
/* ==================================================================== *
|
|
@@ -20,79 +21,25 @@ import { useSyncExternalStore } from "react";
|
|
|
20
21
|
* safe answer is the TEXT, tags removed and escaped by React — never the HTML
|
|
21
22
|
* unchecked. The browser then upgrades it to the cleaned HTML; the switch goes
|
|
22
23
|
* through `useSyncExternalStore`, so hydration does not see two different trees.
|
|
24
|
+
*
|
|
25
|
+
* ── Unless the server already cleaned it (`sanitized`) ──────────────
|
|
26
|
+
*
|
|
27
|
+
* An article read by a search engine, or by anyone before the scripts arrive,
|
|
28
|
+
* needs its headings, images and video in the server's HTML. `sanitized` is
|
|
29
|
+
* the application saying «this HTML was cleaned by a server I trust, under the
|
|
30
|
+
* same policy» (`richTextPolicy.ts`): then the server render draws it AS HTML.
|
|
31
|
+
* It is a contract, not a check — on the server nothing can verify it, so a
|
|
32
|
+
* value that skipped that cleaning runs in the reader's page. The browser does
|
|
33
|
+
* not take the word for it: once hydrated, the value is cleaned by DOMPurify
|
|
34
|
+
* again, as without the flag. If the server's cleaning produced the same
|
|
35
|
+
* string (`sanitizeRichTextWith` with the same options does), nothing moves.
|
|
23
36
|
* ==================================================================== */
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
"strong",
|
|
28
|
-
"b",
|
|
29
|
-
"em",
|
|
30
|
-
"i",
|
|
31
|
-
"u",
|
|
32
|
-
"s",
|
|
33
|
-
"strike",
|
|
34
|
-
"del",
|
|
35
|
-
"code",
|
|
36
|
-
"pre",
|
|
37
|
-
"h1",
|
|
38
|
-
"h2",
|
|
39
|
-
"h3",
|
|
40
|
-
"h4",
|
|
41
|
-
"ul",
|
|
42
|
-
"ol",
|
|
43
|
-
"li",
|
|
44
|
-
"blockquote",
|
|
45
|
-
"hr",
|
|
46
|
-
"a",
|
|
47
|
-
"span",
|
|
48
|
-
"table",
|
|
49
|
-
"thead",
|
|
50
|
-
"tbody",
|
|
51
|
-
"tr",
|
|
52
|
-
"th",
|
|
53
|
-
"td",
|
|
54
|
-
"colgroup",
|
|
55
|
-
"col",
|
|
56
|
-
"img",
|
|
57
|
-
];
|
|
58
|
-
const ALLOWED_ATTR = [
|
|
59
|
-
"href",
|
|
60
|
-
"title",
|
|
61
|
-
"colspan",
|
|
62
|
-
"rowspan",
|
|
63
|
-
"src",
|
|
64
|
-
"alt",
|
|
65
|
-
"data-type",
|
|
66
|
-
"data-id",
|
|
67
|
-
"data-label",
|
|
68
|
-
];
|
|
69
|
-
let hooked = false;
|
|
70
|
-
/** The HTML with everything that runs taken out, or `null` where there is no DOM to do it. */
|
|
71
|
-
export function sanitizeRichText(html) {
|
|
37
|
+
/** The HTML with everything that runs taken out, or `null` where there is no DOM to do it.
|
|
38
|
+
* `embeds` lets the players of those video hosts through (`richTextPolicy.ts`). */
|
|
39
|
+
export function sanitizeRichText(html, options = {}) {
|
|
72
40
|
if (typeof window === "undefined" || !DOMPurify.isSupported)
|
|
73
41
|
return null;
|
|
74
|
-
|
|
75
|
-
hooked = true;
|
|
76
|
-
DOMPurify.addHook("afterSanitizeAttributes", (node) => {
|
|
77
|
-
if (node.tagName === "A") {
|
|
78
|
-
node.setAttribute("target", "_blank");
|
|
79
|
-
node.setAttribute("rel", "noopener noreferrer");
|
|
80
|
-
}
|
|
81
|
-
if (node.tagName === "IMG") {
|
|
82
|
-
/* An image whose address was not allowed is a broken box: gone. One without a
|
|
83
|
-
description is read as decoration (`alt=""`) instead of as its file name. */
|
|
84
|
-
if (!node.hasAttribute("src"))
|
|
85
|
-
node.remove();
|
|
86
|
-
else if (!node.hasAttribute("alt"))
|
|
87
|
-
node.setAttribute("alt", "");
|
|
88
|
-
}
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
return DOMPurify.sanitize(html, {
|
|
92
|
-
ALLOWED_TAGS,
|
|
93
|
-
ALLOWED_ATTR,
|
|
94
|
-
ALLOWED_URI_REGEXP: /^(?:https?:|mailto:|tel:|data:image\/(?:png|jpeg|gif|webp);)/i,
|
|
95
|
-
});
|
|
42
|
+
return sanitizeRichTextWith(DOMPurify, html, options);
|
|
96
43
|
}
|
|
97
44
|
/* `richTextPlain` and `isRichTextEmpty` are plain functions (`richTextPlain.ts`), without the
|
|
98
45
|
directive, so a server component reads them; re-exported so every path that read them here
|
|
@@ -100,16 +47,22 @@ export function sanitizeRichText(html) {
|
|
|
100
47
|
export { isRichTextEmpty, richTextPlain };
|
|
101
48
|
const subscribe = () => () => { };
|
|
102
49
|
/** The HTML of a note, read: cleaned, in the system's text style (`rich-text` in tokens.css). */
|
|
103
|
-
export function RichTextValue({ value }) {
|
|
50
|
+
export function RichTextValue({ value, embeds, sanitized = false, }) {
|
|
104
51
|
const unset = useUiCopy().field.unset;
|
|
105
52
|
const inBrowser = useSyncExternalStore(subscribe, () => true, () => false);
|
|
106
53
|
if (isRichTextEmpty(value)) {
|
|
107
54
|
return _jsx("span", { className: "text-meta text-muted italic", children: unset });
|
|
108
55
|
}
|
|
109
56
|
const html = value ?? "";
|
|
110
|
-
const clean = inBrowser
|
|
57
|
+
const clean = inBrowser
|
|
58
|
+
? sanitizeRichText(html, { embeds })
|
|
59
|
+
: sanitized
|
|
60
|
+
? /* Cleaned by the server, by the application's word (`sanitized`, above). */
|
|
61
|
+
html
|
|
62
|
+
: null;
|
|
111
63
|
if (clean === null)
|
|
112
64
|
return _jsx("p", { className: "rich-text", children: richTextPlain(html) });
|
|
113
|
-
/* Cleaned by DOMPurify just above, with the tags and URLs
|
|
65
|
+
/* Cleaned by DOMPurify just above, with the tags and URLs of `richTextPolicy.ts` — or, on
|
|
66
|
+
the server render, by the server the application vouches for. */
|
|
114
67
|
return _jsx("div", { className: "rich-text min-w-0", dangerouslySetInnerHTML: { __html: clean } });
|
|
115
68
|
}
|
|
@@ -13,6 +13,7 @@ export { QrCode, type QrCodeProps } from "./QrCode.js";
|
|
|
13
13
|
export { RelationCard, type RelationCardProps, type RelationSummary, RelationValue, type RelationValueProps, } from "./Relation.js";
|
|
14
14
|
export { RichTextValue, sanitizeRichText } from "./RichText.js";
|
|
15
15
|
export { isRichTextEmpty, richTextPlain, } from "./richTextPlain.js";
|
|
16
|
+
export { EMBED_IFRAME_ATTRIBUTES, embedOf, type EmbedProvider, embedProviderOf, isRichTextUri, RICH_TEXT_ALLOWED_ATTR, RICH_TEXT_ALLOWED_TAGS, RICH_TEXT_URI, type RichTextPolicyOptions, richTextPurifyConfig, sanitizeRichTextWith, } from "./richTextPolicy.js";
|
|
16
17
|
export { type Rounding, type RoundingMethod, roundTo, } from "./rounding.js";
|
|
17
18
|
export { Elapsed, type ElapsedProps } from "./Elapsed.js";
|
|
18
19
|
export { elapsedMillis, type ElapsedSince, type ElapsedThresholds, elapsedTone, formatElapsed, sinceMillis, } from "./elapsedTime.js";
|
|
@@ -20,6 +20,8 @@ export { RelationCard, RelationValue, } from "./Relation.js";
|
|
|
20
20
|
/* The HTML of a note, read — cleaned of anything that runs. */
|
|
21
21
|
export { RichTextValue, sanitizeRichText } from "./RichText.js";
|
|
22
22
|
export { isRichTextEmpty, richTextPlain, } from "./richTextPlain.js";
|
|
23
|
+
/* The rich text's policy — the same allow-list for the browser, the editor and a server. */
|
|
24
|
+
export { EMBED_IFRAME_ATTRIBUTES, embedOf, embedProviderOf, isRichTextUri, RICH_TEXT_ALLOWED_ATTR, RICH_TEXT_ALLOWED_TAGS, RICH_TEXT_URI, richTextPurifyConfig, sanitizeRichTextWith, } from "./richTextPolicy.js";
|
|
23
25
|
export { roundTo, } from "./rounding.js";
|
|
24
26
|
/* HOW LONG IT HAS BEEN WAITING — a kitchen's ticket, a case under an SLA: live, in a tone by
|
|
25
27
|
two thresholds. The arithmetic is pure (`elapsedTime.ts`), so a sort or a server reads it. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
/** The words of an HTML, without its tags: what is shown where it cannot be cleaned. */
|
|
2
2
|
export declare function richTextPlain(html: string): string;
|
|
3
|
-
/** Nothing written: no text
|
|
3
|
+
/** Nothing written: no text, no image, no video — «<p></p>» from an emptied editor counts as nothing. */
|
|
4
4
|
export declare function isRichTextEmpty(html: string | null | undefined): boolean;
|
|
@@ -15,9 +15,9 @@ export function richTextPlain(html) {
|
|
|
15
15
|
.replace(/\s+/g, " ")
|
|
16
16
|
.trim();
|
|
17
17
|
}
|
|
18
|
-
/** Nothing written: no text
|
|
18
|
+
/** Nothing written: no text, no image, no video — «<p></p>» from an emptied editor counts as nothing. */
|
|
19
19
|
export function isRichTextEmpty(html) {
|
|
20
20
|
if (html === null || html === undefined)
|
|
21
21
|
return true;
|
|
22
|
-
return richTextPlain(html) === "" && !/<(?:img|hr|table)\b/i.test(html);
|
|
22
|
+
return richTextPlain(html) === "" && !/<(?:img|hr|table|iframe)\b/i.test(html);
|
|
23
23
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Config, DOMPurify } from "dompurify";
|
|
2
|
+
/** A video host the rich text may embed. */
|
|
3
|
+
export type EmbedProvider = "youtube" | "vimeo";
|
|
4
|
+
/** The tags a rich text keeps. `div` and `iframe` are added only when embeds are allowed. */
|
|
5
|
+
export declare const RICH_TEXT_ALLOWED_TAGS: readonly string[];
|
|
6
|
+
/** The attributes a rich text keeps (`data-embed` only when embeds are allowed). */
|
|
7
|
+
export declare const RICH_TEXT_ALLOWED_ATTR: readonly string[];
|
|
8
|
+
/** The addresses a link or an image may have: web, email, phone, an inline picture, or a
|
|
9
|
+
* relative one. Anything that starts with another scheme is not matched. */
|
|
10
|
+
export declare const RICH_TEXT_URI: RegExp;
|
|
11
|
+
/** Whether an address may stay in a link or an image — the test DOMPurify makes. */
|
|
12
|
+
export declare function isRichTextUri(address: string): boolean;
|
|
13
|
+
/** The provider whose canonical player this address is — or `null`. Exact, no variants. */
|
|
14
|
+
export declare function embedProviderOf(src: string, providers: readonly EmbedProvider[]): EmbedProvider | null;
|
|
15
|
+
/**
|
|
16
|
+
* The player for a video's address as people copy it — a YouTube watch, short, live or
|
|
17
|
+
* `youtu.be` link, a Vimeo page — or `null` when it is not a video of an allowed provider.
|
|
18
|
+
* YouTube always plays from `youtube-nocookie.com`; Vimeo from `player.vimeo.com`.
|
|
19
|
+
*/
|
|
20
|
+
export declare function embedOf(address: string, providers: readonly EmbedProvider[]): {
|
|
21
|
+
provider: EmbedProvider;
|
|
22
|
+
src: string;
|
|
23
|
+
} | null;
|
|
24
|
+
/** The attributes a video's player is drawn with — written, never taken from the HTML. */
|
|
25
|
+
export declare const EMBED_IFRAME_ATTRIBUTES: Readonly<Record<string, string>>;
|
|
26
|
+
/** What the rich text is cleaned for. */
|
|
27
|
+
export type RichTextPolicyOptions = {
|
|
28
|
+
/** The video hosts whose players survive. Without it, every `<iframe>` is dropped. */
|
|
29
|
+
embeds?: readonly EmbedProvider[] | undefined;
|
|
30
|
+
};
|
|
31
|
+
/** The DOMPurify configuration of the policy (the hooks are in `sanitizeRichTextWith`). */
|
|
32
|
+
export declare function richTextPurifyConfig(options?: RichTextPolicyOptions): Config;
|
|
33
|
+
/**
|
|
34
|
+
* A note's HTML cleaned under the policy with the DOMPurify you bring: the browser's, or — on
|
|
35
|
+
* a server — one bound to a jsdom window (`DOMPurify(new JSDOM("").window)`). Links open in
|
|
36
|
+
* another tab without our window; an image without an allowed address is removed and one
|
|
37
|
+
* without a description is marked as decoration; a video stays only as an allowed player.
|
|
38
|
+
*/
|
|
39
|
+
export declare function sanitizeRichTextWith(purify: DOMPurify, html: string, options?: RichTextPolicyOptions): string;
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/** The tags a rich text keeps. `div` and `iframe` are added only when embeds are allowed. */
|
|
2
|
+
export const RICH_TEXT_ALLOWED_TAGS = [
|
|
3
|
+
"p",
|
|
4
|
+
"br",
|
|
5
|
+
"strong",
|
|
6
|
+
"b",
|
|
7
|
+
"em",
|
|
8
|
+
"i",
|
|
9
|
+
"u",
|
|
10
|
+
"s",
|
|
11
|
+
"strike",
|
|
12
|
+
"del",
|
|
13
|
+
"code",
|
|
14
|
+
"pre",
|
|
15
|
+
"h1",
|
|
16
|
+
"h2",
|
|
17
|
+
"h3",
|
|
18
|
+
"h4",
|
|
19
|
+
"ul",
|
|
20
|
+
"ol",
|
|
21
|
+
"li",
|
|
22
|
+
"blockquote",
|
|
23
|
+
"hr",
|
|
24
|
+
"a",
|
|
25
|
+
"span",
|
|
26
|
+
"table",
|
|
27
|
+
"thead",
|
|
28
|
+
"tbody",
|
|
29
|
+
"tr",
|
|
30
|
+
"th",
|
|
31
|
+
"td",
|
|
32
|
+
"colgroup",
|
|
33
|
+
"col",
|
|
34
|
+
"img",
|
|
35
|
+
];
|
|
36
|
+
/** The attributes a rich text keeps (`data-embed` only when embeds are allowed). */
|
|
37
|
+
export const RICH_TEXT_ALLOWED_ATTR = [
|
|
38
|
+
"href",
|
|
39
|
+
"title",
|
|
40
|
+
"colspan",
|
|
41
|
+
"rowspan",
|
|
42
|
+
"src",
|
|
43
|
+
"alt",
|
|
44
|
+
"data-type",
|
|
45
|
+
"data-id",
|
|
46
|
+
"data-label",
|
|
47
|
+
];
|
|
48
|
+
/** The addresses a link or an image may have: web, email, phone, an inline picture, or a
|
|
49
|
+
* relative one. Anything that starts with another scheme is not matched. */
|
|
50
|
+
export const RICH_TEXT_URI = /^(?:https?:|mailto:|tel:|data:image\/(?:png|jpeg|gif|webp);|(?![a-z][a-z\d+.-]*:))/i;
|
|
51
|
+
/* What DOMPurify strips from an address before testing it (its ATTR_WHITESPACE). */
|
|
52
|
+
// eslint-disable-next-line no-control-regex
|
|
53
|
+
const ATTR_WHITESPACE = /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g;
|
|
54
|
+
/** Whether an address may stay in a link or an image — the test DOMPurify makes. */
|
|
55
|
+
export function isRichTextUri(address) {
|
|
56
|
+
return RICH_TEXT_URI.test(address.replace(ATTR_WHITESPACE, ""));
|
|
57
|
+
}
|
|
58
|
+
const YOUTUBE_ID = /^[\w-]{11}$/;
|
|
59
|
+
const YOUTUBE_EMBED = /^https:\/\/www\.youtube-nocookie\.com\/embed\/[\w-]{11}(?:\?start=\d+)?$/;
|
|
60
|
+
const VIMEO_EMBED = /^https:\/\/player\.vimeo\.com\/video\/\d+(?:\?h=[\da-f]+)?$/;
|
|
61
|
+
/** The provider whose canonical player this address is — or `null`. Exact, no variants. */
|
|
62
|
+
export function embedProviderOf(src, providers) {
|
|
63
|
+
if (providers.includes("youtube") && YOUTUBE_EMBED.test(src))
|
|
64
|
+
return "youtube";
|
|
65
|
+
if (providers.includes("vimeo") && VIMEO_EMBED.test(src))
|
|
66
|
+
return "vimeo";
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
/** «90», «90s», «1m30s» → seconds; anything else → `null`. */
|
|
70
|
+
function seconds(time) {
|
|
71
|
+
if (time === null)
|
|
72
|
+
return null;
|
|
73
|
+
const match = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?$/.exec(time);
|
|
74
|
+
if (match === null || time === "")
|
|
75
|
+
return null;
|
|
76
|
+
const [, h = "0", m = "0", s = "0"] = match;
|
|
77
|
+
const total = Number(h) * 3600 + Number(m) * 60 + Number(s);
|
|
78
|
+
return total > 0 ? total : null;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The player for a video's address as people copy it — a YouTube watch, short, live or
|
|
82
|
+
* `youtu.be` link, a Vimeo page — or `null` when it is not a video of an allowed provider.
|
|
83
|
+
* YouTube always plays from `youtube-nocookie.com`; Vimeo from `player.vimeo.com`.
|
|
84
|
+
*/
|
|
85
|
+
export function embedOf(address, providers) {
|
|
86
|
+
let url;
|
|
87
|
+
try {
|
|
88
|
+
const clean = address.trim();
|
|
89
|
+
url = new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(clean) ? clean : `https://${clean}`);
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
if (url.protocol !== "https:" && url.protocol !== "http:")
|
|
95
|
+
return null;
|
|
96
|
+
const host = url.hostname.toLowerCase().replace(/^(?:www|m)\./, "");
|
|
97
|
+
const parts = url.pathname.split("/").filter((part) => part !== "");
|
|
98
|
+
if (providers.includes("youtube")) {
|
|
99
|
+
let id;
|
|
100
|
+
if (host === "youtu.be")
|
|
101
|
+
id = parts[0];
|
|
102
|
+
else if (host === "youtube.com" || host === "youtube-nocookie.com") {
|
|
103
|
+
if (parts[0] === "watch")
|
|
104
|
+
id = url.searchParams.get("v") ?? undefined;
|
|
105
|
+
else if (["embed", "shorts", "live", "v"].includes(parts[0] ?? ""))
|
|
106
|
+
id = parts[1];
|
|
107
|
+
}
|
|
108
|
+
if (id !== undefined && YOUTUBE_ID.test(id)) {
|
|
109
|
+
const start = seconds(url.searchParams.get("t") ?? url.searchParams.get("start"));
|
|
110
|
+
const src = `https://www.youtube-nocookie.com/embed/${id}${start === null ? "" : `?start=${start}`}`;
|
|
111
|
+
return { provider: "youtube", src };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (providers.includes("vimeo")) {
|
|
115
|
+
let id;
|
|
116
|
+
let hash;
|
|
117
|
+
if (host === "player.vimeo.com" && parts[0] === "video") {
|
|
118
|
+
id = parts[1];
|
|
119
|
+
hash = url.searchParams.get("h") ?? undefined;
|
|
120
|
+
}
|
|
121
|
+
else if (host === "vimeo.com") {
|
|
122
|
+
const at = parts.findIndex((part) => /^\d+$/.test(part));
|
|
123
|
+
if (at !== -1) {
|
|
124
|
+
id = parts[at];
|
|
125
|
+
hash = parts[at + 1] ?? url.searchParams.get("h") ?? undefined;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (id !== undefined && /^\d+$/.test(id)) {
|
|
129
|
+
const unlisted = hash !== undefined && /^[\da-f]+$/i.test(hash) ? hash : null;
|
|
130
|
+
const src = `https://player.vimeo.com/video/${id}${unlisted === null ? "" : `?h=${unlisted.toLowerCase()}`}`;
|
|
131
|
+
return { provider: "vimeo", src };
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
/** The attributes a video's player is drawn with — written, never taken from the HTML. */
|
|
137
|
+
export const EMBED_IFRAME_ATTRIBUTES = {
|
|
138
|
+
allow: "encrypted-media; fullscreen; picture-in-picture",
|
|
139
|
+
allowfullscreen: "",
|
|
140
|
+
loading: "lazy",
|
|
141
|
+
referrerpolicy: "strict-origin-when-cross-origin",
|
|
142
|
+
sandbox: "allow-scripts allow-same-origin allow-presentation allow-popups",
|
|
143
|
+
};
|
|
144
|
+
/** The DOMPurify configuration of the policy (the hooks are in `sanitizeRichTextWith`). */
|
|
145
|
+
export function richTextPurifyConfig(options = {}) {
|
|
146
|
+
const embeds = (options.embeds ?? []).length > 0;
|
|
147
|
+
return {
|
|
148
|
+
ALLOWED_TAGS: [...RICH_TEXT_ALLOWED_TAGS, ...(embeds ? ["div", "iframe"] : [])],
|
|
149
|
+
ALLOWED_ATTR: [...RICH_TEXT_ALLOWED_ATTR, ...(embeds ? ["data-embed"] : [])],
|
|
150
|
+
ALLOWED_URI_REGEXP: RICH_TEXT_URI,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* A note's HTML cleaned under the policy with the DOMPurify you bring: the browser's, or — on
|
|
155
|
+
* a server — one bound to a jsdom window (`DOMPurify(new JSDOM("").window)`). Links open in
|
|
156
|
+
* another tab without our window; an image without an allowed address is removed and one
|
|
157
|
+
* without a description is marked as decoration; a video stays only as an allowed player.
|
|
158
|
+
*/
|
|
159
|
+
export function sanitizeRichTextWith(purify, html, options = {}) {
|
|
160
|
+
const providers = options.embeds ?? [];
|
|
161
|
+
const hook = (node) => {
|
|
162
|
+
if (node.tagName === "A") {
|
|
163
|
+
node.setAttribute("target", "_blank");
|
|
164
|
+
node.setAttribute("rel", "noopener noreferrer");
|
|
165
|
+
}
|
|
166
|
+
if (node.tagName === "IMG") {
|
|
167
|
+
/* An image whose address was not allowed is a broken box: gone. One without a
|
|
168
|
+
description is read as decoration (`alt=""`) instead of as its file name. */
|
|
169
|
+
if (!node.hasAttribute("src"))
|
|
170
|
+
node.remove();
|
|
171
|
+
else if (!node.hasAttribute("alt"))
|
|
172
|
+
node.setAttribute("alt", "");
|
|
173
|
+
}
|
|
174
|
+
if (node.tagName === "IFRAME") {
|
|
175
|
+
const provider = embedProviderOf(node.getAttribute("src") ?? "", providers);
|
|
176
|
+
if (provider === null) {
|
|
177
|
+
node.remove();
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
/* A frame is named for whoever cannot see it; the editor writes «Video de …». Named
|
|
181
|
+
BEFORE the written attributes, so cleaning the output again yields the same string. */
|
|
182
|
+
if (!node.hasAttribute("title"))
|
|
183
|
+
node.setAttribute("title", provider === "youtube" ? "YouTube" : "Vimeo");
|
|
184
|
+
for (const [name, value] of Object.entries(EMBED_IFRAME_ATTRIBUTES))
|
|
185
|
+
node.setAttribute(name, value);
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
purify.addHook("afterSanitizeAttributes", hook);
|
|
189
|
+
try {
|
|
190
|
+
return purify.sanitize(html, richTextPurifyConfig(options));
|
|
191
|
+
}
|
|
192
|
+
finally {
|
|
193
|
+
purify.removeHook("afterSanitizeAttributes", hook);
|
|
194
|
+
}
|
|
195
|
+
}
|
package/dist/tokens.css
CHANGED
|
@@ -1785,6 +1785,28 @@
|
|
|
1785
1785
|
border-radius: var(--radius-mark);
|
|
1786
1786
|
padding: 0 calc(var(--spacing) * 0.5);
|
|
1787
1787
|
}
|
|
1788
|
+
/* A picture of an article never pushes the column wider than the text. */
|
|
1789
|
+
& img {
|
|
1790
|
+
max-width: 100%;
|
|
1791
|
+
height: auto;
|
|
1792
|
+
border-radius: var(--radius-control);
|
|
1793
|
+
}
|
|
1794
|
+
/* A video's player (`RichTextInput embeds`): the column's width, in the 16:9 of a video. */
|
|
1795
|
+
& [data-embed] {
|
|
1796
|
+
aspect-ratio: 16 / 9;
|
|
1797
|
+
width: 100%;
|
|
1798
|
+
}
|
|
1799
|
+
& [data-embed] iframe {
|
|
1800
|
+
width: 100%;
|
|
1801
|
+
height: 100%;
|
|
1802
|
+
border: 0;
|
|
1803
|
+
border-radius: var(--radius-control);
|
|
1804
|
+
}
|
|
1805
|
+
/* In the editor, the picture or player picked as one piece (a click, an arrow). */
|
|
1806
|
+
& .ProseMirror-selectednode {
|
|
1807
|
+
outline: calc(var(--spacing) * 0.5) solid var(--color-primary);
|
|
1808
|
+
outline-offset: calc(var(--spacing) * 0.5);
|
|
1809
|
+
}
|
|
1788
1810
|
& p.is-editor-empty:first-child::before {
|
|
1789
1811
|
content: attr(data-placeholder);
|
|
1790
1812
|
color: var(--color-muted);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sincpro/web-ui",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.15.0",
|
|
4
4
|
"description": "An enterprise web design system for business software — ERPs, back offices, management tools — in React and Tailwind: tokens, primitives, components and the two views every management screen is made of.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -57,6 +57,7 @@
|
|
|
57
57
|
"@fullcalendar/react": "7.1.3",
|
|
58
58
|
"@internationalized/date": "^3.12.4",
|
|
59
59
|
"@svar-ui/react-gantt": "2.8.2",
|
|
60
|
+
"@tiptap/extension-image": "^3.32.2",
|
|
60
61
|
"@tiptap/extension-mention": "^3.32.2",
|
|
61
62
|
"@tiptap/extension-table": "^3.32.2",
|
|
62
63
|
"@tiptap/extensions": "^3.32.2",
|