@tooark/wysiwyg 1.0.0 → 1.1.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/dist/index.d.cts CHANGED
@@ -63,7 +63,10 @@ declare const ARK_WYSIWYG_TOOLBAR_GROUPS: Record<ArkWysiwygToolbarGroup, ArkWysi
63
63
  declare const ARK_WYSIWYG_DEFAULT_TOOLBAR: ArkWysiwygToolbarGroup[];
64
64
  /** Tipo de arquivo que o editor envia ao gancho de upload. */
65
65
  type ArkWysiwygUploadKind = "image" | "video";
66
- /** O que o gancho de upload devolve: a URL final (http(s) ou relativa; nunca base64) e metadados opcionais. */
66
+ /**
67
+ * O que o gancho de upload devolve: a URL final e metadados opcionais. A URL é http(s) ou relativa iniciada por `/`,
68
+ * `#`, `?`, `./` ou `../`; base64, `blob:` ou caminho sem prefixo falham com "invalid-src".
69
+ */
67
70
  type ArkWysiwygUploadResult = {
68
71
  /** URL onde o arquivo ficou. */
69
72
  src: string;
@@ -115,6 +118,9 @@ type ArkWysiwygViewerOptions = {
115
118
  theme?: ArkWysiwygTheme;
116
119
  };
117
120
 
121
+ /** `HTMLElement` no navegador; fora dele, uma classe vazia para o módulo poder ser importado no servidor. */
122
+ declare const HTMLElementBase: typeof HTMLElement;
123
+
118
124
  /**
119
125
  * Editor WYSIWYG (Custom Element) baseado em Tiptap.
120
126
  *
@@ -130,7 +136,7 @@ type ArkWysiwygViewerOptions = {
130
136
  * não aparecem na toolbar e arquivos colados ou arrastados são recusados
131
137
  * (`ark-wysiwyg-upload-error`), nunca embutidos em base64.
132
138
  */
133
- declare class ArkWysiwygEditor extends HTMLElement {
139
+ declare class ArkWysiwygEditor extends HTMLElementBase {
134
140
  static readonly tagName = "ark-wysiwyg-editor";
135
141
  private instance;
136
142
  private root;
@@ -200,7 +206,7 @@ declare class ArkWysiwygEditor extends HTMLElement {
200
206
  *
201
207
  * Conteúdo via propriedade `content` (JSON do Tiptap). Atributo: `theme`.
202
208
  */
203
- declare class ArkWysiwygViewer extends HTMLElement {
209
+ declare class ArkWysiwygViewer extends HTMLElementBase {
204
210
  static readonly tagName = "ark-wysiwyg-viewer";
205
211
  private instance;
206
212
  private root;
@@ -223,6 +229,13 @@ declare class ArkWysiwygViewer extends HTMLElement {
223
229
  private teardown;
224
230
  }
225
231
 
232
+ declare global {
233
+ interface HTMLElementTagNameMap {
234
+ "ark-wysiwyg-editor": ArkWysiwygEditor;
235
+ "ark-wysiwyg-viewer": ArkWysiwygViewer;
236
+ }
237
+ }
238
+
226
239
  /** Documento vazio do ProseMirror (um parágrafo). */
227
240
  declare const EMPTY_DOC: JSONContent;
228
241
  /** Tamanho máximo de arquivo aceito por padrão (10 MiB). */
package/dist/index.d.ts CHANGED
@@ -63,7 +63,10 @@ declare const ARK_WYSIWYG_TOOLBAR_GROUPS: Record<ArkWysiwygToolbarGroup, ArkWysi
63
63
  declare const ARK_WYSIWYG_DEFAULT_TOOLBAR: ArkWysiwygToolbarGroup[];
64
64
  /** Tipo de arquivo que o editor envia ao gancho de upload. */
65
65
  type ArkWysiwygUploadKind = "image" | "video";
66
- /** O que o gancho de upload devolve: a URL final (http(s) ou relativa; nunca base64) e metadados opcionais. */
66
+ /**
67
+ * O que o gancho de upload devolve: a URL final e metadados opcionais. A URL é http(s) ou relativa iniciada por `/`,
68
+ * `#`, `?`, `./` ou `../`; base64, `blob:` ou caminho sem prefixo falham com "invalid-src".
69
+ */
67
70
  type ArkWysiwygUploadResult = {
68
71
  /** URL onde o arquivo ficou. */
69
72
  src: string;
@@ -115,6 +118,9 @@ type ArkWysiwygViewerOptions = {
115
118
  theme?: ArkWysiwygTheme;
116
119
  };
117
120
 
121
+ /** `HTMLElement` no navegador; fora dele, uma classe vazia para o módulo poder ser importado no servidor. */
122
+ declare const HTMLElementBase: typeof HTMLElement;
123
+
118
124
  /**
119
125
  * Editor WYSIWYG (Custom Element) baseado em Tiptap.
120
126
  *
@@ -130,7 +136,7 @@ type ArkWysiwygViewerOptions = {
130
136
  * não aparecem na toolbar e arquivos colados ou arrastados são recusados
131
137
  * (`ark-wysiwyg-upload-error`), nunca embutidos em base64.
132
138
  */
133
- declare class ArkWysiwygEditor extends HTMLElement {
139
+ declare class ArkWysiwygEditor extends HTMLElementBase {
134
140
  static readonly tagName = "ark-wysiwyg-editor";
135
141
  private instance;
136
142
  private root;
@@ -200,7 +206,7 @@ declare class ArkWysiwygEditor extends HTMLElement {
200
206
  *
201
207
  * Conteúdo via propriedade `content` (JSON do Tiptap). Atributo: `theme`.
202
208
  */
203
- declare class ArkWysiwygViewer extends HTMLElement {
209
+ declare class ArkWysiwygViewer extends HTMLElementBase {
204
210
  static readonly tagName = "ark-wysiwyg-viewer";
205
211
  private instance;
206
212
  private root;
@@ -223,6 +229,13 @@ declare class ArkWysiwygViewer extends HTMLElement {
223
229
  private teardown;
224
230
  }
225
231
 
232
+ declare global {
233
+ interface HTMLElementTagNameMap {
234
+ "ark-wysiwyg-editor": ArkWysiwygEditor;
235
+ "ark-wysiwyg-viewer": ArkWysiwygViewer;
236
+ }
237
+ }
238
+
226
239
  /** Documento vazio do ProseMirror (um parágrafo). */
227
240
  declare const EMPTY_DOC: JSONContent;
228
241
  /** Tamanho máximo de arquivo aceito por padrão (10 MiB). */
package/dist/index.js CHANGED
@@ -144,12 +144,20 @@ const Video = Node.create({
144
144
  addAttributes() {
145
145
  return {
146
146
  src: { default: null },
147
- poster: { 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
+ },
148
155
  title: { default: null }
149
156
  };
150
157
  },
151
158
  parseHTML() {
152
- return [{ tag: "video[src]" }];
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) }];
153
161
  },
154
162
  renderHTML({ HTMLAttributes }) {
155
163
  return ["video", mergeAttributes({ controls: "true", preload: "metadata" }, HTMLAttributes)];
@@ -160,6 +168,12 @@ const Video = Node.create({
160
168
  };
161
169
  }
162
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
+ });
163
177
  // --- Extensões compartilhadas ---
164
178
  /**
165
179
  * Extensões do editor e do viewer (o mesmo schema nos dois, senão o conteúdo salvo não renderiza): StarterKit
@@ -184,7 +198,7 @@ function createWysiwygExtensions(options) {
184
198
  Color,
185
199
  Highlight.configure({ multicolor: true }),
186
200
  TextAlign.configure({ types: ["heading", "paragraph"], alignments: ["left", "center", "right", "justify"] }),
187
- Image.configure({ allowBase64: false, inline: false }),
201
+ SafeImage.configure({ allowBase64: false, inline: false }),
188
202
  Video
189
203
  ];
190
204
  if (options.placeholder) {
@@ -199,8 +213,8 @@ function kindOf(file) {
199
213
  return "video";
200
214
  return null;
201
215
  }
202
- function mediaFiles(list) {
203
- return Array.from(list ?? []).filter((file) => kindOf(file) !== null);
216
+ function filesOf(list) {
217
+ return Array.from(list ?? []);
204
218
  }
205
219
  function createInstance(element, options) {
206
220
  let resolved = resolveWysiwygTheme(options.theme, element);
@@ -211,7 +225,8 @@ function createInstance(element, options) {
211
225
  options.onUploadError?.({ reason, file, error });
212
226
  return false;
213
227
  };
214
- // Arquivos colados ou arrastados só entram pelo gancho; sem ele são consumidos (nada de base64 no JSON).
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.
215
230
  const handleFiles = (files, position) => {
216
231
  if (files.length === 0)
217
232
  return false;
@@ -225,12 +240,19 @@ function createInstance(element, options) {
225
240
  extensions: createWysiwygExtensions({ editable: options.editable, placeholder: options.placeholder }),
226
241
  content: EMPTY_DOC,
227
242
  editorProps: {
228
- handlePaste: (_view, event) => handleFiles(mediaFiles(event.clipboardData?.files)),
243
+ handlePaste: (_view, event) => {
244
+ const files = filesOf(event.clipboardData?.files);
245
+ // Planilhas e editores copiam o texto junto de arquivos que não são mídia: aí o texto vence e cola normal.
246
+ const hasText = Array.from(event.clipboardData?.types ?? []).some((type) => type.startsWith("text/"));
247
+ if (hasText && !files.some((file) => kindOf(file)))
248
+ return false;
249
+ return handleFiles(files);
250
+ },
229
251
  handleDrop: (view, event, _slice, moved) => {
230
252
  if (moved)
231
253
  return false;
232
254
  const at = view.posAtCoords({ left: event.clientX, top: event.clientY });
233
- return handleFiles(mediaFiles(event.dataTransfer?.files), at?.pos);
255
+ return handleFiles(filesOf(event.dataTransfer?.files), at?.pos);
234
256
  },
235
257
  // HTML colado com <img>/<video> só vira nó quando há gancho: sem ele, seria um hotlink que o app não controla.
236
258
  transformPastedHTML: (html) => (options.uploadFile ? html : html.replace(/<(img|video|source)\b[^>]*>/gi, ""))
@@ -812,6 +834,13 @@ const ARK_WYSIWYG_DEFAULT_TOOLBAR = [
812
834
  "history"
813
835
  ];
814
836
 
837
+ // Base dos Custom Elements que também carrega fora do navegador. No SSR (Node, Angular SSR, Next, Nuxt) não existe
838
+ // HTMLElement, e um `extends HTMLElement` no topo do módulo derrubaria o import de quem só renderiza o HTML; lá a
839
+ // base é uma classe vazia, e os elementos só passam a existir no cliente, quando registerTooark*() os define.
840
+ /** `HTMLElement` no navegador; fora dele, uma classe vazia para o módulo poder ser importado no servidor. */
841
+ const HTMLElementBase = typeof HTMLElement === "undefined" ? class {
842
+ } : HTMLElement;
843
+
815
844
  const headingAction = (level) => ({
816
845
  icon: "bold",
817
846
  label: "heading",
@@ -962,7 +991,7 @@ let popoverSeq = 0;
962
991
  * não aparecem na toolbar e arquivos colados ou arrastados são recusados
963
992
  * (`ark-wysiwyg-upload-error`), nunca embutidos em base64.
964
993
  */
965
- class ArkWysiwygEditor extends HTMLElement {
994
+ class ArkWysiwygEditor extends HTMLElementBase {
966
995
  constructor() {
967
996
  super(...arguments);
968
997
  this.instance = null;
@@ -1176,9 +1205,6 @@ class ArkWysiwygEditor extends HTMLElement {
1176
1205
  }
1177
1206
  build() {
1178
1207
  this.teardown();
1179
- if (this.pendingContent === null) {
1180
- this.pendingContent = this.content;
1181
- }
1182
1208
  this.labels = resolveWysiwygLabels(this.getAttribute("lang"), this.getAttribute("locale-json"));
1183
1209
  const root = document.createElement("div");
1184
1210
  root.className = "ark-wysiwyg";
@@ -1309,6 +1335,11 @@ class ArkWysiwygEditor extends HTMLElement {
1309
1335
  button.title = label;
1310
1336
  button.setAttribute("aria-label", label);
1311
1337
  button.tabIndex = -1;
1338
+ // 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
1339
+ // comando aplica sobre ela sem vai-e-volta de foco. O focus() do Tiptap só devolve o foco no próximo frame, e
1340
+ // um Enter digitado nesse intervalo acionava o botão em vez de chegar ao editor. Teclado entra pelo Tab.
1341
+ button.addEventListener("mousedown", (event) => event.preventDefault());
1342
+ button.addEventListener("click", () => this.setCurrent(button));
1312
1343
  this.controls.push(button);
1313
1344
  return button;
1314
1345
  }
@@ -1549,6 +1580,8 @@ class ArkWysiwygEditor extends HTMLElement {
1549
1580
  this.disposeTheme?.();
1550
1581
  this.disposeTheme = null;
1551
1582
  if (this.instance) {
1583
+ // Reconstruir (toolbar, rótulos, paletas, gancho) ou mover o nó no DOM não pode perder o que foi digitado.
1584
+ this.pendingContent = this.instance.getJSON();
1552
1585
  this.instance.editor.off("selectionUpdate", this.syncToolbar);
1553
1586
  this.instance.editor.off("transaction", this.syncToolbar);
1554
1587
  this.instance.destroy();
@@ -1575,7 +1608,7 @@ ArkWysiwygEditor.tagName = "ark-wysiwyg-editor";
1575
1608
  *
1576
1609
  * Conteúdo via propriedade `content` (JSON do Tiptap). Atributo: `theme`.
1577
1610
  */
1578
- class ArkWysiwygViewer extends HTMLElement {
1611
+ class ArkWysiwygViewer extends HTMLElementBase {
1579
1612
  constructor() {
1580
1613
  super(...arguments);
1581
1614
  this.instance = null;
@@ -1672,6 +1705,9 @@ ArkWysiwygViewer.tagName = "ark-wysiwyg-viewer";
1672
1705
  * Chame antes de usar em qualquer ambiente (puro, React, Angular, Vue).
1673
1706
  */
1674
1707
  function registerTooarkWysiwyg() {
1708
+ // Fora do navegador (SSR) não há registro de elementos: no-op, e o cliente registra na hidratação.
1709
+ if (typeof customElements === "undefined")
1710
+ return;
1675
1711
  if (!customElements.get(ArkWysiwygEditor.tagName)) {
1676
1712
  customElements.define(ArkWysiwygEditor.tagName, ArkWysiwygEditor);
1677
1713
  }