@boxcc/maildeno-editor 0.0.0-stage → 0.4.14

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.
Files changed (57) hide show
  1. package/CHANGELOG.md +479 -0
  2. package/README.md +442 -2
  3. package/dist/DatePicker-AdfGW0Tw.js +5347 -0
  4. package/dist/DatePicker-aNFlsoOb.js +5347 -0
  5. package/dist/Dialog-By0JLN8s.js +6294 -0
  6. package/dist/HealthIndicator-BLID6Ty0.js +1216 -0
  7. package/dist/HealthIndicator-DfzqzPNw.js +1217 -0
  8. package/dist/PopperContent-N2nAEFeH.js +2538 -0
  9. package/dist/PopperContent-eLmz1Gjd.js +2578 -0
  10. package/dist/PreviewCanvas-D3SpILsV.js +534 -0
  11. package/dist/PreviewCanvas-PtW1UL1J.js +534 -0
  12. package/dist/RichTextEditor-D6DQqbJg.js +12218 -0
  13. package/dist/RichTextEditor-DDEfKPZm.js +12217 -0
  14. package/dist/RowPreviewChildren-BGnilx-K.js +4 -0
  15. package/dist/RowPreviewChildren-CalQWx1C.js +4 -0
  16. package/dist/RowPreviewLegacyComponent-Df_1HTly.js +403 -0
  17. package/dist/RowPreviewLegacyComponent-NECG3wpn.js +403 -0
  18. package/dist/RowPreviewRow-C2XAe5Xs.js +81 -0
  19. package/dist/RowPreviewRow-DG4AdMrv.js +81 -0
  20. package/dist/SavedRowsPanel-2JBfYdxN.js +492 -0
  21. package/dist/SavedRowsPanel-B6_VHQZm.js +493 -0
  22. package/dist/_plugin-vue_export-helper-Dj7HTbfw.js +8 -0
  23. package/dist/adapters/errors.d.ts +59 -0
  24. package/dist/adapters/localStorageAdapter.d.ts +6 -0
  25. package/dist/adapters/types.d.ts +151 -0
  26. package/dist/babel-DV7WPQI0.js +10043 -0
  27. package/dist/blocks/registry.d.ts +23 -0
  28. package/dist/blocks/types.d.ts +73 -0
  29. package/dist/borderRadius-CkSa1lQ9.js +75 -0
  30. package/dist/components/features/emailBuilder/EmailEditor.vue.d.ts +183 -0
  31. package/dist/composables/emailBuilder/export/logic/espLogicWrapper.d.ts +76 -0
  32. package/dist/composables/emailBuilder/persistence/useEmailBuilderPersistence.d.ts +38 -0
  33. package/dist/composables/emailBuilder/transform/pipeline/optimize.d.ts +100 -0
  34. package/dist/composables/system/useColorScheme.d.ts +16 -0
  35. package/dist/element-DQw3HLit.js +21540 -0
  36. package/dist/element.d.ts +6 -0
  37. package/dist/element.js +5 -0
  38. package/dist/esp/registry.d.ts +33 -0
  39. package/dist/estree-DY9POgc0.js +8195 -0
  40. package/dist/html-wb0gSX1o.js +7273 -0
  41. package/dist/index.d.ts +17 -0
  42. package/dist/index.js +15032 -0
  43. package/dist/init.d.ts +180 -0
  44. package/dist/init.js +143 -0
  45. package/dist/maildeno-editor.css +2 -0
  46. package/dist/merge-tags/registry.d.ts +33 -0
  47. package/dist/mergeTagDefinitions-Cler19nv.js +27 -0
  48. package/dist/standalone-DHvJ30Td.js +3554 -0
  49. package/dist/theme.d.ts +206 -0
  50. package/dist/types/assistant.d.ts +56 -0
  51. package/dist/useEmailBuilder-2yCUzRx2.js +4934 -0
  52. package/dist/useEmailBuilder-D3uV7dwL.js +4934 -0
  53. package/dist/useToast-D1GgDMqQ.js +194 -0
  54. package/dist/utils/border.d.ts +15 -0
  55. package/dist/utils/borderRadius.d.ts +10 -0
  56. package/dist/vue.runtime.esm-bundler-D2AjRP90.js +6117 -0
  57. package/package.json +100 -4
