@mzeahmed/rich-editor 0.0.0-stage → 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,77 @@
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.1] - 2026-11-20
15
+
16
+ ### Fixed
17
+
18
+ - The mention bubble now opens when the letters follow the `@` without a pause: it used to open only
19
+ if the `@` was seen alone by the debounced key handler, so typing `@le` quickly opened nothing.
20
+ - An `@` inside a word (such as `jean@…` in an e-mail address) no longer opens the bubble.
21
+ - The bubble now closes when the text after the `@` contains a space, even if no Space key release
22
+ was seen (paste, fast typing).
23
+ - A bubble dismissed with Escape, the cross or a click outside no longer reopens by itself while
24
+ the same `@term` is still being typed; typing a new `@` opens it again.
25
+
26
+ ## [0.1.0] - 2026-11-20
27
+
28
+ First public release.
29
+
30
+ ### Added
31
+
32
+ - `Editor.mount()` and `Editor.init()` turn `<textarea>` elements into rich text editors based on
33
+ `contenteditable`; the textarea keeps the editor's HTML as its value.
34
+ - Options: `toolbar` (`always`, `toggle`, `focus`, `never`), `footer`, `minHeight`, `maxHeight`,
35
+ `emoji`, `mention`, `locale`, `styles`, `onChange`, plus `selector` / `exclude` for `init()`.
36
+ `data-mzre-toolbar`, `data-mzre-min-height` and `data-mzre-max-height` override them per textarea.
37
+ - `onChange({html, text, isEmpty})`, called at mount and on every change (typing, toolbar,
38
+ mention), for example to enable or disable a "publish" button.
39
+ - `@mentions`: a suggestion bubble fed by your `searchUsers()` integration. It closes with its
40
+ **×** button, with Escape, or by clicking outside. Selecting a user inserts
41
+ `<a class="mention" data-user-id="…">`.
42
+ - Emoji picker, inline in the editor (`emoji: true`) or standalone (`EmojiPicker.open()`, which
43
+ returns a promise). Emoji data is loaded on first open, as a separate file per language.
44
+ - English (default) and French interface and emoji data: `locale`, `setEditorLocale()`,
45
+ `messagesEn`, `messagesFr`; every text can be overridden with `setEditorMessages()` or
46
+ `integrations.messages`.
47
+ - Strict Content-Security-Policy support: a `@mzeahmed/rich-editor/style.css` stylesheet,
48
+ `setEditorStyles({inject, nonce})` to turn injection off or to set a CSP nonce, and no
49
+ `style="…"` attribute or inline event handler in the produced markup.
50
+ - TypeScript declarations, ESM build, and `npm run check:package` (checks that the built package
51
+ imports in Node and ships its stylesheet), run before every publication.
52
+
53
+ ### Security
54
+
55
+ - Names, ids, URLs and localized texts are escaped before being rendered; avatar and profile URLs
56
+ must be `http(s)` or relative, and a profile path starting with `//` can never point to another
57
+ site.
58
+ - The HTML found in the textarea at mount time is sanitized with an allow-list of tags and
59
+ attributes; scripts, event handlers, `javascript:` links and images are removed.
60
+
61
+ ### Accessibility
62
+
63
+ - The writing area has the `textbox` role and an accessible name.
64
+ - The mention bubble is fully usable from the keyboard without moving focus out of the writing
65
+ area (arrow keys, `Home` / `End`, `Enter` / `Tab`, `Escape`): a labelled `region` with a
66
+ `listbox` of `option`s, `aria-activedescendant`, and polite announcements of the number of
67
+ suggestions. An `axe-core` audit reports no violation with the bubble open.
68
+ - The toolbar's text-style menu has an accessible name, and the character counter meets the
69
+ contrast requirement.
70
+
71
+ ### Known limitations
72
+
73
+ - No way to unmount an editor yet.
74
+ - The language and the style injection are page-wide settings.
75
+ - Only English and French are bundled.
76
+ - Formatting relies on `document.execCommand`.
77
+ - 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,304 @@
1
- # Temporary Holding Version
1
+ # @mzeahmed/rich-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 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 `@` at the start of a word, then at least two letters, opens a bubble with the matching users.
145
+ Typing fast works (`@le` typed at once opens it); an `@` inside a word, such as in an e-mail
146
+ address, does not.
147
+ - Choosing a user inserts `<a class="mention" href="/path/of/profile" data-user-id="…"
148
+ target="_blank">First Last</a>`. Only the **path** of `profileUrl` is kept in the link.
149
+ - The bubble closes when you choose a user, press Space, Enter or Escape, click its **×** button, or
150
+ click anywhere outside of it.
151
+ - Users without a usable `profileUrl` (`http(s)` or relative) are not offered. An avatar that is not
152
+ an `http(s)` URL is replaced by the user's initials.
153
+
154
+ ## Emoji picker
155
+
156
+ With `emoji: true`, an emoji button is added to the editor. The picker is also available on its own:
157
+
158
+ ```ts
159
+ import {EmojiPicker} from '@mzeahmed/rich-editor';
160
+
161
+ await EmojiPicker.open({
162
+ onSelect: (emoji) => console.log(emoji),
163
+ title: 'Pick one', // optional, defaults to the localized text
164
+ closeLabel: 'Close', // optional
165
+ });
166
+
167
+ EmojiPicker.close();
168
+ ```
169
+
170
+ `open()` shows the dialog immediately and returns a promise that resolves once the emojis are
171
+ displayed (or, if loading fails, once the error message is displayed: it never rejects). The emoji
172
+ data (~700 KB per language) is loaded **on first open** as a separate file by your bundler, so
173
+ importing the package stays light. `EmojiPicker.destroy()` removes the dialog from the page.
174
+
175
+ ## Localization
176
+
177
+ The interface and the emoji data are in English by default. French is built in:
178
+
179
+ ```ts
180
+ import Editor, {messagesFr, setEditorLocale, setEditorMessages} from '@mzeahmed/rich-editor';
181
+
182
+ declare const textarea: HTMLTextAreaElement;
183
+
184
+ // For one mount…
185
+ Editor.mount(textarea, {locale: 'fr'});
186
+
187
+ // …or for the whole page.
188
+ setEditorLocale('fr');
189
+
190
+ // Override individual texts (escaped by the editor, never inserted as HTML).
191
+ setEditorMessages({bold: 'Bold (Ctrl+B)', placeholder: 'Write your message…'});
192
+
193
+ // Same thing, through the integrations argument.
194
+ Editor.mount(textarea, {}, {messages: {close: 'Fermer'}});
195
+
196
+ console.log(Object.keys(messagesFr));
197
+ ```
198
+
199
+ `messagesEn` and `messagesFr` list every text (toolbar, footer, emoji picker, mention bubble).
200
+ The language is a **page-wide setting**: the last `mount()`, `init()` or `setEditorLocale()` wins,
201
+ for all editors and for the emoji picker. Only `en` and `fr` are bundled; to add a language, pass
202
+ all the texts through `setEditorMessages()` (emoji labels stay in English or French).
203
+
204
+ ## Styles and CSP
205
+
206
+ By default the editor injects its own styles into `<head>` (two `<style>` elements). A Content
207
+ Security Policy without `'unsafe-inline'` blocks them. Two options:
208
+
209
+ ```ts
210
+ import '@mzeahmed/rich-editor/style.css';
211
+ import {setEditorStyles} from '@mzeahmed/rich-editor';
212
+
213
+ // 1. Load the stylesheet yourself and turn injection off (no <style> element is added).
214
+ setEditorStyles({inject: false});
215
+
216
+ // 2. Or keep the injection and give it the nonce of your CSP (style-src 'nonce-…').
217
+ setEditorStyles({inject: true, nonce: document.querySelector<HTMLMetaElement>('meta[name="csp-nonce"]')?.content});
218
+ ```
219
+
220
+ The same can be passed on mount: `Editor.mount(textarea, {styles: {inject: false}})`.
221
+
222
+ The markup produced by the editor contains **no `style="…"` attribute and no inline event
223
+ handler**. It was verified in a browser under `default-src 'none'; script-src 'self';
224
+ style-src 'self'` (no violation); with the default injection and no nonce, that policy blocks the
225
+ styles. If your CSP restricts `img-src`, allow the origin of your users' avatars.
226
+
227
+ ## Security
228
+
229
+ - **Output escaping.** Names, ids, URLs and every localized text are escaped before being rendered.
230
+ `searchUsers()` must return **raw** text, never pre-escaped text (it would be displayed escaped
231
+ twice).
232
+ - **URLs.** Avatars and profile links must be `http(s)` or relative. `javascript:`, `data:` and
233
+ similar schemes are refused. A profile path starting with `//` can never point to another site.
234
+ - **Initial content.** The HTML found in the textarea when the editor is mounted is sanitized with an
235
+ allow-list: `a`, `b`, `blockquote`, `br`, `code`, `div`, `em`, `h2`, `h3`, `i`, `li`, `ol`, `p`,
236
+ `pre`, `s`, `span`, `strike`, `strong`, `u`, `ul`. Links keep `http(s):`, `mailto:`, `tel:`,
237
+ site-relative paths and anchors; the only style kept is `text-align`. Scripts, event handlers
238
+ (`onerror`…), `javascript:` links, images and unknown tags are removed (unknown tags keep their text).
239
+ Mentions are preserved.
240
+ - **Output.** The HTML produced by the editor is user input. Sanitize it on the server.
241
+
242
+ ## Accessibility
243
+
244
+ The writing area has the `textbox` role (multiline). Its accessible name comes from the textarea's
245
+ `aria-label`, or else its `placeholder`: give your fields an explicit name.
246
+
247
+ The mention bubble is driven entirely from the keyboard **without moving focus out of the writing
248
+ area** (a listbox linked to the field through `aria-activedescendant`):
249
+
250
+ | Key | Effect |
251
+ | --- | --- |
252
+ | `@` then 2 letters | Opens the bubble. Screen readers announce the number of suggestions. |
253
+ | `↓` / `↑` | Choose the next / previous suggestion (wraps around). |
254
+ | `Home` / `End` | First / last suggestion, once one is chosen (otherwise they move the caret). |
255
+ | `Enter` or `Tab` | Insert the chosen suggestion. With no choice, they keep their usual role. |
256
+ | `Escape` | Closes the bubble without touching the text (and without closing a surrounding modal). |
257
+
258
+ While the bubble is open, the writing area carries `aria-autocomplete`, `aria-controls` and
259
+ `aria-activedescendant`; the bubble is a labelled `region` containing a `listbox` of `option`s, plus
260
+ a polite live region for announcements. An `axe-core` audit (WCAG 2.1 A/AA and best practices) with
261
+ the bubble open and one suggestion chosen reports no violation.
262
+
263
+ > Automated audits only catch part of the problems. The package has **not** been tested yet with
264
+ > NVDA, JAWS or VoiceOver.
265
+
266
+ ## Server-side rendering and compatibility
267
+
268
+ - **Importing** the package in Node (SSR, tests) is safe: it touches neither the DOM nor JSON at
269
+ evaluation time. Call `mount()` / `init()` / `EmojiPicker.open()` in the browser only.
270
+ - **Format:** ESM only, with TypeScript declarations. `@mzeahmed/rich-editor/style.css` is the
271
+ stylesheet.
272
+ - **Bundlers:** the emoji data is loaded with a dynamic `import()` of JSON files from
273
+ `emojibase-data`; bundlers such as Vite, webpack, Rollup or esbuild turn them into separate
274
+ chunks. Verified with Vite.
275
+ - **Browsers:** requires `contenteditable` and, for formatting commands, `document.execCommand`
276
+ (deprecated by the standards but still supported by evergreen browsers). Verified in Chromium and
277
+ in jsdom; Firefox and Safari have not been tested yet.
278
+
279
+ ## Limitations
280
+
281
+ - No `destroy()` / unmount method for an editor yet.
282
+ - The language and the style injection are **page-wide** settings, not per editor.
283
+ - Only English and French are bundled.
284
+ - Formatting relies on `document.execCommand`.
285
+ - The footer's "HTML", "Clear" and "Copy" buttons are part of the footer: hide them all with
286
+ `footer: false`.
287
+
288
+ ## Development
289
+
290
+ ```bash
291
+ npm ci
292
+ npm test # unit and DOM tests (Vitest + jsdom)
293
+ npm run build # tsc + dist/style.css
294
+ npm run check:package # imports dist in Node, checks style.css and the exports
295
+ ```
296
+
297
+ `npm pack` runs the build and `check:package` automatically (`prepack`).
298
+
299
+ Changes are listed in [CHANGELOG.md](./CHANGELOG.md). Releases are published from a version tag, with
300
+ npm provenance: see [RELEASING.md](./RELEASING.md).
301
+
302
+ ## License
303
+
304
+ [MIT](./LICENSE)