@tooark/wysiwyg 1.9.4 → 1.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/README.pt-BR.md +2 -1
- package/dist/components/ark-wysiwyg-editor.cjs +830 -0
- package/dist/components/ark-wysiwyg-editor.cjs.map +1 -0
- package/dist/components/ark-wysiwyg-editor.js +828 -0
- package/dist/components/ark-wysiwyg-editor.js.map +1 -0
- package/dist/components/ark-wysiwyg-viewer.cjs +125 -0
- package/dist/components/ark-wysiwyg-viewer.cjs.map +1 -0
- package/dist/components/ark-wysiwyg-viewer.js +123 -0
- package/dist/components/ark-wysiwyg-viewer.js.map +1 -0
- package/dist/components/html-element-base.cjs +11 -0
- package/dist/components/html-element-base.cjs.map +1 -0
- package/dist/components/html-element-base.js +9 -0
- package/dist/components/html-element-base.js.map +1 -0
- package/dist/components/test-hooks.cjs +19 -0
- package/dist/components/test-hooks.cjs.map +1 -0
- package/dist/components/test-hooks.js +17 -0
- package/dist/components/test-hooks.js.map +1 -0
- package/dist/components/upgrade-properties.cjs +31 -0
- package/dist/components/upgrade-properties.cjs.map +1 -0
- package/dist/components/upgrade-properties.js +29 -0
- package/dist/components/upgrade-properties.js.map +1 -0
- package/dist/engine/index.cjs +278 -0
- package/dist/engine/index.cjs.map +1 -0
- package/dist/engine/index.js +269 -0
- package/dist/engine/index.js.map +1 -0
- package/dist/i18n.cjs +139 -0
- package/dist/i18n.cjs.map +1 -0
- package/dist/i18n.js +137 -0
- package/dist/i18n.js.map +1 -0
- package/dist/icons.cjs +34 -0
- package/dist/icons.cjs.map +1 -0
- package/dist/icons.js +32 -0
- package/dist/icons.js.map +1 -0
- package/dist/index.cjs +31 -1856
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +8 -1837
- package/dist/index.js.map +1 -1
- package/dist/register.cjs +23 -0
- package/dist/register.cjs.map +1 -0
- package/dist/register.js +21 -0
- package/dist/register.js.map +1 -0
- package/dist/security.cjs +117 -0
- package/dist/security.cjs.map +1 -0
- package/dist/security.js +112 -0
- package/dist/security.js.map +1 -0
- package/dist/styles.cjs +288 -0
- package/dist/styles.cjs.map +1 -0
- package/dist/styles.js +284 -0
- package/dist/styles.js.map +1 -0
- package/dist/types/index.cjs +29 -0
- package/dist/types/index.cjs.map +1 -0
- package/dist/types/index.js +26 -0
- package/dist/types/index.js.map +1 -0
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,1838 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
// Regras de segurança do conteúdo: o JSON do Tiptap vem de fora (banco, API,
|
|
11
|
-
// outro usuário), então URLs e cores entram por lista de permissão e nós ou
|
|
12
|
-
// marcas fora do schema caem, em vez de derrubar o documento inteiro.
|
|
13
|
-
const SAFE_PROTOCOLS = new Set(["http:", "https:", "mailto:", "tel:"]);
|
|
14
|
-
// Caracteres de controle e espaços no meio da URL são o truque clássico para passar `java\tscript:`.
|
|
15
|
-
// biome-ignore lint/suspicious/noControlCharactersInRegex: a faixa de controle é justamente o que se remove
|
|
16
|
-
const STRIP = /[\x00-\x1F\x7F-\x9F\s]/g;
|
|
17
|
-
/**
|
|
18
|
-
* URL aceita em `href`/`src`/`poster`: absoluta em http(s), mailto ou tel, ou relativa (`/caminho`, `#ancora`,
|
|
19
|
-
* `?busca`, `./` e `../`). Fora: `javascript:`, `data:`, `blob:`, `vbscript:` e qualquer outro esquema.
|
|
20
|
-
*/
|
|
21
|
-
function isSafeUrl(value) {
|
|
22
|
-
if (typeof value !== "string")
|
|
23
|
-
return false;
|
|
24
|
-
const url = value.replace(STRIP, "");
|
|
25
|
-
if (!url)
|
|
26
|
-
return false;
|
|
27
|
-
if (/^(\/|#|\?|\.\.?\/)/.test(url))
|
|
28
|
-
return true;
|
|
29
|
-
try {
|
|
30
|
-
return SAFE_PROTOCOLS.has(new URL(url).protocol);
|
|
31
|
-
}
|
|
32
|
-
catch {
|
|
33
|
-
return false;
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
/** Nome de host sem esquema ("exemplo.com/pagina"), a que o formulário de link acrescenta `https://`. */
|
|
37
|
-
function looksLikeHostname(value) {
|
|
38
|
-
return /^[a-z0-9-]+(\.[a-z0-9-]+)+(:\d+)?([/?#].*)?$/i.test(value.trim());
|
|
39
|
-
}
|
|
40
|
-
/** Valor de cor aceito em `color`: hex, nome CSS ou função rgb/hsl sem `;` (evita injetar outras declarações). */
|
|
41
|
-
function isSafeColor(value) {
|
|
42
|
-
return (typeof value === "string" &&
|
|
43
|
-
/^(#[0-9a-f]{3,8}|[a-z]{3,24}|(rgb|rgba|hsl|hsla)\([0-9.,%\s/]{1,40}\))$/i.test(value.trim()));
|
|
44
|
-
}
|
|
45
|
-
const ALIGNMENTS = new Set(["left", "center", "right", "justify"]);
|
|
46
|
-
function sanitizeMark(mark, schema) {
|
|
47
|
-
if (!mark || typeof mark.type !== "string" || !schema.marks[mark.type])
|
|
48
|
-
return null;
|
|
49
|
-
const attrs = { ...(mark.attrs ?? {}) };
|
|
50
|
-
if (mark.type === "link") {
|
|
51
|
-
if (!isSafeUrl(attrs.href))
|
|
52
|
-
return null;
|
|
53
|
-
attrs.href = attrs.href.replace(STRIP, "");
|
|
54
|
-
}
|
|
55
|
-
if (mark.type === "textStyle" || mark.type === "highlight") {
|
|
56
|
-
if (attrs.color != null && !isSafeColor(attrs.color))
|
|
57
|
-
delete attrs.color;
|
|
58
|
-
if (attrs.backgroundColor != null && !isSafeColor(attrs.backgroundColor))
|
|
59
|
-
delete attrs.backgroundColor;
|
|
60
|
-
}
|
|
61
|
-
const next = { ...mark };
|
|
62
|
-
if (Object.keys(attrs).length > 0) {
|
|
63
|
-
next.attrs = attrs;
|
|
64
|
-
}
|
|
65
|
-
else {
|
|
66
|
-
delete next.attrs;
|
|
67
|
-
}
|
|
68
|
-
return next;
|
|
69
|
-
}
|
|
70
|
-
function sanitizeNode(node, schema) {
|
|
71
|
-
if (!node || typeof node.type !== "string" || !schema.nodes[node.type])
|
|
72
|
-
return null;
|
|
73
|
-
const attrs = { ...(node.attrs ?? {}) };
|
|
74
|
-
if (node.type === "image" || node.type === "video") {
|
|
75
|
-
if (!isSafeUrl(attrs.src))
|
|
76
|
-
return null;
|
|
77
|
-
attrs.src = attrs.src.replace(STRIP, "");
|
|
78
|
-
if (attrs.poster != null && !isSafeUrl(attrs.poster))
|
|
79
|
-
delete attrs.poster;
|
|
80
|
-
}
|
|
81
|
-
if (attrs.textAlign != null && !ALIGNMENTS.has(String(attrs.textAlign)))
|
|
82
|
-
delete attrs.textAlign;
|
|
83
|
-
if (node.type === "heading") {
|
|
84
|
-
const level = Number(attrs.level);
|
|
85
|
-
attrs.level = Number.isInteger(level) ? Math.min(4, Math.max(1, level)) : 1;
|
|
86
|
-
}
|
|
87
|
-
const marks = Array.isArray(node.marks)
|
|
88
|
-
? node.marks.map((mark) => sanitizeMark(mark, schema)).filter((mark) => mark !== null)
|
|
89
|
-
: undefined;
|
|
90
|
-
const content = Array.isArray(node.content)
|
|
91
|
-
? node.content.map((child) => sanitizeNode(child, schema)).filter((child) => child !== null)
|
|
92
|
-
: undefined;
|
|
93
|
-
const next = { ...node };
|
|
94
|
-
if (Object.keys(attrs).length > 0) {
|
|
95
|
-
next.attrs = attrs;
|
|
96
|
-
}
|
|
97
|
-
else {
|
|
98
|
-
delete next.attrs;
|
|
99
|
-
}
|
|
100
|
-
if (marks)
|
|
101
|
-
next.marks = marks;
|
|
102
|
-
if (content)
|
|
103
|
-
next.content = content;
|
|
104
|
-
return next;
|
|
105
|
-
}
|
|
106
|
-
/**
|
|
107
|
-
* Sanitiza um documento do Tiptap contra o schema do editor: nós e marcas desconhecidos são removidos (com os
|
|
108
|
-
* filhos), links, imagens e vídeos com URL fora da lista de permissão caem, cores inválidas somem e `textAlign`
|
|
109
|
-
* e `level` ficam nos valores previstos. `null` continua `null`.
|
|
110
|
-
*/
|
|
111
|
-
function sanitizeWysiwygContent(content, schema) {
|
|
112
|
-
if (!content)
|
|
113
|
-
return null;
|
|
114
|
-
const doc = sanitizeNode(content, schema);
|
|
115
|
-
if (!doc)
|
|
116
|
-
return null;
|
|
117
|
-
return doc;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
/** Documento vazio do ProseMirror (um parágrafo). */
|
|
121
|
-
const EMPTY_DOC = { type: "doc", content: [{ type: "paragraph" }] };
|
|
122
|
-
/** Tamanho máximo de arquivo aceito por padrão (10 MiB). */
|
|
123
|
-
const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024;
|
|
124
|
-
/** Níveis de título disponíveis no editor. */
|
|
125
|
-
const HEADING_LEVELS = [1, 2, 3, 4];
|
|
126
|
-
/** Resolve "auto" para "light"/"dark" pelo color-scheme computado de `element`, ou pela preferência do sistema. */
|
|
127
|
-
function resolveWysiwygTheme(theme, element) {
|
|
128
|
-
if (theme === "dark")
|
|
129
|
-
return "dark";
|
|
130
|
-
if (theme === "light")
|
|
131
|
-
return "light";
|
|
132
|
-
return resolveColorScheme(element);
|
|
133
|
-
}
|
|
134
|
-
function applyTheme(element, theme) {
|
|
135
|
-
element.setAttribute("data-ark-theme", theme);
|
|
136
|
-
}
|
|
137
|
-
/** Vídeo externo como bloco atômico: `src` (e `poster`) apontam para fora, nunca para base64. */
|
|
138
|
-
const Video = Node.create({
|
|
139
|
-
name: "video",
|
|
140
|
-
group: "block",
|
|
141
|
-
atom: true,
|
|
142
|
-
draggable: true,
|
|
143
|
-
selectable: true,
|
|
144
|
-
addAttributes() {
|
|
145
|
-
return {
|
|
146
|
-
src: { default: null },
|
|
147
|
-
// HTML colado: um poster fora da lista de permissão cai, o vídeo fica.
|
|
148
|
-
poster: {
|
|
149
|
-
default: null,
|
|
150
|
-
parseHTML: (element) => {
|
|
151
|
-
const poster = element.getAttribute("poster");
|
|
152
|
-
return isSafeUrl(poster) ? poster : null;
|
|
153
|
-
}
|
|
154
|
-
},
|
|
155
|
-
title: { default: null }
|
|
156
|
-
};
|
|
157
|
-
},
|
|
158
|
-
parseHTML() {
|
|
159
|
-
// HTML colado: só vira nó com src permitido (nada de data:/blob:, que a sanitização do JSON também barra).
|
|
160
|
-
return [{ tag: "video[src]", getAttrs: (element) => (isSafeUrl(element.getAttribute("src")) ? null : false) }];
|
|
161
|
-
},
|
|
162
|
-
renderHTML({ HTMLAttributes }) {
|
|
163
|
-
return ["video", mergeAttributes({ controls: "true", preload: "metadata" }, HTMLAttributes)];
|
|
164
|
-
},
|
|
165
|
-
addCommands() {
|
|
166
|
-
return {
|
|
167
|
-
setVideo: (attrs) => ({ commands }) => commands.insertContent({ type: this.name, attrs })
|
|
168
|
-
};
|
|
169
|
-
}
|
|
170
|
-
});
|
|
171
|
-
/** Imagem do Tiptap que, no HTML colado, só vira nó com src permitido (o padrão só barra data:, não blob:). */
|
|
172
|
-
const SafeImage = Image.extend({
|
|
173
|
-
parseHTML() {
|
|
174
|
-
return [{ tag: "img[src]", getAttrs: (element) => (isSafeUrl(element.getAttribute("src")) ? null : false) }];
|
|
175
|
-
}
|
|
176
|
-
});
|
|
177
|
-
// --- Extensões compartilhadas ---
|
|
178
|
-
/**
|
|
179
|
-
* Extensões do editor e do viewer (o mesmo schema nos dois, senão o conteúdo salvo não renderiza): StarterKit
|
|
180
|
-
* (títulos 1-4, sublinhado e link com URL validada), cor de texto, marca-texto, alinhamento, imagem sem base64
|
|
181
|
-
* e vídeo externo. Em `editable` o link não abre no clique (o clique edita); no viewer abre em nova aba.
|
|
182
|
-
*/
|
|
183
|
-
function createWysiwygExtensions(options) {
|
|
184
|
-
const extensions = [
|
|
185
|
-
StarterKit.configure({
|
|
186
|
-
heading: { levels: [...HEADING_LEVELS] },
|
|
187
|
-
link: {
|
|
188
|
-
openOnClick: !options.editable,
|
|
189
|
-
autolink: true,
|
|
190
|
-
linkOnPaste: true,
|
|
191
|
-
// A lista de permissão do pacote vale para o que o usuário digita, cola ou autolinka; um host sem
|
|
192
|
-
// esquema ("exemplo.com") passa aqui porque o autolink grava o href já com http.
|
|
193
|
-
isAllowedUri: (url) => isSafeUrl(url) || looksLikeHostname(url),
|
|
194
|
-
HTMLAttributes: { target: "_blank", rel: "noopener noreferrer nofollow" }
|
|
195
|
-
}
|
|
196
|
-
}),
|
|
197
|
-
TextStyle,
|
|
198
|
-
Color,
|
|
199
|
-
Highlight.configure({ multicolor: true }),
|
|
200
|
-
TextAlign.configure({ types: ["heading", "paragraph"], alignments: ["left", "center", "right", "justify"] }),
|
|
201
|
-
SafeImage.configure({ allowBase64: false, inline: false }),
|
|
202
|
-
Video
|
|
203
|
-
];
|
|
204
|
-
if (options.placeholder) {
|
|
205
|
-
extensions.push(Placeholder.configure({ placeholder: options.placeholder }));
|
|
206
|
-
}
|
|
207
|
-
return extensions;
|
|
208
|
-
}
|
|
209
|
-
function kindOf(file) {
|
|
210
|
-
if (file.type.startsWith("image/"))
|
|
211
|
-
return "image";
|
|
212
|
-
if (file.type.startsWith("video/"))
|
|
213
|
-
return "video";
|
|
214
|
-
return null;
|
|
215
|
-
}
|
|
216
|
-
function filesOf(list) {
|
|
217
|
-
return Array.from(list ?? []);
|
|
218
|
-
}
|
|
219
|
-
function createInstance(element, options) {
|
|
220
|
-
let resolved = resolveWysiwygTheme(options.theme, element);
|
|
221
|
-
let applying = false;
|
|
222
|
-
let uploading = 0;
|
|
223
|
-
const maxFileSize = options.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;
|
|
224
|
-
const fail = (reason, file, error) => {
|
|
225
|
-
options.onUploadError?.({ reason, file, error });
|
|
226
|
-
return false;
|
|
227
|
-
};
|
|
228
|
-
// Arquivos colados ou arrastados só entram pelo gancho; sem ele são consumidos (nada de base64 no JSON). Os que
|
|
229
|
-
// não são imagem nem vídeo são recusados com o motivo (insertFile emite unsupported-type), em vez de sumir.
|
|
230
|
-
const handleFiles = (files, position) => {
|
|
231
|
-
if (files.length === 0)
|
|
232
|
-
return false;
|
|
233
|
-
for (const file of files)
|
|
234
|
-
void insertFile(file, position);
|
|
235
|
-
return true;
|
|
236
|
-
};
|
|
237
|
-
const editor = new Editor({
|
|
238
|
-
element,
|
|
239
|
-
editable: options.editable,
|
|
240
|
-
extensions: createWysiwygExtensions({ editable: options.editable, placeholder: options.placeholder }),
|
|
241
|
-
content: EMPTY_DOC,
|
|
242
|
-
editorProps: {
|
|
243
|
-
// O Tiptap já põe role="textbox" no conteúdo editável; o nome acessível vai junto, só quando o app dá um.
|
|
244
|
-
...(options.label ? { attributes: { "aria-label": options.label } } : {}),
|
|
245
|
-
handlePaste: (_view, event) => {
|
|
246
|
-
const files = filesOf(event.clipboardData?.files);
|
|
247
|
-
// Planilhas e editores copiam o texto junto de arquivos que não são mídia: aí o texto vence e cola normal.
|
|
248
|
-
const hasText = Array.from(event.clipboardData?.types ?? []).some((type) => type.startsWith("text/"));
|
|
249
|
-
if (hasText && !files.some((file) => kindOf(file)))
|
|
250
|
-
return false;
|
|
251
|
-
return handleFiles(files);
|
|
252
|
-
},
|
|
253
|
-
handleDrop: (view, event, _slice, moved) => {
|
|
254
|
-
if (moved)
|
|
255
|
-
return false;
|
|
256
|
-
const at = view.posAtCoords({ left: event.clientX, top: event.clientY });
|
|
257
|
-
return handleFiles(filesOf(event.dataTransfer?.files), at?.pos);
|
|
258
|
-
},
|
|
259
|
-
// HTML colado com <img>/<video> só vira nó quando há gancho: sem ele, seria um hotlink que o app não controla.
|
|
260
|
-
transformPastedHTML: (html) => (options.uploadFile ? html : html.replace(/<(img|video|source)\b[^>]*>/gi, ""))
|
|
261
|
-
}
|
|
262
|
-
});
|
|
263
|
-
const setContent = (content) => {
|
|
264
|
-
applying = true;
|
|
265
|
-
try {
|
|
266
|
-
// Fora do histórico: Ctrl+Z depois de o app trocar o conteúdo não pode voltar ao documento anterior.
|
|
267
|
-
editor
|
|
268
|
-
.chain()
|
|
269
|
-
.setMeta("addToHistory", false)
|
|
270
|
-
.setContent(sanitizeWysiwygContent(content, editor.schema) ?? EMPTY_DOC, { emitUpdate: false })
|
|
271
|
-
.run();
|
|
272
|
-
}
|
|
273
|
-
finally {
|
|
274
|
-
applying = false;
|
|
275
|
-
}
|
|
276
|
-
};
|
|
277
|
-
if (options.content)
|
|
278
|
-
setContent(options.content);
|
|
279
|
-
if (options.onChange) {
|
|
280
|
-
editor.on("update", () => {
|
|
281
|
-
if (!applying)
|
|
282
|
-
options.onChange?.(editor.getJSON());
|
|
283
|
-
});
|
|
284
|
-
}
|
|
285
|
-
const setUploading = (next) => {
|
|
286
|
-
uploading = next;
|
|
287
|
-
options.onUploadingChange?.(next);
|
|
288
|
-
};
|
|
289
|
-
const insertFile = async (file, position) => {
|
|
290
|
-
const kind = kindOf(file);
|
|
291
|
-
if (!kind)
|
|
292
|
-
return fail("unsupported-type", file);
|
|
293
|
-
if (!options.uploadFile)
|
|
294
|
-
return fail("no-uploader", file);
|
|
295
|
-
if (file.size > maxFileSize)
|
|
296
|
-
return fail("too-large", file);
|
|
297
|
-
const at = position ?? editor.state.selection.to;
|
|
298
|
-
setUploading(uploading + 1);
|
|
299
|
-
try {
|
|
300
|
-
const result = await options.uploadFile(file, kind);
|
|
301
|
-
if (!result || !isSafeUrl(result.src))
|
|
302
|
-
return fail("invalid-src", file);
|
|
303
|
-
if (editor.isDestroyed)
|
|
304
|
-
return false;
|
|
305
|
-
const pos = Math.min(at, editor.state.doc.content.size);
|
|
306
|
-
const attrs = kind === "image"
|
|
307
|
-
? { src: result.src, alt: result.alt ?? file.name, title: result.title ?? null }
|
|
308
|
-
: { src: result.src, poster: isSafeUrl(result.poster) ? result.poster : null, title: result.title ?? null };
|
|
309
|
-
editor.chain().focus().insertContentAt(pos, { type: kind, attrs }).run();
|
|
310
|
-
return true;
|
|
311
|
-
}
|
|
312
|
-
catch (error) {
|
|
313
|
-
return fail("failed", file, error);
|
|
314
|
-
}
|
|
315
|
-
finally {
|
|
316
|
-
setUploading(uploading - 1);
|
|
317
|
-
}
|
|
318
|
-
};
|
|
319
|
-
applyTheme(element, resolved);
|
|
320
|
-
return {
|
|
321
|
-
editor,
|
|
322
|
-
getJSON: () => editor.getJSON(),
|
|
323
|
-
setContent,
|
|
324
|
-
isActive: (name, attrs) => editor.isActive(name, attrs),
|
|
325
|
-
setEditable: (editable) => editor.setEditable(editable),
|
|
326
|
-
setTheme: (theme) => {
|
|
327
|
-
resolved = resolveWysiwygTheme(theme, element);
|
|
328
|
-
applyTheme(element, resolved);
|
|
329
|
-
},
|
|
330
|
-
resolvedTheme: () => resolved,
|
|
331
|
-
insertFile,
|
|
332
|
-
uploading: () => uploading,
|
|
333
|
-
setLink: (raw) => {
|
|
334
|
-
const trimmed = raw.trim();
|
|
335
|
-
const href = looksLikeHostname(trimmed) && !/^[a-z][a-z0-9+.-]*:/i.test(trimmed) ? `https://${trimmed}` : trimmed;
|
|
336
|
-
if (!isSafeUrl(href))
|
|
337
|
-
return false;
|
|
338
|
-
const chain = editor.chain().focus().extendMarkRange("link");
|
|
339
|
-
if (editor.state.selection.empty && !editor.isActive("link")) {
|
|
340
|
-
chain.insertContent({ type: "text", text: href, marks: [{ type: "link", attrs: { href } }] }).run();
|
|
341
|
-
}
|
|
342
|
-
else {
|
|
343
|
-
chain.setLink({ href }).run();
|
|
344
|
-
}
|
|
345
|
-
return true;
|
|
346
|
-
},
|
|
347
|
-
unsetLink: () => {
|
|
348
|
-
editor.chain().focus().extendMarkRange("link").unsetLink().run();
|
|
349
|
-
},
|
|
350
|
-
destroy: () => editor.destroy()
|
|
351
|
-
};
|
|
352
|
-
}
|
|
353
|
-
/** Cria um editor WYSIWYG (editável) dentro de `element`. */
|
|
354
|
-
function createWysiwygEditor(element, options = {}) {
|
|
355
|
-
return createInstance(element, {
|
|
356
|
-
content: options.content,
|
|
357
|
-
theme: options.theme,
|
|
358
|
-
placeholder: options.placeholder,
|
|
359
|
-
label: options.label,
|
|
360
|
-
editable: options.editable ?? true,
|
|
361
|
-
uploadFile: options.uploadFile,
|
|
362
|
-
maxFileSize: options.maxFileSize,
|
|
363
|
-
onChange: options.onChange,
|
|
364
|
-
onUploadError: options.onUploadError,
|
|
365
|
-
onUploadingChange: options.onUploadingChange
|
|
366
|
-
});
|
|
367
|
-
}
|
|
368
|
-
/** Cria um viewer (somente leitura) que renderiza o mesmo JSON do editor. */
|
|
369
|
-
function createWysiwygViewer(element, options = {}) {
|
|
370
|
-
return createInstance(element, {
|
|
371
|
-
content: options.content,
|
|
372
|
-
theme: options.theme,
|
|
373
|
-
editable: false
|
|
374
|
-
});
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
// Rótulos da toolbar. O pacote não depende de @tooark/core, então carrega o
|
|
378
|
-
// próprio dicionário; `custom` recebe um JSON parcial por cima do inglês.
|
|
379
|
-
const en = {
|
|
380
|
-
textStyle: "Text style",
|
|
381
|
-
paragraph: "Normal",
|
|
382
|
-
heading: "Heading",
|
|
383
|
-
bold: "Bold",
|
|
384
|
-
italic: "Italic",
|
|
385
|
-
underline: "Underline",
|
|
386
|
-
strike: "Strikethrough",
|
|
387
|
-
code: "Code",
|
|
388
|
-
textColor: "Text color",
|
|
389
|
-
highlight: "Highlight",
|
|
390
|
-
noColor: "No color",
|
|
391
|
-
alignLeft: "Align left",
|
|
392
|
-
alignCenter: "Align center",
|
|
393
|
-
alignRight: "Align right",
|
|
394
|
-
alignJustify: "Justify",
|
|
395
|
-
bulletList: "Bulleted list",
|
|
396
|
-
orderedList: "Numbered list",
|
|
397
|
-
indent: "Increase indent",
|
|
398
|
-
outdent: "Decrease indent",
|
|
399
|
-
link: "Link",
|
|
400
|
-
linkUrl: "URL",
|
|
401
|
-
apply: "Apply",
|
|
402
|
-
remove: "Remove",
|
|
403
|
-
invalidUrl: "Enter a valid http(s), mailto or tel address",
|
|
404
|
-
image: "Image",
|
|
405
|
-
video: "Video",
|
|
406
|
-
blockquote: "Quote",
|
|
407
|
-
horizontalRule: "Horizontal rule",
|
|
408
|
-
clearFormat: "Clear formatting",
|
|
409
|
-
undo: "Undo",
|
|
410
|
-
redo: "Redo",
|
|
411
|
-
uploading: "Uploading"
|
|
412
|
-
};
|
|
413
|
-
const pt = {
|
|
414
|
-
textStyle: "Estilo do texto",
|
|
415
|
-
paragraph: "Normal",
|
|
416
|
-
heading: "Título",
|
|
417
|
-
bold: "Negrito",
|
|
418
|
-
italic: "Itálico",
|
|
419
|
-
underline: "Sublinhado",
|
|
420
|
-
strike: "Tachado",
|
|
421
|
-
code: "Código",
|
|
422
|
-
textColor: "Cor do texto",
|
|
423
|
-
highlight: "Marca-texto",
|
|
424
|
-
noColor: "Sem cor",
|
|
425
|
-
alignLeft: "Alinhar à esquerda",
|
|
426
|
-
alignCenter: "Centralizar",
|
|
427
|
-
alignRight: "Alinhar à direita",
|
|
428
|
-
alignJustify: "Justificar",
|
|
429
|
-
bulletList: "Lista com marcadores",
|
|
430
|
-
orderedList: "Lista numerada",
|
|
431
|
-
indent: "Aumentar recuo",
|
|
432
|
-
outdent: "Diminuir recuo",
|
|
433
|
-
link: "Link",
|
|
434
|
-
linkUrl: "URL",
|
|
435
|
-
apply: "Aplicar",
|
|
436
|
-
remove: "Remover",
|
|
437
|
-
invalidUrl: "Informe um endereço http(s), mailto ou tel válido",
|
|
438
|
-
image: "Imagem",
|
|
439
|
-
video: "Vídeo",
|
|
440
|
-
blockquote: "Citação",
|
|
441
|
-
horizontalRule: "Linha horizontal",
|
|
442
|
-
clearFormat: "Limpar formatação",
|
|
443
|
-
undo: "Desfazer",
|
|
444
|
-
redo: "Refazer",
|
|
445
|
-
uploading: "Enviando"
|
|
446
|
-
};
|
|
447
|
-
const es = {
|
|
448
|
-
textStyle: "Estilo del texto",
|
|
449
|
-
paragraph: "Normal",
|
|
450
|
-
heading: "Título",
|
|
451
|
-
bold: "Negrita",
|
|
452
|
-
italic: "Cursiva",
|
|
453
|
-
underline: "Subrayado",
|
|
454
|
-
strike: "Tachado",
|
|
455
|
-
code: "Código",
|
|
456
|
-
textColor: "Color del texto",
|
|
457
|
-
highlight: "Resaltado",
|
|
458
|
-
noColor: "Sin color",
|
|
459
|
-
alignLeft: "Alinear a la izquierda",
|
|
460
|
-
alignCenter: "Centrar",
|
|
461
|
-
alignRight: "Alinear a la derecha",
|
|
462
|
-
alignJustify: "Justificar",
|
|
463
|
-
bulletList: "Lista con viñetas",
|
|
464
|
-
orderedList: "Lista numerada",
|
|
465
|
-
indent: "Aumentar sangría",
|
|
466
|
-
outdent: "Reducir sangría",
|
|
467
|
-
link: "Enlace",
|
|
468
|
-
linkUrl: "URL",
|
|
469
|
-
apply: "Aplicar",
|
|
470
|
-
remove: "Quitar",
|
|
471
|
-
invalidUrl: "Ingrese una dirección http(s), mailto o tel válida",
|
|
472
|
-
image: "Imagen",
|
|
473
|
-
video: "Vídeo",
|
|
474
|
-
blockquote: "Cita",
|
|
475
|
-
horizontalRule: "Línea horizontal",
|
|
476
|
-
clearFormat: "Borrar formato",
|
|
477
|
-
undo: "Deshacer",
|
|
478
|
-
redo: "Rehacer",
|
|
479
|
-
uploading: "Enviando"
|
|
480
|
-
};
|
|
481
|
-
const LOCALES = { en, pt, es };
|
|
482
|
-
/**
|
|
483
|
-
* Resolve os rótulos da toolbar: `en`, `pt` ou `es`, também com região (`pt-BR` usa o `pt`; desconhecido cai em
|
|
484
|
-
* `en`); `localeJson` (objeto ou JSON) sobrescreve chave a chave, e é a única fonte de `custom`. Só strings entram;
|
|
485
|
-
* JSON inválido é ignorado.
|
|
486
|
-
*/
|
|
487
|
-
function resolveWysiwygLabels(lang, localeJson) {
|
|
488
|
-
// Idioma base da tag (`pt-BR` e `pt_br` viram `pt`), buscado como chave própria do mapa.
|
|
489
|
-
const key = (lang || "en").trim().toLowerCase().split(/[-_]/)[0];
|
|
490
|
-
const base = Object.getOwnPropertyDescriptor(LOCALES, key)?.value ?? en;
|
|
491
|
-
let overrides = {};
|
|
492
|
-
if (typeof localeJson === "string" && localeJson.trim()) {
|
|
493
|
-
try {
|
|
494
|
-
overrides = JSON.parse(localeJson);
|
|
495
|
-
}
|
|
496
|
-
catch {
|
|
497
|
-
overrides = {};
|
|
498
|
-
}
|
|
499
|
-
}
|
|
500
|
-
else if (localeJson && typeof localeJson === "object") {
|
|
501
|
-
overrides = localeJson;
|
|
502
|
-
}
|
|
503
|
-
const labels = { ...base };
|
|
504
|
-
for (const key of Object.keys(labels)) {
|
|
505
|
-
const value = overrides[key];
|
|
506
|
-
if (typeof value === "string" && value)
|
|
507
|
-
labels[key] = value;
|
|
508
|
-
}
|
|
509
|
-
return labels;
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
// Ícones da toolbar (traços de 24x24 no estilo Lucide), constantes: o único
|
|
513
|
-
// HTML que o pacote injeta por innerHTML.
|
|
514
|
-
const svg = (body) => `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${body}</svg>`;
|
|
515
|
-
const ICONS = {
|
|
516
|
-
bold: svg('<path d="M6 4h8a4 4 0 0 1 0 8H6z"/><path d="M6 12h9a4 4 0 0 1 0 8H6z"/>'),
|
|
517
|
-
italic: svg('<line x1="19" y1="4" x2="10" y2="4"/><line x1="14" y1="20" x2="5" y2="20"/><line x1="15" y1="4" x2="9" y2="20"/>'),
|
|
518
|
-
underline: svg('<path d="M6 4v6a6 6 0 0 0 12 0V4"/><line x1="4" y1="20" x2="20" y2="20"/>'),
|
|
519
|
-
strike: svg('<path d="M16 4H9a3 3 0 0 0-2.83 4"/><path d="M14 12a4 4 0 0 1 0 8H6"/><line x1="4" y1="12" x2="20" y2="12"/>'),
|
|
520
|
-
code: svg('<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>'),
|
|
521
|
-
textColor: svg('<path d="M4 20h16"/><path d="m6 16 6-12 6 12"/><path d="M8 12h8"/>'),
|
|
522
|
-
highlight: svg('<path d="m9 11-6 6v3h9l3-3"/><path d="m22 12-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4"/>'),
|
|
523
|
-
alignLeft: svg('<line x1="21" y1="6" x2="3" y2="6"/><line x1="15" y1="12" x2="3" y2="12"/><line x1="17" y1="18" x2="3" y2="18"/>'),
|
|
524
|
-
alignCenter: svg('<line x1="21" y1="6" x2="3" y2="6"/><line x1="17" y1="12" x2="7" y2="12"/><line x1="19" y1="18" x2="5" y2="18"/>'),
|
|
525
|
-
alignRight: svg('<line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="12" x2="9" y2="12"/><line x1="21" y1="18" x2="7" y2="18"/>'),
|
|
526
|
-
alignJustify: svg('<line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="12" x2="3" y2="12"/><line x1="21" y1="18" x2="3" y2="18"/>'),
|
|
527
|
-
bulletList: svg('<line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><circle cx="4" cy="6" r="1" fill="currentColor"/><circle cx="4" cy="12" r="1" fill="currentColor"/><circle cx="4" cy="18" r="1" fill="currentColor"/>'),
|
|
528
|
-
orderedList: svg('<line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/><path d="M4 6h1v4"/><path d="M4 10h2"/><path d="M6 18H4c0-1 2-2 2-3s-1-1.5-2-1"/>'),
|
|
529
|
-
indent: svg('<polyline points="3 8 7 12 3 16"/><line x1="21" y1="12" x2="11" y2="12"/><line x1="21" y1="6" x2="11" y2="6"/><line x1="21" y1="18" x2="11" y2="18"/>'),
|
|
530
|
-
outdent: svg('<polyline points="7 8 3 12 7 16"/><line x1="21" y1="12" x2="11" y2="12"/><line x1="21" y1="6" x2="11" y2="6"/><line x1="21" y1="18" x2="11" y2="18"/>'),
|
|
531
|
-
link: svg('<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>'),
|
|
532
|
-
image: svg('<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/>'),
|
|
533
|
-
video: svg('<rect x="2" y="4" width="14" height="16" rx="2"/><path d="m22 8-6 4 6 4V8z"/>'),
|
|
534
|
-
blockquote: svg('<path d="M10 11H6a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v6a4 4 0 0 1-4 4"/><path d="M20 11h-4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v6a4 4 0 0 1-4 4"/>'),
|
|
535
|
-
horizontalRule: svg('<line x1="4" y1="12" x2="20" y2="12"/>'),
|
|
536
|
-
clearFormat: svg('<path d="M4 7V4h16v3"/><path d="M5 20h6"/><path d="M13 4 8 20"/><path d="m15 15 5 5"/><path d="m20 15-5 5"/>'),
|
|
537
|
-
undo: svg('<path d="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13"/>'),
|
|
538
|
-
redo: svg('<path d="M21 7v6h-6"/><path d="M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7"/>'),
|
|
539
|
-
none: svg('<circle cx="12" cy="12" r="9"/><line x1="5.6" y1="5.6" x2="18.4" y2="18.4"/>')
|
|
540
|
-
};
|
|
541
|
-
|
|
542
|
-
const WYSIWYG_STYLE_ID = "ark-wysiwyg-styles";
|
|
543
|
-
/**
|
|
544
|
-
* CSS base do editor/viewer. Plano e independente de Tailwind para que o pacote
|
|
545
|
-
* funcione em qualquer projeto. Temas via atributo `data-ark-theme`.
|
|
546
|
-
*/
|
|
547
|
-
const wysiwygCss = `
|
|
548
|
-
.ark-wysiwyg {
|
|
549
|
-
display: flex;
|
|
550
|
-
flex-direction: column;
|
|
551
|
-
gap: 8px;
|
|
552
|
-
font-family: inherit;
|
|
553
|
-
color: #0f172a;
|
|
554
|
-
}
|
|
555
|
-
.ark-wysiwyg[data-ark-theme="dark"] { color: #e2e8f0; }
|
|
556
|
-
|
|
557
|
-
/* ---------- Toolbar ---------- */
|
|
558
|
-
.ark-wysiwyg__toolbar {
|
|
559
|
-
display: flex;
|
|
560
|
-
flex-wrap: wrap;
|
|
561
|
-
align-items: center;
|
|
562
|
-
gap: 4px;
|
|
563
|
-
padding: 6px;
|
|
564
|
-
border: 1px solid #e2e8f0;
|
|
565
|
-
border-radius: 8px;
|
|
566
|
-
background: #f8fafc;
|
|
567
|
-
}
|
|
568
|
-
.ark-wysiwyg[data-ark-theme="dark"] .ark-wysiwyg__toolbar {
|
|
569
|
-
border-color: #334155;
|
|
570
|
-
background: #1e293b;
|
|
571
|
-
}
|
|
572
|
-
.ark-wysiwyg__group {
|
|
573
|
-
display: flex;
|
|
574
|
-
align-items: center;
|
|
575
|
-
gap: 2px;
|
|
576
|
-
}
|
|
577
|
-
.ark-wysiwyg__item {
|
|
578
|
-
display: inline-flex;
|
|
579
|
-
position: relative;
|
|
580
|
-
}
|
|
581
|
-
.ark-wysiwyg__separator {
|
|
582
|
-
width: 1px;
|
|
583
|
-
align-self: stretch;
|
|
584
|
-
margin: 4px 2px;
|
|
585
|
-
background: #e2e8f0;
|
|
586
|
-
}
|
|
587
|
-
.ark-wysiwyg[data-ark-theme="dark"] .ark-wysiwyg__separator { background: #334155; }
|
|
588
|
-
|
|
589
|
-
.ark-wysiwyg__btn {
|
|
590
|
-
position: relative;
|
|
591
|
-
display: inline-flex;
|
|
592
|
-
align-items: center;
|
|
593
|
-
justify-content: center;
|
|
594
|
-
min-width: 32px;
|
|
595
|
-
height: 32px;
|
|
596
|
-
padding: 0 6px;
|
|
597
|
-
border: 1px solid transparent;
|
|
598
|
-
border-radius: 6px;
|
|
599
|
-
background: transparent;
|
|
600
|
-
color: inherit;
|
|
601
|
-
font-size: 14px;
|
|
602
|
-
font-weight: 600;
|
|
603
|
-
line-height: 1;
|
|
604
|
-
cursor: pointer;
|
|
605
|
-
transition: background 120ms ease, border-color 120ms ease;
|
|
606
|
-
}
|
|
607
|
-
.ark-wysiwyg__btn svg { width: 18px; height: 18px; }
|
|
608
|
-
.ark-wysiwyg__btn--text { padding: 0 10px; font-size: 13px; }
|
|
609
|
-
.ark-wysiwyg__btn:hover { background: rgba(100, 116, 139, 0.15); }
|
|
610
|
-
.ark-wysiwyg__btn:focus-visible { outline: 2px solid #6366f1; outline-offset: 1px; }
|
|
611
|
-
.ark-wysiwyg__btn[aria-pressed="true"] {
|
|
612
|
-
background: rgba(99, 102, 241, 0.16);
|
|
613
|
-
border-color: rgba(99, 102, 241, 0.5);
|
|
614
|
-
}
|
|
615
|
-
.ark-wysiwyg__btn:disabled {
|
|
616
|
-
opacity: 0.45;
|
|
617
|
-
cursor: not-allowed;
|
|
618
|
-
background: transparent;
|
|
619
|
-
}
|
|
620
|
-
/* Barra com a cor atual sob o icone de cor do texto e de marca-texto. */
|
|
621
|
-
.ark-wysiwyg__btn--swatch::after {
|
|
622
|
-
content: "";
|
|
623
|
-
position: absolute;
|
|
624
|
-
left: 7px;
|
|
625
|
-
right: 7px;
|
|
626
|
-
bottom: 4px;
|
|
627
|
-
height: 3px;
|
|
628
|
-
border-radius: 2px;
|
|
629
|
-
background: var(--ark-wysiwyg-swatch, transparent);
|
|
630
|
-
}
|
|
631
|
-
|
|
632
|
-
.ark-wysiwyg__select {
|
|
633
|
-
height: 32px;
|
|
634
|
-
padding: 0 8px;
|
|
635
|
-
border: 1px solid #cbd5e1;
|
|
636
|
-
border-radius: 6px;
|
|
637
|
-
background: #ffffff;
|
|
638
|
-
color: inherit;
|
|
639
|
-
font: inherit;
|
|
640
|
-
font-size: 13px;
|
|
641
|
-
cursor: pointer;
|
|
642
|
-
}
|
|
643
|
-
.ark-wysiwyg__select:focus-visible { outline: 2px solid #6366f1; outline-offset: 1px; }
|
|
644
|
-
.ark-wysiwyg__select:disabled { opacity: 0.45; cursor: not-allowed; }
|
|
645
|
-
.ark-wysiwyg[data-ark-theme="dark"] .ark-wysiwyg__select {
|
|
646
|
-
border-color: #475569;
|
|
647
|
-
background: #0f172a;
|
|
648
|
-
}
|
|
649
|
-
|
|
650
|
-
/* ---------- Popovers (paletas e link) ---------- */
|
|
651
|
-
/* Redefine o que o UA da a [popover]; left/top vem inline, calculados a partir do botao. */
|
|
652
|
-
.ark-wysiwyg__popover {
|
|
653
|
-
position: fixed;
|
|
654
|
-
inset: auto;
|
|
655
|
-
margin: 0;
|
|
656
|
-
padding: 8px;
|
|
657
|
-
border: 1px solid #e2e8f0;
|
|
658
|
-
border-radius: 8px;
|
|
659
|
-
background: #ffffff;
|
|
660
|
-
color: #0f172a;
|
|
661
|
-
box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
|
|
662
|
-
font-family: inherit;
|
|
663
|
-
}
|
|
664
|
-
.ark-wysiwyg[data-ark-theme="dark"] .ark-wysiwyg__popover {
|
|
665
|
-
border-color: #334155;
|
|
666
|
-
background: #1e293b;
|
|
667
|
-
color: #e2e8f0;
|
|
668
|
-
}
|
|
669
|
-
.ark-wysiwyg__swatches {
|
|
670
|
-
display: grid;
|
|
671
|
-
grid-template-columns: repeat(5, 24px);
|
|
672
|
-
gap: 6px;
|
|
673
|
-
}
|
|
674
|
-
.ark-wysiwyg__swatch {
|
|
675
|
-
width: 24px;
|
|
676
|
-
height: 24px;
|
|
677
|
-
padding: 0;
|
|
678
|
-
border: 1px solid rgba(15, 23, 42, 0.15);
|
|
679
|
-
border-radius: 6px;
|
|
680
|
-
cursor: pointer;
|
|
681
|
-
display: inline-flex;
|
|
682
|
-
align-items: center;
|
|
683
|
-
justify-content: center;
|
|
684
|
-
color: inherit;
|
|
685
|
-
background: transparent;
|
|
686
|
-
}
|
|
687
|
-
.ark-wysiwyg__swatch svg { width: 16px; height: 16px; }
|
|
688
|
-
.ark-wysiwyg__swatch:hover { transform: scale(1.1); }
|
|
689
|
-
.ark-wysiwyg__swatch:focus-visible { outline: 2px solid #6366f1; outline-offset: 1px; }
|
|
690
|
-
.ark-wysiwyg__link {
|
|
691
|
-
display: flex;
|
|
692
|
-
align-items: center;
|
|
693
|
-
gap: 6px;
|
|
694
|
-
}
|
|
695
|
-
.ark-wysiwyg__input {
|
|
696
|
-
width: 16rem;
|
|
697
|
-
max-width: 60vw;
|
|
698
|
-
height: 32px;
|
|
699
|
-
padding: 0 8px;
|
|
700
|
-
border: 1px solid #cbd5e1;
|
|
701
|
-
border-radius: 6px;
|
|
702
|
-
background: #ffffff;
|
|
703
|
-
color: inherit;
|
|
704
|
-
font: inherit;
|
|
705
|
-
font-size: 13px;
|
|
706
|
-
}
|
|
707
|
-
.ark-wysiwyg__input:focus-visible { outline: 2px solid #6366f1; outline-offset: 1px; }
|
|
708
|
-
.ark-wysiwyg__input[aria-invalid="true"] { border-color: #dc2626; }
|
|
709
|
-
.ark-wysiwyg[data-ark-theme="dark"] .ark-wysiwyg__input {
|
|
710
|
-
border-color: #475569;
|
|
711
|
-
background: #0f172a;
|
|
712
|
-
}
|
|
713
|
-
.ark-wysiwyg__error {
|
|
714
|
-
margin: 6px 0 0;
|
|
715
|
-
font-size: 12px;
|
|
716
|
-
color: #dc2626;
|
|
717
|
-
}
|
|
718
|
-
|
|
719
|
-
/* ---------- Conteudo ---------- */
|
|
720
|
-
.ark-wysiwyg__content {
|
|
721
|
-
border: 1px solid #e2e8f0;
|
|
722
|
-
border-radius: 8px;
|
|
723
|
-
background: #ffffff;
|
|
724
|
-
}
|
|
725
|
-
.ark-wysiwyg[data-ark-theme="dark"] .ark-wysiwyg__content {
|
|
726
|
-
border-color: #334155;
|
|
727
|
-
background: #0f172a;
|
|
728
|
-
}
|
|
729
|
-
.ark-wysiwyg--viewer .ark-wysiwyg__content {
|
|
730
|
-
border: none;
|
|
731
|
-
background: transparent;
|
|
732
|
-
}
|
|
733
|
-
|
|
734
|
-
.ark-wysiwyg .ProseMirror {
|
|
735
|
-
min-height: 120px;
|
|
736
|
-
padding: 12px 14px;
|
|
737
|
-
outline: none;
|
|
738
|
-
line-height: 1.6;
|
|
739
|
-
}
|
|
740
|
-
.ark-wysiwyg--viewer .ProseMirror { min-height: 0; padding: 0; }
|
|
741
|
-
.ark-wysiwyg .ProseMirror > * + * { margin-top: 0.6em; }
|
|
742
|
-
.ark-wysiwyg .ProseMirror h1 { font-size: 1.6em; font-weight: 700; }
|
|
743
|
-
.ark-wysiwyg .ProseMirror h2 { font-size: 1.35em; font-weight: 700; }
|
|
744
|
-
.ark-wysiwyg .ProseMirror h3 { font-size: 1.15em; font-weight: 700; }
|
|
745
|
-
.ark-wysiwyg .ProseMirror h4 { font-size: 1em; font-weight: 700; }
|
|
746
|
-
.ark-wysiwyg .ProseMirror ul,
|
|
747
|
-
.ark-wysiwyg .ProseMirror ol { padding-left: 1.4em; }
|
|
748
|
-
.ark-wysiwyg .ProseMirror ul { list-style: disc; }
|
|
749
|
-
.ark-wysiwyg .ProseMirror ol { list-style: decimal; }
|
|
750
|
-
.ark-wysiwyg .ProseMirror blockquote {
|
|
751
|
-
border-left: 3px solid #cbd5e1;
|
|
752
|
-
padding-left: 12px;
|
|
753
|
-
color: #475569;
|
|
754
|
-
}
|
|
755
|
-
.ark-wysiwyg[data-ark-theme="dark"] .ProseMirror blockquote {
|
|
756
|
-
border-left-color: #475569;
|
|
757
|
-
color: #94a3b8;
|
|
758
|
-
}
|
|
759
|
-
.ark-wysiwyg .ProseMirror code {
|
|
760
|
-
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
|
761
|
-
font-size: 0.9em;
|
|
762
|
-
background: rgba(100, 116, 139, 0.18);
|
|
763
|
-
padding: 0.1em 0.3em;
|
|
764
|
-
border-radius: 4px;
|
|
765
|
-
}
|
|
766
|
-
.ark-wysiwyg .ProseMirror hr {
|
|
767
|
-
border: none;
|
|
768
|
-
border-top: 1px solid #cbd5e1;
|
|
769
|
-
margin: 1em 0;
|
|
770
|
-
}
|
|
771
|
-
.ark-wysiwyg[data-ark-theme="dark"] .ProseMirror hr { border-top-color: #475569; }
|
|
772
|
-
.ark-wysiwyg .ProseMirror a {
|
|
773
|
-
color: #2563eb;
|
|
774
|
-
text-decoration: underline;
|
|
775
|
-
text-underline-offset: 2px;
|
|
776
|
-
}
|
|
777
|
-
.ark-wysiwyg[data-ark-theme="dark"] .ProseMirror a { color: #93c5fd; }
|
|
778
|
-
/* Marca-texto: fundo pastel com texto escuro nos dois temas, para ler sempre. */
|
|
779
|
-
.ark-wysiwyg .ProseMirror mark {
|
|
780
|
-
color: #0f172a;
|
|
781
|
-
border-radius: 2px;
|
|
782
|
-
padding: 0 0.1em;
|
|
783
|
-
}
|
|
784
|
-
.ark-wysiwyg .ProseMirror img,
|
|
785
|
-
.ark-wysiwyg .ProseMirror video {
|
|
786
|
-
display: block;
|
|
787
|
-
max-width: 100%;
|
|
788
|
-
height: auto;
|
|
789
|
-
border-radius: 6px;
|
|
790
|
-
}
|
|
791
|
-
.ark-wysiwyg .ProseMirror img.ProseMirror-selectednode,
|
|
792
|
-
.ark-wysiwyg .ProseMirror video.ProseMirror-selectednode {
|
|
793
|
-
outline: 2px solid #6366f1;
|
|
794
|
-
outline-offset: 2px;
|
|
795
|
-
}
|
|
796
|
-
.ark-wysiwyg[aria-busy="true"] .ark-wysiwyg__content { cursor: progress; }
|
|
797
|
-
|
|
798
|
-
/* Placeholder (extension-placeholder) */
|
|
799
|
-
.ark-wysiwyg .ProseMirror p.is-editor-empty:first-child::before {
|
|
800
|
-
content: attr(data-placeholder);
|
|
801
|
-
float: left;
|
|
802
|
-
height: 0;
|
|
803
|
-
pointer-events: none;
|
|
804
|
-
color: #94a3b8;
|
|
805
|
-
}
|
|
806
|
-
`;
|
|
807
|
-
/** Injeta o CSS base no <head> uma única vez. */
|
|
808
|
-
function ensureWysiwygStyles() {
|
|
809
|
-
if (typeof document === "undefined")
|
|
810
|
-
return;
|
|
811
|
-
if (document.getElementById(WYSIWYG_STYLE_ID))
|
|
812
|
-
return;
|
|
813
|
-
const style = document.createElement("style");
|
|
814
|
-
style.id = WYSIWYG_STYLE_ID;
|
|
815
|
-
style.textContent = wysiwygCss;
|
|
816
|
-
document.head.appendChild(style);
|
|
817
|
-
}
|
|
818
|
-
|
|
819
|
-
/** Itens de cada grupo, na ordem em que aparecem. */
|
|
820
|
-
const ARK_WYSIWYG_TOOLBAR_GROUPS = {
|
|
821
|
-
style: ["heading"],
|
|
822
|
-
marks: ["bold", "italic", "underline", "strike", "code"],
|
|
823
|
-
color: ["text-color", "highlight"],
|
|
824
|
-
align: ["align-left", "align-center", "align-right", "align-justify"],
|
|
825
|
-
lists: ["bullet-list", "ordered-list", "outdent", "indent"],
|
|
826
|
-
link: ["link"],
|
|
827
|
-
media: ["image", "video"],
|
|
828
|
-
blocks: ["blockquote", "horizontal-rule"],
|
|
829
|
-
clear: ["clear-format"],
|
|
830
|
-
history: ["undo", "redo"]
|
|
831
|
-
};
|
|
832
|
-
/** Grupos exibidos sem o atributo `toolbar`; cor, alinhamento e mídia são opt-in. */
|
|
833
|
-
const ARK_WYSIWYG_DEFAULT_TOOLBAR = [
|
|
834
|
-
"style",
|
|
835
|
-
"marks",
|
|
836
|
-
"lists",
|
|
837
|
-
"link",
|
|
838
|
-
"blocks",
|
|
839
|
-
"clear",
|
|
840
|
-
"history"
|
|
841
|
-
];
|
|
842
|
-
|
|
843
|
-
// Base dos Custom Elements que também carrega fora do navegador. No SSR (Node, Angular SSR, Next, Nuxt) não existe
|
|
844
|
-
// HTMLElement, e um `extends HTMLElement` no topo do módulo derrubaria o import de quem só renderiza o HTML; lá a
|
|
845
|
-
// base é uma classe vazia, e os elementos só passam a existir no cliente, quando registerTooark*() os define.
|
|
846
|
-
/** `HTMLElement` no navegador; fora dele, uma classe vazia para o módulo poder ser importado no servidor. */
|
|
847
|
-
const HTMLElementBase = typeof HTMLElement === "undefined" ? class {
|
|
848
|
-
} : HTMLElement;
|
|
849
|
-
|
|
850
|
-
// Mesmos hooks de E2E de @tooark/web-components (este pacote não depende dele): `data-ark` estático em cada parte e,
|
|
851
|
-
// com `testid` no host, `data-testid` na parte principal e sufixado nas demais.
|
|
852
|
-
/** Marca `el` com `data-ark="<componente>[-parte]"` e, com `testid` no host, `data-testid="<testid>[-parte]"`. */
|
|
853
|
-
function applyTestHooks(host, component, el, part) {
|
|
854
|
-
const suffix = part ? `-${part}` : "";
|
|
855
|
-
el.setAttribute("data-ark", `${component}${suffix}`);
|
|
856
|
-
const testid = host.getAttribute("testid");
|
|
857
|
-
if (testid) {
|
|
858
|
-
el.setAttribute("data-testid", `${testid}${suffix}`);
|
|
859
|
-
}
|
|
860
|
-
else {
|
|
861
|
-
el.removeAttribute("data-testid");
|
|
862
|
-
}
|
|
863
|
-
}
|
|
864
|
-
|
|
865
|
-
// Um framework (ou o app) pode gravar uma propriedade no elemento antes de registerTooark*() defini-lo: sem a classe,
|
|
866
|
-
// `el.rows = x` vira uma propriedade própria do nó, que depois do upgrade esconde o setter da classe e o valor nunca
|
|
867
|
-
// chega ao componente. Ao conectar, toda propriedade própria que tem setter na classe é retirada e regravada por ele,
|
|
868
|
-
// na ordem em que foi gravada. Os campos da própria classe e o que os frameworks penduram no nó (chaves internas do
|
|
869
|
-
// React e do Vue) não têm setter e ficam como estão.
|
|
870
|
-
/** Reaplica pelo setter da classe as propriedades gravadas no nó antes de o elemento ser registrado. */
|
|
871
|
-
function upgradeProperties(element) {
|
|
872
|
-
const target = element;
|
|
873
|
-
for (const name of Object.keys(element)) {
|
|
874
|
-
if (!hasSetter(Object.getPrototypeOf(element), name))
|
|
875
|
-
continue;
|
|
876
|
-
const value = target[name];
|
|
877
|
-
delete target[name];
|
|
878
|
-
target[name] = value;
|
|
879
|
-
}
|
|
880
|
-
}
|
|
881
|
-
// Procura o acessor na cadeia de protótipos até o HTMLElement: as propriedades nativas nunca viram propriedade própria,
|
|
882
|
-
// porque o nó já é um HTMLElement antes do registro.
|
|
883
|
-
function hasSetter(prototype, name) {
|
|
884
|
-
for (let proto = prototype; proto && proto !== HTMLElement.prototype; proto = Object.getPrototypeOf(proto)) {
|
|
885
|
-
const descriptor = Object.getOwnPropertyDescriptor(proto, name);
|
|
886
|
-
if (descriptor)
|
|
887
|
-
return typeof descriptor.set === "function";
|
|
888
|
-
}
|
|
889
|
-
return false;
|
|
890
|
-
}
|
|
891
|
-
|
|
892
|
-
const headingAction = (level) => ({
|
|
893
|
-
icon: "bold",
|
|
894
|
-
label: "heading",
|
|
895
|
-
run: (e) => e.chain().focus().toggleHeading({ level }).run(),
|
|
896
|
-
active: (e) => e.isActive("heading", { level })
|
|
897
|
-
});
|
|
898
|
-
// Botões simples: um comando, um estado. Os itens com popover, select ou arquivo têm construção própria.
|
|
899
|
-
const ACTIONS = {
|
|
900
|
-
"heading-1": headingAction(1),
|
|
901
|
-
"heading-2": headingAction(2),
|
|
902
|
-
"heading-3": headingAction(3),
|
|
903
|
-
"heading-4": headingAction(4),
|
|
904
|
-
bold: {
|
|
905
|
-
icon: "bold",
|
|
906
|
-
label: "bold",
|
|
907
|
-
run: (e) => e.chain().focus().toggleBold().run(),
|
|
908
|
-
active: (e) => e.isActive("bold")
|
|
909
|
-
},
|
|
910
|
-
italic: {
|
|
911
|
-
icon: "italic",
|
|
912
|
-
label: "italic",
|
|
913
|
-
run: (e) => e.chain().focus().toggleItalic().run(),
|
|
914
|
-
active: (e) => e.isActive("italic")
|
|
915
|
-
},
|
|
916
|
-
underline: {
|
|
917
|
-
icon: "underline",
|
|
918
|
-
label: "underline",
|
|
919
|
-
run: (e) => e.chain().focus().toggleUnderline().run(),
|
|
920
|
-
active: (e) => e.isActive("underline")
|
|
921
|
-
},
|
|
922
|
-
strike: {
|
|
923
|
-
icon: "strike",
|
|
924
|
-
label: "strike",
|
|
925
|
-
run: (e) => e.chain().focus().toggleStrike().run(),
|
|
926
|
-
active: (e) => e.isActive("strike")
|
|
927
|
-
},
|
|
928
|
-
code: {
|
|
929
|
-
icon: "code",
|
|
930
|
-
label: "code",
|
|
931
|
-
run: (e) => e.chain().focus().toggleCode().run(),
|
|
932
|
-
active: (e) => e.isActive("code")
|
|
933
|
-
},
|
|
934
|
-
"align-left": {
|
|
935
|
-
icon: "alignLeft",
|
|
936
|
-
label: "alignLeft",
|
|
937
|
-
run: (e) => e.chain().focus().setTextAlign("left").run(),
|
|
938
|
-
active: (e) => e.isActive({ textAlign: "left" })
|
|
939
|
-
},
|
|
940
|
-
"align-center": {
|
|
941
|
-
icon: "alignCenter",
|
|
942
|
-
label: "alignCenter",
|
|
943
|
-
run: (e) => e.chain().focus().setTextAlign("center").run(),
|
|
944
|
-
active: (e) => e.isActive({ textAlign: "center" })
|
|
945
|
-
},
|
|
946
|
-
"align-right": {
|
|
947
|
-
icon: "alignRight",
|
|
948
|
-
label: "alignRight",
|
|
949
|
-
run: (e) => e.chain().focus().setTextAlign("right").run(),
|
|
950
|
-
active: (e) => e.isActive({ textAlign: "right" })
|
|
951
|
-
},
|
|
952
|
-
"align-justify": {
|
|
953
|
-
icon: "alignJustify",
|
|
954
|
-
label: "alignJustify",
|
|
955
|
-
run: (e) => e.chain().focus().setTextAlign("justify").run(),
|
|
956
|
-
active: (e) => e.isActive({ textAlign: "justify" })
|
|
957
|
-
},
|
|
958
|
-
"bullet-list": {
|
|
959
|
-
icon: "bulletList",
|
|
960
|
-
label: "bulletList",
|
|
961
|
-
run: (e) => e.chain().focus().toggleBulletList().run(),
|
|
962
|
-
active: (e) => e.isActive("bulletList")
|
|
963
|
-
},
|
|
964
|
-
"ordered-list": {
|
|
965
|
-
icon: "orderedList",
|
|
966
|
-
label: "orderedList",
|
|
967
|
-
run: (e) => e.chain().focus().toggleOrderedList().run(),
|
|
968
|
-
active: (e) => e.isActive("orderedList")
|
|
969
|
-
},
|
|
970
|
-
// Recuo só em listas (aninhar/desaninhar itens): recuo de parágrafo não tem semântica no documento.
|
|
971
|
-
outdent: {
|
|
972
|
-
icon: "outdent",
|
|
973
|
-
label: "outdent",
|
|
974
|
-
run: (e) => e.chain().focus().liftListItem("listItem").run(),
|
|
975
|
-
can: (e) => e.can().liftListItem("listItem")
|
|
976
|
-
},
|
|
977
|
-
indent: {
|
|
978
|
-
icon: "indent",
|
|
979
|
-
label: "indent",
|
|
980
|
-
run: (e) => e.chain().focus().sinkListItem("listItem").run(),
|
|
981
|
-
can: (e) => e.can().sinkListItem("listItem")
|
|
982
|
-
},
|
|
983
|
-
blockquote: {
|
|
984
|
-
icon: "blockquote",
|
|
985
|
-
label: "blockquote",
|
|
986
|
-
run: (e) => e.chain().focus().toggleBlockquote().run(),
|
|
987
|
-
active: (e) => e.isActive("blockquote")
|
|
988
|
-
},
|
|
989
|
-
"horizontal-rule": {
|
|
990
|
-
icon: "horizontalRule",
|
|
991
|
-
label: "horizontalRule",
|
|
992
|
-
run: (e) => e.chain().focus().setHorizontalRule().run()
|
|
993
|
-
},
|
|
994
|
-
"clear-format": {
|
|
995
|
-
icon: "clearFormat",
|
|
996
|
-
label: "clearFormat",
|
|
997
|
-
run: (e) => e.chain().focus().unsetAllMarks().clearNodes().run()
|
|
998
|
-
},
|
|
999
|
-
undo: { icon: "undo", label: "undo", run: (e) => e.chain().focus().undo().run(), can: (e) => e.can().undo() },
|
|
1000
|
-
redo: { icon: "redo", label: "redo", run: (e) => e.chain().focus().redo().run(), can: (e) => e.can().redo() }
|
|
1001
|
-
};
|
|
1002
|
-
const ALL_ITEMS = new Set(Object.values(ARK_WYSIWYG_TOOLBAR_GROUPS).flat());
|
|
1003
|
-
function groupOf(item) {
|
|
1004
|
-
if (item.startsWith("heading"))
|
|
1005
|
-
return "style";
|
|
1006
|
-
for (const [group, items] of Object.entries(ARK_WYSIWYG_TOOLBAR_GROUPS)) {
|
|
1007
|
-
if (items.includes(item))
|
|
1008
|
-
return group;
|
|
1009
|
-
}
|
|
1010
|
-
return "marks";
|
|
1011
|
-
}
|
|
1012
|
-
/** Cores oferecidas por padrão: tons médios, legíveis nos dois temas. */
|
|
1013
|
-
const DEFAULT_COLORS = [
|
|
1014
|
-
"#ef4444",
|
|
1015
|
-
"#f97316",
|
|
1016
|
-
"#eab308",
|
|
1017
|
-
"#22c55e",
|
|
1018
|
-
"#06b6d4",
|
|
1019
|
-
"#3b82f6",
|
|
1020
|
-
"#8b5cf6",
|
|
1021
|
-
"#ec4899",
|
|
1022
|
-
"#64748b"
|
|
1023
|
-
];
|
|
1024
|
-
/** Marca-texto por padrão: pastéis; o CSS força texto escuro dentro de `mark` para ler nos dois temas. */
|
|
1025
|
-
const DEFAULT_HIGHLIGHTS = ["#fde047", "#fdba74", "#86efac", "#7dd3fc", "#c4b5fd", "#f9a8d4"];
|
|
1026
|
-
let popoverSeq = 0;
|
|
1027
|
-
/**
|
|
1028
|
-
* Editor WYSIWYG (Custom Element) baseado em Tiptap.
|
|
1029
|
-
*
|
|
1030
|
-
* O conteúdo é trocado pela propriedade `content` (JSON do Tiptap, sanitizado
|
|
1031
|
-
* ao entrar), não por atributo. Dispara `ark-wysiwyg-change` (bubbles/composed)
|
|
1032
|
-
* com `detail` = JSON a cada edição do usuário.
|
|
1033
|
-
*
|
|
1034
|
-
* Atributos: `theme`, `placeholder`, `editable` ("false" desabilita), `lang` e
|
|
1035
|
-
* `locale-json` (rótulos), `toolbar` (grupos e/ou itens separados por vírgula,
|
|
1036
|
-
* `all`, ou "none"/"false" para ocultar; padrão: style, marks, lists, link,
|
|
1037
|
-
* blocks, clear, history), `colors` e `highlights` (JSON com a paleta),
|
|
1038
|
-
* `max-file-size` (bytes), `aria-label` (vai para o conteúdo editável, o
|
|
1039
|
-
* `role="textbox"`) e `testid` (`data-ark="wysiwyg-editor"` na raiz, com as
|
|
1040
|
-
* partes `-toolbar` e `-content`). Propriedade `uploadFile`: sem ela, imagem
|
|
1041
|
-
* e vídeo não aparecem na toolbar e arquivos colados ou arrastados são
|
|
1042
|
-
* recusados (`ark-wysiwyg-upload-error`), nunca embutidos em base64.
|
|
1043
|
-
*/
|
|
1044
|
-
class ArkWysiwygEditor extends HTMLElementBase {
|
|
1045
|
-
constructor() {
|
|
1046
|
-
super(...arguments);
|
|
1047
|
-
this.instance = null;
|
|
1048
|
-
this.root = null;
|
|
1049
|
-
this.toolbarEl = null;
|
|
1050
|
-
this.pendingContent = null;
|
|
1051
|
-
this.uploader = null;
|
|
1052
|
-
this.labels = resolveWysiwygLabels("en");
|
|
1053
|
-
/** Controles da toolbar na ordem visual, para o tabindex circulante. */
|
|
1054
|
-
this.controls = [];
|
|
1055
|
-
/** Sincronizadores por controle (estado ativo, habilitado, cor atual), rodados a cada mudança de seleção. */
|
|
1056
|
-
this.syncers = [];
|
|
1057
|
-
/** Para de observar o tema da página; só existe com `theme="auto"`. */
|
|
1058
|
-
this.disposeTheme = null;
|
|
1059
|
-
/** Para de seguir `setArkLocale()`; existe enquanto conectado. */
|
|
1060
|
-
this.disposeLocale = null;
|
|
1061
|
-
// Um tab stop por toolbar: setas movem entre os controles habilitados, Home/End vão às pontas.
|
|
1062
|
-
this.handleToolbarKeydown = (event) => {
|
|
1063
|
-
if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key))
|
|
1064
|
-
return;
|
|
1065
|
-
const target = event.target;
|
|
1066
|
-
const enabled = this.controls.filter((control) => !control.disabled);
|
|
1067
|
-
const index = enabled.indexOf(target);
|
|
1068
|
-
if (index < 0)
|
|
1069
|
-
return;
|
|
1070
|
-
event.preventDefault();
|
|
1071
|
-
let next = index;
|
|
1072
|
-
if (event.key === "ArrowLeft")
|
|
1073
|
-
next = (index - 1 + enabled.length) % enabled.length;
|
|
1074
|
-
if (event.key === "ArrowRight")
|
|
1075
|
-
next = (index + 1) % enabled.length;
|
|
1076
|
-
if (event.key === "Home")
|
|
1077
|
-
next = 0;
|
|
1078
|
-
if (event.key === "End")
|
|
1079
|
-
next = enabled.length - 1;
|
|
1080
|
-
this.setCurrent(enabled[next]);
|
|
1081
|
-
enabled[next].focus();
|
|
1082
|
-
};
|
|
1083
|
-
this.handleToolbarFocus = (event) => {
|
|
1084
|
-
const target = event.target;
|
|
1085
|
-
if (this.controls.includes(target))
|
|
1086
|
-
this.setCurrent(target);
|
|
1087
|
-
};
|
|
1088
|
-
this.syncToolbar = () => {
|
|
1089
|
-
if (!this.instance)
|
|
1090
|
-
return;
|
|
1091
|
-
for (const sync of this.syncers)
|
|
1092
|
-
sync();
|
|
1093
|
-
// O controle corrente do tabindex não pode ser um desabilitado, senão a toolbar some da ordem do Tab.
|
|
1094
|
-
const current = this.controls.find((control) => control.tabIndex === 0);
|
|
1095
|
-
if (current && current.disabled) {
|
|
1096
|
-
const first = this.controls.find((control) => !control.disabled);
|
|
1097
|
-
if (first)
|
|
1098
|
-
this.setCurrent(first);
|
|
1099
|
-
}
|
|
1100
|
-
};
|
|
1101
|
-
}
|
|
1102
|
-
static get observedAttributes() {
|
|
1103
|
-
return [
|
|
1104
|
-
"theme",
|
|
1105
|
-
"placeholder",
|
|
1106
|
-
"editable",
|
|
1107
|
-
"toolbar",
|
|
1108
|
-
"lang",
|
|
1109
|
-
"locale-json",
|
|
1110
|
-
"colors",
|
|
1111
|
-
"highlights",
|
|
1112
|
-
"max-file-size",
|
|
1113
|
-
"aria-label",
|
|
1114
|
-
"testid"
|
|
1115
|
-
];
|
|
1116
|
-
}
|
|
1117
|
-
/** Conteúdo do editor como JSON do Tiptap. Atribuir substitui (sanitizado) sem disparar `ark-wysiwyg-change`. */
|
|
1118
|
-
get content() {
|
|
1119
|
-
return this.instance ? this.instance.getJSON() : this.pendingContent;
|
|
1120
|
-
}
|
|
1121
|
-
set content(value) {
|
|
1122
|
-
this.pendingContent = value;
|
|
1123
|
-
this.instance?.setContent(value);
|
|
1124
|
-
}
|
|
1125
|
-
/** Gancho de upload de imagem/vídeo (propriedade JS). Sem ele o grupo `media` não aparece e arquivos são recusados. */
|
|
1126
|
-
get uploadFile() {
|
|
1127
|
-
return this.uploader;
|
|
1128
|
-
}
|
|
1129
|
-
set uploadFile(value) {
|
|
1130
|
-
this.uploader = typeof value === "function" ? value : null;
|
|
1131
|
-
if (this.instance)
|
|
1132
|
-
this.build();
|
|
1133
|
-
}
|
|
1134
|
-
/** Paleta da cor do texto (atributo `colors` em JSON ou propriedade). */
|
|
1135
|
-
get colors() {
|
|
1136
|
-
return this.readPalette("colors", DEFAULT_COLORS);
|
|
1137
|
-
}
|
|
1138
|
-
set colors(value) {
|
|
1139
|
-
this.writePalette("colors", value);
|
|
1140
|
-
}
|
|
1141
|
-
/** Paleta do marca-texto (atributo `highlights` em JSON ou propriedade). */
|
|
1142
|
-
get highlights() {
|
|
1143
|
-
return this.readPalette("highlights", DEFAULT_HIGHLIGHTS);
|
|
1144
|
-
}
|
|
1145
|
-
set highlights(value) {
|
|
1146
|
-
this.writePalette("highlights", value);
|
|
1147
|
-
}
|
|
1148
|
-
/** Tema efetivamente aplicado (depois de resolver `auto`); `null` antes de renderizar. */
|
|
1149
|
-
get resolvedTheme() {
|
|
1150
|
-
return this.instance?.resolvedTheme() ?? null;
|
|
1151
|
-
}
|
|
1152
|
-
/** Instância nativa do Tiptap (uso avançado); `null` antes de renderizar. */
|
|
1153
|
-
get editor() {
|
|
1154
|
-
return this.instance?.editor ?? null;
|
|
1155
|
-
}
|
|
1156
|
-
connectedCallback() {
|
|
1157
|
-
// Gravadas antes do registro: o setter guarda e só a montagem abaixo constrói.
|
|
1158
|
-
upgradeProperties(this);
|
|
1159
|
-
ensureWysiwygStyles();
|
|
1160
|
-
// Sem `lang` próprio os rótulos seguem setArkLocale(): a troca reconstrói, como a do atributo (o texto fica).
|
|
1161
|
-
this.disposeLocale ?? (this.disposeLocale = observeArkLocale(() => {
|
|
1162
|
-
if (!this.hasAttribute("lang") && this.instance)
|
|
1163
|
-
this.build();
|
|
1164
|
-
}));
|
|
1165
|
-
this.build();
|
|
1166
|
-
}
|
|
1167
|
-
disconnectedCallback() {
|
|
1168
|
-
this.disposeLocale?.();
|
|
1169
|
-
this.disposeLocale = null;
|
|
1170
|
-
this.teardown();
|
|
1171
|
-
}
|
|
1172
|
-
attributeChangedCallback(name, oldValue, newValue) {
|
|
1173
|
-
if (oldValue === newValue || !this.instance)
|
|
1174
|
-
return;
|
|
1175
|
-
if (name === "theme") {
|
|
1176
|
-
this.applyTheme(this.getTheme());
|
|
1177
|
-
this.syncThemeObserver();
|
|
1178
|
-
return;
|
|
1179
|
-
}
|
|
1180
|
-
if (name === "editable") {
|
|
1181
|
-
this.instance.setEditable(this.isEditable());
|
|
1182
|
-
this.syncToolbar();
|
|
1183
|
-
return;
|
|
1184
|
-
}
|
|
1185
|
-
if (name === "testid") {
|
|
1186
|
-
this.applyHooks();
|
|
1187
|
-
return;
|
|
1188
|
-
}
|
|
1189
|
-
// placeholder, toolbar, rótulos, paletas e limite exigem reconstrução.
|
|
1190
|
-
this.build();
|
|
1191
|
-
}
|
|
1192
|
-
/** Envia um arquivo pelo gancho e insere a mídia na seleção; `false` se recusado (o evento diz por quê). */
|
|
1193
|
-
insertFile(file) {
|
|
1194
|
-
return this.instance ? this.instance.insertFile(file) : Promise.resolve(false);
|
|
1195
|
-
}
|
|
1196
|
-
/**
|
|
1197
|
-
* Rótulos da toolbar: o `lang` próprio com o `locale-json`; sem `lang`, o padrão de `setArkLocale()` (do
|
|
1198
|
-
* `@tooark/tokens`, que o core reexporta), com as strings dele por baixo do `locale-json` do elemento.
|
|
1199
|
-
*/
|
|
1200
|
-
resolveLabels() {
|
|
1201
|
-
const lang = this.getAttribute("lang");
|
|
1202
|
-
const json = this.getAttribute("locale-json");
|
|
1203
|
-
if (lang)
|
|
1204
|
-
return resolveWysiwygLabels(lang, json);
|
|
1205
|
-
const fallback = getArkLocale();
|
|
1206
|
-
let own = {};
|
|
1207
|
-
if (json?.trim()) {
|
|
1208
|
-
try {
|
|
1209
|
-
const parsed = JSON.parse(json);
|
|
1210
|
-
if (parsed && typeof parsed === "object")
|
|
1211
|
-
own = parsed;
|
|
1212
|
-
}
|
|
1213
|
-
catch {
|
|
1214
|
-
// JSON inválido é ignorado, como em resolveWysiwygLabels.
|
|
1215
|
-
}
|
|
1216
|
-
}
|
|
1217
|
-
return resolveWysiwygLabels(fallback.lang, { ...fallback.localeJson, ...own });
|
|
1218
|
-
}
|
|
1219
|
-
getTheme() {
|
|
1220
|
-
const value = (this.getAttribute("theme") || "auto").toLowerCase();
|
|
1221
|
-
if (value === "light" || value === "dark")
|
|
1222
|
-
return value;
|
|
1223
|
-
return "auto";
|
|
1224
|
-
}
|
|
1225
|
-
isEditable() {
|
|
1226
|
-
return this.getAttribute("editable") !== "false";
|
|
1227
|
-
}
|
|
1228
|
-
readPalette(name, fallback) {
|
|
1229
|
-
const raw = this.getAttribute(name);
|
|
1230
|
-
if (raw === null)
|
|
1231
|
-
return [...fallback];
|
|
1232
|
-
try {
|
|
1233
|
-
const parsed = JSON.parse(raw);
|
|
1234
|
-
return Array.isArray(parsed) ? parsed.filter(isSafeColor) : [...fallback];
|
|
1235
|
-
}
|
|
1236
|
-
catch {
|
|
1237
|
-
return [...fallback];
|
|
1238
|
-
}
|
|
1239
|
-
}
|
|
1240
|
-
writePalette(name, value) {
|
|
1241
|
-
// Uma string é o JSON do atributo (React 19 e Vue gravam a prop como propriedade): vai como está, e a leitura
|
|
1242
|
-
// filtra as cores inválidas.
|
|
1243
|
-
if (typeof value === "string") {
|
|
1244
|
-
this.setAttribute(name, value);
|
|
1245
|
-
}
|
|
1246
|
-
else if (Array.isArray(value)) {
|
|
1247
|
-
this.setAttribute(name, JSON.stringify(value.filter(isSafeColor)));
|
|
1248
|
-
}
|
|
1249
|
-
else {
|
|
1250
|
-
this.removeAttribute(name);
|
|
1251
|
-
}
|
|
1252
|
-
}
|
|
1253
|
-
getMaxFileSize() {
|
|
1254
|
-
const raw = Number(this.getAttribute("max-file-size"));
|
|
1255
|
-
return this.hasAttribute("max-file-size") && Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_MAX_FILE_SIZE;
|
|
1256
|
-
}
|
|
1257
|
-
// Grupos e itens viram segmentos (um por grupo, na ordem pedida); `media` só entra com o gancho de upload.
|
|
1258
|
-
getToolbar() {
|
|
1259
|
-
const raw = this.getAttribute("toolbar");
|
|
1260
|
-
let tokens;
|
|
1261
|
-
if (raw === null) {
|
|
1262
|
-
tokens = [...ARK_WYSIWYG_DEFAULT_TOOLBAR];
|
|
1263
|
-
}
|
|
1264
|
-
else if (raw === "none" || raw === "false" || raw.trim() === "") {
|
|
1265
|
-
return false;
|
|
1266
|
-
}
|
|
1267
|
-
else if (raw.trim() === "all") {
|
|
1268
|
-
tokens = Object.keys(ARK_WYSIWYG_TOOLBAR_GROUPS);
|
|
1269
|
-
}
|
|
1270
|
-
else {
|
|
1271
|
-
tokens = raw.split(",").map((token) => token.trim());
|
|
1272
|
-
}
|
|
1273
|
-
const segments = [];
|
|
1274
|
-
const push = (group, items) => {
|
|
1275
|
-
const last = segments[segments.length - 1];
|
|
1276
|
-
if (last && last.group === group) {
|
|
1277
|
-
last.items.push(...items);
|
|
1278
|
-
}
|
|
1279
|
-
else {
|
|
1280
|
-
segments.push({ group, items: [...items] });
|
|
1281
|
-
}
|
|
1282
|
-
};
|
|
1283
|
-
for (const token of tokens) {
|
|
1284
|
-
if (token in ARK_WYSIWYG_TOOLBAR_GROUPS) {
|
|
1285
|
-
const group = token;
|
|
1286
|
-
push(group, ARK_WYSIWYG_TOOLBAR_GROUPS[group]);
|
|
1287
|
-
}
|
|
1288
|
-
else if (ALL_ITEMS.has(token) || token in ACTIONS) {
|
|
1289
|
-
const item = token;
|
|
1290
|
-
push(groupOf(item), [item]);
|
|
1291
|
-
}
|
|
1292
|
-
}
|
|
1293
|
-
const result = segments
|
|
1294
|
-
.map((segment) => ({
|
|
1295
|
-
group: segment.group,
|
|
1296
|
-
items: segment.items.filter((item) => (item === "image" || item === "video" ? this.uploader !== null : true))
|
|
1297
|
-
}))
|
|
1298
|
-
.filter((segment) => segment.items.length > 0);
|
|
1299
|
-
return result.length > 0 ? result : false;
|
|
1300
|
-
}
|
|
1301
|
-
build() {
|
|
1302
|
-
this.teardown();
|
|
1303
|
-
this.labels = this.resolveLabels();
|
|
1304
|
-
const root = document.createElement("div");
|
|
1305
|
-
root.className = "ark-wysiwyg";
|
|
1306
|
-
const segments = this.getToolbar();
|
|
1307
|
-
if (segments) {
|
|
1308
|
-
this.toolbarEl = this.buildToolbar(segments);
|
|
1309
|
-
root.appendChild(this.toolbarEl);
|
|
1310
|
-
}
|
|
1311
|
-
const mount = document.createElement("div");
|
|
1312
|
-
mount.className = "ark-wysiwyg__content";
|
|
1313
|
-
root.appendChild(mount);
|
|
1314
|
-
this.appendChild(root);
|
|
1315
|
-
this.root = root;
|
|
1316
|
-
this.instance = createWysiwygEditor(mount, {
|
|
1317
|
-
content: this.pendingContent,
|
|
1318
|
-
theme: this.getTheme(),
|
|
1319
|
-
placeholder: this.getAttribute("placeholder") || undefined,
|
|
1320
|
-
label: this.getAttribute("aria-label") || undefined,
|
|
1321
|
-
editable: this.isEditable(),
|
|
1322
|
-
uploadFile: this.uploader ?? undefined,
|
|
1323
|
-
maxFileSize: this.getMaxFileSize(),
|
|
1324
|
-
onChange: (content) => {
|
|
1325
|
-
this.dispatchEvent(new CustomEvent("ark-wysiwyg-change", {
|
|
1326
|
-
detail: content,
|
|
1327
|
-
bubbles: true,
|
|
1328
|
-
composed: true
|
|
1329
|
-
}));
|
|
1330
|
-
this.syncToolbar();
|
|
1331
|
-
},
|
|
1332
|
-
onUploadError: (error) => {
|
|
1333
|
-
this.dispatchEvent(new CustomEvent("ark-wysiwyg-upload-error", { detail: error, bubbles: true, composed: true }));
|
|
1334
|
-
},
|
|
1335
|
-
onUploadingChange: (count) => {
|
|
1336
|
-
this.root?.toggleAttribute("aria-busy", count > 0);
|
|
1337
|
-
this.root?.setAttribute("data-uploading", String(count));
|
|
1338
|
-
this.syncToolbar();
|
|
1339
|
-
}
|
|
1340
|
-
});
|
|
1341
|
-
this.instance.editor.on("selectionUpdate", this.syncToolbar);
|
|
1342
|
-
this.instance.editor.on("transaction", this.syncToolbar);
|
|
1343
|
-
this.syncToolbar();
|
|
1344
|
-
this.root.setAttribute("data-ark-theme", this.instance.resolvedTheme());
|
|
1345
|
-
this.applyHooks();
|
|
1346
|
-
this.syncThemeObserver();
|
|
1347
|
-
}
|
|
1348
|
-
// Raiz, toolbar e conteúdo editável levam os hooks de E2E, como os componentes de @tooark/web-components.
|
|
1349
|
-
applyHooks() {
|
|
1350
|
-
if (!this.root || !this.instance)
|
|
1351
|
-
return;
|
|
1352
|
-
applyTestHooks(this, "wysiwyg-editor", this.root);
|
|
1353
|
-
if (this.toolbarEl)
|
|
1354
|
-
applyTestHooks(this, "wysiwyg-editor", this.toolbarEl, "toolbar");
|
|
1355
|
-
applyTestHooks(this, "wysiwyg-editor", this.instance.editor.view.dom, "content");
|
|
1356
|
-
}
|
|
1357
|
-
// Em `auto`, a troca de tema da página re-resolve o tema do editor; com tema fixo não há o que observar.
|
|
1358
|
-
syncThemeObserver() {
|
|
1359
|
-
this.disposeTheme?.();
|
|
1360
|
-
this.disposeTheme = null;
|
|
1361
|
-
if (this.getTheme() !== "auto")
|
|
1362
|
-
return;
|
|
1363
|
-
this.disposeTheme = observeColorScheme(this, () => this.applyTheme("auto"));
|
|
1364
|
-
}
|
|
1365
|
-
// O engine marca o mount com data-ark-theme; o CSS do tema lê a raiz .ark-wysiwyg, então ela recebe o mesmo.
|
|
1366
|
-
applyTheme(theme) {
|
|
1367
|
-
if (!this.instance)
|
|
1368
|
-
return;
|
|
1369
|
-
this.instance.setTheme(theme);
|
|
1370
|
-
this.root?.setAttribute("data-ark-theme", this.instance.resolvedTheme());
|
|
1371
|
-
}
|
|
1372
|
-
// --- Toolbar ---
|
|
1373
|
-
buildToolbar(segments) {
|
|
1374
|
-
const toolbar = document.createElement("div");
|
|
1375
|
-
toolbar.className = "ark-wysiwyg__toolbar";
|
|
1376
|
-
toolbar.setAttribute("part", "toolbar");
|
|
1377
|
-
toolbar.setAttribute("role", "toolbar");
|
|
1378
|
-
toolbar.addEventListener("keydown", this.handleToolbarKeydown);
|
|
1379
|
-
toolbar.addEventListener("focusin", this.handleToolbarFocus);
|
|
1380
|
-
this.controls = [];
|
|
1381
|
-
this.syncers = [];
|
|
1382
|
-
segments.forEach((segment, index) => {
|
|
1383
|
-
if (index > 0) {
|
|
1384
|
-
const separator = document.createElement("span");
|
|
1385
|
-
separator.className = "ark-wysiwyg__separator";
|
|
1386
|
-
separator.setAttribute("role", "separator");
|
|
1387
|
-
separator.setAttribute("aria-orientation", "vertical");
|
|
1388
|
-
toolbar.appendChild(separator);
|
|
1389
|
-
}
|
|
1390
|
-
const group = document.createElement("div");
|
|
1391
|
-
group.className = "ark-wysiwyg__group";
|
|
1392
|
-
group.setAttribute("data-group", segment.group);
|
|
1393
|
-
for (const item of segment.items)
|
|
1394
|
-
group.appendChild(this.buildItem(item));
|
|
1395
|
-
toolbar.appendChild(group);
|
|
1396
|
-
});
|
|
1397
|
-
if (this.controls.length > 0)
|
|
1398
|
-
this.controls[0].tabIndex = 0;
|
|
1399
|
-
return toolbar;
|
|
1400
|
-
}
|
|
1401
|
-
buildItem(item) {
|
|
1402
|
-
if (item === "heading")
|
|
1403
|
-
return this.buildHeadingSelect();
|
|
1404
|
-
if (item === "text-color")
|
|
1405
|
-
return this.buildPalette("text-color");
|
|
1406
|
-
if (item === "highlight")
|
|
1407
|
-
return this.buildPalette("highlight");
|
|
1408
|
-
if (item === "link")
|
|
1409
|
-
return this.buildLink();
|
|
1410
|
-
if (item === "image" || item === "video")
|
|
1411
|
-
return this.buildFilePicker(item);
|
|
1412
|
-
const action = ACTIONS[item];
|
|
1413
|
-
const level = item.startsWith("heading-") ? item.slice(-1) : "";
|
|
1414
|
-
const label = level ? `${this.labels.heading} ${level}` : this.labels[action.label];
|
|
1415
|
-
const button = this.createButton(label, action.icon);
|
|
1416
|
-
if (level) {
|
|
1417
|
-
button.textContent = `H${level}`;
|
|
1418
|
-
button.classList.add("ark-wysiwyg__btn--text");
|
|
1419
|
-
}
|
|
1420
|
-
button.addEventListener("click", () => {
|
|
1421
|
-
if (!this.instance)
|
|
1422
|
-
return;
|
|
1423
|
-
action.run(this.instance.editor);
|
|
1424
|
-
this.syncToolbar();
|
|
1425
|
-
});
|
|
1426
|
-
this.syncers.push(() => {
|
|
1427
|
-
if (!this.instance)
|
|
1428
|
-
return;
|
|
1429
|
-
const editor = this.instance.editor;
|
|
1430
|
-
if (action.active)
|
|
1431
|
-
button.setAttribute("aria-pressed", String(action.active(editor)));
|
|
1432
|
-
button.disabled = !editor.isEditable || (action.can ? !action.can(editor) : false);
|
|
1433
|
-
});
|
|
1434
|
-
return button;
|
|
1435
|
-
}
|
|
1436
|
-
createButton(label, icon) {
|
|
1437
|
-
const button = document.createElement("button");
|
|
1438
|
-
button.type = "button";
|
|
1439
|
-
button.className = "ark-wysiwyg__btn";
|
|
1440
|
-
button.innerHTML = ICONS[icon];
|
|
1441
|
-
button.title = label;
|
|
1442
|
-
button.setAttribute("aria-label", label);
|
|
1443
|
-
button.tabIndex = -1;
|
|
1444
|
-
// No mouse o botão não rouba o foco do editor (padrão de toolbar de editor): a seleção continua visível e o
|
|
1445
|
-
// comando aplica sobre ela sem vai-e-volta de foco. O focus() do Tiptap só devolve o foco no próximo frame, e
|
|
1446
|
-
// um Enter digitado nesse intervalo acionava o botão em vez de chegar ao editor. Teclado entra pelo Tab.
|
|
1447
|
-
button.addEventListener("mousedown", (event) => event.preventDefault());
|
|
1448
|
-
button.addEventListener("click", () => this.setCurrent(button));
|
|
1449
|
-
this.controls.push(button);
|
|
1450
|
-
return button;
|
|
1451
|
-
}
|
|
1452
|
-
// Estilo do bloco: um <select> nativo (teclado e leitor de tela de graça) mostrando o estilo atual.
|
|
1453
|
-
buildHeadingSelect() {
|
|
1454
|
-
const select = document.createElement("select");
|
|
1455
|
-
select.className = "ark-wysiwyg__select";
|
|
1456
|
-
select.setAttribute("aria-label", this.labels.textStyle);
|
|
1457
|
-
select.title = this.labels.textStyle;
|
|
1458
|
-
select.tabIndex = -1;
|
|
1459
|
-
const normal = document.createElement("option");
|
|
1460
|
-
normal.value = "paragraph";
|
|
1461
|
-
normal.textContent = this.labels.paragraph;
|
|
1462
|
-
select.appendChild(normal);
|
|
1463
|
-
for (const level of HEADING_LEVELS) {
|
|
1464
|
-
const option = document.createElement("option");
|
|
1465
|
-
option.value = String(level);
|
|
1466
|
-
option.textContent = `${this.labels.heading} ${level}`;
|
|
1467
|
-
select.appendChild(option);
|
|
1468
|
-
}
|
|
1469
|
-
select.addEventListener("change", () => {
|
|
1470
|
-
if (!this.instance)
|
|
1471
|
-
return;
|
|
1472
|
-
const chain = this.instance.editor.chain().focus();
|
|
1473
|
-
if (select.value === "paragraph") {
|
|
1474
|
-
chain.setParagraph().run();
|
|
1475
|
-
}
|
|
1476
|
-
else {
|
|
1477
|
-
chain.setHeading({ level: Number(select.value) }).run();
|
|
1478
|
-
}
|
|
1479
|
-
this.syncToolbar();
|
|
1480
|
-
});
|
|
1481
|
-
this.controls.push(select);
|
|
1482
|
-
this.syncers.push(() => {
|
|
1483
|
-
if (!this.instance)
|
|
1484
|
-
return;
|
|
1485
|
-
const editor = this.instance.editor;
|
|
1486
|
-
const level = HEADING_LEVELS.find((candidate) => editor.isActive("heading", { level: candidate }));
|
|
1487
|
-
const value = level ? String(level) : "paragraph";
|
|
1488
|
-
if (select.value !== value)
|
|
1489
|
-
select.value = value;
|
|
1490
|
-
select.disabled = !editor.isEditable;
|
|
1491
|
-
});
|
|
1492
|
-
return select;
|
|
1493
|
-
}
|
|
1494
|
-
// Cor do texto e marca-texto: botão com a cor atual na barra e uma paleta em popover (light dismiss nativo).
|
|
1495
|
-
buildPalette(item) {
|
|
1496
|
-
const isText = item === "text-color";
|
|
1497
|
-
const wrap = document.createElement("span");
|
|
1498
|
-
wrap.className = "ark-wysiwyg__item";
|
|
1499
|
-
const button = this.createButton(isText ? this.labels.textColor : this.labels.highlight, isText ? "textColor" : "highlight");
|
|
1500
|
-
button.classList.add("ark-wysiwyg__btn--swatch");
|
|
1501
|
-
const popover = this.createPopover();
|
|
1502
|
-
button.setAttribute("popovertarget", popover.id);
|
|
1503
|
-
button.setAttribute("aria-haspopup", "true");
|
|
1504
|
-
const grid = document.createElement("div");
|
|
1505
|
-
grid.className = "ark-wysiwyg__swatches";
|
|
1506
|
-
grid.setAttribute("role", "group");
|
|
1507
|
-
grid.setAttribute("aria-label", button.title);
|
|
1508
|
-
const apply = (color) => {
|
|
1509
|
-
if (!this.instance)
|
|
1510
|
-
return;
|
|
1511
|
-
const chain = this.instance.editor.chain().focus();
|
|
1512
|
-
if (isText) {
|
|
1513
|
-
(color ? chain.setColor(color) : chain.unsetColor()).run();
|
|
1514
|
-
}
|
|
1515
|
-
else {
|
|
1516
|
-
(color ? chain.setHighlight({ color }) : chain.unsetHighlight()).run();
|
|
1517
|
-
}
|
|
1518
|
-
popover.hidePopover();
|
|
1519
|
-
this.syncToolbar();
|
|
1520
|
-
};
|
|
1521
|
-
for (const color of isText ? this.colors : this.highlights) {
|
|
1522
|
-
const swatch = document.createElement("button");
|
|
1523
|
-
swatch.type = "button";
|
|
1524
|
-
swatch.className = "ark-wysiwyg__swatch";
|
|
1525
|
-
swatch.style.backgroundColor = color;
|
|
1526
|
-
swatch.title = color;
|
|
1527
|
-
swatch.setAttribute("aria-label", color);
|
|
1528
|
-
swatch.addEventListener("click", () => apply(color));
|
|
1529
|
-
grid.appendChild(swatch);
|
|
1530
|
-
}
|
|
1531
|
-
const none = document.createElement("button");
|
|
1532
|
-
none.type = "button";
|
|
1533
|
-
none.className = "ark-wysiwyg__swatch ark-wysiwyg__swatch--none";
|
|
1534
|
-
none.innerHTML = ICONS.none;
|
|
1535
|
-
none.title = this.labels.noColor;
|
|
1536
|
-
none.setAttribute("aria-label", this.labels.noColor);
|
|
1537
|
-
none.addEventListener("click", () => apply(null));
|
|
1538
|
-
grid.appendChild(none);
|
|
1539
|
-
popover.appendChild(grid);
|
|
1540
|
-
wrap.append(button, popover);
|
|
1541
|
-
this.syncers.push(() => {
|
|
1542
|
-
if (!this.instance)
|
|
1543
|
-
return;
|
|
1544
|
-
const editor = this.instance.editor;
|
|
1545
|
-
const current = isText ? editor.getAttributes("textStyle").color : editor.getAttributes("highlight").color;
|
|
1546
|
-
button.style.setProperty("--ark-wysiwyg-swatch", isSafeColor(current) ? current : "transparent");
|
|
1547
|
-
button.setAttribute("aria-pressed", String(isSafeColor(current)));
|
|
1548
|
-
button.disabled = !editor.isEditable;
|
|
1549
|
-
});
|
|
1550
|
-
return wrap;
|
|
1551
|
-
}
|
|
1552
|
-
// Link: popover com campo de URL; aplica na seleção (ou insere a URL) e recusa esquemas fora da lista.
|
|
1553
|
-
buildLink() {
|
|
1554
|
-
const wrap = document.createElement("span");
|
|
1555
|
-
wrap.className = "ark-wysiwyg__item";
|
|
1556
|
-
const button = this.createButton(this.labels.link, "link");
|
|
1557
|
-
const popover = this.createPopover();
|
|
1558
|
-
popover.classList.add("ark-wysiwyg__popover--link");
|
|
1559
|
-
button.setAttribute("popovertarget", popover.id);
|
|
1560
|
-
button.setAttribute("aria-haspopup", "dialog");
|
|
1561
|
-
const form = document.createElement("form");
|
|
1562
|
-
form.className = "ark-wysiwyg__link";
|
|
1563
|
-
const input = document.createElement("input");
|
|
1564
|
-
input.type = "text";
|
|
1565
|
-
input.inputMode = "url";
|
|
1566
|
-
input.setAttribute("autocomplete", "url");
|
|
1567
|
-
input.className = "ark-wysiwyg__input";
|
|
1568
|
-
input.placeholder = "https://";
|
|
1569
|
-
input.setAttribute("aria-label", this.labels.linkUrl);
|
|
1570
|
-
const error = document.createElement("p");
|
|
1571
|
-
error.className = "ark-wysiwyg__error";
|
|
1572
|
-
error.id = `${popover.id}-error`;
|
|
1573
|
-
error.hidden = true;
|
|
1574
|
-
error.textContent = this.labels.invalidUrl;
|
|
1575
|
-
const applyBtn = document.createElement("button");
|
|
1576
|
-
applyBtn.type = "submit";
|
|
1577
|
-
applyBtn.className = "ark-wysiwyg__btn ark-wysiwyg__btn--text";
|
|
1578
|
-
applyBtn.textContent = this.labels.apply;
|
|
1579
|
-
const removeBtn = document.createElement("button");
|
|
1580
|
-
removeBtn.type = "button";
|
|
1581
|
-
removeBtn.className = "ark-wysiwyg__btn ark-wysiwyg__btn--text";
|
|
1582
|
-
removeBtn.textContent = this.labels.remove;
|
|
1583
|
-
form.addEventListener("submit", (event) => {
|
|
1584
|
-
event.preventDefault();
|
|
1585
|
-
if (!this.instance)
|
|
1586
|
-
return;
|
|
1587
|
-
const ok = this.instance.setLink(input.value);
|
|
1588
|
-
error.hidden = ok;
|
|
1589
|
-
input.setAttribute("aria-invalid", ok ? "false" : "true");
|
|
1590
|
-
if (ok) {
|
|
1591
|
-
input.removeAttribute("aria-describedby");
|
|
1592
|
-
popover.hidePopover();
|
|
1593
|
-
this.syncToolbar();
|
|
1594
|
-
}
|
|
1595
|
-
else {
|
|
1596
|
-
input.setAttribute("aria-describedby", error.id);
|
|
1597
|
-
input.focus();
|
|
1598
|
-
}
|
|
1599
|
-
});
|
|
1600
|
-
removeBtn.addEventListener("click", () => {
|
|
1601
|
-
this.instance?.unsetLink();
|
|
1602
|
-
popover.hidePopover();
|
|
1603
|
-
this.syncToolbar();
|
|
1604
|
-
});
|
|
1605
|
-
popover.addEventListener("toggle", (event) => {
|
|
1606
|
-
if (event.newState !== "open" || !this.instance)
|
|
1607
|
-
return;
|
|
1608
|
-
const href = this.instance.editor.getAttributes("link").href;
|
|
1609
|
-
input.value = typeof href === "string" ? href : "";
|
|
1610
|
-
error.hidden = true;
|
|
1611
|
-
input.removeAttribute("aria-invalid");
|
|
1612
|
-
input.removeAttribute("aria-describedby");
|
|
1613
|
-
removeBtn.hidden = !this.instance.editor.isActive("link");
|
|
1614
|
-
input.focus();
|
|
1615
|
-
input.select();
|
|
1616
|
-
});
|
|
1617
|
-
form.append(input, applyBtn, removeBtn);
|
|
1618
|
-
popover.append(form, error);
|
|
1619
|
-
wrap.append(button, popover);
|
|
1620
|
-
this.syncers.push(() => {
|
|
1621
|
-
if (!this.instance)
|
|
1622
|
-
return;
|
|
1623
|
-
const editor = this.instance.editor;
|
|
1624
|
-
button.setAttribute("aria-pressed", String(editor.isActive("link")));
|
|
1625
|
-
button.disabled = !editor.isEditable;
|
|
1626
|
-
});
|
|
1627
|
-
return wrap;
|
|
1628
|
-
}
|
|
1629
|
-
// Imagem e vídeo: input de arquivo oculto; o envio é do gancho `uploadFile`, o editor só insere a URL.
|
|
1630
|
-
buildFilePicker(item) {
|
|
1631
|
-
const wrap = document.createElement("span");
|
|
1632
|
-
wrap.className = "ark-wysiwyg__item";
|
|
1633
|
-
const label = item === "image" ? this.labels.image : this.labels.video;
|
|
1634
|
-
const button = this.createButton(label, item === "image" ? "image" : "video");
|
|
1635
|
-
const input = document.createElement("input");
|
|
1636
|
-
input.type = "file";
|
|
1637
|
-
input.accept = `${item}/*`;
|
|
1638
|
-
input.hidden = true;
|
|
1639
|
-
input.tabIndex = -1;
|
|
1640
|
-
input.setAttribute("aria-hidden", "true");
|
|
1641
|
-
input.addEventListener("change", () => {
|
|
1642
|
-
const file = input.files?.[0];
|
|
1643
|
-
input.value = "";
|
|
1644
|
-
if (file)
|
|
1645
|
-
void this.insertFile(file);
|
|
1646
|
-
});
|
|
1647
|
-
button.addEventListener("click", () => input.click());
|
|
1648
|
-
wrap.append(button, input);
|
|
1649
|
-
this.syncers.push(() => {
|
|
1650
|
-
if (!this.instance)
|
|
1651
|
-
return;
|
|
1652
|
-
const busy = this.instance.uploading() > 0;
|
|
1653
|
-
button.disabled = !this.instance.editor.isEditable || busy;
|
|
1654
|
-
button.title = busy ? `${this.labels.uploading}…` : label;
|
|
1655
|
-
});
|
|
1656
|
-
return wrap;
|
|
1657
|
-
}
|
|
1658
|
-
// `popover="auto"` + popovertarget abrem e fecham sem JS (light dismiss nativo); só a posição é calculada aqui.
|
|
1659
|
-
createPopover() {
|
|
1660
|
-
const popover = document.createElement("div");
|
|
1661
|
-
popover.id = `ark-wysiwyg-popover-${++popoverSeq}`;
|
|
1662
|
-
popover.className = "ark-wysiwyg__popover";
|
|
1663
|
-
popover.setAttribute("popover", "auto");
|
|
1664
|
-
popover.addEventListener("toggle", (event) => {
|
|
1665
|
-
if (event.newState !== "open")
|
|
1666
|
-
return;
|
|
1667
|
-
const anchor = this.toolbarEl?.querySelector(`[popovertarget="${popover.id}"]`);
|
|
1668
|
-
if (!anchor)
|
|
1669
|
-
return;
|
|
1670
|
-
const rect = anchor.getBoundingClientRect();
|
|
1671
|
-
const width = popover.offsetWidth;
|
|
1672
|
-
const height = popover.offsetHeight;
|
|
1673
|
-
const maxLeft = Math.max(8, document.documentElement.clientWidth - width - 8);
|
|
1674
|
-
const below = rect.bottom + 4;
|
|
1675
|
-
const top = below + height > document.documentElement.clientHeight - 8 ? Math.max(8, rect.top - height - 4) : below;
|
|
1676
|
-
popover.style.left = `${Math.round(Math.min(Math.max(8, rect.left), maxLeft))}px`;
|
|
1677
|
-
popover.style.top = `${Math.round(top)}px`;
|
|
1678
|
-
});
|
|
1679
|
-
return popover;
|
|
1680
|
-
}
|
|
1681
|
-
setCurrent(control) {
|
|
1682
|
-
for (const candidate of this.controls)
|
|
1683
|
-
candidate.tabIndex = candidate === control ? 0 : -1;
|
|
1684
|
-
}
|
|
1685
|
-
teardown() {
|
|
1686
|
-
this.disposeTheme?.();
|
|
1687
|
-
this.disposeTheme = null;
|
|
1688
|
-
if (this.instance) {
|
|
1689
|
-
// Reconstruir (toolbar, rótulos, paletas, gancho) ou mover o nó no DOM não pode perder o que foi digitado.
|
|
1690
|
-
this.pendingContent = this.instance.getJSON();
|
|
1691
|
-
this.instance.editor.off("selectionUpdate", this.syncToolbar);
|
|
1692
|
-
this.instance.editor.off("transaction", this.syncToolbar);
|
|
1693
|
-
this.instance.destroy();
|
|
1694
|
-
this.instance = null;
|
|
1695
|
-
}
|
|
1696
|
-
this.controls = [];
|
|
1697
|
-
this.syncers = [];
|
|
1698
|
-
this.toolbarEl = null;
|
|
1699
|
-
if (this.root) {
|
|
1700
|
-
this.root.remove();
|
|
1701
|
-
this.root = null;
|
|
1702
|
-
}
|
|
1703
|
-
}
|
|
1704
|
-
}
|
|
1705
|
-
ArkWysiwygEditor.tagName = "ark-wysiwyg-editor";
|
|
1706
|
-
|
|
1707
|
-
/**
|
|
1708
|
-
* Viewer somente-leitura (Custom Element) que renderiza o mesmo JSON do editor.
|
|
1709
|
-
*
|
|
1710
|
-
* Usa Tiptap em modo `editable: false` com o mesmo schema do editor (links,
|
|
1711
|
-
* cores, alinhamento, imagens e vídeos externos): renderiza a partir do JSON,
|
|
1712
|
-
* sanitizado ao entrar (`sanitizeWysiwygContent`), sem injetar HTML
|
|
1713
|
-
* arbitrário; links abrem em nova aba com `rel="noopener noreferrer nofollow"`.
|
|
1714
|
-
*
|
|
1715
|
-
* Conteúdo via propriedade `content` (JSON do Tiptap). Atributos: `theme` e
|
|
1716
|
-
* `testid` (`data-ark="wysiwyg-viewer"` na raiz e `-content` no conteúdo).
|
|
1717
|
-
*/
|
|
1718
|
-
class ArkWysiwygViewer extends HTMLElementBase {
|
|
1719
|
-
constructor() {
|
|
1720
|
-
super(...arguments);
|
|
1721
|
-
this.instance = null;
|
|
1722
|
-
this.root = null;
|
|
1723
|
-
this.pendingContent = null;
|
|
1724
|
-
/** Para de observar o tema da página; só existe com `theme="auto"`. */
|
|
1725
|
-
this.disposeTheme = null;
|
|
1726
|
-
}
|
|
1727
|
-
static get observedAttributes() {
|
|
1728
|
-
return ["theme", "testid"];
|
|
1729
|
-
}
|
|
1730
|
-
/** Conteúdo a renderizar como JSON do Tiptap. */
|
|
1731
|
-
get content() {
|
|
1732
|
-
return this.instance ? this.instance.getJSON() : this.pendingContent;
|
|
1733
|
-
}
|
|
1734
|
-
set content(value) {
|
|
1735
|
-
this.pendingContent = value;
|
|
1736
|
-
this.instance?.setContent(value);
|
|
1737
|
-
}
|
|
1738
|
-
/** Tema efetivamente aplicado (depois de resolver `auto`); `null` antes de renderizar. */
|
|
1739
|
-
get resolvedTheme() {
|
|
1740
|
-
return this.instance?.resolvedTheme() ?? null;
|
|
1741
|
-
}
|
|
1742
|
-
connectedCallback() {
|
|
1743
|
-
upgradeProperties(this);
|
|
1744
|
-
ensureWysiwygStyles();
|
|
1745
|
-
this.build();
|
|
1746
|
-
}
|
|
1747
|
-
disconnectedCallback() {
|
|
1748
|
-
this.teardown();
|
|
1749
|
-
}
|
|
1750
|
-
attributeChangedCallback(name, oldValue, newValue) {
|
|
1751
|
-
if (oldValue === newValue || !this.instance)
|
|
1752
|
-
return;
|
|
1753
|
-
if (name === "theme") {
|
|
1754
|
-
this.applyTheme(this.getTheme());
|
|
1755
|
-
this.syncThemeObserver();
|
|
1756
|
-
}
|
|
1757
|
-
if (name === "testid")
|
|
1758
|
-
this.applyHooks();
|
|
1759
|
-
}
|
|
1760
|
-
getTheme() {
|
|
1761
|
-
const value = (this.getAttribute("theme") || "auto").toLowerCase();
|
|
1762
|
-
if (value === "light" || value === "dark")
|
|
1763
|
-
return value;
|
|
1764
|
-
return "auto";
|
|
1765
|
-
}
|
|
1766
|
-
build() {
|
|
1767
|
-
this.teardown();
|
|
1768
|
-
if (this.pendingContent === null) {
|
|
1769
|
-
this.pendingContent = this.content;
|
|
1770
|
-
}
|
|
1771
|
-
const root = document.createElement("div");
|
|
1772
|
-
root.className = "ark-wysiwyg ark-wysiwyg--viewer";
|
|
1773
|
-
const mount = document.createElement("div");
|
|
1774
|
-
mount.className = "ark-wysiwyg__content";
|
|
1775
|
-
root.appendChild(mount);
|
|
1776
|
-
this.appendChild(root);
|
|
1777
|
-
this.root = root;
|
|
1778
|
-
this.instance = createWysiwygViewer(mount, {
|
|
1779
|
-
content: this.pendingContent,
|
|
1780
|
-
theme: this.getTheme()
|
|
1781
|
-
});
|
|
1782
|
-
this.root.setAttribute("data-ark-theme", this.instance.resolvedTheme());
|
|
1783
|
-
this.applyHooks();
|
|
1784
|
-
this.syncThemeObserver();
|
|
1785
|
-
}
|
|
1786
|
-
// Raiz e conteúdo levam os hooks de E2E, como os componentes de @tooark/web-components.
|
|
1787
|
-
applyHooks() {
|
|
1788
|
-
if (!this.root || !this.instance)
|
|
1789
|
-
return;
|
|
1790
|
-
applyTestHooks(this, "wysiwyg-viewer", this.root);
|
|
1791
|
-
applyTestHooks(this, "wysiwyg-viewer", this.instance.editor.view.dom, "content");
|
|
1792
|
-
}
|
|
1793
|
-
// Em `auto`, a troca de tema da página re-resolve o tema do viewer; com tema fixo não há o que observar.
|
|
1794
|
-
syncThemeObserver() {
|
|
1795
|
-
this.disposeTheme?.();
|
|
1796
|
-
this.disposeTheme = null;
|
|
1797
|
-
if (this.getTheme() !== "auto")
|
|
1798
|
-
return;
|
|
1799
|
-
this.disposeTheme = observeColorScheme(this, () => this.applyTheme("auto"));
|
|
1800
|
-
}
|
|
1801
|
-
// O engine marca o mount com data-ark-theme; o CSS do tema lê a raiz .ark-wysiwyg, então ela recebe o mesmo.
|
|
1802
|
-
applyTheme(theme) {
|
|
1803
|
-
if (!this.instance)
|
|
1804
|
-
return;
|
|
1805
|
-
this.instance.setTheme(theme);
|
|
1806
|
-
this.root?.setAttribute("data-ark-theme", this.instance.resolvedTheme());
|
|
1807
|
-
}
|
|
1808
|
-
teardown() {
|
|
1809
|
-
this.disposeTheme?.();
|
|
1810
|
-
this.disposeTheme = null;
|
|
1811
|
-
this.instance?.destroy();
|
|
1812
|
-
this.instance = null;
|
|
1813
|
-
if (this.root) {
|
|
1814
|
-
this.root.remove();
|
|
1815
|
-
this.root = null;
|
|
1816
|
-
}
|
|
1817
|
-
}
|
|
1818
|
-
}
|
|
1819
|
-
ArkWysiwygViewer.tagName = "ark-wysiwyg-viewer";
|
|
1820
|
-
|
|
1821
|
-
/**
|
|
1822
|
-
* Registra os Custom Elements `<ark-wysiwyg-editor>` e `<ark-wysiwyg-viewer>`.
|
|
1823
|
-
* Chame antes de usar em qualquer ambiente (puro, React, Angular, Vue).
|
|
1824
|
-
*/
|
|
1825
|
-
function registerTooarkWysiwyg() {
|
|
1826
|
-
// Fora do navegador (SSR) não há registro de elementos: no-op, e o cliente registra na hidratação.
|
|
1827
|
-
if (typeof customElements === "undefined")
|
|
1828
|
-
return;
|
|
1829
|
-
if (!customElements.get(ArkWysiwygEditor.tagName)) {
|
|
1830
|
-
customElements.define(ArkWysiwygEditor.tagName, ArkWysiwygEditor);
|
|
1831
|
-
}
|
|
1832
|
-
if (!customElements.get(ArkWysiwygViewer.tagName)) {
|
|
1833
|
-
customElements.define(ArkWysiwygViewer.tagName, ArkWysiwygViewer);
|
|
1834
|
-
}
|
|
1835
|
-
}
|
|
1836
|
-
|
|
1837
|
-
export { ARK_WYSIWYG_DEFAULT_TOOLBAR, ARK_WYSIWYG_TOOLBAR_GROUPS, ArkWysiwygEditor, ArkWysiwygViewer, DEFAULT_MAX_FILE_SIZE, EMPTY_DOC, HEADING_LEVELS, Video, WYSIWYG_STYLE_ID, createWysiwygEditor, createWysiwygExtensions, createWysiwygViewer, ensureWysiwygStyles, isSafeColor, isSafeUrl, registerTooarkWysiwyg, resolveWysiwygLabels, resolveWysiwygTheme, sanitizeWysiwygContent, wysiwygCss };
|
|
1
|
+
export { ArkWysiwygEditor } from './components/ark-wysiwyg-editor.js';
|
|
2
|
+
export { ArkWysiwygViewer } from './components/ark-wysiwyg-viewer.js';
|
|
3
|
+
export { DEFAULT_MAX_FILE_SIZE, EMPTY_DOC, HEADING_LEVELS, Video, createWysiwygEditor, createWysiwygExtensions, createWysiwygViewer, resolveWysiwygTheme } from './engine/index.js';
|
|
4
|
+
export { resolveWysiwygLabels } from './i18n.js';
|
|
5
|
+
export { registerTooarkWysiwyg } from './register.js';
|
|
6
|
+
export { isSafeColor, isSafeUrl, sanitizeWysiwygContent } from './security.js';
|
|
7
|
+
export { WYSIWYG_STYLE_ID, ensureWysiwygStyles, wysiwygCss } from './styles.js';
|
|
8
|
+
export { ARK_WYSIWYG_DEFAULT_TOOLBAR, ARK_WYSIWYG_TOOLBAR_GROUPS } from './types/index.js';
|
|
1838
9
|
//# sourceMappingURL=index.js.map
|