package/README.md CHANGED
@@ -1,3 +1,443 @@
1
- # Temporary Holding Version
1
+ # @maildeno/editor
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A drag-and-drop email template editor.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @maildeno/editor
9
+ ```
10
+
11
+ One package, no peer dependencies, no CSS import. The editor injects its own
12
+ styling when it mounts.
13
+
14
+ ## Minimal usage React
15
+
16
+ ```tsx
17
+ import { useEffect, useRef } from "react";
18
+ import { init, type EditorHandle } from "@maildeno/editor/init";
19
+
20
+ export default function Editor() {
21
+ const container = useRef<HTMLDivElement>(null);
22
+ const handle = useRef<EditorHandle | null>(null);
23
+
24
+ useEffect(() => {
25
+ let cancelled = false;
26
+
27
+ const setup = async () => {
28
+ try {
29
+ const editor = await init({
30
+ container: container.current!,
31
+ capabilities: {
32
+ export: ["html", "mjml", "json"],
33
+ },
34
+ onSave: ({ templateId }) => {
35
+ console.log("Saved", templateId);
36
+
37
+ const html = handle.current?.getHtml(); // handle.current?.getReactEmail() or handle.current?.getMjml()
38
+ console.log("HTML:", html);
39
+ },
40
+ });
41
+
42
+ if (cancelled) {
43
+ editor.destroy();
44
+ return;
45
+ }
46
+
47
+ handle.current = editor;
48
+ } catch (error) {
49
+ if (!cancelled) {
50
+ console.error("Failed to initialize Maildeno editor:", error);
51
+ }
52
+ }
53
+ };
54
+
55
+ setup();
56
+
57
+ return () => {
58
+ cancelled = true;
59
+ handle.current?.destroy();
60
+ handle.current = null;
61
+ };
62
+ }, []);
63
+
64
+ return <div ref={container} />;
65
+ }
66
+ ```
67
+
68
+ > This mounts **read-only** — no `onSave` means no Save button. See
69
+ > [Persisting which template is open](#persisting-which-template-is-open) to
70
+ > enable saving.
71
+
72
+ ## `EditorHandle`
73
+
74
+ `init()` resolves to this once the editor has mounted:
75
+
76
+ | Member | Description |
77
+ | --- | --- |
78
+ | `element` | The underlying `<maildeno-editor>` DOM node. |
79
+ | `on(event, fn)` / `off(event, fn)` | Subscribe to editor events. Currently `"save"`. Only fires if `onSave` was passed to `init()` at mount time — subscribing after the fact doesn't retroactively enable saving or reveal a button that was never rendered. |
80
+ | `setTheme(theme)` | Re-theme live, any time after mount. |
81
+ | `setTemplateName(name)` | Update the name shown in the header and used for saves and exports. Pass `""` to clear it. |
82
+ | `getHtml(mode?)` | Current template as an HTML email string, or `null` if empty. |
83
+ | `getMjml(mode?)` | Current template as MJML. |
84
+ | `getReactEmail(mode?)` | Current template as React Email `.tsx` source. |
85
+ | `getJson()` | Current template as a plain object. |
86
+ | `setJson(data, opts?)` | Replace the canvas. Accepts what `getJson()` returns, so `setJson(getJson())` round-trips. `opts.history` is `"undoable"` (default) or `"reset"`. |
87
+ | `getSelection()` | `{ id, type }` for the selected block, or `null`. `type` is the block type (`"paragraph"`, `"image"`…). |
88
+ | `setSelection(id)` | Select by id, or clear with `null`. Returns `false` if no block has that id. |
89
+ | `onChange(cb)` | Runs `cb` after each committed change. Returns an unsubscribe function. |
90
+ | `destroy()` | Unmount and clean up. Always call this on unmount. |
91
+
92
+
93
+ ### Getting content out
94
+
95
+ Four getters, available on the handle (`init()`) or a template ref (Vue component):
96
+
97
+ ```ts
98
+ getHtml(mode?) // production-ready HTML email
99
+ getMjml(mode?) // MJML source
100
+ getReactEmail(mode?) // React Email .tsx source
101
+ getJson() // the template as a plain object
102
+ ```
103
+
104
+ `mode` is `"prune"` (default) or `"wrap"`, and only matters if you use ESP conditional visibility:
105
+
106
+ - **`"prune"`** evaluates conditions against the current preview context and outputs only the branches that match. Use it for a concrete send.
107
+ - **`"wrap"`** keeps every branch, wrapped in your ESP's conditional syntax. Use it when handing the HTML to an ESP that will do the evaluation itself.
108
+
109
+ They all return `null` when the canvas is empty, so check before using:
110
+
111
+ ```ts
112
+ const html = handle.getHtml();
113
+ if (!html) return; // nothing built yet
114
+ ```
115
+
116
+ `getJson()` returns the portable template format — `template_id`, `template_name`, `canvas`, `rows`, `schema_version`. Store it and pass it back via your adapter's `loadTemplate` to restore exactly.
117
+
118
+ ## Minimal usage Vue
119
+
120
+ ```vue
121
+ <script setup lang="ts">
122
+ import { EmailEditor } from "@maildeno/editor";
123
+ </script>
124
+
125
+ <template>
126
+ <EmailEditor />
127
+ </template>
128
+ ```
129
+
130
+ ## Props and events
131
+
132
+ | Prop | Type |
133
+ | --- | --- |
134
+ | `templateId` | `string` |
135
+ | `storageAdapter` | `EditorStorageAdapter` |
136
+ | `theme` | `{ primaryColor?, surfaceColor? }` |
137
+ | `capabilities` | `{ export?: Array<"html"\|"mjml"\|"react"\|"json"> }` |
138
+ | `onSendTestEmail` | `(payload) => Promise<void>` |
139
+ | `brandName` | `string` |
140
+ | `versions` | `boolean` |
141
+ | `assistant` | `AssistantMount` |
142
+
143
+ | Event | Payload |
144
+ | --- | --- |
145
+ | `@save` | `{ templateId: string \| null }` |
146
+
147
+ > **`@save`'s presence controls whether the Save button renders at all.** Bind a
148
+ > listener — `@save="..."` on the Vue component, or `onSave` in `init()`'s config
149
+ > object — and the Save button, save-status indicator, and autosave timer all
150
+ > appear. Omit it and the editor mounts **read-only**, useful for previews or
151
+ > guest embeds. (Vue compiles `@save="fn"` down to an `onSave` prop internally,
152
+ > so this is the same mechanism on both paths, not two separate features.) See
153
+ > [Persisting which template is open](#persisting-which-template-is-open) below.
154
+
155
+ Reading content out uses a template ref:
156
+
157
+ ```ts
158
+ const editor = ref();
159
+ editor.value.getHtml("prune");
160
+ editor.value.getMjml();
161
+ editor.value.getReactEmail();
162
+ editor.value.getJson();
163
+ ```
164
+
165
+
166
+ ## Feature reference
167
+
168
+ Everything below is identical across frameworks. Only the mounting differs.
169
+
170
+ ### The editor at a glance
171
+
172
+ - **Drag-and-drop block editor** — paragraph, heading, image, video, list, button, anchor, divider, spacer, menu, socials, plus custom blocks you register.
173
+ - **Four export formats** — HTML, MJML, React Email (`.tsx`), JSON.
174
+ - **ESP-aware conditional logic** — visibility rules compile to the right syntax for Klaviyo, Mailchimp, Braze, SFMC, HubSpot, Iterable, Handlebars and more.
175
+ - **Merge tags** with an in-editor picker.
176
+ - **Saved templates and saved rows** — reusable snippets and full documents.
177
+ - **Desktop/mobile styling** — per-block mobile overrides.
178
+ - **Undo/redo**, autosave draft recovery, and a preview with client-specific rendering checks.
179
+ - **Zero backend required** — defaults to `localStorage`; bring an adapter to use your own.
180
+
181
+
182
+ ### Storage adapter
183
+
184
+ The editor never talks to your backend directly. Implement this and it uses your storage for everything:
185
+
186
+ ```ts
187
+ import type { EditorStorageAdapter } from "@maildeno/editor";
188
+
189
+ const adapter: EditorStorageAdapter = {
190
+ // ── Templates ──────────────────────────────────────────────
191
+ async loadTemplate(templateId) {
192
+ if (!templateId) return null; // null = start blank
193
+ const res = await fetch(`/api/templates/${templateId}`);
194
+ if (!res.ok) return null;
195
+ const t = await res.json();
196
+ return { rows: t.rows, canvasStyles: t.canvasStyles, name: t.name };
197
+ },
198
+ async saveTemplate(snapshot, templateId) {
199
+ const res = await fetch(`/api/templates/${templateId ?? ""}`, {
200
+ method: templateId ? "PUT" : "POST",
201
+ body: JSON.stringify(snapshot),
202
+ });
203
+ return { templateId: (await res.json()).id }; // editor stamps this for later saves
204
+ },
205
+
206
+ // ── Optional: powers the "Saved templates" panel ───────────
207
+ // Return summaries, not full documents — listing shouldn't fetch every
208
+ // template's rows. Omit both and the panel says listing isn't supported.
209
+ async listTemplates() {
210
+ return fetch("/api/templates").then((r) => r.json());
211
+ // -> [{ templateId, name, updatedAt }]
212
+ },
213
+ async deleteTemplate(id) {
214
+ await fetch(`/api/templates/${id}`, { method: "DELETE" });
215
+ },
216
+
217
+ // ── Saved rows (reusable snippets) ─────────────────────────
218
+ // Optional second, read-only row library — an org's shared blocks.
219
+ // Shown in a "Shared" tab beside the user's own rows, and only when
220
+ // this returns something, so omitting it changes nothing. There is no
221
+ // save/rename/delete counterpart: curating a shared library is an admin
222
+ // concern the editor has no user model to express.
223
+ async listSystemSavedRows() {
224
+ return api.get("/org/saved-rows");
225
+ },
226
+
227
+ async listSavedRows() {
228
+ return fetch("/api/saved-rows").then((r) => r.json());
229
+ },
230
+ async saveSavedRow(row, name) {
231
+ return fetch("/api/saved-rows", {
232
+ method: "POST", body: JSON.stringify({ row, name }),
233
+ }).then((r) => r.json());
234
+ },
235
+ async deleteSavedRow(id) {
236
+ await fetch(`/api/saved-rows/${id}`, { method: "DELETE" });
237
+ },
238
+ async renameSavedRow(id, name) {
239
+ await fetch(`/api/saved-rows/${id}`, {
240
+ method: "PATCH", body: JSON.stringify({ name }),
241
+ });
242
+ },
243
+ // Synchronous — it runs during a drag, so it can't await. Read from
244
+ // whatever you already have client-side (e.g. your last listSavedRows result).
245
+ cloneSavedRowForCanvas(id) {
246
+ return structuredClone(rowCache.get(id) ?? null);
247
+ },
248
+
249
+ // ── Images ─────────────────────────────────────────────────
250
+ // Called when a user drops or picks an image. Return a public URL.
251
+ async uploadImage(file) {
252
+ const form = new FormData();
253
+ form.append("file", file);
254
+ const { url } = await fetch("/api/upload", { method: "POST", body: form })
255
+ .then((r) => r.json());
256
+ return url;
257
+ },
258
+ };
259
+ ```
260
+
261
+ Without an adapter, everything persists to `localStorage` — fine for demos, but images are stored as base64 data URIs, which will hit the ~5 MB quota quickly on image-heavy templates.
262
+
263
+ ### Partial adapters
264
+
265
+ Every method is optional. Anything you leave out falls back to the built-in
266
+ localStorage adapter, so you can override only the parts you need:
267
+
268
+ ```ts
269
+ // Upload images to your own storage; keep everything else local.
270
+ init({
271
+ storageAdapter: {
272
+ async uploadImage(file) {
273
+ const form = new FormData();
274
+ form.append("file", file);
275
+ const { url } = await fetch("/api/upload", { method: "POST", body: form })
276
+ .then((r) => r.json());
277
+ return url;
278
+ },
279
+ },
280
+ });
281
+ ```
282
+
283
+ The fallback is per-method, not per-area. If you implement `saveTemplate`
284
+ against your own backend but leave `listTemplates` out, the saved-templates
285
+ panel will list localStorage templates rather than yours — the editor warns
286
+ about that specific mismatch in development. Implement `listTemplates` and
287
+ `deleteTemplate` alongside `loadTemplate`/`saveTemplate` to keep them
288
+ consistent.
289
+
290
+ ### Sending email
291
+
292
+ The editor hands you `{ to, subject, html }` and stops there. Your ESP key must never reach the browser, so the send happens on your server:
293
+
294
+ ```ts
295
+ // client
296
+ onSendTestEmail: async ({ to, subject, html }) => {
297
+ await fetch("/api/send-test", {
298
+ method: "POST",
299
+ body: JSON.stringify({ to, subject, html }),
300
+ });
301
+ }
302
+ ```
303
+
304
+ ```ts
305
+ // server — Resend shown; Postmark/SendGrid are the same shape
306
+ import { Resend } from "resend";
307
+ const resend = new Resend(process.env.RESEND_API_KEY);
308
+
309
+ export async function POST(req) {
310
+ const { to, subject, html } = await req.json();
311
+ await resend.emails.send({ from: "you@yourdomain.com", to, subject, html });
312
+ }
313
+ ```
314
+
315
+ This is the **test-send** button only — one recipient, manual click. For a real campaign, pull the HTML yourself (`getHtml()`) and drive your own send to a list.
316
+
317
+ ### Theming
318
+
319
+ One hex re-themes the whole editor coherently:
320
+
321
+ ```ts
322
+ setTheme({ primary: "#6366f1" });
323
+ ```
324
+
325
+ Every surface reads from semantic tokens, so you can override just the parts
326
+ you care about without redefining the rest:
327
+
328
+ ```ts
329
+ setTheme({
330
+ // Core — everything else derives from these
331
+ primary: "#e11d48",
332
+ background: "#f8fafc",
333
+ surface: "#ffffff",
334
+ text: "#111827",
335
+ border: "#e5e7eb",
336
+
337
+ // Individual surfaces
338
+ headerBg: "#111827",
339
+ headerText: "#f9fafb",
340
+ sidebarBg: "#ffffff",
341
+ canvasBg: "#f1f5f9",
342
+ inputBg: "#ffffff",
343
+ inputText: "#111827",
344
+ overlayBg: "#ffffff", // dialogs, toasts, dropdowns, date picker
345
+ toolbarBg: "#ffffff", // floating + rich-text toolbars
346
+
347
+ // The Save / Update button
348
+ buttonPrimaryBg: "#e11d48",
349
+ buttonPrimaryText: "#ffffff",
350
+ buttonPrimaryHoverBg: "#be123c",
351
+
352
+ // Dark mode — has its own complete defaults, so override only what differs
353
+ dark: {
354
+ primary: "#fb7185",
355
+ headerBg: "#0b0f19",
356
+ buttonPrimaryText: "#1e1b4b",
357
+ },
358
+ });
359
+ ```
360
+
361
+ Dark mode activates when the editor element carries the `dark` class:
362
+
363
+ ```ts
364
+ handle.element.classList.toggle("dark");
365
+ ```
366
+
367
+ **Anything you leave out keeps its default**, so a partial theme is always
368
+ coherent rather than half-applied. Two things worth knowing:
369
+
370
+ - Set `onPrimary` (or `buttonPrimaryText`) when using a light brand colour, or
371
+ the primary button's label will be low-contrast against it.
372
+ - Severity tints for toasts and messages (`successBg`, `dangerFg`, …) have
373
+ separate dark defaults, so they don't leave pale panels sitting on a dark
374
+ surface.
375
+
376
+ Multiple editors on one page theme independently.
377
+
378
+
379
+ ### Extension points
380
+
381
+ All three are additive — no need to fork or edit built-ins.
382
+
383
+ ```ts
384
+ import { registerBlock, registerESPSyntax, registerMergeTags } from "@maildeno/editor";
385
+
386
+ // A custom block type
387
+ registerBlock({
388
+ name: "product-card",
389
+ label: "Product Card",
390
+ icon: "<svg …>",
391
+ schema: { /* default props */ },
392
+ renderCanvas: ProductCardCanvas, // Vue component shown in the editor
393
+ renderSettings: ProductCardPanel, // Vue component for the right panel
394
+ renderEmail: {
395
+ html: (props, ctx) => `<table>…</table>`,
396
+ mjml: (props, ctx) => `<mj-section>…</mj-section>`,
397
+ reactEmail: (props, ctx) => `<Section>…</Section>`,
398
+ },
399
+ });
400
+
401
+ // Conditional syntax for an ESP that isn't built in
402
+ registerESPSyntax("my-esp", {
403
+ wrapOpenTag: (expr) => `{% if ${expr} %}`,
404
+ wrapCloseTag: () => `{% endif %}`,
405
+ wrapMergeTag: (key, fallback) =>
406
+ fallback ? `{{ ${key} | default: "${fallback}" }}` : `{{ ${key} }}`,
407
+ });
408
+
409
+ // Extra merge tags in the picker
410
+ registerMergeTags([
411
+ { key: "customer.first_name" },
412
+ { key: "order.total" },
413
+ ]);
414
+ ```
415
+
416
+ Call these **before** the editor mounts.
417
+
418
+ ### Persisting which template is open
419
+
420
+ This requires `onSave` to have been passed to `init()` at mount time (or `@save`
421
+ bound on the Vue component) — that's what reveals the Save button in the first
422
+ place. `handle.on("save", ...)` added after mount subscribes to an event that
423
+ will never fire if `onSave` wasn't part of the original `init()` call.
424
+
425
+ ```ts
426
+ init({
427
+ container: "#editor",
428
+ onSave: ({ templateId }) => {
429
+ router.replace(`/editor/${templateId}`); // or your DB, or app state
430
+ },
431
+ });
432
+ ```
433
+
434
+ The editor doesn't own persisting *which* template is open beyond that — store
435
+ the id however your app already tracks routes or state, and pass it back as
436
+ `templateId` next time to reopen the same document.
437
+
438
+ ### Practical notes
439
+
440
+ - **The container needs a real height.** The editor fills its parent; `height: 100vh` or a sized flex child both work.
441
+ - **`transform`, `filter`, `perspective` or `will-change` on any ancestor** breaks `position: fixed` inside it — floating toolbars and pickers will land in the wrong place. Avoid them above the mount point.
442
+ - **Desktop only.** The editor shows a notice on small screens rather than attempting a mobile drag-and-drop UI.
443
+ - **Autosave** keeps a local draft, so a refresh mid-edit recovers. "New template" clears it deliberately.