@rathkit/rte-headless 0.0.0-stage → 0.1.0-alpha.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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Rathkit RTE
2
+ Copyright 2026 Steven Rathbauer
3
+
4
+ Licensed under the Apache License, Version 2.0. See LICENSE.
package/README.md CHANGED
@@ -1,3 +1,45 @@
1
- # Temporary Holding Version
1
+ # @rathkit/rte-headless
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
+ > **Alpha** (0.1.0-alpha.0). Not for production: the APIs will change between releases. Published to the `next` tag only.
4
+
5
+ How a toolbar, menu, dialog, tooltip and live announcement should behave for the keyboard and assistive technology, with no markup or CSS of its own. Draw the elements yourself and this makes them behave (roving focus, ARIA state, focus returned to the editor); also external stores for any framework.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @rathkit/rte-headless@next @rathkit/rte-core@next
11
+ ```
12
+
13
+ This package has no dependencies of its own. It works with `@rathkit/rte-core` (peer dependencies, all optional so that npm installs nothing you did not ask for), so install the ones you use alongside it.
14
+
15
+ ## Example
16
+
17
+ ```js
18
+ import { createEditor } from "@rathkit/rte-core/standard";
19
+ import { createToolbar } from "@rathkit/rte-headless";
20
+
21
+ const surface = document.createElement("div");
22
+ surface.setAttribute("aria-label", "Body");
23
+ document.body.append(surface);
24
+ const editor = createEditor({ element: surface, html: "<p>Hello</p>" });
25
+
26
+ // Draw the controls yourself and mark each with data-rk-item="<id>"; the toolbar makes them behave.
27
+ const bar = document.createElement("div");
28
+ const toolbar = createToolbar(editor, { label: "Formatting" });
29
+ for (const item of toolbar.items.filter((i) => i.kind === "button" || i.kind === "toggle")) {
30
+ const button = document.createElement("button");
31
+ button.setAttribute("data-rk-item", item.id);
32
+ button.textContent = toolbar.state(item.id).label;
33
+ bar.append(button);
34
+ }
35
+ document.body.prepend(bar);
36
+ toolbar.bind(bar); // roving focus, aria-pressed, focus kept in the editor
37
+ ```
38
+
39
+ ## More
40
+
41
+ Documentation: <https://rathkit.com>. Source and issues: <https://github.com/rathkit/rte>. What is checked: [SUPPORT.md](https://github.com/rathkit/rte/blob/main/docs/SUPPORT.md). Changes: [CHANGELOG.md](https://github.com/rathkit/rte/blob/main/CHANGELOG.md). How a release is verified: [VERIFY.md](https://github.com/rathkit/rte/blob/main/docs/VERIFY.md).
42
+
43
+ ## License
44
+
45
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,9 @@
1
+ import type { Unsubscribe } from "./types.ts";
2
+ export interface Announcer {
3
+ /** Says a message to assistive technology. The same message twice in a row is said twice. */
4
+ announce(message: string): void;
5
+ /** The element, so a host can place it. It is visually hidden, but not removed from the accessibility tree. */
6
+ readonly element: HTMLElement;
7
+ destroy: Unsubscribe;
8
+ }
9
+ export declare function createAnnouncer(parent?: HTMLElement): Announcer;
@@ -0,0 +1,23 @@
1
+ export function createAnnouncer(parent = document.body) {
2
+ const element = document.createElement("div");
3
+ element.setAttribute("role", "status");
4
+ element.setAttribute("aria-live", "polite");
5
+ element.setAttribute("aria-atomic", "true");
6
+ element.style.cssText = "position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;border:0";
7
+ parent.appendChild(element);
8
+ let timer;
9
+ return {
10
+ element,
11
+ announce(message) {
12
+ element.textContent = "";
13
+ if (timer)
14
+ clearTimeout(timer);
15
+ timer = setTimeout(() => { element.textContent = message; }, 50);
16
+ },
17
+ destroy() {
18
+ if (timer)
19
+ clearTimeout(timer);
20
+ element.remove();
21
+ },
22
+ };
23
+ }
@@ -0,0 +1,33 @@
1
+ import type { Field } from "@rathkit/rte-core";
2
+ import type { Unsubscribe } from "./types.ts";
3
+ export interface DialogOptions {
4
+ readonly dialog: HTMLElement;
5
+ /** What opened it; focus returns here. If it is gone, focus goes to the editor. */
6
+ readonly opener?: HTMLElement | null;
7
+ readonly editor?: {
8
+ focus(): void;
9
+ };
10
+ readonly onClose?: (result: "submit" | "cancel") => void;
11
+ /** Called with a developer-facing warning, such as a dialog with no name. Default: the console. */
12
+ readonly warn?: (message: string) => void;
13
+ }
14
+ export interface Dialog {
15
+ readonly isOpen: boolean;
16
+ open(): void;
17
+ close(result?: "submit" | "cancel"): void;
18
+ destroy: Unsubscribe;
19
+ }
20
+ export declare function createDialog(options: DialogOptions): Dialog;
21
+ export interface FormCheck {
22
+ readonly ok: boolean;
23
+ readonly values: Record<string, string | boolean>;
24
+ }
25
+ /**
26
+ * Checks a dialog's form against the fields an item asked for. Each field that is missing or wrong gets `aria-invalid` and is tied to
27
+ * its message by `aria-describedby`; put an element marked `data-rk-error="<field name>"` where the message should appear. The first
28
+ * bad field takes the focus, and the messages are announced when an announcer is given.
29
+ */
30
+ export declare function checkFields(form: HTMLElement, fields: readonly Field[], messages?: {
31
+ readonly required?: string;
32
+ readonly url?: string;
33
+ }, announce?: (message: string) => void): FormCheck;
package/dist/dialog.js ADDED
@@ -0,0 +1,130 @@
1
+ import { uniqueId } from "./disclosure.js";
2
+ const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]):not([type=hidden]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';
3
+ export function createDialog(options) {
4
+ const { dialog } = options;
5
+ const warn = options.warn ?? ((m) => console.warn(`[rte] ${m}`));
6
+ const native = typeof HTMLDialogElement !== "undefined" && dialog instanceof HTMLDialogElement && typeof dialog.showModal === "function";
7
+ if (!dialog.hasAttribute("aria-labelledby") && !dialog.hasAttribute("aria-label"))
8
+ warn("A dialog needs a name: give it aria-labelledby or aria-label.");
9
+ dialog.setAttribute("role", "dialog");
10
+ dialog.setAttribute("aria-modal", "true");
11
+ let isOpen = false;
12
+ let result = "cancel";
13
+ const focusable = () => [...dialog.querySelectorAll(FOCUSABLE)].filter((e) => !e.hidden && e.getAttribute("aria-hidden") !== "true");
14
+ const returnFocus = () => {
15
+ const opener = options.opener;
16
+ if (opener && opener.isConnected)
17
+ opener.focus();
18
+ else
19
+ options.editor?.focus();
20
+ };
21
+ const finish = () => {
22
+ if (!isOpen)
23
+ return;
24
+ isOpen = false;
25
+ dialog.setAttribute("data-state", "closed");
26
+ returnFocus();
27
+ options.onClose?.(result);
28
+ };
29
+ const onKeyDown = (e) => {
30
+ if (e.key === "Escape") {
31
+ e.preventDefault();
32
+ close("cancel");
33
+ }
34
+ else if (e.key === "Tab" && !native) {
35
+ const list = focusable();
36
+ if (list.length === 0)
37
+ return;
38
+ const first = list[0];
39
+ const last = list[list.length - 1];
40
+ if (e.shiftKey && document.activeElement === first) {
41
+ e.preventDefault();
42
+ last.focus();
43
+ }
44
+ else if (!e.shiftKey && document.activeElement === last) {
45
+ e.preventDefault();
46
+ first.focus();
47
+ }
48
+ }
49
+ };
50
+ const onCancel = (e) => { e.preventDefault(); close("cancel"); };
51
+ dialog.addEventListener("keydown", onKeyDown);
52
+ if (native)
53
+ dialog.addEventListener("cancel", onCancel);
54
+ function close(how = "cancel") {
55
+ if (!isOpen)
56
+ return;
57
+ result = how;
58
+ if (native)
59
+ dialog.close();
60
+ else
61
+ dialog.hidden = true;
62
+ finish();
63
+ }
64
+ function open() {
65
+ if (isOpen)
66
+ return;
67
+ isOpen = true;
68
+ result = "cancel";
69
+ dialog.setAttribute("data-state", "open");
70
+ if (native)
71
+ dialog.showModal();
72
+ else
73
+ dialog.hidden = false;
74
+ const target = dialog.querySelector("[autofocus]") ?? focusable()[0] ?? dialog;
75
+ if (target === dialog && !dialog.hasAttribute("tabindex"))
76
+ dialog.tabIndex = -1;
77
+ target.focus();
78
+ }
79
+ return {
80
+ get isOpen() { return isOpen; },
81
+ open, close,
82
+ destroy() {
83
+ dialog.removeEventListener("keydown", onKeyDown);
84
+ dialog.removeEventListener("cancel", onCancel);
85
+ },
86
+ };
87
+ }
88
+ export function checkFields(form, fields, messages = {}, announce) {
89
+ const values = {};
90
+ const problems = [];
91
+ let firstBad;
92
+ for (const field of fields) {
93
+ const input = form.querySelector(`[name="${field.name}"]`);
94
+ if (!input)
95
+ continue;
96
+ if (field.type === "checkbox") {
97
+ values[field.name] = input.checked;
98
+ continue;
99
+ }
100
+ const value = input.value.trim();
101
+ values[field.name] = value;
102
+ let problem = "";
103
+ if (field.required && value === "")
104
+ problem = messages.required ?? `${field.label} is required.`;
105
+ else if (value !== "" && field.type === "url" && /^\s*(javascript|vbscript|data):/i.test(value))
106
+ problem = messages.url ?? `${field.label} must be a web, mail or phone address.`;
107
+ const slot = form.querySelector(`[data-rk-error="${field.name}"]`);
108
+ if (slot)
109
+ slot.textContent = problem;
110
+ if (problem) {
111
+ input.setAttribute("aria-invalid", "true");
112
+ if (slot) {
113
+ if (!slot.id)
114
+ slot.id = uniqueId("rk-error");
115
+ input.setAttribute("aria-describedby", slot.id);
116
+ }
117
+ problems.push(problem);
118
+ firstBad ??= input;
119
+ }
120
+ else {
121
+ input.removeAttribute("aria-invalid");
122
+ input.removeAttribute("aria-describedby");
123
+ }
124
+ }
125
+ if (firstBad) {
126
+ firstBad.focus();
127
+ announce?.(problems.join(" "));
128
+ }
129
+ return { ok: problems.length === 0, values };
130
+ }
@@ -0,0 +1,18 @@
1
+ import type { Unsubscribe } from "./types.ts";
2
+ export interface DisclosureOptions {
3
+ readonly trigger: HTMLElement;
4
+ readonly popup: HTMLElement;
5
+ /** What the trigger opens, for `aria-haspopup`. Default `true` (a generic popup). */
6
+ readonly kind?: "menu" | "dialog" | "listbox" | "true";
7
+ readonly onToggle?: (open: boolean) => void;
8
+ }
9
+ export interface Disclosure {
10
+ readonly isOpen: boolean;
11
+ open(): void;
12
+ /** Closes it. By default the focus goes back to the trigger; pass false when the person has already moved on (a click elsewhere). */
13
+ close(returnFocus?: boolean): void;
14
+ toggle(): void;
15
+ destroy: Unsubscribe;
16
+ }
17
+ export declare const uniqueId: (prefix: string) => string;
18
+ export declare function createDisclosure(options: DisclosureOptions): Disclosure;
@@ -0,0 +1,64 @@
1
+ let counter = 0;
2
+ export const uniqueId = (prefix) => `${prefix}-${++counter}`;
3
+ export function createDisclosure(options) {
4
+ const { trigger, popup } = options;
5
+ if (!popup.id)
6
+ popup.id = uniqueId("rk-popup");
7
+ trigger.setAttribute("aria-haspopup", options.kind ?? "true");
8
+ trigger.setAttribute("aria-controls", popup.id);
9
+ let isOpen = false;
10
+ const apply = (open) => {
11
+ isOpen = open;
12
+ trigger.setAttribute("aria-expanded", String(open));
13
+ trigger.setAttribute("data-state", open ? "open" : "closed");
14
+ popup.setAttribute("data-state", open ? "open" : "closed");
15
+ popup.hidden = !open;
16
+ options.onToggle?.(open);
17
+ };
18
+ apply(false);
19
+ const close = (returnFocus = true) => {
20
+ if (!isOpen)
21
+ return;
22
+ apply(false);
23
+ if (returnFocus)
24
+ trigger.focus();
25
+ };
26
+ const open = () => {
27
+ if (!isOpen)
28
+ apply(true);
29
+ };
30
+ const onPointerDown = (e) => {
31
+ const target = e.target;
32
+ if (isOpen && target && !popup.contains(target) && !trigger.contains(target))
33
+ close(false);
34
+ };
35
+ const onFocusOut = (e) => {
36
+ const next = e.relatedTarget;
37
+ if (isOpen && next && !popup.contains(next) && !trigger.contains(next))
38
+ close(false);
39
+ };
40
+ const onKeyDown = (e) => {
41
+ if (isOpen && e.key === "Escape") {
42
+ e.preventDefault();
43
+ e.stopPropagation();
44
+ close(true);
45
+ }
46
+ };
47
+ const onClick = () => (isOpen ? close(true) : open());
48
+ document.addEventListener("pointerdown", onPointerDown, true);
49
+ popup.addEventListener("focusout", onFocusOut);
50
+ trigger.addEventListener("keydown", onKeyDown);
51
+ popup.addEventListener("keydown", onKeyDown);
52
+ trigger.addEventListener("click", onClick);
53
+ return {
54
+ get isOpen() { return isOpen; },
55
+ open, close, toggle: () => (isOpen ? close(true) : open()),
56
+ destroy() {
57
+ document.removeEventListener("pointerdown", onPointerDown, true);
58
+ popup.removeEventListener("focusout", onFocusOut);
59
+ trigger.removeEventListener("keydown", onKeyDown);
60
+ popup.removeEventListener("keydown", onKeyDown);
61
+ trigger.removeEventListener("click", onClick);
62
+ },
63
+ };
64
+ }
@@ -0,0 +1,8 @@
1
+ export { createToolbar, type BindOptions, type ItemState, type Toolbar, type ToolbarOptions } from "./toolbar.ts";
2
+ export { createAnnouncer, type Announcer } from "./announcer.ts";
3
+ export { createDisclosure, type Disclosure, type DisclosureOptions } from "./disclosure.ts";
4
+ export { createMenu, type Menu, type MenuOptions } from "./menu.ts";
5
+ export { checkFields, createDialog, type Dialog, type DialogOptions, type FormCheck } from "./dialog.ts";
6
+ export { commandStore, selectStore, snapshotStore, toReadable, type ExternalStore, type Readable } from "./stores.ts";
7
+ export type { HeadlessEditor, Unsubscribe } from "./types.ts";
8
+ export { createTooltip, type Tooltip, type TooltipOptions } from "./tooltip.ts";
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { createToolbar } from "./toolbar.js";
2
+ export { createAnnouncer } from "./announcer.js";
3
+ export { createDisclosure } from "./disclosure.js";
4
+ export { createMenu } from "./menu.js";
5
+ export { checkFields, createDialog } from "./dialog.js";
6
+ export { commandStore, selectStore, snapshotStore, toReadable } from "./stores.js";
7
+ export { createTooltip } from "./tooltip.js";
package/dist/menu.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import { type Disclosure } from "./disclosure.ts";
2
+ import type { Unsubscribe } from "./types.ts";
3
+ export interface MenuOptions {
4
+ readonly trigger: HTMLElement;
5
+ readonly menu: HTMLElement;
6
+ /** Called with the item that was chosen. The menu closes and the focus returns to the trigger afterwards. */
7
+ readonly onSelect: (item: HTMLElement) => void;
8
+ /** Called when the menu has just opened and is showing, so it can be put where it fits on the screen. */
9
+ readonly onOpen?: () => void;
10
+ }
11
+ export interface Menu extends Pick<Disclosure, "isOpen" | "open" | "close" | "toggle"> {
12
+ destroy: Unsubscribe;
13
+ }
14
+ export declare function createMenu(options: MenuOptions): Menu;
package/dist/menu.js ADDED
@@ -0,0 +1,104 @@
1
+ import { createDisclosure, uniqueId } from "./disclosure.js";
2
+ export function createMenu(options) {
3
+ const { trigger, menu } = options;
4
+ if (!trigger.id)
5
+ trigger.id = uniqueId("rk-menu-button");
6
+ menu.setAttribute("role", "menu");
7
+ menu.setAttribute("aria-labelledby", trigger.id);
8
+ const items = () => [...menu.querySelectorAll("[data-rk-menuitem]")];
9
+ let typed = "";
10
+ let typedTimer;
11
+ const disclosure = createDisclosure({
12
+ trigger, popup: menu, kind: "menu",
13
+ onToggle: (open) => { if (open) {
14
+ options.onOpen?.();
15
+ queueMicrotask(() => focusAt(0));
16
+ } },
17
+ });
18
+ const sync = () => items().forEach((item) => { item.setAttribute("role", "menuitem"); item.tabIndex = -1; });
19
+ sync();
20
+ function focusAt(index) {
21
+ const list = items();
22
+ if (list.length === 0)
23
+ return;
24
+ const i = (index + list.length) % list.length;
25
+ list.forEach((item, at) => { item.tabIndex = at === i ? 0 : -1; });
26
+ list[i]?.focus();
27
+ }
28
+ const current = () => items().indexOf(document.activeElement);
29
+ const choose = (item) => {
30
+ if (item.getAttribute("aria-disabled") === "true")
31
+ return;
32
+ disclosure.close(true);
33
+ options.onSelect(item);
34
+ };
35
+ const onMenuKey = (e) => {
36
+ const list = items();
37
+ const at = current();
38
+ switch (e.key) {
39
+ case "ArrowDown":
40
+ focusAt(at + 1);
41
+ break;
42
+ case "ArrowUp":
43
+ focusAt(at <= 0 ? list.length - 1 : at - 1);
44
+ break;
45
+ case "Home":
46
+ focusAt(0);
47
+ break;
48
+ case "End":
49
+ focusAt(list.length - 1);
50
+ break;
51
+ case "Enter":
52
+ case " ": {
53
+ const item = list[at];
54
+ if (item)
55
+ choose(item);
56
+ break;
57
+ }
58
+ case "Tab":
59
+ disclosure.close(false);
60
+ return;
61
+ default: {
62
+ if (e.key.length !== 1 || e.ctrlKey || e.metaKey || e.altKey)
63
+ return;
64
+ typed += e.key.toLowerCase();
65
+ if (typedTimer)
66
+ clearTimeout(typedTimer);
67
+ typedTimer = setTimeout(() => { typed = ""; }, 500);
68
+ const names = list.map((item) => (item.textContent ?? item.getAttribute("aria-label") ?? "").trim().toLowerCase());
69
+ const start = typed.length === 1 ? at + 1 : at;
70
+ const hit = [...names.keys()].map((k) => (k + start + names.length) % names.length).find((k) => names[k]?.startsWith(typed));
71
+ if (hit !== undefined)
72
+ focusAt(hit);
73
+ }
74
+ }
75
+ e.preventDefault();
76
+ };
77
+ const onTriggerKey = (e) => {
78
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
79
+ e.preventDefault();
80
+ disclosure.open();
81
+ queueMicrotask(() => focusAt(e.key === "ArrowDown" ? 0 : items().length - 1));
82
+ }
83
+ };
84
+ const onClick = (e) => {
85
+ const item = e.target?.closest("[data-rk-menuitem]");
86
+ if (item && menu.contains(item))
87
+ choose(item);
88
+ };
89
+ menu.addEventListener("keydown", onMenuKey);
90
+ menu.addEventListener("click", onClick);
91
+ trigger.addEventListener("keydown", onTriggerKey);
92
+ return {
93
+ get isOpen() { return disclosure.isOpen; },
94
+ open: disclosure.open, close: disclosure.close, toggle: disclosure.toggle,
95
+ destroy() {
96
+ if (typedTimer)
97
+ clearTimeout(typedTimer);
98
+ menu.removeEventListener("keydown", onMenuKey);
99
+ menu.removeEventListener("click", onClick);
100
+ trigger.removeEventListener("keydown", onTriggerKey);
101
+ disclosure.destroy();
102
+ },
103
+ };
104
+ }
@@ -0,0 +1,20 @@
1
+ import type { CommandState, EditorSnapshot } from "@rathkit/rte-core";
2
+ import type { HeadlessEditor, Unsubscribe } from "./types.ts";
3
+ export interface ExternalStore<T> {
4
+ subscribe(onChange: () => void): Unsubscribe;
5
+ getSnapshot(): T;
6
+ }
7
+ /** A command's state: enabled, active, value. The same object until it changes. */
8
+ export declare function commandStore(editor: HeadlessEditor, command: string): ExternalStore<CommandState>;
9
+ /** The whole editor state. A new object after every change to the document, selection, focus or read-only state. */
10
+ export declare function snapshotStore(editor: HeadlessEditor): ExternalStore<EditorSnapshot>;
11
+ /**
12
+ * One value worked out from the state, such as the document's word count. Only changes in that value wake the subscriber. The snapshot is
13
+ * remembered per editor state, so asking twice between changes costs nothing and returns the same value.
14
+ */
15
+ export declare function selectStore<T>(editor: HeadlessEditor, selector: (snapshot: EditorSnapshot) => T, equals?: (a: T, b: T) => boolean): ExternalStore<T>;
16
+ /** The Svelte store contract: `subscribe(run)` calls `run` at once with the value, again on each change, and returns how to stop. */
17
+ export interface Readable<T> {
18
+ subscribe(run: (value: T) => void): Unsubscribe;
19
+ }
20
+ export declare function toReadable<T>(store: ExternalStore<T>): Readable<T>;
package/dist/stores.js ADDED
@@ -0,0 +1,44 @@
1
+ export function commandStore(editor, command) {
2
+ return {
3
+ subscribe: (onChange) => editor.commands.subscribe(command, onChange),
4
+ getSnapshot: () => editor.commands.state(command),
5
+ };
6
+ }
7
+ export function snapshotStore(editor) {
8
+ return {
9
+ subscribe: (onChange) => editor.subscribe(() => onChange()),
10
+ getSnapshot: () => editor.snapshot,
11
+ };
12
+ }
13
+ export function selectStore(editor, selector, equals = Object.is) {
14
+ let version = -1;
15
+ let value;
16
+ return {
17
+ subscribe: (onChange) => editor.select(selector, () => onChange(), equals),
18
+ getSnapshot() {
19
+ const snap = editor.snapshot;
20
+ if (snap.version === version)
21
+ return value;
22
+ const next = selector(snap);
23
+ if (version === -1 || !equals(value, next))
24
+ value = next;
25
+ version = snap.version;
26
+ return value;
27
+ },
28
+ };
29
+ }
30
+ export function toReadable(store) {
31
+ return {
32
+ subscribe(run) {
33
+ run(store.getSnapshot());
34
+ let last = store.getSnapshot();
35
+ return store.subscribe(() => {
36
+ const next = store.getSnapshot();
37
+ if (!Object.is(next, last)) {
38
+ last = next;
39
+ run(next);
40
+ }
41
+ });
42
+ },
43
+ };
44
+ }
@@ -0,0 +1,44 @@
1
+ import type { UiItem } from "@rathkit/rte-core";
2
+ import type { HeadlessEditor, Unsubscribe } from "./types.ts";
3
+ export interface ItemState {
4
+ readonly id: string;
5
+ readonly kind: UiItem["kind"];
6
+ /** Always set: the item's own label, else the command's, else the item's id. A control without a name is a bug. */
7
+ readonly label: string;
8
+ readonly icon: string | undefined;
9
+ /** Not available right now. The control stays focusable (`aria-disabled`), so people can find it. */
10
+ readonly disabled: boolean;
11
+ /** For toggles: on or off. Undefined for other kinds. */
12
+ readonly pressed: boolean | undefined;
13
+ /** For selects: the current value. */
14
+ readonly value: unknown;
15
+ /** The key that runs it, written for `aria-keyshortcuts`, if it has one. */
16
+ readonly shortcut: string | undefined;
17
+ /** The same key written for people ("Ctrl+B"), for a tooltip. */
18
+ readonly shortcutLabel: string | undefined;
19
+ }
20
+ export interface ToolbarOptions {
21
+ /** The place to read items from. Default: the main toolbar. */
22
+ readonly slot?: string;
23
+ /** Names the toolbar for assistive technology. Required in practice: a toolbar without a name is announced as just "toolbar". */
24
+ readonly label?: string;
25
+ readonly orientation?: "horizontal" | "vertical";
26
+ }
27
+ export interface BindOptions {
28
+ /** Called for items that open something rather than run a command (a dialog, a menu, a panel), with the control that was pressed. */
29
+ readonly onOpen?: (item: UiItem, control: HTMLElement) => void;
30
+ }
31
+ export interface Toolbar {
32
+ /** The items now, in display order: the top level, with the items of a menu inside it. The same array until the items change. */
33
+ readonly items: readonly UiItem[];
34
+ /** The state of one item. The same object until that item's state changes, so a framework can compare by identity. */
35
+ state(id: string): ItemState | undefined;
36
+ /** Runs the item's command: a button or toggle with its own argument; a select with the chosen value. False if it did nothing. */
37
+ activate(id: string, value?: unknown): boolean;
38
+ /** Called, once per turn, when the items or the state of any of them change. */
39
+ subscribe(callback: () => void): Unsubscribe;
40
+ /** Makes the elements a person's own interface drew behave. Mark each with `data-rk-item="<id>"`. */
41
+ bind(root: HTMLElement, options?: BindOptions): Unsubscribe;
42
+ destroy(): void;
43
+ }
44
+ export declare function createToolbar(editor: HeadlessEditor, options?: ToolbarOptions): Toolbar;
@@ -0,0 +1,208 @@
1
+ const commandOf = (item) => ("command" in item ? item.command : undefined);
2
+ export function createToolbar(editor, options = {}) {
3
+ const slot = options.slot ?? "toolbar.main";
4
+ const labels = new Map(editor.commands.list().map((c) => [c.name, c.label]));
5
+ const listeners = new Set();
6
+ const cache = new Map();
7
+ let items = editor.ui.items(slot);
8
+ const flatten = (list) => list.flatMap((i) => (i.kind === "menu" ? [i, ...flatten(i.items)] : [i]));
9
+ let everything = flatten(items);
10
+ let watching = [];
11
+ let scheduled = false;
12
+ let destroyed = false;
13
+ const notify = () => {
14
+ if (scheduled || destroyed)
15
+ return;
16
+ scheduled = true;
17
+ queueMicrotask(() => {
18
+ scheduled = false;
19
+ if (!destroyed)
20
+ for (const callback of [...listeners])
21
+ callback();
22
+ });
23
+ };
24
+ const watch = () => {
25
+ for (const stop of watching)
26
+ stop();
27
+ watching = [];
28
+ const seen = new Set();
29
+ for (const item of everything) {
30
+ const command = commandOf(item);
31
+ if (command && !seen.has(command)) {
32
+ seen.add(command);
33
+ watching.push(editor.commands.subscribe(command, notify));
34
+ }
35
+ }
36
+ };
37
+ watch();
38
+ const stopItems = editor.ui.subscribe(slot, () => {
39
+ items = editor.ui.items(slot);
40
+ everything = flatten(items);
41
+ watch();
42
+ notify();
43
+ });
44
+ const find = (id) => everything.find((i) => i.id === id);
45
+ function state(id) {
46
+ const item = find(id);
47
+ if (!item)
48
+ return undefined;
49
+ const command = commandOf(item);
50
+ const source = command ? editor.commands.state(command) : undefined;
51
+ const label = ("label" in item && item.label) || (command && labels.get(command)) || item.id;
52
+ const shortcut = command ? editor.keymap.ariaShortcut(command) : undefined;
53
+ const hit = cache.get(id);
54
+ if (hit && hit.source === source && hit.label === label && hit.shortcut === shortcut)
55
+ return hit.state;
56
+ const arg = "arg" in item ? item.arg : undefined;
57
+ const pressed = item.kind === "toggle" && source ? (arg !== undefined && source.value !== undefined ? Object.is(source.value, arg) : source.active) : undefined;
58
+ const next = {
59
+ id, kind: item.kind, label, icon: "icon" in item ? item.icon : undefined,
60
+ disabled: source ? !source.enabled : false,
61
+ pressed, value: item.kind === "select" ? source?.value : undefined,
62
+ shortcut, shortcutLabel: command ? editor.keymap.shortcutFor(command) : undefined,
63
+ };
64
+ cache.set(id, { state: next, source, label, shortcut });
65
+ return next;
66
+ }
67
+ function activate(id, value) {
68
+ const item = find(id);
69
+ const command = item ? commandOf(item) : undefined;
70
+ if (!item || !command)
71
+ return false;
72
+ const arg = item.kind === "select" ? value : item.kind === "button" || item.kind === "toggle" ? item.arg : value;
73
+ const ran = editor.commands.run(command, arg);
74
+ return ran;
75
+ }
76
+ function bind(root, bindOptions = {}) {
77
+ root.setAttribute("role", "toolbar");
78
+ root.setAttribute("aria-orientation", options.orientation ?? "horizontal");
79
+ if (options.label)
80
+ root.setAttribute("aria-label", options.label);
81
+ const controls = () => [...root.querySelectorAll("[data-rk-item]")];
82
+ let current = 0;
83
+ const sync = () => {
84
+ const all = controls();
85
+ all.forEach((control, index) => {
86
+ const s = state(control.getAttribute("data-rk-item") ?? "");
87
+ if (!s)
88
+ return;
89
+ control.setAttribute("aria-disabled", String(s.disabled));
90
+ if (s.pressed !== undefined)
91
+ control.setAttribute("aria-pressed", String(s.pressed));
92
+ if (s.shortcut)
93
+ control.setAttribute("aria-keyshortcuts", s.shortcut);
94
+ else
95
+ control.removeAttribute("aria-keyshortcuts");
96
+ if (!control.hasAttribute("aria-label") && !(control.textContent ?? "").trim())
97
+ control.setAttribute("aria-label", s.label);
98
+ if (control.tagName === "SELECT" && s.value !== undefined)
99
+ control.value = String(s.value);
100
+ control.tabIndex = index === current ? 0 : -1;
101
+ });
102
+ };
103
+ sync();
104
+ const stop = (() => { listeners.add(sync); return () => listeners.delete(sync); })();
105
+ const focusAt = (index) => {
106
+ const all = controls();
107
+ if (all.length === 0)
108
+ return;
109
+ current = (index + all.length) % all.length;
110
+ all.forEach((c, i) => { c.tabIndex = i === current ? 0 : -1; });
111
+ all[current]?.focus();
112
+ };
113
+ const control = (target) => (target instanceof Element ? target.closest("[data-rk-item]") : null);
114
+ const press = (el) => {
115
+ const id = el.getAttribute("data-rk-item") ?? "";
116
+ const item = find(id);
117
+ if (!item || el.getAttribute("aria-disabled") === "true")
118
+ return;
119
+ if (item.kind === "dialog" || item.kind === "menu" || item.kind === "panel") {
120
+ bindOptions.onOpen?.(item, el);
121
+ return;
122
+ }
123
+ if (activate(id))
124
+ editor.focus();
125
+ };
126
+ const onMouseDown = (e) => {
127
+ const el = control(e.target);
128
+ if (el && el.tagName !== "SELECT" && el.tagName !== "INPUT")
129
+ e.preventDefault();
130
+ };
131
+ const onClick = (e) => {
132
+ const el = control(e.target);
133
+ if (el && el.tagName !== "SELECT")
134
+ press(el);
135
+ };
136
+ const onChange = (e) => {
137
+ const el = control(e.target);
138
+ if (!el || el.tagName !== "SELECT")
139
+ return;
140
+ const item = find(el.getAttribute("data-rk-item") ?? "");
141
+ if (item?.kind !== "select")
142
+ return;
143
+ const chosen = item.options.find((o) => String(o.value) === el.value);
144
+ if (chosen && activate(item.id, chosen.value))
145
+ editor.focus();
146
+ };
147
+ const onFocusIn = (e) => {
148
+ const el = control(e.target);
149
+ if (el)
150
+ current = controls().indexOf(el);
151
+ sync();
152
+ };
153
+ const onKeyDown = (e) => {
154
+ const el = control(e.target);
155
+ if (!el)
156
+ return;
157
+ const vertical = (options.orientation ?? "horizontal") === "vertical";
158
+ const index = controls().indexOf(el);
159
+ const next = vertical ? "ArrowDown" : "ArrowRight";
160
+ const prev = vertical ? "ArrowUp" : "ArrowLeft";
161
+ if (e.key === next)
162
+ focusAt(index + 1);
163
+ else if (e.key === prev)
164
+ focusAt(index - 1);
165
+ else if (e.key === "Home")
166
+ focusAt(0);
167
+ else if (e.key === "End")
168
+ focusAt(controls().length - 1);
169
+ else if (e.key === "Escape")
170
+ editor.focus();
171
+ else if ((e.key === "Enter" || e.key === " ") && el.tagName !== "BUTTON" && el.tagName !== "SELECT")
172
+ press(el);
173
+ else
174
+ return;
175
+ e.preventDefault();
176
+ };
177
+ root.addEventListener("mousedown", onMouseDown);
178
+ root.addEventListener("click", onClick);
179
+ root.addEventListener("change", onChange);
180
+ root.addEventListener("focusin", onFocusIn);
181
+ root.addEventListener("keydown", onKeyDown);
182
+ return () => {
183
+ stop();
184
+ root.removeEventListener("mousedown", onMouseDown);
185
+ root.removeEventListener("click", onClick);
186
+ root.removeEventListener("change", onChange);
187
+ root.removeEventListener("focusin", onFocusIn);
188
+ root.removeEventListener("keydown", onKeyDown);
189
+ };
190
+ }
191
+ return {
192
+ get items() { return items; },
193
+ state, activate,
194
+ subscribe(callback) {
195
+ listeners.add(callback);
196
+ return () => listeners.delete(callback);
197
+ },
198
+ bind,
199
+ destroy() {
200
+ destroyed = true;
201
+ stopItems();
202
+ for (const stop of watching)
203
+ stop();
204
+ watching = [];
205
+ listeners.clear();
206
+ },
207
+ };
208
+ }
@@ -0,0 +1,20 @@
1
+ import type { Unsubscribe } from "./types.ts";
2
+ export interface TooltipOptions {
3
+ /** Events are listened for here, so controls added later work without more setup. */
4
+ readonly container: HTMLElement;
5
+ /** The tooltip's element. It is hidden and shown, and its text is set; the caller puts it in the page. */
6
+ readonly popup: HTMLElement;
7
+ /** Milliseconds the pointer must rest on a control before the tip shows. Default 500. Keyboard focus shows it at once. */
8
+ readonly delay?: number;
9
+ /** Milliseconds the tip stays when the pointer leaves, so it can be moved onto the tip. Default 150. */
10
+ readonly grace?: number;
11
+ /** Called with the control and the shown popup, to position it. */
12
+ readonly onShow?: (target: HTMLElement, popup: HTMLElement) => void;
13
+ }
14
+ export interface Tooltip {
15
+ /** The control whose tip is showing. */
16
+ readonly shown: HTMLElement | undefined;
17
+ hide(): void;
18
+ destroy: Unsubscribe;
19
+ }
20
+ export declare function createTooltip(options: TooltipOptions): Tooltip;
@@ -0,0 +1,125 @@
1
+ import { uniqueId } from "./disclosure.js";
2
+ const TIP = "[data-rk-tip]";
3
+ export function createTooltip(options) {
4
+ const { container, popup } = options;
5
+ const delay = options.delay ?? 500;
6
+ const grace = options.grace ?? 150;
7
+ if (!popup.id)
8
+ popup.id = uniqueId("rk-tooltip");
9
+ popup.setAttribute("role", "tooltip");
10
+ popup.hidden = true;
11
+ let shown;
12
+ let showTimer;
13
+ let hideTimer;
14
+ const clear = () => {
15
+ if (showTimer)
16
+ clearTimeout(showTimer);
17
+ if (hideTimer)
18
+ clearTimeout(hideTimer);
19
+ showTimer = hideTimer = undefined;
20
+ };
21
+ const hide = () => {
22
+ clear();
23
+ shown = undefined;
24
+ popup.hidden = true;
25
+ };
26
+ const show = (target) => {
27
+ clear();
28
+ const text = target.getAttribute("data-rk-tip");
29
+ if (!text)
30
+ return;
31
+ shown = target;
32
+ popup.textContent = text;
33
+ popup.hidden = false;
34
+ options.onShow?.(target, popup);
35
+ };
36
+ const tipOf = (node) => (node instanceof Element ? node.closest(TIP) : null);
37
+ const later = () => {
38
+ if (hideTimer)
39
+ clearTimeout(hideTimer);
40
+ hideTimer = setTimeout(hide, grace);
41
+ };
42
+ const onOver = (e) => {
43
+ if (typeof matchMedia === "function" && matchMedia("(hover: none)").matches)
44
+ return;
45
+ const target = tipOf(e.target);
46
+ if (!target || target === shown) {
47
+ if (target && hideTimer) {
48
+ clearTimeout(hideTimer);
49
+ hideTimer = undefined;
50
+ }
51
+ return;
52
+ }
53
+ clear();
54
+ showTimer = setTimeout(() => show(target), shown ? 0 : delay);
55
+ };
56
+ const onOut = (e) => {
57
+ const from = tipOf(e.target);
58
+ if (!from)
59
+ return;
60
+ const to = e.relatedTarget;
61
+ if (to && (from.contains(to) || popup.contains(to)))
62
+ return;
63
+ if (showTimer) {
64
+ clearTimeout(showTimer);
65
+ showTimer = undefined;
66
+ }
67
+ if (shown)
68
+ later();
69
+ };
70
+ const onFocusIn = (e) => {
71
+ const target = tipOf(e.target);
72
+ if (!target)
73
+ return;
74
+ let visible = true;
75
+ try {
76
+ visible = target.matches(":focus-visible");
77
+ }
78
+ catch { }
79
+ if (visible)
80
+ show(target);
81
+ };
82
+ const onFocusOut = (e) => {
83
+ if (tipOf(e.target) && e.relatedTarget !== popup)
84
+ hide();
85
+ };
86
+ const onPress = () => hide();
87
+ const onKey = (e) => {
88
+ if (shown && e.key === "Escape") {
89
+ e.stopPropagation();
90
+ e.preventDefault();
91
+ hide();
92
+ }
93
+ };
94
+ const onPopupEnter = () => { if (hideTimer) {
95
+ clearTimeout(hideTimer);
96
+ hideTimer = undefined;
97
+ } };
98
+ const onPopupLeave = (e) => { if (!(e.relatedTarget instanceof Node && shown?.contains(e.relatedTarget)))
99
+ later(); };
100
+ container.addEventListener("mouseover", onOver);
101
+ container.addEventListener("mouseout", onOut);
102
+ container.addEventListener("focusin", onFocusIn);
103
+ container.addEventListener("focusout", onFocusOut);
104
+ container.addEventListener("pointerdown", onPress);
105
+ const page = container.ownerDocument;
106
+ page.addEventListener("keydown", onKey, true);
107
+ popup.addEventListener("mouseenter", onPopupEnter);
108
+ popup.addEventListener("mouseleave", onPopupLeave);
109
+ return {
110
+ get shown() { return shown; },
111
+ hide,
112
+ destroy() {
113
+ clear();
114
+ popup.hidden = true;
115
+ container.removeEventListener("mouseover", onOver);
116
+ container.removeEventListener("mouseout", onOut);
117
+ container.removeEventListener("focusin", onFocusIn);
118
+ container.removeEventListener("focusout", onFocusOut);
119
+ container.removeEventListener("pointerdown", onPress);
120
+ page.removeEventListener("keydown", onKey, true);
121
+ popup.removeEventListener("mouseenter", onPopupEnter);
122
+ popup.removeEventListener("mouseleave", onPopupLeave);
123
+ },
124
+ };
125
+ }
@@ -0,0 +1,16 @@
1
+ import type { Engine } from "@rathkit/rte-core";
2
+ /**
3
+ * What the interaction rules need of an editor. The browser `Editor` fits as it is. A bare engine fits too, once it is given
4
+ * somewhere to send the keyboard focus.
5
+ */
6
+ export interface HeadlessEditor {
7
+ readonly commands: Engine["commands"];
8
+ readonly keymap: Engine["keymap"];
9
+ readonly ui: Engine["ui"];
10
+ readonly snapshot: Engine["snapshot"];
11
+ readonly subscribe: Engine["subscribe"];
12
+ readonly select: Engine["select"];
13
+ /** Puts the keyboard focus back in the editing surface. */
14
+ focus(): void;
15
+ }
16
+ export type Unsubscribe = () => void;
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "@rathkit/rte-headless",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-alpha.0",
4
+ "description": "How a toolbar, menu, dialog or announcement should behave for keyboard and assistive technology, with no markup or CSS of its own.",
5
+ "keywords": [
6
+ "rich-text",
7
+ "editor",
8
+ "wysiwyg",
9
+ "contenteditable",
10
+ "zero-dependencies",
11
+ "typescript",
12
+ "accessibility",
13
+ "headless",
14
+ "aria"
15
+ ],
16
+ "license": "Apache-2.0",
17
+ "homepage": "https://rathkit.com",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/rathkit/rte.git",
21
+ "directory": "packages/rte-headless"
22
+ },
23
+ "bugs": {
24
+ "url": "https://github.com/rathkit/rte/issues"
25
+ },
26
+ "type": "module",
27
+ "sideEffects": false,
28
+ "engines": {
29
+ "node": ">=22.14.0"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public",
33
+ "provenance": true,
34
+ "tag": "next"
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "NOTICE",
39
+ "!dist/**/*.map"
40
+ ],
41
+ "exports": {
42
+ ".": {
43
+ "types": "./dist/index.d.ts",
44
+ "default": "./dist/index.js"
45
+ }
46
+ },
47
+ "peerDependencies": {
48
+ "@rathkit/rte-core": ">=0.1.0-alpha.0 <0.2.0"
49
+ },
50
+ "peerDependenciesMeta": {
51
+ "@rathkit/rte-core": {
52
+ "optional": true
53
+ }
54
+ },
55
+ "devDependencies": {
56
+ "@rathkit/rte-core": "workspace:*"
57
+ },
58
+ "scripts": {
59
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json && tsc -p tsconfig.build.js.json",
60
+ "typecheck": "tsc -p tsconfig.json",
61
+ "test": "node --test \"src/**/*.test.ts\""
62
+ },
63
+ "rathkit": {
64
+ "budgets": [
65
+ {
66
+ "name": "headless",
67
+ "entry": "dist/index.js",
68
+ "gzipKB": 12
69
+ }
70
+ ]
71
+ }
72
+ }