@labnol/email-editor 0.0.0-stage → 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Amit Agarwal
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,189 @@
1
- # Temporary Holding Version
1
+ # @labnol/email-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 rich-text editor for composing email bodies in React, built on [Tiptap](https://tiptap.dev) 3. It writes email-safe HTML (inline styles, no classes) or Markdown, inserts `{{merge fields}}`, and uploads pasted, dropped and picked images through your own server.
4
+
5
+ ```bash
6
+ npm install @labnol/email-editor
7
+ ```
8
+
9
+ React 18 or 19 is a peer dependency. Tiptap comes with the package. The toolbar uses Google's [Material Symbols](https://fonts.google.com/icons), the icons Gmail and Google Docs use, built in under the Apache License 2.0 (see `licenses/`).
10
+
11
+ ## Usage
12
+
13
+ ```jsx
14
+ import '@labnol/email-editor/style.css';
15
+
16
+ import { EmailEditor } from '@labnol/email-editor';
17
+ import toast from 'react-hot-toast';
18
+
19
+ const uploadImage = async (file) => {
20
+ // Send the image to your own server and resolve to its public URL
21
+ const body = new FormData();
22
+ body.append('file', file);
23
+ const response = await fetch('/api/upload', { method: 'POST', body });
24
+ if (!response.ok) {
25
+ toast.error('Sorry, the image could not be uploaded.');
26
+ return null;
27
+ }
28
+ const { url } = await response.json();
29
+ return url;
30
+ };
31
+
32
+ export const Editor = ({ html, onChange }) => (
33
+ <EmailEditor
34
+ value={html}
35
+ onChange={onChange}
36
+ onUploadImage={uploadImage}
37
+ onError={(message) => toast.error(message)}
38
+ fields={['First Name', 'Email', 'Company', 'What is your first name?']}
39
+ placeholder='Write your email. Use {{First Name}} and other fields to personalize it.'
40
+ />
41
+ );
42
+ ```
43
+
44
+ ### Props
45
+
46
+ | Prop | Default | |
47
+ | ----------------------------------------------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
48
+ | `value` | `''` | The HTML (or Markdown) to show. When it changes to something the editor did not send, the editor loads it, so an HTML source view can edit the same value. |
49
+ | `onChange(value)` | | Called with the content after the user stops typing for `debounce` ms, and right away on blur and unmount. |
50
+ | `format` | `'html'` | `'html'` or `'markdown'`. Read once, when the editor is created. |
51
+ | `dir` | `'ltr'` | `'rtl'` for an editor used mainly in Arabic, Hebrew, Persian or Urdu: mirrors the toolbar, and paragraphs with no letters run right to left. Every paragraph still follows its own text. Read once. |
52
+ | `debounce` | `300` | Milliseconds. |
53
+ | `onUploadImage(file)` | | Upload an image and resolve to its public `http(s)` URL, or to `null` when you have already told the user why it failed. If it throws, `onError` gets the message. Without it, the image button is hidden and pasted or dropped images are ignored. |
54
+ | `onError(message)` | | Show a message to the user. Gets the image checks and upload failures. |
55
+ | `fields` | | Merge fields for the built-in **Fields** menu: strings, or `{ label, value }` when the inserted name differs from the label. One toolbar button however many there are; past six it adds a search box, and long names wrap to two lines. |
56
+ | `renderMarkers({ insertMarker, insertText, editor })` | | Render your own merge-field picker at the end of the toolbar instead of the built-in menu. `insertMarker('First Name')` inserts `{{First Name}}` with spaces around it. |
57
+ | `placeholder` | | Shown while the editor is empty. |
58
+ | `editable` | `true` | |
59
+ | `toolbar` | `DEFAULT_TOOLBAR` | Groups of item ids: `undo`, `redo`, `heading`, `bold`, `italic`, `underline`, `color`, `backgroundColor`, `bulletList`, `orderedList`, `align`, `more`, `link`, `image`, and `spacer`, which pushes the groups after it to the right. `hardBreak` (a line break, like Shift+Enter), `strike`, `blockquote`, `codeBlock`, `clear` and `rtl` can also be buttons of their own. Text direction (Auto, left-to-right, right-to-left) is in the `align` menu. |
60
+ | `moreItems` | `['hardBreak', 'strike', 'blockquote', 'codeBlock', 'clear']` | What the toolbar's **More** (⋯) menu holds: any of `hardBreak`, `blockquote`, `codeBlock`, `strike`, `underline`, `rtl` and `clear`. |
61
+ | `colors` | `DEFAULT_COLORS` | Swatches for text and background colour. |
62
+ | `maxImageSize` | 4 MB | In bytes. |
63
+ | `imageTypes` | PNG, JPEG, GIF, WebP | MIME types accepted for images. Not SVG by default: Gmail does not display it. |
64
+ | `resizableImages` | `true` | Drag handles on images. The size is saved as `width` and `height` attributes, which Outlook reads. |
65
+ | `autofocus` | `false` | |
66
+ | `extensions` | | Extra Tiptap extensions. Read once. |
67
+ | `className`, `style`, `ariaLabel` | | On the outer element and the editable area. |
68
+
69
+ ### Ref
70
+
71
+ ```jsx
72
+ const ref = useRef(null);
73
+ <EmailEditor ref={ref} … />;
74
+
75
+ ref.current.insertMarker('Email'); // insert {{Email}} at the cursor
76
+ ref.current.insertText('Hello');
77
+ ref.current.getValue(); // the current HTML or Markdown, without waiting for onChange
78
+ ref.current.flush(); // send a pending onChange now
79
+ ref.current.focus();
80
+ ref.current.editor; // the Tiptap editor
81
+ ```
82
+
83
+ ## Tooltips
84
+
85
+ Every toolbar button has a tooltip with its name. Tooltips appear after a short pause, move straight to the next button, show on keyboard focus too, and close on click or Escape. The usual keyboard shortcuts work (⌘B, ⌘I, ⌘U, ⌘Z and Tiptap's others) and buttons carry `aria-keyshortcuts` for screen readers, but the tooltips do not list them.
86
+
87
+ Tooltip colours: `--lee-tooltip-bg` and `--lee-tooltip-text`.
88
+
89
+ ## The HTML it writes
90
+
91
+ - Colours, background colours and alignment are inline `style` attributes; right-to-left text is `dir="rtl"`. Email clients ignore classes.
92
+ - Links open in a new tab: `<a target="_blank" rel="noopener noreferrer" href="…">`. Typing `example.com` in the link box saves `https://example.com`, and an email address saves `mailto:`.
93
+ - An empty line is `<p><br></p>`, because email clients collapse `<p></p>`. An empty editor sends `''`.
94
+ - A single `&nbsp;` between words becomes a space so lines can wrap.
95
+ - `<<First Name>>` markers are kept as text. Without help, the browser's HTML parser would read `<First Name>` as a tag and drop it.
96
+ - Images get `style="max-width: 100%; height: auto;"` and an empty `alt=""` (a file name such as IMG_2034.png means nothing to a reader).
97
+ - While an image uploads, a faded preview with a spinner shows where it will go. The preview is drawn over the document, not in it, so it never reaches `onChange` or the undo history; if the upload fails it disappears.
98
+
99
+ ### What it drops
100
+
101
+ The editor keeps only what its toolbar can make. When it loads stored HTML, it drops anything else: tables, `<div>` layouts, `<font>` tags, classes, and `data:` images (email clients block those, so pasted images are uploaded instead). Keep a separate HTML source view for full email templates.
102
+
103
+ ## Right-to-left languages
104
+
105
+ Each paragraph and heading takes its direction from its first letter, so an Arabic, Hebrew, Persian or Urdu paragraph runs right to left and an English one left to right, in the same email. Merge fields are skipped when deciding, so `{{First Name}} عزيزي` is right to left. Lists and quotes follow their first paragraph, so bullets and the quote bar sit on the correct side. In a right-to-left paragraph, right is the default alignment.
106
+
107
+ The HTML says so explicitly, because email clients handle `dir="rtl"` more reliably than `dir="auto"`:
108
+
109
+ ```html
110
+ <p>Hello {{First Name}},</p>
111
+ <p dir="rtl">مرحبا بكم في متجرنا</p>
112
+ <ul dir="rtl">
113
+ <li dir="rtl">إرجاع مجاني</li>
114
+ </ul>
115
+ ```
116
+
117
+ A left-to-right editor writes no `dir` on left-to-right paragraphs. A right-to-left editor (`dir='rtl'`) writes `dir` on every block, since the email has no wrapper to inherit it from.
118
+
119
+ To override a paragraph, open the alignment menu and pick **Left-to-right** or **Right-to-left**; the choice sticks as the text changes. **Auto** goes back to following the text. Stored HTML whose `dir` disagrees with its text is treated as a choice and kept.
120
+
121
+ A stored email gets its `dir` attributes the first time it is edited and saved. Markdown has no way to store direction.
122
+
123
+ ## Markdown
124
+
125
+ ```jsx
126
+ <EmailEditor format='markdown' value={markdown} onChange={setMarkdown} />
127
+ ```
128
+
129
+ `value` and `onChange` carry Markdown. Markdown cannot store colours, underline, alignment, text direction or image sizes, so those toolbar items are hidden (`DEFAULT_MARKDOWN_TOOLBAR`). Merge fields stay as `{{First Name}}`.
130
+
131
+ ## Theming
132
+
133
+ The stylesheet is plain CSS and the editor does not need Tailwind. It is not in a cascade layer, so in an app that does use Tailwind it wins over Tailwind's preflight. Every class starts with `lee-`. The toolbar measures itself as the editor resizes, so it stays on one row as long as it can: when space runs short, **Link** and **Image** show only their icons first (they are familiar), and **Fields** keeps its label longest. When the toolbar has to wrap anyway, as in a narrow sidebar, every label comes back and the group dividers go.
134
+
135
+ The editor draws no outer border, shadow or focus ring, and nothing around it lights up while typing. Put it in a container that draws the frame you want; its corners follow the container's `border-radius`. For example:
136
+
137
+ ```css
138
+ .email-body {
139
+ border: 1px solid #e5e5e5;
140
+ border-radius: 10px;
141
+ }
142
+ ```
143
+
144
+ The colours are neutral greys with a graphite accent. Override the custom properties on `.lee-editor`:
145
+
146
+ ```css
147
+ .lee-editor {
148
+ --lee-text: #171717;
149
+ --lee-icon: #525252; /* toolbar icons */
150
+ --lee-border: #e5e5e5; /* the line under the toolbar, menu borders */
151
+ --lee-hover: #f0f0f0;
152
+ --lee-active: #ededed; /* pressed toolbar button */
153
+ --lee-active-text: #171717;
154
+ --lee-focus: #171717; /* keyboard focus outline, Apply button */
155
+ --lee-link: #1155cc; /* Gmail's link colour, which recipients see */
156
+ --lee-font-size: 15px;
157
+ --lee-min-height: 14rem;
158
+ --lee-max-height: 28rem; /* the content scrolls past this */
159
+ }
160
+ ```
161
+
162
+ ## Helpers
163
+
164
+ `normalizeInput(html)`, `normalizeOutput(html)`, `isEmptyHtml(html)`, `markerText(name)`, `validateImage(file, { maxSize })`, `readAsDataURL(file)` and `isHttpUrl(url)` are exported for code that handles the same HTML outside the editor.
165
+
166
+ ## Developing
167
+
168
+ ```bash
169
+ npm install
170
+ npm run dev # the example page, using the source
171
+ npm run lint
172
+ npm test # unit tests for the helpers
173
+ npm run test:browser # builds, then runs the example page in Chromium with Playwright
174
+ ```
175
+
176
+ The browser tests need Playwright's Chromium (`npx playwright install chromium`). To use another Chromium, set `CHROMIUM_PATH`.
177
+
178
+ ## Publishing
179
+
180
+ ```bash
181
+ npm version patch
182
+ npm publish --access public
183
+ ```
184
+
185
+ `prepublishOnly` runs lint, the unit tests and the browser tests first.
186
+
187
+ ## License
188
+
189
+ MIT. The Material Symbols icons are © Google, under the Apache License 2.0: `licenses/material-symbols.txt`.