grayling 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/LICENSE +661 -0
- package/README.md +268 -2
- package/dist/index.d.ts +290 -0
- package/dist/index.js +50 -0
- package/dist/node/archive.d.ts +4 -0
- package/dist/node/archive.js +115 -0
- package/dist/node/client.d.ts +188 -0
- package/dist/node/client.js +669 -0
- package/dist/node/connection.d.ts +56 -0
- package/dist/node/connection.js +240 -0
- package/dist/node/errors.d.ts +14 -0
- package/dist/node/errors.js +13 -0
- package/dist/node/handler.d.ts +56 -0
- package/dist/node/handler.js +208 -0
- package/dist/node/index.d.ts +15 -0
- package/dist/node/index.js +14 -0
- package/dist/node/paths.d.ts +51 -0
- package/dist/node/paths.js +115 -0
- package/dist/node/program.d.ts +74 -0
- package/dist/node/program.js +385 -0
- package/dist/node/state.d.ts +7 -0
- package/dist/node/state.js +12 -0
- package/dist/node/suggest.d.ts +13 -0
- package/dist/node/suggest.js +87 -0
- package/dist/node/types.d.ts +142 -0
- package/dist/node/types.js +13 -0
- package/dist/node/version.d.ts +10 -0
- package/dist/node/version.js +50 -0
- package/dist/node/wire.d.ts +32 -0
- package/dist/node/wire.js +44 -0
- package/dist/react/index.d.ts +121 -0
- package/dist/react/index.js +205 -0
- package/dist/web/announce.d.ts +51 -0
- package/dist/web/announce.js +141 -0
- package/dist/web/attach.d.ts +77 -0
- package/dist/web/attach.js +89 -0
- package/dist/web/box.d.ts +57 -0
- package/dist/web/box.js +150 -0
- package/dist/web/dom.d.ts +80 -0
- package/dist/web/dom.js +265 -0
- package/dist/web/index.d.ts +8 -0
- package/dist/web/index.js +8 -0
- package/dist/web/logic.d.ts +308 -0
- package/dist/web/logic.js +467 -0
- package/dist/web/overlay.d.ts +56 -0
- package/dist/web/overlay.js +211 -0
- package/dist/web/style.css +193 -0
- package/dist/web/suggester.d.ts +189 -0
- package/dist/web/suggester.js +696 -0
- package/dist/web/ui.d.ts +65 -0
- package/dist/web/ui.js +32 -0
- package/dist/web/usage.d.ts +39 -0
- package/dist/web/usage.js +84 -0
- package/package.json +89 -4
- package/program.json +35 -0
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
// Word suggestions in a React text box: `createSuggest(options)` gives `useTextareaSuggest`, which draws the grey rest of the
|
|
3
|
+
// word after the caret (and the next word, dimmer) with a mirror of the textarea laid over it, and handles the keys that take
|
|
4
|
+
// it; and `makeSuggester`, for a box that is not a plain textarea (an editor: give it your own adapter). The pieces it draws
|
|
5
|
+
// are exported on their own as well: GreyMirror, FixChip, MidChip and Layer.
|
|
6
|
+
import { Fragment, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
|
7
|
+
import { createPortal } from 'react-dom';
|
|
8
|
+
import { BoxAdapter, bindBox, isOn, keepBoxClass } from '../web/box.js';
|
|
9
|
+
import { LAYER_STYLE, MIRROR_STYLE, followBox, followChip, isTouch, placeChip, placeMirror, segments, typedLetters } from '../web/dom.js';
|
|
10
|
+
import { chipsOf, diffLetters, moveSpot } from '../web/logic.js';
|
|
11
|
+
import { Announcer, spokenOf } from '../web/announce.js';
|
|
12
|
+
import { Suggester } from '../web/suggester.js';
|
|
13
|
+
import { CLOSE_ICON, DEFAULT_CLASSES, DEFAULT_LABELS } from '../web/ui.js';
|
|
14
|
+
export { newClientId, typedLetters } from '../web/dom.js';
|
|
15
|
+
// For a box that is not a textarea (`makeSuggester`): `new Announcer(document, { labels })`, then `announcer.show(spokenOf(view, before))` whenever the view
|
|
16
|
+
// changes, `announcer.listen(box)` for composing, and `announcer.destroy()` when the box goes.
|
|
17
|
+
export { ANNOUNCE_MS, Announcer, spokenOf } from '../web/announce.js';
|
|
18
|
+
export { BOX_CLASS, DEFAULT_CLASSES, DEFAULT_LABELS } from '../web/ui.js';
|
|
19
|
+
export { insertInto, replaceIn } from '../web/dom.js';
|
|
20
|
+
const look = (l) => ({ c: { ...DEFAULT_CLASSES, ...l.classes }, t: { ...DEFAULT_LABELS, ...l.labels } });
|
|
21
|
+
const Key = ({ label, l }) => _jsx(_Fragment, { children: l.kbd ? l.kbd(label) : _jsx("kbd", { className: look(l).c.kbd, children: label }) });
|
|
22
|
+
/** Whether the screen has no hover (a phone or a tablet): there is no Tab key to show, and the chip is the button. */
|
|
23
|
+
function useTouch() {
|
|
24
|
+
const [touch, setTouch] = useState(isTouch);
|
|
25
|
+
useEffect(() => {
|
|
26
|
+
if (typeof matchMedia !== 'function')
|
|
27
|
+
return;
|
|
28
|
+
const q = matchMedia('(hover:none)');
|
|
29
|
+
const on = () => setTouch(q.matches);
|
|
30
|
+
on();
|
|
31
|
+
q.addEventListener('change', on);
|
|
32
|
+
return () => q.removeEventListener('change', on);
|
|
33
|
+
}, []);
|
|
34
|
+
return touch;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* A layer laid exactly over a textarea's inside (same font, wrapping, padding, width and scroll, kept in step as it grows and
|
|
38
|
+
* scrolls) that lets the pointer through. Returns the layer's ref; the layer draws its own content.
|
|
39
|
+
*/
|
|
40
|
+
function useMirror(ta) {
|
|
41
|
+
const box = useRef(null);
|
|
42
|
+
const place = () => {
|
|
43
|
+
if (box.current && ta)
|
|
44
|
+
placeMirror(box.current, ta);
|
|
45
|
+
};
|
|
46
|
+
// Measured after every draw (the textarea grows with its text), and again as it resizes or scrolls.
|
|
47
|
+
useLayoutEffect(place);
|
|
48
|
+
useEffect(() => (ta ? followBox(place, ta) : undefined), [ta]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
49
|
+
return box;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The textarea's text, wrapped as the textarea wraps it: its text up to the caret unseen, then the grey words. Laid
|
|
53
|
+
* over the textarea, it lets the pointer through and is hidden from screen readers and from translation.
|
|
54
|
+
*/
|
|
55
|
+
export function GreyMirror({ ta, before, grey, ...l }) {
|
|
56
|
+
const box = useMirror(ta);
|
|
57
|
+
const { c } = look(l);
|
|
58
|
+
return (_jsxs("div", { ref: box, "aria-hidden": "true", translate: "no", className: c.mirror, style: MIRROR_STYLE, children: [_jsx("span", { style: { visibility: 'hidden' }, children: before }), _jsxs("span", { ...l.attributes?.grey, children: [_jsx("span", { className: c.grey, children: grey.word }), grey.next && _jsx("span", { className: c.greyNext, children: grey.next })] })] }));
|
|
59
|
+
}
|
|
60
|
+
const MARKS_STYLE = { ...MIRROR_STYLE, color: 'transparent' };
|
|
61
|
+
/**
|
|
62
|
+
* Exactly the textarea's text, its letters unseen, with each word typed wrong marked (so that nothing shifts), and an empty
|
|
63
|
+
* span at the caret where a chip points at. `markRef` is given the first mark's span of `fixAt` (a chip points at its first
|
|
64
|
+
* line), `caretRef` the span at `caret` when there is one.
|
|
65
|
+
*/
|
|
66
|
+
export function MarksMirror({ ta, text, marks, fixAt, caret, markRef, caretRef, ...l }) {
|
|
67
|
+
const box = useMirror(ta);
|
|
68
|
+
const { c } = look(l);
|
|
69
|
+
return (_jsxs("div", { ref: box, "aria-hidden": "true", translate: "no", className: c.marks, style: MARKS_STYLE, ...l.attributes?.marks, children: [segments(text, marks, fixAt, caret).map((s, i) => 'caret' in s ? (_jsx("span", { ref: caretRef }, `c${i}`)) : s.marked ? (_jsx("span", { ref: s.first ? markRef : undefined, className: c.mark, children: s.text }, i)) : (_jsx(Fragment, { children: s.text }, i))), text.endsWith('\n') && ''] }));
|
|
70
|
+
}
|
|
71
|
+
const keepFocus = (e) => e.preventDefault();
|
|
72
|
+
/** The fixed layer, in the page's body: placed above its anchor, or below it, and inside the screen. It never takes the focus. */
|
|
73
|
+
export function Layer({ anchor, within, children, ...l }) {
|
|
74
|
+
const ref = useRef(null);
|
|
75
|
+
const fns = useRef({ anchor, within });
|
|
76
|
+
fns.current = { anchor, within };
|
|
77
|
+
const place = useCallback(() => {
|
|
78
|
+
if (ref.current)
|
|
79
|
+
placeChip(ref.current, fns.current.anchor(), fns.current.within());
|
|
80
|
+
}, []);
|
|
81
|
+
// Measured after every draw (the words change), and again as the page scrolls or resizes.
|
|
82
|
+
useLayoutEffect(place);
|
|
83
|
+
useEffect(() => (ref.current ? followChip(ref.current, () => fns.current.within(), place).stop : undefined), [place]);
|
|
84
|
+
const { c } = look(l);
|
|
85
|
+
return createPortal(_jsx("div", { ref: ref, "data-grayling-chip": "", "aria-hidden": "true", ...l.attributes?.chip, className: c.layer, style: LAYER_STYLE, onPointerDown: keepFocus, onMouseDown: keepFocus, children: _jsx("div", { className: c.chip, children: children }) }), document.body);
|
|
86
|
+
}
|
|
87
|
+
/** The right word for one typed wrong: its changed letters strong, then Tab (dim when the grey word's Tab is the box's), then × to keep the word as typed. */
|
|
88
|
+
export function FixChip({ fix, anchor, within, onAccept, onKeep, ...l }) {
|
|
89
|
+
const touch = useTouch();
|
|
90
|
+
const d = diffLetters(fix.typed, fix.word);
|
|
91
|
+
const { c, t } = look(l);
|
|
92
|
+
return (_jsx(Layer, { anchor: anchor, within: within, ...l, children: _jsxs("div", { className: c.chipBox, children: [_jsx("span", { "aria-hidden": "true", className: c.chipBar }), _jsxs("button", { type: "button", tabIndex: -1, "aria-label": t.replace(fix.word), className: c.chipPart, onClick: onAccept, children: [_jsxs("span", { translate: "no", children: [d.pre, _jsx("span", { className: c.chipStrong, children: d.mid }), d.post] }), !touch && (fix.tab ? _jsx(Key, { label: t.tab(), l: l }) : _jsx("span", { className: c.chipDim, children: _jsx(Key, { label: t.tab(), l: l }) }))] }), l.icons?.close ? (_jsx("button", { type: "button", tabIndex: -1, "aria-label": t.keep(), className: c.chipClose, onClick: onKeep, children: l.icons.close })) : (_jsx("button", { type: "button", tabIndex: -1, "aria-label": t.keep(), className: c.chipClose, onClick: onKeep, dangerouslySetInnerHTML: { __html: CLOSE_ICON } }))] }) }));
|
|
93
|
+
}
|
|
94
|
+
/** A word suggested inside a text: the letters already typed in the text colour, the rest in grey, and Tab; a tap takes it. */
|
|
95
|
+
export function MidChip({ typed, word, anchor, within, onTake, ...l }) {
|
|
96
|
+
const touch = useTouch();
|
|
97
|
+
const { c, t } = look(l);
|
|
98
|
+
return (_jsx(Layer, { anchor: anchor, within: within, ...l, children: _jsx("div", { className: c.chipBox, children: _jsxs("button", { type: "button", tabIndex: -1, "aria-label": t.complete(typed + word), className: c.chipPart, onClick: onTake, children: [_jsxs("span", { translate: "no", children: [_jsx("span", { className: c.chipTyped, children: typed }), _jsx("span", { className: c.chipRest, children: word })] }), !touch && _jsx(Key, { label: t.tab(), l: l })] }) }) }));
|
|
99
|
+
}
|
|
100
|
+
export function createSuggest(o) {
|
|
101
|
+
const lk = { classes: o.classes, labels: o.labels, kbd: o.kbd, attributes: o.attributes, icons: o.icons };
|
|
102
|
+
const outside = { send: o.send, gate: o.gate, client: o.client, count: o.count, judge: o.judge, keep: o.keep, rest: o.rest };
|
|
103
|
+
/** A suggester for the box `adapter` reaches; `on` is told what to show (the grey word, the marks, the chip) whenever any of it changes. */
|
|
104
|
+
const makeSuggester = (adapter, on) => new Suggester(adapter, on, outside);
|
|
105
|
+
/**
|
|
106
|
+
* Word suggestions for the textarea in `ref`. `value` is its text (the hook asks again when it changes); `context`
|
|
107
|
+
* gives what goes with it (read when a request goes out, so it may be a function of the latest state).
|
|
108
|
+
*/
|
|
109
|
+
function useTextareaSuggest(ref, opt) {
|
|
110
|
+
const [view, setView] = useState(null);
|
|
111
|
+
const markRef = useRef(null);
|
|
112
|
+
const caretRef = useRef(null);
|
|
113
|
+
const opts = useRef(opt);
|
|
114
|
+
opts.current = opt;
|
|
115
|
+
const made = useRef(null);
|
|
116
|
+
if (!made.current) {
|
|
117
|
+
const ad = new BoxAdapter(() => ref.current, () => opts.current);
|
|
118
|
+
const ctl = makeSuggester(ad, (v) => setView(v.grey || v.marks.length || v.fix ? { v, before: ref.current ? ref.current.value.slice(0, ref.current.selectionStart) : '' } : null));
|
|
119
|
+
made.current = { ad, ctl };
|
|
120
|
+
}
|
|
121
|
+
const { ad, ctl } = made.current;
|
|
122
|
+
// What a screen reader is told (a polite live region, one for the page).
|
|
123
|
+
const ann = useRef(null);
|
|
124
|
+
useEffect(() => {
|
|
125
|
+
if (o.announce === false)
|
|
126
|
+
return;
|
|
127
|
+
const a = new Announcer(document, { labels: o.labels });
|
|
128
|
+
ann.current = a;
|
|
129
|
+
return () => {
|
|
130
|
+
a.destroy();
|
|
131
|
+
ann.current = null;
|
|
132
|
+
};
|
|
133
|
+
}, []);
|
|
134
|
+
useEffect(() => {
|
|
135
|
+
ann.current?.show(view && spokenOf(view.v, view.before));
|
|
136
|
+
}, [view]);
|
|
137
|
+
// The class the box carries while suggestions are on in it. A render that sets the box's className drops it: put back after
|
|
138
|
+
// every render, and by the observer in between.
|
|
139
|
+
const cls = useRef(null);
|
|
140
|
+
useEffect(() => {
|
|
141
|
+
const el = ref.current;
|
|
142
|
+
if (cls.current && cls.current.el !== el)
|
|
143
|
+
(cls.current.k.stop(), (cls.current = null));
|
|
144
|
+
if (!cls.current && el)
|
|
145
|
+
cls.current = { el, k: keepBoxClass(el, () => isOn(o.gate, opts.current)) };
|
|
146
|
+
else
|
|
147
|
+
cls.current?.k.refresh();
|
|
148
|
+
});
|
|
149
|
+
useEffect(() => () => {
|
|
150
|
+
cls.current?.k.stop();
|
|
151
|
+
cls.current = null;
|
|
152
|
+
}, []);
|
|
153
|
+
// The textarea's own events, on whichever element the ref holds now (a box may appear after the component did).
|
|
154
|
+
const bound = useRef(null);
|
|
155
|
+
const unbind = useRef(null);
|
|
156
|
+
useEffect(() => {
|
|
157
|
+
const el = ref.current;
|
|
158
|
+
if (el === bound.current)
|
|
159
|
+
return;
|
|
160
|
+
unbind.current?.();
|
|
161
|
+
bound.current = el;
|
|
162
|
+
if (!el)
|
|
163
|
+
return;
|
|
164
|
+
const stop = bindBox(el, ctl, ad, o.warm);
|
|
165
|
+
const unlisten = ann.current?.listen(el);
|
|
166
|
+
unbind.current = () => (stop(), unlisten?.());
|
|
167
|
+
});
|
|
168
|
+
useEffect(() => () => {
|
|
169
|
+
unbind.current?.();
|
|
170
|
+
bound.current = null;
|
|
171
|
+
ctl.reset();
|
|
172
|
+
}, []);
|
|
173
|
+
// Text set from outside (a draft coming back, a send emptying the box), and the switches turned on or off.
|
|
174
|
+
useEffect(() => {
|
|
175
|
+
ctl.sync();
|
|
176
|
+
}, [opt.value, opt.off, opt.place]);
|
|
177
|
+
useEffect(() => o.subscribe?.(() => {
|
|
178
|
+
cls.current?.k.refresh();
|
|
179
|
+
ctl.sync();
|
|
180
|
+
}), []);
|
|
181
|
+
// What is drawn: the grey word at the end of a text, the marks on words typed wrong, and the chips over the text.
|
|
182
|
+
const el = ref.current;
|
|
183
|
+
let overlay = null;
|
|
184
|
+
if (view) {
|
|
185
|
+
const { v, before } = view;
|
|
186
|
+
const { fix, mid } = chipsOf(v);
|
|
187
|
+
const text = el?.value ?? opt.value;
|
|
188
|
+
// A letter typed since the box was last read moves the words after it: drawn with them, not a letter off until it is read again.
|
|
189
|
+
const marks = v.marks.flatMap((m) => moveSpot(m, ctl.text, text) ?? []);
|
|
190
|
+
const rectOf = (n) => (n?.isConnected ? (n.getClientRects()[0] ?? n.getBoundingClientRect()) : null);
|
|
191
|
+
overlay = (_jsxs(_Fragment, { children: [v.grey && !v.mid && _jsx(GreyMirror, { ta: el, before: before, grey: v.grey, ...lk }), (marks.length > 0 || mid) && _jsx(MarksMirror, { ta: el, text: text, marks: marks, fixAt: fix ? (moveSpot(fix, ctl.text, text)?.start ?? null) : null, caret: mid ? before.length : null, markRef: markRef, caretRef: caretRef, ...lk }), fix && _jsx(FixChip, { fix: fix, anchor: () => rectOf(markRef.current), within: () => ref.current, onAccept: () => ctl.accept(), onKeep: () => ctl.keep(), ...lk }), mid && _jsx(MidChip, { typed: typedLetters(before), word: mid.word, anchor: () => rectOf(caretRef.current), within: () => ref.current, onTake: () => ctl.tab(), ...lk })] }));
|
|
192
|
+
}
|
|
193
|
+
return {
|
|
194
|
+
onKeyDown: (e) => ctl.key({ key: e.key, shiftKey: e.shiftKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, altKey: e.altKey, isComposing: e.nativeEvent.isComposing, preventDefault: () => e.preventDefault(), stopPropagation: () => e.stopPropagation() }),
|
|
195
|
+
overlay,
|
|
196
|
+
shown: !!view?.v.grey,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
/** The chips with this app's look already on them (for a box that is not a textarea: an editor draws them itself). */
|
|
200
|
+
const bound = {
|
|
201
|
+
FixChip: (p) => _jsx(FixChip, { ...lk, ...p }),
|
|
202
|
+
MidChip: (p) => _jsx(MidChip, { ...lk, ...p }),
|
|
203
|
+
};
|
|
204
|
+
return { useTextareaSuggest, makeSuggester, ...bound };
|
|
205
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { type View } from './logic.js';
|
|
2
|
+
import { type Labels } from './ui.js';
|
|
3
|
+
/** A suggestion that has stood this long (ms) unchanged is announced. */
|
|
4
|
+
export declare const ANNOUNCE_MS = 1200;
|
|
5
|
+
/** What is announced: the whole word, or a word typed wrong and the word for it. */
|
|
6
|
+
export type Spoken = {
|
|
7
|
+
kind: 'word';
|
|
8
|
+
word: string;
|
|
9
|
+
} | {
|
|
10
|
+
kind: 'fix';
|
|
11
|
+
word: string;
|
|
12
|
+
typed: string;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* What a view says to a screen reader: the right word of a fix that Tab puts in, else the whole word of the grey suggestion (the letters
|
|
16
|
+
* typed and the rest of it). Only what a key takes is announced. `before` is the text before the caret.
|
|
17
|
+
*/
|
|
18
|
+
export declare function spokenOf(v: View, before: string): Spoken | null;
|
|
19
|
+
export interface AnnouncerOptions {
|
|
20
|
+
/** Your words (`suggestion`, `correction`, `tab`). */
|
|
21
|
+
labels?: Partial<Labels>;
|
|
22
|
+
/** How long a suggestion must stand before it is announced (ms; 1200). */
|
|
23
|
+
after?: number;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Announces what a box shows. Call `show` with what stands now (`spokenOf(view, before)`, or null) every time the view changes: a
|
|
27
|
+
* suggestion is announced once, when it has stood for 1.2 s, and the region is emptied when it goes. Nothing is announced while an input
|
|
28
|
+
* method composes (`listen(box)` watches for it). `destroy` takes the region away when no other box uses it.
|
|
29
|
+
*/
|
|
30
|
+
export declare class Announcer {
|
|
31
|
+
private labels;
|
|
32
|
+
private doc;
|
|
33
|
+
private region;
|
|
34
|
+
private after;
|
|
35
|
+
/** What stands and is not announced yet, and the timer that will say it. */
|
|
36
|
+
private pending;
|
|
37
|
+
private timer;
|
|
38
|
+
/** What was announced and still stands. */
|
|
39
|
+
private said;
|
|
40
|
+
private composing;
|
|
41
|
+
constructor(doc?: Document, o?: AnnouncerOptions);
|
|
42
|
+
/** Watch a box for an input method composing (nothing is announced then). Returns what stops it. */
|
|
43
|
+
listen(box: EventTarget): () => void;
|
|
44
|
+
/** What stands now (null: nothing). */
|
|
45
|
+
show(what: Spoken | null): void;
|
|
46
|
+
private say;
|
|
47
|
+
private cancel;
|
|
48
|
+
/** Nothing shows: what is waiting is dropped, and what was said is taken out of the region (so that it is not read again later). */
|
|
49
|
+
clear(): void;
|
|
50
|
+
destroy(): void;
|
|
51
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// What a screen reader is told (docs/accessibility.md): a text box of a web page cannot tell whether a screen reader runs, so a suggestion
|
|
2
|
+
// that has stood for 1.2 s is put in a polite live region that cannot be seen ("Suggestion: questions. Tab takes it."). The grey text and
|
|
3
|
+
// the chips themselves are hidden from screen readers (the box's own text is what is being read).
|
|
4
|
+
//
|
|
5
|
+
// One region per page, shared by every box and taken away with the last `destroy`. It is visually hidden the way assistive text is
|
|
6
|
+
// (a 1 px clipped box, not `display:none`, which a screen reader would skip).
|
|
7
|
+
import { chipsOf } from './logic.js';
|
|
8
|
+
import { typedLetters } from './dom.js';
|
|
9
|
+
import { DEFAULT_LABELS } from './ui.js';
|
|
10
|
+
/** A suggestion that has stood this long (ms) unchanged is announced. */
|
|
11
|
+
export const ANNOUNCE_MS = 1200;
|
|
12
|
+
/**
|
|
13
|
+
* What a view says to a screen reader: the right word of a fix that Tab puts in, else the whole word of the grey suggestion (the letters
|
|
14
|
+
* typed and the rest of it). Only what a key takes is announced. `before` is the text before the caret.
|
|
15
|
+
*/
|
|
16
|
+
export function spokenOf(v, before) {
|
|
17
|
+
const { fix } = chipsOf(v);
|
|
18
|
+
if (fix?.tab)
|
|
19
|
+
return { kind: 'fix', word: fix.word, typed: fix.typed };
|
|
20
|
+
if (v.grey && (v.grey.word || v.grey.next)) {
|
|
21
|
+
const word = (typedLetters(before) + v.grey.word).trim();
|
|
22
|
+
return word ? { kind: 'word', word } : null;
|
|
23
|
+
}
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
const sameSpoken = (a, b) => !!a && !!b && a.kind === b.kind && a.word === b.word && (a.kind === 'fix' ? a.typed : '') === (b.kind === 'fix' ? b.typed : '');
|
|
27
|
+
const HIDDEN = {
|
|
28
|
+
position: 'absolute',
|
|
29
|
+
width: '1px',
|
|
30
|
+
height: '1px',
|
|
31
|
+
margin: '-1px',
|
|
32
|
+
padding: '0',
|
|
33
|
+
border: '0',
|
|
34
|
+
overflow: 'hidden',
|
|
35
|
+
clip: 'rect(0 0 0 0)',
|
|
36
|
+
clipPath: 'inset(50%)',
|
|
37
|
+
whiteSpace: 'nowrap',
|
|
38
|
+
};
|
|
39
|
+
const regions = new WeakMap();
|
|
40
|
+
function acquire(doc) {
|
|
41
|
+
let r = regions.get(doc);
|
|
42
|
+
if (!r) {
|
|
43
|
+
const el = doc.createElement('div');
|
|
44
|
+
el.setAttribute('role', 'status');
|
|
45
|
+
el.setAttribute('aria-live', 'polite');
|
|
46
|
+
el.setAttribute('aria-atomic', 'true');
|
|
47
|
+
el.setAttribute('data-grayling-live', '');
|
|
48
|
+
Object.assign(el.style, HIDDEN);
|
|
49
|
+
doc.body.append(el);
|
|
50
|
+
r = { el, users: 0 };
|
|
51
|
+
regions.set(doc, r);
|
|
52
|
+
}
|
|
53
|
+
r.users++;
|
|
54
|
+
return r.el;
|
|
55
|
+
}
|
|
56
|
+
function release(doc) {
|
|
57
|
+
const r = regions.get(doc);
|
|
58
|
+
if (!r || --r.users > 0)
|
|
59
|
+
return;
|
|
60
|
+
r.el.remove();
|
|
61
|
+
regions.delete(doc);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Announces what a box shows. Call `show` with what stands now (`spokenOf(view, before)`, or null) every time the view changes: a
|
|
65
|
+
* suggestion is announced once, when it has stood for 1.2 s, and the region is emptied when it goes. Nothing is announced while an input
|
|
66
|
+
* method composes (`listen(box)` watches for it). `destroy` takes the region away when no other box uses it.
|
|
67
|
+
*/
|
|
68
|
+
export class Announcer {
|
|
69
|
+
labels;
|
|
70
|
+
doc;
|
|
71
|
+
region;
|
|
72
|
+
after;
|
|
73
|
+
/** What stands and is not announced yet, and the timer that will say it. */
|
|
74
|
+
pending = null;
|
|
75
|
+
timer;
|
|
76
|
+
/** What was announced and still stands. */
|
|
77
|
+
said = null;
|
|
78
|
+
composing = false;
|
|
79
|
+
constructor(doc = document, o = {}) {
|
|
80
|
+
this.doc = doc;
|
|
81
|
+
this.labels = { ...DEFAULT_LABELS, ...o.labels };
|
|
82
|
+
this.after = o.after ?? ANNOUNCE_MS;
|
|
83
|
+
this.region = acquire(doc);
|
|
84
|
+
}
|
|
85
|
+
/** Watch a box for an input method composing (nothing is announced then). Returns what stops it. */
|
|
86
|
+
listen(box) {
|
|
87
|
+
const start = () => ((this.composing = true), this.clear());
|
|
88
|
+
const end = () => (this.composing = false);
|
|
89
|
+
box.addEventListener('compositionstart', start);
|
|
90
|
+
box.addEventListener('compositionend', end);
|
|
91
|
+
return () => {
|
|
92
|
+
box.removeEventListener('compositionstart', start);
|
|
93
|
+
box.removeEventListener('compositionend', end);
|
|
94
|
+
this.composing = false;
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
/** What stands now (null: nothing). */
|
|
98
|
+
show(what) {
|
|
99
|
+
if (!this.region)
|
|
100
|
+
return;
|
|
101
|
+
if (!what || this.composing)
|
|
102
|
+
return this.clear();
|
|
103
|
+
if (sameSpoken(what, this.said))
|
|
104
|
+
return this.cancel();
|
|
105
|
+
if (sameSpoken(what, this.pending))
|
|
106
|
+
return;
|
|
107
|
+
this.cancel();
|
|
108
|
+
this.pending = what;
|
|
109
|
+
this.timer = setTimeout(() => this.say(), this.after);
|
|
110
|
+
}
|
|
111
|
+
say() {
|
|
112
|
+
this.timer = undefined;
|
|
113
|
+
const p = this.pending;
|
|
114
|
+
this.pending = null;
|
|
115
|
+
if (!p || !this.region)
|
|
116
|
+
return;
|
|
117
|
+
const key = this.labels.tab();
|
|
118
|
+
this.region.textContent = p.kind === 'word' ? this.labels.suggestion(p.word, key) : this.labels.correction(p.word, p.typed, key);
|
|
119
|
+
this.said = p;
|
|
120
|
+
}
|
|
121
|
+
cancel() {
|
|
122
|
+
if (this.timer !== undefined)
|
|
123
|
+
clearTimeout(this.timer);
|
|
124
|
+
this.timer = undefined;
|
|
125
|
+
this.pending = null;
|
|
126
|
+
}
|
|
127
|
+
/** Nothing shows: what is waiting is dropped, and what was said is taken out of the region (so that it is not read again later). */
|
|
128
|
+
clear() {
|
|
129
|
+
this.cancel();
|
|
130
|
+
this.said = null;
|
|
131
|
+
if (this.region)
|
|
132
|
+
this.region.textContent = '';
|
|
133
|
+
}
|
|
134
|
+
destroy() {
|
|
135
|
+
if (!this.region)
|
|
136
|
+
return;
|
|
137
|
+
this.clear();
|
|
138
|
+
this.region = null;
|
|
139
|
+
release(this.doc);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { SuggestCounts, SuggestPlan, SuggestRequest, SuggestResponse } from '../index.js';
|
|
2
|
+
import { type TextBox } from './dom.js';
|
|
3
|
+
import type { Gate, Place } from './logic.js';
|
|
4
|
+
import { type OverlayOptions } from './overlay.js';
|
|
5
|
+
import { type Adapter } from './suggester.js';
|
|
6
|
+
import type { Attributes, Classes, Labels } from './ui.js';
|
|
7
|
+
type Context = ReturnType<Adapter['context']>;
|
|
8
|
+
/** How a box gets an answer: given the request and a signal that says when it is no longer wanted. null: nothing to show. */
|
|
9
|
+
export type Send = (req: SuggestRequest, signal: AbortSignal) => Promise<SuggestResponse | null>;
|
|
10
|
+
export interface AttachOptions {
|
|
11
|
+
/** A POST endpoint that takes a SuggestRequest as JSON and answers a SuggestResponse as JSON, or 204 for nothing. */
|
|
12
|
+
url?: string;
|
|
13
|
+
/** Extra headers for the POST to `url` (an authorization header, say). */
|
|
14
|
+
headers?: Record<string, string>;
|
|
15
|
+
/** Cookies and the like for the POST to `url` (fetch's `credentials`). */
|
|
16
|
+
credentials?: RequestCredentials;
|
|
17
|
+
/** Your own way to get an answer (used instead of `url`). */
|
|
18
|
+
send?: Send;
|
|
19
|
+
/** Where the box is (`other`: any text box; `chat`: a message to an agent; `docs`; `notes`). Decides what is sent and which `gate` switches count. */
|
|
20
|
+
place?: Place;
|
|
21
|
+
/** What goes with the text: the reply being answered (chat), the document before the paragraph (docs), the session. Read when a request goes out. */
|
|
22
|
+
context?: () => Context;
|
|
23
|
+
/** The switches, when you have them (see `Gate`). Else the simple ones below are used. */
|
|
24
|
+
gate?: () => Gate;
|
|
25
|
+
/** Simple switches: on at all (default true), a word inside a text (default true), words typed wrong (default true). */
|
|
26
|
+
enabled?: boolean | (() => boolean);
|
|
27
|
+
midText?: boolean;
|
|
28
|
+
fixTypos?: boolean;
|
|
29
|
+
/** Called when the switches change from outside (return what stops it): the box looks again. */
|
|
30
|
+
subscribe?: (cb: () => void) => () => void;
|
|
31
|
+
/** Called when the box gets the focus (to start the engine, say). */
|
|
32
|
+
warm?: () => void;
|
|
33
|
+
/** This client's id: a new request cancels the client's one before (default: one for this page). */
|
|
34
|
+
client?: string;
|
|
35
|
+
labels?: Partial<Labels>;
|
|
36
|
+
classes?: Partial<Classes>;
|
|
37
|
+
attributes?: Attributes;
|
|
38
|
+
/** The key drawn beside a word on a chip (default: a <kbd> with the label). */
|
|
39
|
+
kbd?: OverlayOptions['kbd'];
|
|
40
|
+
/**
|
|
41
|
+
* Tell a screen reader about a suggestion that has stood for 1.2 s, in a polite live region that cannot be seen (default true; the words are
|
|
42
|
+
* `labels.suggestion` and `labels.correction`). A web page cannot tell whether a screen reader runs, so this is for everyone.
|
|
43
|
+
*/
|
|
44
|
+
announce?: boolean;
|
|
45
|
+
/** Told what suggestions did, as counts only (see `UsageBatch`). */
|
|
46
|
+
onCount?: (c: Partial<SuggestCounts>) => void;
|
|
47
|
+
/** Told whether a guess, shown or not, was right: how sure it was and which plan made it, never the word. */
|
|
48
|
+
onJudge?: (plan: SuggestPlan, conf: number, right: boolean) => void;
|
|
49
|
+
/** Told which word the person kept as typed (Esc on its fix). */
|
|
50
|
+
onKeep?: (word: string) => void;
|
|
51
|
+
/** How long the caret rests before its word is checked (ms). */
|
|
52
|
+
rest?: number;
|
|
53
|
+
}
|
|
54
|
+
export interface Attached {
|
|
55
|
+
/** Take everything away again: the listeners, the mirror, the chips, the class. */
|
|
56
|
+
detach(): void;
|
|
57
|
+
/** Look at the box and the switches again (after changing what `gate` or `enabled` says). */
|
|
58
|
+
refresh(): void;
|
|
59
|
+
}
|
|
60
|
+
/** A POST to `url`: the request as JSON, the answer as JSON, or null for a 204. */
|
|
61
|
+
export declare function postTo(url: string, o?: {
|
|
62
|
+
headers?: Record<string, string>;
|
|
63
|
+
credentials?: RequestCredentials;
|
|
64
|
+
}): Send;
|
|
65
|
+
/** The switches when none were given: everything on, in every place. */
|
|
66
|
+
export declare function simpleGate(o?: {
|
|
67
|
+
enabled?: boolean | (() => boolean);
|
|
68
|
+
midText?: boolean;
|
|
69
|
+
fixTypos?: boolean;
|
|
70
|
+
}): () => Gate;
|
|
71
|
+
/**
|
|
72
|
+
* Give a <textarea> or <input type="text"> word suggestions: the rest of the word being typed in grey after the caret (Tab
|
|
73
|
+
* takes it, → takes it and the next word, Esc hides it), a chip over the caret for a word suggested inside a text, and a mark
|
|
74
|
+
* with a chip for a word typed wrong.
|
|
75
|
+
*/
|
|
76
|
+
export declare function attach(el: TextBox, options?: AttachOptions): Attached;
|
|
77
|
+
export {};
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { Announcer, spokenOf } from './announce.js';
|
|
2
|
+
import { BoxAdapter, bindBox, isOn, keepBoxClass } from './box.js';
|
|
3
|
+
import { newClientId } from './dom.js';
|
|
4
|
+
import { Overlay } from './overlay.js';
|
|
5
|
+
import { Suggester } from './suggester.js';
|
|
6
|
+
/** A POST to `url`: the request as JSON, the answer as JSON, or null for a 204. */
|
|
7
|
+
export function postTo(url, o = {}) {
|
|
8
|
+
return async (req, signal) => {
|
|
9
|
+
const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', ...o.headers }, body: JSON.stringify(req), signal, ...(o.credentials ? { credentials: o.credentials } : {}) });
|
|
10
|
+
if (res.status === 204)
|
|
11
|
+
return null;
|
|
12
|
+
if (!res.ok)
|
|
13
|
+
throw new Error(`suggest: ${res.status}`);
|
|
14
|
+
return (await res.json());
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/** The switches when none were given: everything on, in every place. */
|
|
18
|
+
export function simpleGate(o = {}) {
|
|
19
|
+
return () => ({
|
|
20
|
+
enabled: typeof o.enabled === 'function' ? o.enabled() : (o.enabled ?? true),
|
|
21
|
+
state: 'ready',
|
|
22
|
+
where: { chat: true, docs: true, notes: true, other: true },
|
|
23
|
+
browser: true,
|
|
24
|
+
midText: o.midText ?? true,
|
|
25
|
+
fixTypos: o.fixTypos ?? true,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Give a <textarea> or <input type="text"> word suggestions: the rest of the word being typed in grey after the caret (Tab
|
|
30
|
+
* takes it, → takes it and the next word, Esc hides it), a chip over the caret for a word suggested inside a text, and a mark
|
|
31
|
+
* with a chip for a word typed wrong.
|
|
32
|
+
*/
|
|
33
|
+
export function attach(el, options = {}) {
|
|
34
|
+
const send = options.send ?? (options.url ? postTo(options.url, options) : null);
|
|
35
|
+
if (!send)
|
|
36
|
+
throw new Error('grayling attach: give `url` or `send`');
|
|
37
|
+
const gate = options.gate ?? simpleGate(options);
|
|
38
|
+
const state = { place: options.place ?? 'other', context: options.context };
|
|
39
|
+
const ad = new BoxAdapter(() => el, () => state);
|
|
40
|
+
let shown = null;
|
|
41
|
+
const announcer = options.announce === false ? null : new Announcer(el.ownerDocument, { labels: options.labels });
|
|
42
|
+
const overlay = new Overlay(el, {
|
|
43
|
+
classes: options.classes,
|
|
44
|
+
labels: options.labels,
|
|
45
|
+
attributes: options.attributes,
|
|
46
|
+
kbd: options.kbd,
|
|
47
|
+
onAccept: () => ctl.accept(),
|
|
48
|
+
onKeep: () => ctl.keep(),
|
|
49
|
+
onTake: () => ctl.tab(),
|
|
50
|
+
});
|
|
51
|
+
const redraw = () => overlay.update(shown, ctl.text);
|
|
52
|
+
const ctl = new Suggester(ad, (v) => {
|
|
53
|
+
shown = v.grey || v.marks.length || v.fix ? { v, before: el.value.slice(0, el.selectionStart ?? 0) } : null;
|
|
54
|
+
redraw();
|
|
55
|
+
announcer?.show(shown && spokenOf(shown.v, shown.before));
|
|
56
|
+
}, { send, gate, client: options.client ?? newClientId(), count: options.onCount, judge: options.onJudge, keep: options.onKeep, rest: options.rest });
|
|
57
|
+
const cls = keepBoxClass(el, () => isOn(gate, state));
|
|
58
|
+
const refresh = () => (cls.refresh(), ctl.sync());
|
|
59
|
+
const unbind = bindBox(el, ctl, ad, options.warm);
|
|
60
|
+
// A letter typed moves the marks after it: drawn with the text as it is now, before the suggester has looked again.
|
|
61
|
+
const typed = () => (cls.refresh(), shown && redraw());
|
|
62
|
+
el.addEventListener('input', typed);
|
|
63
|
+
el.addEventListener('focus', cls.refresh);
|
|
64
|
+
const key = (e) => void ctl.key({ key: e.key, shiftKey: e.shiftKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, altKey: e.altKey, isComposing: e.isComposing, preventDefault: () => e.preventDefault(), stopPropagation: () => e.stopPropagation() });
|
|
65
|
+
// In the capture phase, so that the box's own Tab handling (a form's, an editor's) never gets the key a suggestion takes.
|
|
66
|
+
el.addEventListener('keydown', key, true);
|
|
67
|
+
const unsub = options.subscribe?.(refresh);
|
|
68
|
+
const unlisten = announcer?.listen(el);
|
|
69
|
+
ctl.sync();
|
|
70
|
+
let gone = false;
|
|
71
|
+
return {
|
|
72
|
+
refresh,
|
|
73
|
+
detach() {
|
|
74
|
+
if (gone)
|
|
75
|
+
return;
|
|
76
|
+
gone = true;
|
|
77
|
+
unsub?.();
|
|
78
|
+
unlisten?.();
|
|
79
|
+
el.removeEventListener('input', typed);
|
|
80
|
+
el.removeEventListener('focus', cls.refresh);
|
|
81
|
+
el.removeEventListener('keydown', key, true);
|
|
82
|
+
unbind();
|
|
83
|
+
ctl.reset();
|
|
84
|
+
overlay.destroy();
|
|
85
|
+
announcer?.destroy();
|
|
86
|
+
cls.stop();
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { type TextBox } from './dom.js';
|
|
2
|
+
import { type Gate, type Place } from './logic.js';
|
|
3
|
+
import type { Adapter, Suggester } from './suggester.js';
|
|
4
|
+
type Context = ReturnType<Adapter['context']>;
|
|
5
|
+
/** What a box's adapter needs to know from outside, each read when it is needed. */
|
|
6
|
+
export interface BoxState {
|
|
7
|
+
place: Place;
|
|
8
|
+
context?: () => Context;
|
|
9
|
+
/** Suggestions are off in this box (a read-only box, a password box). */
|
|
10
|
+
off?: boolean;
|
|
11
|
+
}
|
|
12
|
+
/** The adapter of one box: the suggester reads the box and writes into it through this. */
|
|
13
|
+
export declare class BoxAdapter implements Adapter {
|
|
14
|
+
private box;
|
|
15
|
+
private state;
|
|
16
|
+
/** An input method (Japanese, Chinese, an accent key…) is composing. */
|
|
17
|
+
composing: boolean;
|
|
18
|
+
constructor(box: () => TextBox | null, state: () => BoxState);
|
|
19
|
+
get place(): Place;
|
|
20
|
+
read(): {
|
|
21
|
+
before: string;
|
|
22
|
+
after: string;
|
|
23
|
+
selected: boolean;
|
|
24
|
+
picked?: string | undefined;
|
|
25
|
+
composing: boolean;
|
|
26
|
+
} | null;
|
|
27
|
+
insert(text: string): void;
|
|
28
|
+
replace(start: number, end: number, word: string): boolean;
|
|
29
|
+
context(): {
|
|
30
|
+
reply?: string;
|
|
31
|
+
prev?: string;
|
|
32
|
+
doc?: string;
|
|
33
|
+
session?: string;
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The box's own events, so that the suggester looks again after each: typing, a composition, the focus, a click, a key up, a
|
|
38
|
+
* caret move. Returns what takes them off. `warm` is called when the box gets the focus.
|
|
39
|
+
*/
|
|
40
|
+
export declare function bindBox(el: TextBox, ctl: Pick<Suggester, 'sync' | 'reset'>, ad: {
|
|
41
|
+
composing: boolean;
|
|
42
|
+
}, warm?: () => void): () => void;
|
|
43
|
+
/** Whether suggestions are on in a box in `place` now: the switches allow the place, and the box is not off. */
|
|
44
|
+
export declare const isOn: (gate: () => Gate, s: BoxState) => boolean;
|
|
45
|
+
/**
|
|
46
|
+
* Keep the class `grayling-box` and `aria-autocomplete` on a box exactly while `on()` says so, even when something else (a framework's
|
|
47
|
+
* render) rewrites the box's attributes. Both say, to the desktop app and to assistive technology, that the box completes by itself,
|
|
48
|
+
* so that suggestions never show twice in it: `aria-autocomplete` is `inline` when the page gave none or `none`, `both` when it gave
|
|
49
|
+
* `list` (and what it gave when that already says inline). Firefox shows neither of them to accessibility clients on macOS, but a box's
|
|
50
|
+
* `id`: one without an `id` gets `grayling-box-…`. What the page set is put back when `on()` says no, and by `stop`; a page
|
|
51
|
+
* that changes it meanwhile is followed. Returns `refresh` (check now) and what stops it.
|
|
52
|
+
*/
|
|
53
|
+
export declare function keepBoxClass(el: Element, on: () => boolean): {
|
|
54
|
+
refresh: () => void;
|
|
55
|
+
stop: () => void;
|
|
56
|
+
};
|
|
57
|
+
export {};
|