@mzeahmed/rich-editor 0.0.0-stage → 0.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/CHANGELOG.md +65 -0
- package/LICENSE +21 -0
- package/README.md +301 -2
- package/dist/Editor.d.ts +273 -0
- package/dist/Editor.js +959 -0
- package/dist/EmojiPicker.d.ts +33 -0
- package/dist/EmojiPicker.js +268 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +5 -0
- package/dist/messages.d.ts +61 -0
- package/dist/messages.js +111 -0
- package/dist/security.d.ts +20 -0
- package/dist/security.js +124 -0
- package/dist/style.css +486 -0
- package/dist/styles.d.ts +22 -0
- package/dist/styles.js +515 -0
- package/dist/types.d.ts +28 -0
- package/dist/types.js +1 -0
- package/package.json +60 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented in this file.
|
|
4
|
+
|
|
5
|
+
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project
|
|
6
|
+
adheres to [Semantic Versioning](https://semver.org/). While the version is `0.x`, a minor version
|
|
7
|
+
may contain breaking changes; they are always listed here.
|
|
8
|
+
|
|
9
|
+
Before a release, the pending entries below `[Unreleased]` are moved under a heading
|
|
10
|
+
`## [x.y.z] - YYYY-MM-DD` (see [RELEASING.md](./RELEASING.md)).
|
|
11
|
+
|
|
12
|
+
## [Unreleased]
|
|
13
|
+
|
|
14
|
+
## [0.1.0] - 2026-11-20
|
|
15
|
+
|
|
16
|
+
First public release.
|
|
17
|
+
|
|
18
|
+
### Added
|
|
19
|
+
|
|
20
|
+
- `Editor.mount()` and `Editor.init()` turn `<textarea>` elements into rich text editors based on
|
|
21
|
+
`contenteditable`; the textarea keeps the editor's HTML as its value.
|
|
22
|
+
- Options: `toolbar` (`always`, `toggle`, `focus`, `never`), `footer`, `minHeight`, `maxHeight`,
|
|
23
|
+
`emoji`, `mention`, `locale`, `styles`, `onChange`, plus `selector` / `exclude` for `init()`.
|
|
24
|
+
`data-mzre-toolbar`, `data-mzre-min-height` and `data-mzre-max-height` override them per textarea.
|
|
25
|
+
- `onChange({html, text, isEmpty})`, called at mount and on every change (typing, toolbar,
|
|
26
|
+
mention), for example to enable or disable a "publish" button.
|
|
27
|
+
- `@mentions`: a suggestion bubble fed by your `searchUsers()` integration. It closes with its
|
|
28
|
+
**×** button, with Escape, or by clicking outside. Selecting a user inserts
|
|
29
|
+
`<a class="mention" data-user-id="…">`.
|
|
30
|
+
- Emoji picker, inline in the editor (`emoji: true`) or standalone (`EmojiPicker.open()`, which
|
|
31
|
+
returns a promise). Emoji data is loaded on first open, as a separate file per language.
|
|
32
|
+
- English (default) and French interface and emoji data: `locale`, `setEditorLocale()`,
|
|
33
|
+
`messagesEn`, `messagesFr`; every text can be overridden with `setEditorMessages()` or
|
|
34
|
+
`integrations.messages`.
|
|
35
|
+
- Strict Content-Security-Policy support: a `@mzeahmed/rich-editor/style.css` stylesheet,
|
|
36
|
+
`setEditorStyles({inject, nonce})` to turn injection off or to set a CSP nonce, and no
|
|
37
|
+
`style="…"` attribute or inline event handler in the produced markup.
|
|
38
|
+
- TypeScript declarations, ESM build, and `npm run check:package` (checks that the built package
|
|
39
|
+
imports in Node and ships its stylesheet), run before every publication.
|
|
40
|
+
|
|
41
|
+
### Security
|
|
42
|
+
|
|
43
|
+
- Names, ids, URLs and localized texts are escaped before being rendered; avatar and profile URLs
|
|
44
|
+
must be `http(s)` or relative, and a profile path starting with `//` can never point to another
|
|
45
|
+
site.
|
|
46
|
+
- The HTML found in the textarea at mount time is sanitized with an allow-list of tags and
|
|
47
|
+
attributes; scripts, event handlers, `javascript:` links and images are removed.
|
|
48
|
+
|
|
49
|
+
### Accessibility
|
|
50
|
+
|
|
51
|
+
- The writing area has the `textbox` role and an accessible name.
|
|
52
|
+
- The mention bubble is fully usable from the keyboard without moving focus out of the writing
|
|
53
|
+
area (arrow keys, `Home` / `End`, `Enter` / `Tab`, `Escape`): a labelled `region` with a
|
|
54
|
+
`listbox` of `option`s, `aria-activedescendant`, and polite announcements of the number of
|
|
55
|
+
suggestions. An `axe-core` audit reports no violation with the bubble open.
|
|
56
|
+
- The toolbar's text-style menu has an accessible name, and the character counter meets the
|
|
57
|
+
contrast requirement.
|
|
58
|
+
|
|
59
|
+
### Known limitations
|
|
60
|
+
|
|
61
|
+
- No way to unmount an editor yet.
|
|
62
|
+
- The language and the style injection are page-wide settings.
|
|
63
|
+
- Only English and French are bundled.
|
|
64
|
+
- Formatting relies on `document.execCommand`.
|
|
65
|
+
- Not yet tested with screen readers (NVDA, JAWS, VoiceOver), nor in Firefox and Safari.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 mzeahmed
|
|
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,302 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mzeahmed/rich-editor
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A small, framework-agnostic rich text editor built on `contenteditable`, with **@mentions**, a
|
|
4
|
+
built-in **emoji picker**, strict-CSP support and keyboard accessibility.
|
|
5
|
+
|
|
6
|
+
> **Status: early release (0.x).** The API may still change between minor versions.
|
|
7
|
+
|
|
8
|
+
- Turns any `<textarea>` into an editor and keeps its value in sync (HTML).
|
|
9
|
+
- Optional toolbar, footer (character counter, HTML view, copy, clear), inline emoji button.
|
|
10
|
+
- `@mentions` with a suggestion bubble that is fully usable with the keyboard.
|
|
11
|
+
- Interface and emojis in English or French, every text can be overridden.
|
|
12
|
+
- Works under a strict Content-Security-Policy (no inline styles required).
|
|
13
|
+
- Safe to import on the server (SSR); the editor itself needs a browser DOM.
|
|
14
|
+
- Escapes everything it renders and sanitizes the HTML it loads. No runtime dependency other than
|
|
15
|
+
`emojibase-data`, which is loaded lazily.
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install @mzeahmed/rich-editor
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Quick start
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import Editor from '@mzeahmed/rich-editor';
|
|
27
|
+
|
|
28
|
+
const textarea = document.querySelector<HTMLTextAreaElement>('#message')!;
|
|
29
|
+
|
|
30
|
+
Editor.mount(textarea, {
|
|
31
|
+
toolbar: 'always',
|
|
32
|
+
emoji: true,
|
|
33
|
+
});
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The `<textarea>` is hidden and replaced by the editor. Its `value` always holds the editor's
|
|
37
|
+
**HTML**, so it keeps working inside a regular `<form>`.
|
|
38
|
+
|
|
39
|
+
Mount every textarea of a page, or a selection:
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
import Editor from '@mzeahmed/rich-editor';
|
|
43
|
+
|
|
44
|
+
Editor.init({selector: 'textarea.richtext', exclude: '.plain', toolbar: 'focus'});
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
`mount()` and `init()` ignore a textarea that is already mounted. There is currently no way to
|
|
48
|
+
unmount an editor (see [Limitations](#limitations)).
|
|
49
|
+
|
|
50
|
+
## Options
|
|
51
|
+
|
|
52
|
+
Passed as the second argument of `Editor.mount()` / `Editor.init()`.
|
|
53
|
+
|
|
54
|
+
| Option | Type | Default | Description |
|
|
55
|
+
| --- | --- | --- | --- |
|
|
56
|
+
| `selector` | `string` | `'textarea'` | CSS selector of the textareas to mount (`init()` only). |
|
|
57
|
+
| `exclude` | `string` | – | CSS selector of textareas to skip (`init()` only). |
|
|
58
|
+
| `toolbar` | `'always' \| 'toggle' \| 'focus' \| 'never'` | `'always'` | Formatting toolbar: always visible, behind a toggle button, shown on focus, or absent. |
|
|
59
|
+
| `footer` | `boolean` | `true` | Footer with the character counter and the HTML / Clear / Copy buttons. |
|
|
60
|
+
| `minHeight` | `string` | `'160px'` | Minimum height of the writing area (any CSS length). |
|
|
61
|
+
| `maxHeight` | `string` | – | Maximum height before the area scrolls. |
|
|
62
|
+
| `emoji` | `boolean` | `false` | Adds an inline emoji button that opens the built-in picker. |
|
|
63
|
+
| `mention` | `boolean` | `false` | Enables `@mentions`. Requires `integrations.mentions`. |
|
|
64
|
+
| `locale` | `'en' \| 'fr'` | `'en'` | Language of the interface and of the emojis. Page-wide setting. |
|
|
65
|
+
| `styles` | `{inject?: boolean; nonce?: string}` | `{inject: true}` | How styles reach the page. See [Styles and CSP](#styles-and-csp). Page-wide setting. |
|
|
66
|
+
| `onChange` | `(change: EditorChange) => void` | – | Called on every change and once at mount. |
|
|
67
|
+
|
|
68
|
+
A few options can also be set per textarea with data attributes, which take precedence:
|
|
69
|
+
`data-mzre-toolbar="toggle"`, `data-mzre-min-height="100px"`, `data-mzre-max-height="400px"`.
|
|
70
|
+
|
|
71
|
+
The third argument carries the [integrations](#mentions) (`mentions`, `messages`).
|
|
72
|
+
|
|
73
|
+
## Reading the content
|
|
74
|
+
|
|
75
|
+
The textarea's `value` is updated on every change. For finer control, use `onChange`:
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
import Editor, {type EditorChange} from '@mzeahmed/rich-editor';
|
|
79
|
+
|
|
80
|
+
declare const textarea: HTMLTextAreaElement;
|
|
81
|
+
declare const publishButton: HTMLButtonElement;
|
|
82
|
+
|
|
83
|
+
Editor.mount(textarea, {
|
|
84
|
+
onChange: ({html, text, isEmpty}: EditorChange) => {
|
|
85
|
+
publishButton.disabled = isEmpty;
|
|
86
|
+
console.log(html, text);
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`onChange` receives `{html, text, isEmpty}`. It is called once at mount (so you can set the initial
|
|
92
|
+
state of a "publish" button), then after every typing, toolbar action or inserted mention. The
|
|
93
|
+
editor never touches any element outside of itself.
|
|
94
|
+
|
|
95
|
+
> The HTML written to the textarea comes from a browser. **Sanitize it on your server** before
|
|
96
|
+
> storing or displaying it, as you would with any user-submitted HTML.
|
|
97
|
+
|
|
98
|
+
## Mentions
|
|
99
|
+
|
|
100
|
+
Set `mention: true` and provide the `mentions` integration. The editor asks you for users, you
|
|
101
|
+
decide where they come from:
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
import Editor, {type EditorMentionIntegration, type EditorUser} from '@mzeahmed/rich-editor';
|
|
105
|
+
|
|
106
|
+
declare const textarea: HTMLTextAreaElement;
|
|
107
|
+
|
|
108
|
+
const mentions: EditorMentionIntegration = {
|
|
109
|
+
// Called while a search is running: show a busy state if you want one.
|
|
110
|
+
loader: {
|
|
111
|
+
freezeElement: (element) => element.setAttribute('aria-busy', 'true'),
|
|
112
|
+
unfreezeElement: () =>
|
|
113
|
+
document
|
|
114
|
+
.querySelectorAll('.mzre-mentions-dropdown[aria-busy="true"]')
|
|
115
|
+
.forEach((element) => element.removeAttribute('aria-busy')),
|
|
116
|
+
},
|
|
117
|
+
// Return RAW text: the editor escapes names, ids and URLs itself.
|
|
118
|
+
searchUsers: async (term): Promise<EditorUser[]> => {
|
|
119
|
+
const response = await fetch(`/api/members?q=${encodeURIComponent(term)}`);
|
|
120
|
+
|
|
121
|
+
return (await response.json()) as EditorUser[];
|
|
122
|
+
},
|
|
123
|
+
// How a user id is written into the mention (`data-user-id`).
|
|
124
|
+
encodeUserId: (id) => id,
|
|
125
|
+
// Debounce the search while the user is typing.
|
|
126
|
+
debounce: (callback, delay) => {
|
|
127
|
+
let timer: number | undefined;
|
|
128
|
+
|
|
129
|
+
return (...args) => {
|
|
130
|
+
window.clearTimeout(timer);
|
|
131
|
+
timer = window.setTimeout(() => callback(...args), delay);
|
|
132
|
+
};
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
Editor.mount(textarea, {mention: true}, {mentions});
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
An `EditorUser` is `{ID: string | number, avatarUrl: string, firstName: string, lastName: string,
|
|
140
|
+
profileUrl: string}`.
|
|
141
|
+
|
|
142
|
+
**How it behaves**
|
|
143
|
+
|
|
144
|
+
- Typing `@`, then at least two letters opens a bubble with the matching users.
|
|
145
|
+
- Choosing a user inserts `<a class="mention" href="/path/of/profile" data-user-id="…"
|
|
146
|
+
target="_blank">First Last</a>`. Only the **path** of `profileUrl` is kept in the link.
|
|
147
|
+
- The bubble closes when you choose a user, press Space, Enter or Escape, click its **×** button, or
|
|
148
|
+
click anywhere outside of it.
|
|
149
|
+
- Users without a usable `profileUrl` (`http(s)` or relative) are not offered. An avatar that is not
|
|
150
|
+
an `http(s)` URL is replaced by the user's initials.
|
|
151
|
+
|
|
152
|
+
## Emoji picker
|
|
153
|
+
|
|
154
|
+
With `emoji: true`, an emoji button is added to the editor. The picker is also available on its own:
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
import {EmojiPicker} from '@mzeahmed/rich-editor';
|
|
158
|
+
|
|
159
|
+
await EmojiPicker.open({
|
|
160
|
+
onSelect: (emoji) => console.log(emoji),
|
|
161
|
+
title: 'Pick one', // optional, defaults to the localized text
|
|
162
|
+
closeLabel: 'Close', // optional
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
EmojiPicker.close();
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`open()` shows the dialog immediately and returns a promise that resolves once the emojis are
|
|
169
|
+
displayed (or, if loading fails, once the error message is displayed: it never rejects). The emoji
|
|
170
|
+
data (~700 KB per language) is loaded **on first open** as a separate file by your bundler, so
|
|
171
|
+
importing the package stays light. `EmojiPicker.destroy()` removes the dialog from the page.
|
|
172
|
+
|
|
173
|
+
## Localization
|
|
174
|
+
|
|
175
|
+
The interface and the emoji data are in English by default. French is built in:
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
import Editor, {messagesFr, setEditorLocale, setEditorMessages} from '@mzeahmed/rich-editor';
|
|
179
|
+
|
|
180
|
+
declare const textarea: HTMLTextAreaElement;
|
|
181
|
+
|
|
182
|
+
// For one mount…
|
|
183
|
+
Editor.mount(textarea, {locale: 'fr'});
|
|
184
|
+
|
|
185
|
+
// …or for the whole page.
|
|
186
|
+
setEditorLocale('fr');
|
|
187
|
+
|
|
188
|
+
// Override individual texts (escaped by the editor, never inserted as HTML).
|
|
189
|
+
setEditorMessages({bold: 'Bold (Ctrl+B)', placeholder: 'Write your message…'});
|
|
190
|
+
|
|
191
|
+
// Same thing, through the integrations argument.
|
|
192
|
+
Editor.mount(textarea, {}, {messages: {close: 'Fermer'}});
|
|
193
|
+
|
|
194
|
+
console.log(Object.keys(messagesFr));
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
`messagesEn` and `messagesFr` list every text (toolbar, footer, emoji picker, mention bubble).
|
|
198
|
+
The language is a **page-wide setting**: the last `mount()`, `init()` or `setEditorLocale()` wins,
|
|
199
|
+
for all editors and for the emoji picker. Only `en` and `fr` are bundled; to add a language, pass
|
|
200
|
+
all the texts through `setEditorMessages()` (emoji labels stay in English or French).
|
|
201
|
+
|
|
202
|
+
## Styles and CSP
|
|
203
|
+
|
|
204
|
+
By default the editor injects its own styles into `<head>` (two `<style>` elements). A Content
|
|
205
|
+
Security Policy without `'unsafe-inline'` blocks them. Two options:
|
|
206
|
+
|
|
207
|
+
```ts
|
|
208
|
+
import '@mzeahmed/rich-editor/style.css';
|
|
209
|
+
import {setEditorStyles} from '@mzeahmed/rich-editor';
|
|
210
|
+
|
|
211
|
+
// 1. Load the stylesheet yourself and turn injection off (no <style> element is added).
|
|
212
|
+
setEditorStyles({inject: false});
|
|
213
|
+
|
|
214
|
+
// 2. Or keep the injection and give it the nonce of your CSP (style-src 'nonce-…').
|
|
215
|
+
setEditorStyles({inject: true, nonce: document.querySelector<HTMLMetaElement>('meta[name="csp-nonce"]')?.content});
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
The same can be passed on mount: `Editor.mount(textarea, {styles: {inject: false}})`.
|
|
219
|
+
|
|
220
|
+
The markup produced by the editor contains **no `style="…"` attribute and no inline event
|
|
221
|
+
handler**. It was verified in a browser under `default-src 'none'; script-src 'self';
|
|
222
|
+
style-src 'self'` (no violation); with the default injection and no nonce, that policy blocks the
|
|
223
|
+
styles. If your CSP restricts `img-src`, allow the origin of your users' avatars.
|
|
224
|
+
|
|
225
|
+
## Security
|
|
226
|
+
|
|
227
|
+
- **Output escaping.** Names, ids, URLs and every localized text are escaped before being rendered.
|
|
228
|
+
`searchUsers()` must return **raw** text, never pre-escaped text (it would be displayed escaped
|
|
229
|
+
twice).
|
|
230
|
+
- **URLs.** Avatars and profile links must be `http(s)` or relative. `javascript:`, `data:` and
|
|
231
|
+
similar schemes are refused. A profile path starting with `//` can never point to another site.
|
|
232
|
+
- **Initial content.** The HTML found in the textarea when the editor is mounted is sanitized with an
|
|
233
|
+
allow-list: `a`, `b`, `blockquote`, `br`, `code`, `div`, `em`, `h2`, `h3`, `i`, `li`, `ol`, `p`,
|
|
234
|
+
`pre`, `s`, `span`, `strike`, `strong`, `u`, `ul`. Links keep `http(s):`, `mailto:`, `tel:`,
|
|
235
|
+
site-relative paths and anchors; the only style kept is `text-align`. Scripts, event handlers
|
|
236
|
+
(`onerror`…), `javascript:` links, images and unknown tags are removed (unknown tags keep their text).
|
|
237
|
+
Mentions are preserved.
|
|
238
|
+
- **Output.** The HTML produced by the editor is user input. Sanitize it on the server.
|
|
239
|
+
|
|
240
|
+
## Accessibility
|
|
241
|
+
|
|
242
|
+
The writing area has the `textbox` role (multiline). Its accessible name comes from the textarea's
|
|
243
|
+
`aria-label`, or else its `placeholder`: give your fields an explicit name.
|
|
244
|
+
|
|
245
|
+
The mention bubble is driven entirely from the keyboard **without moving focus out of the writing
|
|
246
|
+
area** (a listbox linked to the field through `aria-activedescendant`):
|
|
247
|
+
|
|
248
|
+
| Key | Effect |
|
|
249
|
+
| --- | --- |
|
|
250
|
+
| `@` then 2 letters | Opens the bubble. Screen readers announce the number of suggestions. |
|
|
251
|
+
| `↓` / `↑` | Choose the next / previous suggestion (wraps around). |
|
|
252
|
+
| `Home` / `End` | First / last suggestion, once one is chosen (otherwise they move the caret). |
|
|
253
|
+
| `Enter` or `Tab` | Insert the chosen suggestion. With no choice, they keep their usual role. |
|
|
254
|
+
| `Escape` | Closes the bubble without touching the text (and without closing a surrounding modal). |
|
|
255
|
+
|
|
256
|
+
While the bubble is open, the writing area carries `aria-autocomplete`, `aria-controls` and
|
|
257
|
+
`aria-activedescendant`; the bubble is a labelled `region` containing a `listbox` of `option`s, plus
|
|
258
|
+
a polite live region for announcements. An `axe-core` audit (WCAG 2.1 A/AA and best practices) with
|
|
259
|
+
the bubble open and one suggestion chosen reports no violation.
|
|
260
|
+
|
|
261
|
+
> Automated audits only catch part of the problems. The package has **not** been tested yet with
|
|
262
|
+
> NVDA, JAWS or VoiceOver.
|
|
263
|
+
|
|
264
|
+
## Server-side rendering and compatibility
|
|
265
|
+
|
|
266
|
+
- **Importing** the package in Node (SSR, tests) is safe: it touches neither the DOM nor JSON at
|
|
267
|
+
evaluation time. Call `mount()` / `init()` / `EmojiPicker.open()` in the browser only.
|
|
268
|
+
- **Format:** ESM only, with TypeScript declarations. `@mzeahmed/rich-editor/style.css` is the
|
|
269
|
+
stylesheet.
|
|
270
|
+
- **Bundlers:** the emoji data is loaded with a dynamic `import()` of JSON files from
|
|
271
|
+
`emojibase-data`; bundlers such as Vite, webpack, Rollup or esbuild turn them into separate
|
|
272
|
+
chunks. Verified with Vite.
|
|
273
|
+
- **Browsers:** requires `contenteditable` and, for formatting commands, `document.execCommand`
|
|
274
|
+
(deprecated by the standards but still supported by evergreen browsers). Verified in Chromium and
|
|
275
|
+
in jsdom; Firefox and Safari have not been tested yet.
|
|
276
|
+
|
|
277
|
+
## Limitations
|
|
278
|
+
|
|
279
|
+
- No `destroy()` / unmount method for an editor yet.
|
|
280
|
+
- The language and the style injection are **page-wide** settings, not per editor.
|
|
281
|
+
- Only English and French are bundled.
|
|
282
|
+
- Formatting relies on `document.execCommand`.
|
|
283
|
+
- The footer's "HTML", "Clear" and "Copy" buttons are part of the footer: hide them all with
|
|
284
|
+
`footer: false`.
|
|
285
|
+
|
|
286
|
+
## Development
|
|
287
|
+
|
|
288
|
+
```bash
|
|
289
|
+
npm ci
|
|
290
|
+
npm test # unit and DOM tests (Vitest + jsdom)
|
|
291
|
+
npm run build # tsc + dist/style.css
|
|
292
|
+
npm run check:package # imports dist in Node, checks style.css and the exports
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
`npm pack` runs the build and `check:package` automatically (`prepack`).
|
|
296
|
+
|
|
297
|
+
Changes are listed in [CHANGELOG.md](./CHANGELOG.md). Releases are published from a version tag, with
|
|
298
|
+
npm provenance: see [RELEASING.md](./RELEASING.md).
|
|
299
|
+
|
|
300
|
+
## License
|
|
301
|
+
|
|
302
|
+
[MIT](./LICENSE)
|
package/dist/Editor.d.ts
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standalone rich text editor.
|
|
3
|
+
* Automatically replaces <textarea> elements with an enhanced contenteditable editor.
|
|
4
|
+
*
|
|
5
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6
|
+
* BASIC USAGE
|
|
7
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
8
|
+
*
|
|
9
|
+
* 1) Every <textarea> on the page
|
|
10
|
+
* Editor.init();
|
|
11
|
+
*
|
|
12
|
+
* 2) Targeted CSS selector
|
|
13
|
+
* Editor.init({ selector: '.richtext' });
|
|
14
|
+
*
|
|
15
|
+
* 3) Exclude some textareas
|
|
16
|
+
* Editor.init({ exclude: '.no-editor' });
|
|
17
|
+
*
|
|
18
|
+
* 4) Mount on a specific element (dynamic DOM)
|
|
19
|
+
* Editor.mount('#my-textarea');
|
|
20
|
+
* Editor.mount(textareaElement);
|
|
21
|
+
*
|
|
22
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
23
|
+
* TOOLBAR OPTIONS
|
|
24
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
25
|
+
*
|
|
26
|
+
* toolbar: 'always' → toolbar always visible (default)
|
|
27
|
+
* Editor.init({ toolbar: 'always' });
|
|
28
|
+
*
|
|
29
|
+
* toolbar: 'focus' → toolbar shown only while the field is focused
|
|
30
|
+
* Editor.init({ toolbar: 'focus' });
|
|
31
|
+
*
|
|
32
|
+
* toolbar: 'toggle' → a "Formatting" button shows/hides the toolbar
|
|
33
|
+
* Editor.init({ toolbar: 'toggle' });
|
|
34
|
+
*
|
|
35
|
+
* toolbar: 'never' → no toolbar (plain rich input field)
|
|
36
|
+
* Editor.init({ toolbar: 'never' });
|
|
37
|
+
*
|
|
38
|
+
* Per-textarea override through a data attribute:
|
|
39
|
+
* <textarea data-mzre-toolbar="focus"></textarea>
|
|
40
|
+
*
|
|
41
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
42
|
+
* FOOTER (character counter + HTML / Clear / Copy buttons)
|
|
43
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
44
|
+
*
|
|
45
|
+
* Hide the footer (useful for embedded fields, e.g. messaging):
|
|
46
|
+
* Editor.mount('#msg-textarea', { footer: false });
|
|
47
|
+
*
|
|
48
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
49
|
+
* HEIGHT OF THE WRITING AREA
|
|
50
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
51
|
+
*
|
|
52
|
+
* Through the JS options:
|
|
53
|
+
* Editor.mount('#my-textarea', { minHeight: '80px', maxHeight: '300px' });
|
|
54
|
+
*
|
|
55
|
+
* Through data attributes on the <textarea> (they take precedence over the JS options):
|
|
56
|
+
* <textarea data-mzre-min-height="60px" data-mzre-max-height="200px"></textarea>
|
|
57
|
+
*
|
|
58
|
+
* When maxHeight is set, overflow-y: auto is enabled automatically.
|
|
59
|
+
*
|
|
60
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
61
|
+
* EMOJI
|
|
62
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
63
|
+
*
|
|
64
|
+
* Adds an inline 😊 button to the writing area. The picker is provided by the package
|
|
65
|
+
* (no modal to prepare); its data is loaded on first open.
|
|
66
|
+
*
|
|
67
|
+
* Editor.mount('#editor', { emoji: true });
|
|
68
|
+
*
|
|
69
|
+
* Combined with no toolbar (post/comment field style):
|
|
70
|
+
* Editor.mount('#post-textarea', {
|
|
71
|
+
* toolbar: 'never',
|
|
72
|
+
* footer: false,
|
|
73
|
+
* emoji: true,
|
|
74
|
+
* });
|
|
75
|
+
*
|
|
76
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
77
|
+
* MENTIONS
|
|
78
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
79
|
+
*
|
|
80
|
+
* Enables assisted @user mentions (requires integrations.mentions):
|
|
81
|
+
* · Typing @ → user search bubble (integrations.mentions.searchUsers)
|
|
82
|
+
* · Selection → inserts <a class="mention" href="/profile" data-user-id="…">First Last</a>
|
|
83
|
+
* · Closes on Space / Escape / Enter, with the cross, or by clicking outside
|
|
84
|
+
*
|
|
85
|
+
* Simple activation:
|
|
86
|
+
* Editor.mount('#editor', { mention: true }, { mentions: … });
|
|
87
|
+
*
|
|
88
|
+
* Full combination (publishing form style), with a "publish" button disabled
|
|
89
|
+
* while the field is empty (onChange is also called once at mount):
|
|
90
|
+
* Editor.mount('#post-textarea', {
|
|
91
|
+
* toolbar: 'never',
|
|
92
|
+
* footer: false,
|
|
93
|
+
* emoji: true,
|
|
94
|
+
* mention: true,
|
|
95
|
+
* onChange: ({ isEmpty }) => { publishButton.disabled = isEmpty; },
|
|
96
|
+
* }, { mentions: … });
|
|
97
|
+
*
|
|
98
|
+
* Comment combination:
|
|
99
|
+
* Editor.mount('#comment-textarea', {
|
|
100
|
+
* toolbar: 'never',
|
|
101
|
+
* footer: false,
|
|
102
|
+
* emoji: true,
|
|
103
|
+
* mention: true,
|
|
104
|
+
* });
|
|
105
|
+
*
|
|
106
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
107
|
+
* LANGUAGE
|
|
108
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
109
|
+
*
|
|
110
|
+
* Interface and emojis in English by default; { locale: 'fr' } (or setEditorLocale('fr')) for
|
|
111
|
+
* French. A text can be overridden: integrations.messages = { close: 'Dismiss' }.
|
|
112
|
+
*
|
|
113
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
114
|
+
* COMPLETE USE CASES
|
|
115
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
116
|
+
*
|
|
117
|
+
* A) Rich content editor (article, long description)
|
|
118
|
+
* Editor.init({
|
|
119
|
+
* selector: 'textarea.rich-content',
|
|
120
|
+
* toolbar: 'always',
|
|
121
|
+
* minHeight: '300px',
|
|
122
|
+
* });
|
|
123
|
+
*
|
|
124
|
+
* B) Compact comment editor (toolbar on focus)
|
|
125
|
+
* Editor.init({
|
|
126
|
+
* selector: 'textarea.comment',
|
|
127
|
+
* toolbar: 'focus',
|
|
128
|
+
* minHeight: '80px',
|
|
129
|
+
* maxHeight: '200px',
|
|
130
|
+
* footer: false,
|
|
131
|
+
* });
|
|
132
|
+
*
|
|
133
|
+
* C) Messaging input field (no toolbar, no footer, fixed height)
|
|
134
|
+
* Editor.mount('#messaging-textarea', {
|
|
135
|
+
* toolbar: 'never',
|
|
136
|
+
* footer: false,
|
|
137
|
+
* minHeight: '40px',
|
|
138
|
+
* maxHeight: '120px',
|
|
139
|
+
* });
|
|
140
|
+
*
|
|
141
|
+
* D) Editor with an optional toolbar behind a toggle button
|
|
142
|
+
* Editor.mount('#post-content', { toolbar: 'toggle' });
|
|
143
|
+
*
|
|
144
|
+
* E) Mounting on a dynamically added element (e.g. an opened modal)
|
|
145
|
+
* modal.addEventListener('shown', () => { // your modal's open event
|
|
146
|
+
* Editor.mount('#modal-textarea', { toolbar: 'focus', minHeight: '120px' });
|
|
147
|
+
* });
|
|
148
|
+
*
|
|
149
|
+
* F) Per-textarea override (data attributes, no extra JS)
|
|
150
|
+
* <textarea
|
|
151
|
+
* data-mzre-toolbar="toggle"
|
|
152
|
+
* data-mzre-min-height="100px"
|
|
153
|
+
* data-mzre-max-height="400px"
|
|
154
|
+
* ></textarea>
|
|
155
|
+
* then: Editor.init(); ← the data attributes take precedence
|
|
156
|
+
*
|
|
157
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
158
|
+
* CHAINING
|
|
159
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
160
|
+
*
|
|
161
|
+
* init() and mount() return the class, so calls can be chained:
|
|
162
|
+
* Editor
|
|
163
|
+
* .init({ selector: '.rich', toolbar: 'always' })
|
|
164
|
+
* .mount('#extra-field', { toolbar: 'never', footer: false });
|
|
165
|
+
*/
|
|
166
|
+
import type { StyleOptions } from './styles.js';
|
|
167
|
+
import type { EditorLocale } from './messages.js';
|
|
168
|
+
import type { EditorIntegrations } from './types.js';
|
|
169
|
+
/** Content state, passed to `onChange` on every change and once at mount. */
|
|
170
|
+
export interface EditorChange {
|
|
171
|
+
html: string;
|
|
172
|
+
text: string;
|
|
173
|
+
isEmpty: boolean;
|
|
174
|
+
}
|
|
175
|
+
export interface EditorOptions {
|
|
176
|
+
selector?: string;
|
|
177
|
+
exclude?: string;
|
|
178
|
+
/** 'always' | 'toggle' | 'focus' | 'never' — default: 'always' */
|
|
179
|
+
toolbar?: 'always' | 'toggle' | 'focus' | 'never';
|
|
180
|
+
/** Show or hide the footer (counter + buttons) — default: true */
|
|
181
|
+
footer?: boolean;
|
|
182
|
+
/** Minimum height of the writing area (e.g. '80px', '4rem') — default: '160px' */
|
|
183
|
+
minHeight?: string;
|
|
184
|
+
/** Maximum height of the writing area before it scrolls (e.g. '400px') */
|
|
185
|
+
maxHeight?: string;
|
|
186
|
+
/** Adds an inline emoji button to the writing area */
|
|
187
|
+
emoji?: boolean;
|
|
188
|
+
/** Enables @mentions (requires `integrations.mentions`) */
|
|
189
|
+
mention?: boolean;
|
|
190
|
+
/** Language of the interface and of the emojis: 'en' (default) or 'fr'. Page-wide setting. */
|
|
191
|
+
locale?: EditorLocale;
|
|
192
|
+
/**
|
|
193
|
+
* Style injection (page-wide setting): `{inject: false}` to load
|
|
194
|
+
* `@mzeahmed/rich-editor/style.css` yourself, `{nonce}` for a nonce-based CSP. See `setEditorStyles()`.
|
|
195
|
+
*/
|
|
196
|
+
styles?: StyleOptions;
|
|
197
|
+
/**
|
|
198
|
+
* Called on every content change (typing, toolbar, mention) and once at
|
|
199
|
+
* mount: handy to enable or disable a "publish" button depending on whether the field is empty.
|
|
200
|
+
*/
|
|
201
|
+
onChange?: (change: EditorChange) => void;
|
|
202
|
+
}
|
|
203
|
+
export default class Editor {
|
|
204
|
+
private static injectStyles;
|
|
205
|
+
private static buildEditorHTML;
|
|
206
|
+
private static mountEditor;
|
|
207
|
+
private static _addEmojiInEditor;
|
|
208
|
+
private static _saveSelection;
|
|
209
|
+
private static _showEmojiPicker;
|
|
210
|
+
private static _setupMentions;
|
|
211
|
+
private static _handleMentionSearch;
|
|
212
|
+
/**
|
|
213
|
+
* Creates the bubble on document.body with fixed positioning — works around the overflow:hidden of
|
|
214
|
+
* .mzre-editor-wrap, same pattern as the emoji picker. Placed below the writing area,
|
|
215
|
+
* shifted upward if needed.
|
|
216
|
+
*
|
|
217
|
+
* Its structure is built once: a header with the cross, an announcement area for screen
|
|
218
|
+
* readers (present before it changes, otherwise nothing is read) and a results area. It stays
|
|
219
|
+
* hidden while there is nothing to show.
|
|
220
|
+
*/
|
|
221
|
+
private static _showMentionDropdown;
|
|
222
|
+
private static _positionDropdown;
|
|
223
|
+
/**
|
|
224
|
+
* Closes the bubble as soon as the user presses (mouse or finger) anywhere but on it, including in the text
|
|
225
|
+
* of the editor. The listener is added on open and removed by _closeMentionDropdown().
|
|
226
|
+
*/
|
|
227
|
+
private static _closeOnOutsidePointer;
|
|
228
|
+
private static _closeMentionDropdown;
|
|
229
|
+
private static _performMentionSearch;
|
|
230
|
+
private static _renderMentionResults;
|
|
231
|
+
/** Options shown in the bubble (empty until it has results). */
|
|
232
|
+
private static _mentionOptions;
|
|
233
|
+
/** Chooses an option with the keyboard: `aria-selected` on the option, `aria-activedescendant` on the writing area. */
|
|
234
|
+
private static _setActiveMention;
|
|
235
|
+
/**
|
|
236
|
+
* Keyboard, while the bubble is open. Focus never leaves the writing area:
|
|
237
|
+
* · Escape → closes the bubble without touching the text (and without closing a host modal)
|
|
238
|
+
* · Up/Down arrows, Home/End → choose a suggestion (Home/End only once
|
|
239
|
+
* a suggestion is chosen; otherwise they move the caret as usual)
|
|
240
|
+
* · Enter or Tab → insert the chosen suggestion; with no choice, they keep their usual role
|
|
241
|
+
*/
|
|
242
|
+
private static _handleMentionKeydown;
|
|
243
|
+
/** A member's row in the bubble; empty string if their profile URL is unusable. */
|
|
244
|
+
private static _mentionItemHtml;
|
|
245
|
+
private static _insertMention;
|
|
246
|
+
/**
|
|
247
|
+
* Initializes the editor on every textarea matching the selector.
|
|
248
|
+
*
|
|
249
|
+
* @param options.selector CSS selector to target (default: 'textarea')
|
|
250
|
+
* @param options.exclude CSS selector to exclude
|
|
251
|
+
* @param options.toolbar Toolbar mode: 'always' | 'toggle' | 'focus' | 'never'
|
|
252
|
+
* @param options.footer Show the footer — default: true
|
|
253
|
+
* @param options.minHeight Minimum height of the writing area (e.g. '160px')
|
|
254
|
+
* @param options.maxHeight Maximum height before it scrolls (e.g. '400px')
|
|
255
|
+
*
|
|
256
|
+
* The data-mzre-* attributes on each textarea take precedence over the JS options.
|
|
257
|
+
* See the documentation block at the top of the file for detailed use cases.
|
|
258
|
+
*
|
|
259
|
+
* @returns Editor (chainable)
|
|
260
|
+
*/
|
|
261
|
+
static init(options?: EditorOptions, integrations?: EditorIntegrations): typeof Editor;
|
|
262
|
+
/**
|
|
263
|
+
* Mounts the editor on a specific textarea.
|
|
264
|
+
* Ideal for elements added dynamically to the DOM (modals, ajax widgets…).
|
|
265
|
+
*
|
|
266
|
+
* @param target HTMLTextAreaElement element or CSS selector
|
|
267
|
+
* @param options Same options as init()
|
|
268
|
+
*
|
|
269
|
+
* @param integrations
|
|
270
|
+
* @returns Editor (chainable)
|
|
271
|
+
*/
|
|
272
|
+
static mount(target: HTMLTextAreaElement | string, options?: EditorOptions, integrations?: EditorIntegrations): typeof Editor;
|
|
273
|
+
}
|