rubyfield 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +237 -2
- package/dist/chunk-TFNIKGHG.js +548 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +20 -0
- package/dist/session.d.ts +24 -0
- package/dist/session.js +6 -0
- package/dist/types-B8H5PDW4.d.ts +127 -0
- package/package.json +45 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 graphemecluster
|
|
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,238 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Rubyfield
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/rubyfield)
|
|
4
|
+
[](https://jsr.io/@rubyfield/core)
|
|
5
|
+
[](https://www.npmjs.com/package/rubyfield?activeTab=code)
|
|
6
|
+
[](https://github.com/graphemecluster/rubyfield/blob/main/LICENSE)
|
|
7
|
+
|
|
8
|
+
Rubyfield turns readings, glosses, and other text annotations into an input field you can see and try immediately. Type and edit the base text while the annotations update live above it.
|
|
9
|
+
|
|
10
|
+
Use it as a Pinyin, Jyutping, or Furigana input field with the [recipes](#recipes) below—or plug in your own annotation function. NLP library authors can use the same component as a playground: change the function, type a sentence, and see its output live.
|
|
11
|
+
|
|
12
|
+
- [Mandarin Pinyin](#mandarin-pinyin) with `pinyin-pro`.
|
|
13
|
+
- [Cantonese Jyutping](#cantonese-jyutping) with `to-jyutping`.
|
|
14
|
+
- [Japanese Furigana](#japanese-furigana) with `kuromoji` and `wanakana`.
|
|
15
|
+
- Custom readings, glosses, and other annotations through one `annotate` function.
|
|
16
|
+
|
|
17
|
+
Try the [live demo](https://graphemecluster.github.io/rubyfield/).
|
|
18
|
+
|
|
19
|
+
| For | Use Package |
|
|
20
|
+
| --- | --- |
|
|
21
|
+
| Framework-agnostic JavaScript | [rubyfield][core] [current] |
|
|
22
|
+
| React 18+ | [@rubyfield/react][react] |
|
|
23
|
+
| Vue 3+ | [@rubyfield/vue][vue] |
|
|
24
|
+
|
|
25
|
+
## Quick start
|
|
26
|
+
|
|
27
|
+
Install `rubyfield`.
|
|
28
|
+
|
|
29
|
+
```html
|
|
30
|
+
<div id="field" class="your-wrapper-class"></div>
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
import { createRubyfield } from "rubyfield";
|
|
35
|
+
|
|
36
|
+
const content = { current: "你好" };
|
|
37
|
+
|
|
38
|
+
const field = createRubyfield(document.querySelector("#field")!, {
|
|
39
|
+
content: content.current,
|
|
40
|
+
onUpdate: value => { content.current = value; },
|
|
41
|
+
placeholder: "Start typing…",
|
|
42
|
+
annotate: text => text === "你好" ? [[0, 1, "nei5"], [1, 2, "hou2"]] : [],
|
|
43
|
+
attributes: { class: "your-input-field-class" },
|
|
44
|
+
});
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Recipes
|
|
48
|
+
|
|
49
|
+
Each example mounts into an existing `<div id="field"></div>`. Call `field.destroy()` when removing the field.
|
|
50
|
+
|
|
51
|
+
### Mandarin Pinyin
|
|
52
|
+
|
|
53
|
+
Install `pinyin-pro`.
|
|
54
|
+
|
|
55
|
+
```js
|
|
56
|
+
import { pinyin } from "pinyin-pro";
|
|
57
|
+
import { createRubyfield, segmentsToRanges } from "rubyfield";
|
|
58
|
+
|
|
59
|
+
const annotate = text => segmentsToRanges(pinyin(text, { type: "all" }).map(({ origin, pinyin, isZh }) => [origin, isZh ? pinyin : null]));
|
|
60
|
+
|
|
61
|
+
const field = createRubyfield(document.getElementById("field"), {
|
|
62
|
+
annotate,
|
|
63
|
+
attributes: { lang: "zh" },
|
|
64
|
+
ruby: { rt: { attributes: { lang: "zh-Latn-pinyin" } } },
|
|
65
|
+
});
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### Cantonese Jyutping
|
|
69
|
+
|
|
70
|
+
Install `to-jyutping`.
|
|
71
|
+
|
|
72
|
+
```js
|
|
73
|
+
import { getJyutpingList } from "to-jyutping";
|
|
74
|
+
import { createRubyfield, segmentsToRanges } from "rubyfield";
|
|
75
|
+
|
|
76
|
+
const annotate = text => segmentsToRanges(getJyutpingList(text));
|
|
77
|
+
|
|
78
|
+
const field = createRubyfield(document.getElementById("field"), {
|
|
79
|
+
annotate,
|
|
80
|
+
attributes: { lang: "yue" },
|
|
81
|
+
ruby: { rt: { attributes: { lang: "yue-Latn-jyutping" } } },
|
|
82
|
+
});
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### Japanese Furigana
|
|
86
|
+
|
|
87
|
+
Install `kuromoji` and `wanakana`.
|
|
88
|
+
|
|
89
|
+
Serve Kuromoji's `dict` directory at `/dict/` as binary files without a `Content-Encoding` header. Load the tokenizer once before mounting the field; this example uses its browser bundle.
|
|
90
|
+
|
|
91
|
+
```js
|
|
92
|
+
import kuromoji from "kuromoji/build/kuromoji.js";
|
|
93
|
+
import { toHiragana } from "wanakana";
|
|
94
|
+
import { createRubyfield, segmentsToRanges } from "rubyfield";
|
|
95
|
+
|
|
96
|
+
const tokenizer = await new Promise((resolve, reject) => kuromoji.builder({ dicPath: "/dict/" }).build((error, tokenizer) => error ? reject(error) : resolve(tokenizer)));
|
|
97
|
+
const annotate = text => segmentsToRanges(tokenizer.tokenize(text).map(({ surface_form, reading }) => [surface_form, /\p{Script=Han}/u.test(surface_form) && reading ? toHiragana(reading) : null]));
|
|
98
|
+
|
|
99
|
+
const field = createRubyfield(document.getElementById("field"), {
|
|
100
|
+
annotate,
|
|
101
|
+
attributes: { lang: "ja" },
|
|
102
|
+
ruby: { rt: { attributes: { lang: "ja-Hira" } } },
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### An unreliable narrator
|
|
107
|
+
|
|
108
|
+
This example demonstrates custom annotation with context-sensitive handling. `有趣` reads **yǒu qù** (“interesting”), but adding `真` (“really”) before it changes the reading to **wú liáo** (“boring”). `生命` gets the Japanese reading **いのち**: a narrator who finds life less interesting the more you insist otherwise.
|
|
109
|
+
|
|
110
|
+
```js
|
|
111
|
+
import { createRubyfield } from "rubyfield";
|
|
112
|
+
|
|
113
|
+
const annotate = text => [...text.matchAll(/(?<とき>時間|瞬間)|(?<いのち>生命)|(?<yǒu>有)(?<qù>趣)|真(?<wú>有)(?<liáo>趣)/gd)].flatMap(match => Object.entries(match.indices.groups).flatMap(([groupName, indices]) => indices ? [[...indices, groupName]] : []));
|
|
114
|
+
|
|
115
|
+
const field = createRubyfield(document.getElementById("field"), {
|
|
116
|
+
defaultContent: "生命真有趣",
|
|
117
|
+
annotate,
|
|
118
|
+
});
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### Plain-text annotation separators
|
|
122
|
+
|
|
123
|
+
`<rp>` supplies separators for plain-text representations, such as search-engine rendering and programmatically copying content with annotations. Without it, `textContent` sticks base text and annotation together. Browsers with ruby support normally hide these separators.
|
|
124
|
+
|
|
125
|
+
```js
|
|
126
|
+
import { createRubyfield } from "rubyfield";
|
|
127
|
+
|
|
128
|
+
const annotate = () => [[0, 1, "nei5"]];
|
|
129
|
+
|
|
130
|
+
const field = createRubyfield(document.getElementById("field"), {
|
|
131
|
+
annotate,
|
|
132
|
+
ruby: { rp: { before: { text: "(" }, after: { text: ")" } } },
|
|
133
|
+
});
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
For base text `你` and reading `nei5`, the editable element (available through the handle's `element` property) has a `textContent` of `你(nei5)`. The same annotated text is available through `new DOMParser().parseFromString(html, "text/html").body.textContent`, where `html` is the string returned by the handle's `getHTML()` method. Normal copying from the field copies base text only.
|
|
137
|
+
|
|
138
|
+
## API
|
|
139
|
+
|
|
140
|
+
### Options
|
|
141
|
+
|
|
142
|
+
<table>
|
|
143
|
+
<thead><tr><th colspan="4">Option</th><th>Type</th><th>Default</th><th>Description</th></tr></thead>
|
|
144
|
+
<tbody>
|
|
145
|
+
<tr><td colspan="4"><code>annotate</code></td><td><code>(text: string) => readonly (readonly [startIndex: number, endIndex: number, rubyText: string])[]</code></td><td><strong>Required</strong></td><td>Pure function returning annotation ranges. Indices are zero-based UTF-16 offsets with an exclusive end, matching JavaScript string slicing. Empty ruby text leaves the base text unannotated.</td></tr>
|
|
146
|
+
<tr><td colspan="4"><code>annotationBehavior</code></td><td><code>AnnotationBehaviorOptions</code></td><td><code>undefined</code></td><td>Control annotation scope, invalid results, and errors.</td></tr>
|
|
147
|
+
<tr><td></td><td colspan="3"><code>scope</code></td><td><code>"line" | "text"</code></td><td><code>"line"</code></td><td><ul><li><code>line</code>: pass only new or changed newline-delimited lines to the annotator; unchanged lines retain their marks and reuse results. Useful when annotation is expensive.</li><li><code>text</code>: pass the whole base text so the annotator can use context across paragraphs; ranges crossing line breaks repeat their ruby text on each line. Changing the annotator, scope, or validation resets cached results.</li></ul></td></tr>
|
|
148
|
+
<tr><td></td><td colspan="3"><code>validation</code></td><td><code>"lenient" | "strict"</code></td><td><code>"lenient"</code></td><td><ul><li><code>lenient</code>: intended for integrating third-party annotation providers whose output you do not control. Discard non-array entries, non-number/non-finite/fractional indices, non-string ruby text, and reversed or empty ranges; clamp bounds. Preserve array order, overlaps, and surrogate/grapheme splits. Later ranges replace earlier marks where they overlap.</li><li><code>strict</code>: intended for annotator authors developing or debugging their functions. Discard out-of-bounds ranges instead of clamping; also discard overlaps and surrogate/grapheme splits. Process ranges in starting-index order; retain the previously accepted range on overlap. Report discarded entries in an <code>AggregateError</code>.</li></ul>A non-array result is treated as empty; strict mode also reports an error.</td></tr>
|
|
149
|
+
<tr><td></td><td colspan="3"><code>onError</code></td><td><code>(error: unknown) => void</code></td><td><code>undefined</code></td><td>Receive errors after the edit commits; without a handler, errors are thrown asynchronously. A throwing annotator leaves the affected text unannotated; strict validation retains valid entries. Annotation errors do not reject text edits.</td></tr>
|
|
150
|
+
<tr><td colspan="4"><code>content</code></td><td><code>string</code></td><td><code>undefined</code></td><td>Externally managed base text. Changes replace the current text; keep it in sync with <code>onUpdate</code>.</td></tr>
|
|
151
|
+
<tr><td colspan="4"><code>defaultContent</code></td><td><code>string</code></td><td><code>""</code></td><td>Initial base text for an uncontrolled field. Do not combine with <code>content</code>.</td></tr>
|
|
152
|
+
<tr><td colspan="4"><code>onUpdate</code></td><td><code>(content: string) => void</code></td><td><code>undefined</code></td><td>Called with the base text after an edit.</td></tr>
|
|
153
|
+
<tr><td colspan="4"><code>ruby</code></td><td><code>RubyOptions</code></td><td><code>undefined</code></td><td>Configure ruby elements in both the live field and HTML export.</td></tr>
|
|
154
|
+
<tr><td></td><td colspan="3"><code>attributes</code></td><td><code>Attributes</code></td><td><code>{}</code></td><td>Raw HTML attributes on <code><ruby></code>.</td></tr>
|
|
155
|
+
<tr><td></td><td colspan="3"><code>rt</code></td><td><code>ElementOptions</code></td><td><code>undefined</code></td><td>Configure <code><rt></code>. Omitting this option still creates the annotation element.</td></tr>
|
|
156
|
+
<tr><td></td><td></td><td colspan="2"><code>attributes</code></td><td><code>Attributes</code></td><td><code>{}</code></td><td>Raw HTML attributes on <code><rt></code>, such as the annotation language.</td></tr>
|
|
157
|
+
<tr><td></td><td colspan="3"><code>rp</code></td><td><code>{ before?: RPElementOptions; after?: RPElementOptions }</code></td><td><code>undefined</code></td><td>Configure plain-text separators around annotations. Omitting this option creates neither <code><rp></code> element.</td></tr>
|
|
158
|
+
<tr><td></td><td></td><td colspan="2"><code>before</code></td><td><code>RPElementOptions</code></td><td><code>undefined</code></td><td>Create an <code><rp></code> before the annotation only when this object is supplied.</td></tr>
|
|
159
|
+
<tr><td></td><td></td><td></td><td colspan="1"><code>text</code></td><td><code>string</code></td><td><code>"("</code></td><td>Plain text inside the preceding <code><rp></code>; HTML is not interpreted.</td></tr>
|
|
160
|
+
<tr><td></td><td></td><td></td><td colspan="1"><code>attributes</code></td><td><code>Attributes</code></td><td><code>{}</code></td><td>Raw HTML attributes on the preceding <code><rp></code>.</td></tr>
|
|
161
|
+
<tr><td></td><td></td><td colspan="2"><code>after</code></td><td><code>RPElementOptions</code></td><td><code>undefined</code></td><td>Create an <code><rp></code> after the annotation only when this object is supplied.</td></tr>
|
|
162
|
+
<tr><td></td><td></td><td></td><td colspan="1"><code>text</code></td><td><code>string</code></td><td><code>")"</code></td><td>Plain text inside the following <code><rp></code>; HTML is not interpreted.</td></tr>
|
|
163
|
+
<tr><td></td><td></td><td></td><td colspan="1"><code>attributes</code></td><td><code>Attributes</code></td><td><code>{}</code></td><td>Raw HTML attributes on the following <code><rp></code>.</td></tr>
|
|
164
|
+
<tr><td colspan="4"><code>attributes</code></td><td><code>Attributes</code></td><td><code>{}</code></td><td>Raw HTML attributes on the editable element, such as <code>lang</code>, <code>class</code>, or <code>aria-*</code>.</td></tr>
|
|
165
|
+
<tr><td colspan="4"><code>multiline</code></td><td><code>boolean</code></td><td><code>true</code></td><td>Allow line breaks. When false, the field stays on one line; supplied or pasted/dropped line breaks become spaces. Set at creation; recreate or remount to change it.</td></tr>
|
|
166
|
+
<tr><td colspan="4"><code>readOnly</code></td><td><code>boolean</code></td><td><code>false</code></td><td>Prevent editing while allowing focus, selection, and copying.</td></tr>
|
|
167
|
+
<tr><td colspan="4"><code>disabled</code></td><td><code>boolean</code></td><td><code>false</code></td><td>Prevent editing and remove the field from keyboard tab navigation.</td></tr>
|
|
168
|
+
<tr><td colspan="4"><code>placeholder</code></td><td><code>string</code></td><td><code>""</code></td><td>Text displayed while the base text is empty.</td></tr>
|
|
169
|
+
<tr><td colspan="4"><code>autoFocus</code></td><td><code>boolean</code></td><td><code>false</code></td><td>Focus the field when it mounts.</td></tr>
|
|
170
|
+
</tbody>
|
|
171
|
+
</table>
|
|
172
|
+
|
|
173
|
+
### Usage
|
|
174
|
+
|
|
175
|
+
Rubyfield installs no CSS apart from the minimal styles needed for placeholders and single-line fields. Supply your own styles.
|
|
176
|
+
|
|
177
|
+
Input is plain text: pasted formatting and images are not retained, and line endings become `\n`. Base text is editable; annotations are read-only.
|
|
178
|
+
|
|
179
|
+
Each Rubyfield package exports the optional utility `segmentsToRanges(pairs)`, which converts `[baseText, rubyText]` pairs into UTF-16 annotation ranges. The `baseText` strings, joined in order, must reproduce the original text, including spaces and punctuation. A pair such as `["你好", "nei5 hou2"]` adds an annotation; `["!", null]` leaves that segment unannotated while counting its length for subsequent ranges.
|
|
180
|
+
|
|
181
|
+
Raw `Attributes` objects use HTML names (`class`, not `className`):
|
|
182
|
+
|
|
183
|
+
- Null/undefined omit an attribute.
|
|
184
|
+
- Other values are stringified. Use CSS strings for `style`; functions are not event listeners.
|
|
185
|
+
|
|
186
|
+
For example, use `hidden: ""` to enable `hidden` and omit it to disable it; `hidden: false` becomes `hidden="false"`, which still hides the element.
|
|
187
|
+
|
|
188
|
+
The field's handle provides access to its properties and methods through React's `ref.current`, Vue's template-ref `.value`, or the object returned by `createRubyfield(...)`. Its TypeScript type is `RubyfieldHandle`. The handle exposes:
|
|
189
|
+
|
|
190
|
+
- Properties:
|
|
191
|
+
- `element`: the editable `HTMLElement`, or null.
|
|
192
|
+
- `value`: the current base text, read-only.
|
|
193
|
+
- Methods:
|
|
194
|
+
- `focus()` / `blur()`: focus or blur the field.
|
|
195
|
+
- `select()`: select all base text.
|
|
196
|
+
- `setSelectionRange(start, end)`: select a range using zero-based UTF-16 offsets.
|
|
197
|
+
- `getHTML()`: return an annotated HTML string. Normal copying copies base text only.
|
|
198
|
+
|
|
199
|
+
Create the field after its DOM container exists. Use `element.addEventListener()` for native DOM events. The returned `Rubyfield` also exposes `setOptions(options)` and `destroy()`; destroy it when removing the field.
|
|
200
|
+
|
|
201
|
+
## Launching the Demo
|
|
202
|
+
|
|
203
|
+
Try the [hosted demo](https://graphemecluster.github.io/rubyfield/), or run it locally from the repository root:
|
|
204
|
+
|
|
205
|
+
```sh
|
|
206
|
+
bun install
|
|
207
|
+
bun run dev
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
Open the URL printed by Vite. The demo includes Pinyin, Jyutping, and Furigana; the Japanese dictionary loads when Furigana is selected.
|
|
211
|
+
|
|
212
|
+
## Development
|
|
213
|
+
|
|
214
|
+
From the repository root:
|
|
215
|
+
|
|
216
|
+
- Build: `bun run build`.
|
|
217
|
+
- Check types: `bun run typecheck`.
|
|
218
|
+
- Format: `bun run format`.
|
|
219
|
+
- Check formatting: `bun run format:check`.
|
|
220
|
+
- Run tests:
|
|
221
|
+
- Install managed Chromium once: `bunx --no-install playwright-core install chromium`.
|
|
222
|
+
- All tests: `bun test`.
|
|
223
|
+
- Browser tests only: `bun run test:browser`.
|
|
224
|
+
- Unit tests only: `bun test tests/text.test.ts`.
|
|
225
|
+
|
|
226
|
+
Tests start and stop their own servers.
|
|
227
|
+
|
|
228
|
+
JSR uses the `deno.json` workspace configuration and publishes TypeScript source as `@rubyfield/core`, `@rubyfield/react`, and `@rubyfield/vue`. The JSR CLI downloads Deno internally; development uses Bun.
|
|
229
|
+
|
|
230
|
+
To release, set the same version in all three packages' `package.json` and `deno.json` files, update the core import versions in the root `deno.json` to match, then push a matching `vX.Y.Z` tag. The `publish.yml` workflow checks, builds, tests, and publishes to npm and JSR before creating a GitHub release. Prereleases use npm's `next` tag. Both registries require repository linking; npm also requires trusted publisher configuration for `publish.yml`. Failed runs can be retried; already published versions are skipped.
|
|
231
|
+
|
|
232
|
+
## License
|
|
233
|
+
|
|
234
|
+
[MIT](https://github.com/graphemecluster/rubyfield/blob/main/LICENSE).
|
|
235
|
+
|
|
236
|
+
[core]: https://github.com/graphemecluster/rubyfield/tree/main/packages/core#readme
|
|
237
|
+
[react]: https://github.com/graphemecluster/rubyfield/tree/main/packages/react#readme
|
|
238
|
+
[vue]: https://github.com/graphemecluster/rubyfield/tree/main/packages/vue#readme
|
|
@@ -0,0 +1,548 @@
|
|
|
1
|
+
// src/session.ts
|
|
2
|
+
import Document from "@tiptap/extension-document";
|
|
3
|
+
import Paragraph from "@tiptap/extension-paragraph";
|
|
4
|
+
import Text from "@tiptap/extension-text";
|
|
5
|
+
import { Placeholder, UndoRedo } from "@tiptap/extensions";
|
|
6
|
+
import { Fragment, Slice } from "@tiptap/pm/model";
|
|
7
|
+
import { TextSelection as TextSelection2 } from "@tiptap/pm/state";
|
|
8
|
+
|
|
9
|
+
// src/annotation.ts
|
|
10
|
+
import { Extension } from "@tiptap/core";
|
|
11
|
+
import { Plugin as Plugin2, PluginKey, TextSelection } from "@tiptap/pm/state";
|
|
12
|
+
|
|
13
|
+
// src/ruby.ts
|
|
14
|
+
import RubyText from "@tiptap/extension-ruby-text";
|
|
15
|
+
import { Plugin } from "@tiptap/pm/state";
|
|
16
|
+
import { Decoration, DecorationSet } from "@tiptap/pm/view";
|
|
17
|
+
|
|
18
|
+
// src/attributes.ts
|
|
19
|
+
function htmlAttributes(attributes = {}) {
|
|
20
|
+
return Object.fromEntries(
|
|
21
|
+
Object.entries(attributes).filter(([, value]) => value != null).map(([name, value]) => [name, String(value)])
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
var previousAttributes = /* @__PURE__ */ new WeakMap();
|
|
25
|
+
function applyAttributes(element, attributes = {}) {
|
|
26
|
+
const next = htmlAttributes(attributes);
|
|
27
|
+
for (const name of previousAttributes.get(element) ?? []) {
|
|
28
|
+
if (!Object.hasOwn(next, name)) element.removeAttribute(name);
|
|
29
|
+
}
|
|
30
|
+
for (const [name, value] of Object.entries(next)) {
|
|
31
|
+
if (element.getAttribute(name) !== value) element.setAttribute(name, value);
|
|
32
|
+
}
|
|
33
|
+
previousAttributes.set(element, new Set(Object.keys(next)));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// src/ruby.ts
|
|
37
|
+
var refreshKey = "rubyfield:refresh";
|
|
38
|
+
function rubyOptionsSignature(options = {}) {
|
|
39
|
+
return JSON.stringify([
|
|
40
|
+
htmlAttributes(options.attributes),
|
|
41
|
+
htmlAttributes(options.rt?.attributes),
|
|
42
|
+
options.rp?.before && [options.rp.before.text ?? "(", htmlAttributes(options.rp.before.attributes)],
|
|
43
|
+
options.rp?.after && [options.rp.after.text ?? ")", htmlAttributes(options.rp.after.attributes)]
|
|
44
|
+
]);
|
|
45
|
+
}
|
|
46
|
+
function createRubyExtension(getOptions) {
|
|
47
|
+
return RubyText.extend({
|
|
48
|
+
addAttributes() {
|
|
49
|
+
return {
|
|
50
|
+
rt: { default: null, rendered: false },
|
|
51
|
+
// Distinct ranges may share annotation text; keep ProseMirror from merging them.
|
|
52
|
+
annotationId: { default: null, rendered: false }
|
|
53
|
+
};
|
|
54
|
+
},
|
|
55
|
+
renderHTML({ mark }) {
|
|
56
|
+
const { attributes, rt, rp } = getOptions();
|
|
57
|
+
const children = [["rb", 0]];
|
|
58
|
+
if (mark.attrs.rt != null) {
|
|
59
|
+
if (rp?.before) children.push(["rp", htmlAttributes(rp.before.attributes), rp.before.text ?? "("]);
|
|
60
|
+
children.push(["rt", htmlAttributes(rt?.attributes), mark.attrs.rt]);
|
|
61
|
+
if (rp?.after) children.push(["rp", htmlAttributes(rp.after.attributes), rp.after.text ?? ")"]);
|
|
62
|
+
}
|
|
63
|
+
return ["ruby", htmlAttributes(attributes), ...children];
|
|
64
|
+
},
|
|
65
|
+
addMarkView() {
|
|
66
|
+
return () => {
|
|
67
|
+
const dom = document.createElement("ruby");
|
|
68
|
+
applyAttributes(dom, getOptions().attributes);
|
|
69
|
+
return { dom, contentDOM: dom };
|
|
70
|
+
};
|
|
71
|
+
},
|
|
72
|
+
addProseMirrorPlugins() {
|
|
73
|
+
const rubyType = this.type;
|
|
74
|
+
let revision = 0;
|
|
75
|
+
function decorations(doc) {
|
|
76
|
+
const { rt, rp } = getOptions();
|
|
77
|
+
const ranges = [];
|
|
78
|
+
doc.descendants((node, pos) => {
|
|
79
|
+
const mark = node.isText && node.marks.find((mark2) => mark2.type === rubyType);
|
|
80
|
+
if (!mark) return;
|
|
81
|
+
const previous = ranges.at(-1);
|
|
82
|
+
if (previous?.to === pos && previous.mark.eq(mark)) previous.to += node.nodeSize;
|
|
83
|
+
else ranges.push({ from: pos, to: pos + node.nodeSize, mark });
|
|
84
|
+
});
|
|
85
|
+
return DecorationSet.create(
|
|
86
|
+
doc,
|
|
87
|
+
ranges.flatMap(({ from, to, mark }) => {
|
|
88
|
+
function widget(tag, text, attributes, side) {
|
|
89
|
+
return Decoration.widget(to, () => {
|
|
90
|
+
const dom = document.createElement(tag);
|
|
91
|
+
applyAttributes(dom, attributes);
|
|
92
|
+
dom.contentEditable = "false";
|
|
93
|
+
dom.textContent = text;
|
|
94
|
+
return dom;
|
|
95
|
+
}, { key: `rubyfield-${revision}-${from}-${to}-${side}-${text}`, marks: [mark], side });
|
|
96
|
+
}
|
|
97
|
+
return [
|
|
98
|
+
...rp?.before ? [widget("rp", rp.before.text ?? "(", rp.before.attributes, 1)] : [],
|
|
99
|
+
widget("rt", mark.attrs.rt ?? "", rt?.attributes, 2),
|
|
100
|
+
...rp?.after ? [widget("rp", rp.after.text ?? ")", rp.after.attributes, 3)] : []
|
|
101
|
+
];
|
|
102
|
+
})
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
return [new Plugin({
|
|
106
|
+
state: {
|
|
107
|
+
init: (_, state) => decorations(state.doc),
|
|
108
|
+
apply(tr, previous) {
|
|
109
|
+
if (tr.getMeta(refreshKey) === "options") revision++;
|
|
110
|
+
return tr.docChanged || tr.getMeta(refreshKey) ? decorations(tr.doc) : previous.map(tr.mapping, tr.doc);
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
props: {
|
|
114
|
+
decorations(state) {
|
|
115
|
+
return this.getState(state);
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
view(view) {
|
|
119
|
+
return {
|
|
120
|
+
update() {
|
|
121
|
+
for (const ruby of view.dom.querySelectorAll("ruby")) applyAttributes(ruby, getOptions().attributes);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
})];
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// src/text.ts
|
|
131
|
+
function normalizeText(text, multiline = true) {
|
|
132
|
+
const normalized = text.replace(/\r\n?/g, "\n");
|
|
133
|
+
return multiline ? normalized : normalized.replace(/\n/g, " ");
|
|
134
|
+
}
|
|
135
|
+
function textDocument(text) {
|
|
136
|
+
return {
|
|
137
|
+
type: "doc",
|
|
138
|
+
content: normalizeText(text).split("\n").map((line) => ({
|
|
139
|
+
type: "paragraph",
|
|
140
|
+
...line ? { content: [{ type: "text", text: line }] } : {}
|
|
141
|
+
}))
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
var documentText = (doc) => doc.textBetween(0, doc.content.size, "\n");
|
|
145
|
+
function documentPosition(doc, index) {
|
|
146
|
+
const target = Math.max(0, Math.min(documentText(doc).length, Math.trunc(index) || 0));
|
|
147
|
+
let offset = 0;
|
|
148
|
+
let position = 1;
|
|
149
|
+
doc.forEach((paragraph, pos) => {
|
|
150
|
+
if (target >= offset) position = pos + 1 + Math.min(target - offset, paragraph.content.size);
|
|
151
|
+
offset += paragraph.content.size + 1;
|
|
152
|
+
});
|
|
153
|
+
return position;
|
|
154
|
+
}
|
|
155
|
+
function segmentsToRanges(pairs) {
|
|
156
|
+
let offset = 0;
|
|
157
|
+
return pairs.flatMap(([base, rubyText]) => {
|
|
158
|
+
const start = offset;
|
|
159
|
+
offset += base.length;
|
|
160
|
+
return base.length && rubyText ? [[start, offset, rubyText]] : [];
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
function validateAnnotations(text, input, mode) {
|
|
164
|
+
const annotations = [];
|
|
165
|
+
const errors = [];
|
|
166
|
+
const strict = mode === "strict";
|
|
167
|
+
function malformed(message, value) {
|
|
168
|
+
let item;
|
|
169
|
+
try {
|
|
170
|
+
item = JSON.stringify(value, (_key, part) => typeof part === "bigint" || typeof part === "number" && !Number.isFinite(part) ? String(part) : part) ?? String(value);
|
|
171
|
+
} catch {
|
|
172
|
+
try {
|
|
173
|
+
item = String(value);
|
|
174
|
+
} catch {
|
|
175
|
+
item = "[unserializable item]";
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return new RangeError(`${message} Received: ${item}`);
|
|
179
|
+
}
|
|
180
|
+
if (!Array.isArray(input)) {
|
|
181
|
+
if (strict) errors.push(malformed("Annotation result must be an array.", input));
|
|
182
|
+
return { annotations, errors };
|
|
183
|
+
}
|
|
184
|
+
const boundaries = strict ? /* @__PURE__ */ new Set([text.length, ...Array.from(new Intl.Segmenter("zxx", { granularity: "grapheme" }).segment(text), (part) => part.index)]) : void 0;
|
|
185
|
+
for (const entry of input) {
|
|
186
|
+
if (!Array.isArray(entry)) {
|
|
187
|
+
if (strict) errors.push(malformed("Annotation must be a [start, end, rubyText] tuple.", entry));
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
const [start, end, rubyText] = entry;
|
|
191
|
+
if (!Number.isInteger(start) || !Number.isInteger(end) || typeof rubyText !== "string" || start > end) {
|
|
192
|
+
if (strict) errors.push(malformed("Annotation indices must be integers in ascending order and the ruby text must be a string.", entry));
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
if (strict && (start < 0 || end > text.length || start === end || !boundaries.has(start) || !boundaries.has(end))) {
|
|
196
|
+
errors.push(malformed("Annotation must be a non-empty range within the text at grapheme boundaries.", entry));
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
const from = Math.max(0, Math.min(text.length, start));
|
|
200
|
+
const to = Math.max(0, Math.min(text.length, end));
|
|
201
|
+
if (from < to) annotations.push([from, to, rubyText]);
|
|
202
|
+
}
|
|
203
|
+
if (strict) {
|
|
204
|
+
annotations.sort((a, b) => a[0] - b[0]);
|
|
205
|
+
let previousEnd = 0;
|
|
206
|
+
return {
|
|
207
|
+
annotations: annotations.filter((entry) => {
|
|
208
|
+
const [start, end] = entry;
|
|
209
|
+
if (start < previousEnd) {
|
|
210
|
+
errors.push(malformed("Annotation ranges must not overlap.", entry));
|
|
211
|
+
return false;
|
|
212
|
+
}
|
|
213
|
+
previousEnd = end;
|
|
214
|
+
return true;
|
|
215
|
+
}),
|
|
216
|
+
errors
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
return { annotations, errors };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// src/annotation.ts
|
|
223
|
+
var key = new PluginKey("rubyfieldAnnotation");
|
|
224
|
+
function createAnnotationExtension(getOptions, onCompositionEnd) {
|
|
225
|
+
return Extension.create({
|
|
226
|
+
name: "rubyfieldAnnotation",
|
|
227
|
+
onCreate() {
|
|
228
|
+
this.editor.view.dispatch(this.editor.state.tr.setMeta(refreshKey, true));
|
|
229
|
+
},
|
|
230
|
+
addProseMirrorPlugins() {
|
|
231
|
+
const editor = this.editor;
|
|
232
|
+
let composing = false;
|
|
233
|
+
let cachedAnnotate;
|
|
234
|
+
let cachedMode;
|
|
235
|
+
let cachedScope;
|
|
236
|
+
let cache = /* @__PURE__ */ new Map();
|
|
237
|
+
let annotatedParagraphs = /* @__PURE__ */ new WeakMap();
|
|
238
|
+
let timer;
|
|
239
|
+
let start;
|
|
240
|
+
function report(error) {
|
|
241
|
+
const handler = getOptions().annotationBehavior?.onError;
|
|
242
|
+
queueMicrotask(() => {
|
|
243
|
+
if (handler) handler(error);
|
|
244
|
+
else throw error;
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
return [new Plugin2({
|
|
248
|
+
key,
|
|
249
|
+
props: {
|
|
250
|
+
handleDOMEvents: {
|
|
251
|
+
compositionstart(view) {
|
|
252
|
+
clearTimeout(timer);
|
|
253
|
+
composing = true;
|
|
254
|
+
start = view.state.selection.empty ? { position: view.state.selection.from, text: documentText(view.state.doc) } : void 0;
|
|
255
|
+
return false;
|
|
256
|
+
},
|
|
257
|
+
compositionend(view, event) {
|
|
258
|
+
timer = setTimeout(() => {
|
|
259
|
+
composing = false;
|
|
260
|
+
if (view.isDestroyed) return;
|
|
261
|
+
const tr = view.state.tr.setMeta(refreshKey, true);
|
|
262
|
+
if (event.data === "" && start && documentText(tr.doc) === start.text) {
|
|
263
|
+
tr.setSelection(TextSelection.create(tr.doc, Math.min(start.position, tr.doc.content.size - 1)));
|
|
264
|
+
}
|
|
265
|
+
view.dispatch(tr);
|
|
266
|
+
start = void 0;
|
|
267
|
+
const selection = view.dom.ownerDocument.getSelection();
|
|
268
|
+
if (view.hasFocus() && (!selection?.rangeCount || selection.focusNode === view.dom)) view.focus();
|
|
269
|
+
onCompositionEnd();
|
|
270
|
+
}, 0);
|
|
271
|
+
return false;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
},
|
|
275
|
+
view() {
|
|
276
|
+
return {
|
|
277
|
+
destroy() {
|
|
278
|
+
clearTimeout(timer);
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
},
|
|
282
|
+
appendTransaction(transactions, _oldState, state) {
|
|
283
|
+
if (composing || editor.view.composing) return null;
|
|
284
|
+
if (!transactions.some((tr2) => tr2.docChanged && !tr2.getMeta(key) || tr2.getMeta(refreshKey))) return null;
|
|
285
|
+
const { annotate, annotationBehavior } = getOptions();
|
|
286
|
+
const mode = annotationBehavior?.validation ?? "lenient";
|
|
287
|
+
const scope = annotationBehavior?.scope ?? "line";
|
|
288
|
+
if (annotate !== cachedAnnotate || mode !== cachedMode || scope !== cachedScope) {
|
|
289
|
+
cache.clear();
|
|
290
|
+
annotatedParagraphs = /* @__PURE__ */ new WeakMap();
|
|
291
|
+
}
|
|
292
|
+
cachedAnnotate = annotate;
|
|
293
|
+
cachedMode = mode;
|
|
294
|
+
cachedScope = scope;
|
|
295
|
+
const nextCache = /* @__PURE__ */ new Map();
|
|
296
|
+
function annotationsFor(text) {
|
|
297
|
+
const cached = nextCache.get(text) ?? cache.get(text);
|
|
298
|
+
if (cached) {
|
|
299
|
+
nextCache.set(text, cached);
|
|
300
|
+
return cached;
|
|
301
|
+
}
|
|
302
|
+
let annotations = [];
|
|
303
|
+
try {
|
|
304
|
+
const result = validateAnnotations(text, annotate(text), mode);
|
|
305
|
+
annotations = result.annotations;
|
|
306
|
+
if (result.errors.length) report(new AggregateError(result.errors, result.errors.map((error) => error.message).join("\n")));
|
|
307
|
+
} catch (error) {
|
|
308
|
+
report(error);
|
|
309
|
+
}
|
|
310
|
+
nextCache.set(text, annotations);
|
|
311
|
+
return annotations;
|
|
312
|
+
}
|
|
313
|
+
const ruby = state.schema.marks.rubyText;
|
|
314
|
+
const tr = state.tr;
|
|
315
|
+
if (scope === "line") {
|
|
316
|
+
state.doc.forEach((paragraph, pos) => {
|
|
317
|
+
const previous = annotatedParagraphs.get(paragraph);
|
|
318
|
+
if (previous) {
|
|
319
|
+
nextCache.set(paragraph.textContent, previous);
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
tr.removeMark(pos + 1, pos + 1 + paragraph.content.size, ruby);
|
|
323
|
+
for (const [from, to, rubyText] of annotationsFor(paragraph.textContent)) {
|
|
324
|
+
if (rubyText) tr.addMark(pos + 1 + from, pos + 1 + to, ruby.create({ rt: rubyText, annotationId: `${from}:${to}` }));
|
|
325
|
+
}
|
|
326
|
+
});
|
|
327
|
+
tr.doc.forEach((paragraph) => annotatedParagraphs.set(paragraph, nextCache.get(paragraph.textContent)));
|
|
328
|
+
} else {
|
|
329
|
+
tr.removeMark(0, state.doc.content.size, ruby);
|
|
330
|
+
const annotations = annotationsFor(documentText(state.doc));
|
|
331
|
+
let offset = 0;
|
|
332
|
+
state.doc.forEach((paragraph, pos) => {
|
|
333
|
+
const end = offset + paragraph.content.size;
|
|
334
|
+
for (const [from, to, rubyText] of annotations) {
|
|
335
|
+
const a = Math.max(from, offset), b = Math.min(to, end);
|
|
336
|
+
if (a < b && rubyText) tr.addMark(pos + 1 + a - offset, pos + 1 + b - offset, ruby.create({ rt: rubyText, annotationId: `${from}:${to}` }));
|
|
337
|
+
}
|
|
338
|
+
offset = end + 1;
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
cache = nextCache;
|
|
342
|
+
return tr.setStoredMarks([]).setMeta(key, true).setMeta("addToHistory", false);
|
|
343
|
+
}
|
|
344
|
+
})];
|
|
345
|
+
}
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// src/placeholder-style.ts
|
|
350
|
+
var styles = /* @__PURE__ */ new WeakMap();
|
|
351
|
+
function ensurePlaceholderStyle(document2) {
|
|
352
|
+
let style = styles.get(document2);
|
|
353
|
+
if (!style) {
|
|
354
|
+
style = new document2.defaultView.CSSStyleSheet();
|
|
355
|
+
style.replaceSync(`.ProseMirror[aria-multiline="false"] {
|
|
356
|
+
white-space: pre;
|
|
357
|
+
overflow-x: auto;
|
|
358
|
+
}
|
|
359
|
+
.ProseMirror p.is-editor-empty:first-child::before {
|
|
360
|
+
content: attr(data-placeholder);
|
|
361
|
+
position: absolute;
|
|
362
|
+
pointer-events: none;
|
|
363
|
+
}`);
|
|
364
|
+
styles.set(document2, style);
|
|
365
|
+
}
|
|
366
|
+
if (!document2.adoptedStyleSheets.includes(style)) {
|
|
367
|
+
document2.adoptedStyleSheets = [...document2.adoptedStyleSheets, style];
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// src/session.ts
|
|
372
|
+
var BindingSession = class {
|
|
373
|
+
editor = null;
|
|
374
|
+
config;
|
|
375
|
+
multiline;
|
|
376
|
+
lastText;
|
|
377
|
+
pendingRefresh = false;
|
|
378
|
+
pendingContent;
|
|
379
|
+
rubySignature;
|
|
380
|
+
annotationSignature;
|
|
381
|
+
handle;
|
|
382
|
+
constructor(options) {
|
|
383
|
+
if (options.content !== void 0 && options.defaultContent !== void 0) {
|
|
384
|
+
throw new TypeError("Use either content or defaultContent, not both.");
|
|
385
|
+
}
|
|
386
|
+
this.config = options;
|
|
387
|
+
this.multiline = options.multiline !== false;
|
|
388
|
+
this.annotationSignature = JSON.stringify([options.annotationBehavior?.scope, options.annotationBehavior?.validation]);
|
|
389
|
+
this.rubySignature = rubyOptionsSignature(options.ruby);
|
|
390
|
+
this.lastText = normalizeText(options.content ?? options.defaultContent ?? "", this.multiline);
|
|
391
|
+
const self = this;
|
|
392
|
+
this.handle = {
|
|
393
|
+
get element() {
|
|
394
|
+
return self.editor && !self.editor.isDestroyed ? self.editor.view.dom : null;
|
|
395
|
+
},
|
|
396
|
+
get value() {
|
|
397
|
+
return self.editor && !self.editor.isDestroyed ? documentText(self.editor.state.doc) : self.lastText;
|
|
398
|
+
},
|
|
399
|
+
focus() {
|
|
400
|
+
if (!self.config.disabled && self.editor && !self.editor.isDestroyed) self.editor.view.focus();
|
|
401
|
+
},
|
|
402
|
+
blur() {
|
|
403
|
+
self.handle.element?.blur();
|
|
404
|
+
},
|
|
405
|
+
select() {
|
|
406
|
+
self.handle.setSelectionRange(0, self.handle.value.length);
|
|
407
|
+
},
|
|
408
|
+
setSelectionRange(start, end) {
|
|
409
|
+
const editor = self.editor;
|
|
410
|
+
if (!editor || editor.isDestroyed || self.config.disabled) return;
|
|
411
|
+
const a = documentPosition(editor.state.doc, Math.min(start, end));
|
|
412
|
+
const b = documentPosition(editor.state.doc, end);
|
|
413
|
+
editor.view.dispatch(editor.state.tr.setSelection(TextSelection2.create(editor.state.doc, a, b)));
|
|
414
|
+
},
|
|
415
|
+
getHTML() {
|
|
416
|
+
return self.editor && !self.editor.isDestroyed ? self.editor.getHTML() : "";
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
createOptions() {
|
|
421
|
+
return {
|
|
422
|
+
extensions: [
|
|
423
|
+
this.multiline ? Document : Document.extend({ content: "paragraph" }),
|
|
424
|
+
Paragraph,
|
|
425
|
+
Text,
|
|
426
|
+
UndoRedo,
|
|
427
|
+
Placeholder.configure({
|
|
428
|
+
placeholder: () => this.config.placeholder ?? "",
|
|
429
|
+
showOnlyWhenEditable: false
|
|
430
|
+
}),
|
|
431
|
+
createRubyExtension(() => this.config.ruby ?? {}),
|
|
432
|
+
createAnnotationExtension(() => this.config, () => this.flushComposition())
|
|
433
|
+
],
|
|
434
|
+
content: textDocument(this.lastText),
|
|
435
|
+
editable: !this.config.readOnly && !this.config.disabled,
|
|
436
|
+
onCreate: ({ editor }) => {
|
|
437
|
+
this.attach(editor);
|
|
438
|
+
if (this.config.autoFocus) this.handle.focus();
|
|
439
|
+
},
|
|
440
|
+
onUpdate: ({ editor }) => {
|
|
441
|
+
const text = documentText(editor.state.doc);
|
|
442
|
+
if (text === this.lastText) return;
|
|
443
|
+
this.lastText = text;
|
|
444
|
+
this.config.onUpdate?.(text);
|
|
445
|
+
},
|
|
446
|
+
editorProps: {
|
|
447
|
+
// ProseMirror owns root attribute updates, removals, and editor classes.
|
|
448
|
+
attributes: () => htmlAttributes({
|
|
449
|
+
...this.config.attributes,
|
|
450
|
+
"role": "textbox",
|
|
451
|
+
"aria-multiline": String(this.multiline),
|
|
452
|
+
"aria-disabled": this.config.disabled ? "true" : void 0,
|
|
453
|
+
"aria-readonly": this.config.readOnly ? "true" : void 0,
|
|
454
|
+
"tabindex": this.config.disabled ? "-1" : this.config.attributes?.tabindex ?? "0"
|
|
455
|
+
}),
|
|
456
|
+
// Copy base text even though annotations are visible in the editor DOM.
|
|
457
|
+
clipboardTextSerializer: (slice) => slice.content.textBetween(0, slice.content.size, "\n"),
|
|
458
|
+
// Always use the plain-text clipboard representation.
|
|
459
|
+
handlePaste: (view, event) => {
|
|
460
|
+
event.preventDefault();
|
|
461
|
+
const text = normalizeText(event.clipboardData?.getData("text/plain") ?? "", this.multiline);
|
|
462
|
+
if (text) {
|
|
463
|
+
const paragraphs = normalizeText(text).split("\n").map(
|
|
464
|
+
(line) => view.state.schema.nodes.paragraph.create(
|
|
465
|
+
null,
|
|
466
|
+
line ? view.state.schema.text(line) : void 0
|
|
467
|
+
)
|
|
468
|
+
);
|
|
469
|
+
view.dispatch(view.state.tr.replaceSelection(new Slice(Fragment.fromArray(paragraphs), 1, 1)).scrollIntoView());
|
|
470
|
+
}
|
|
471
|
+
return true;
|
|
472
|
+
},
|
|
473
|
+
// Use ProseMirror's clipboard/drop hook to preserve text across paragraph boundaries.
|
|
474
|
+
transformPasted: (slice, view) => {
|
|
475
|
+
if (this.multiline) return slice;
|
|
476
|
+
const text = normalizeText(slice.content.textBetween(0, slice.content.size, "\n"), false);
|
|
477
|
+
return new Slice(text ? Fragment.from(view.state.schema.text(text)) : Fragment.empty, 0, 0);
|
|
478
|
+
},
|
|
479
|
+
// Keep file/image drops out of the document.
|
|
480
|
+
handleDrop: (_view, event) => Boolean(event.dataTransfer?.files.length)
|
|
481
|
+
}
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
attach(editor) {
|
|
485
|
+
this.editor = editor;
|
|
486
|
+
ensurePlaceholderStyle(editor.view.dom.ownerDocument);
|
|
487
|
+
}
|
|
488
|
+
setContent(text) {
|
|
489
|
+
const editor = this.editor;
|
|
490
|
+
const value = normalizeText(text, this.multiline);
|
|
491
|
+
if (!editor || editor.isDestroyed || value === documentText(editor.state.doc)) return;
|
|
492
|
+
if (editor.view.composing) {
|
|
493
|
+
this.pendingContent = value;
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
const selection = editor.state.selection;
|
|
497
|
+
const oldStart = documentText(editor.state.doc.cut(0, selection.from)).length;
|
|
498
|
+
this.lastText = value;
|
|
499
|
+
editor.commands.setContent(textDocument(value), { emitUpdate: false });
|
|
500
|
+
const pos = documentPosition(editor.state.doc, oldStart);
|
|
501
|
+
editor.view.dispatch(editor.state.tr.setSelection(TextSelection2.create(editor.state.doc, pos)));
|
|
502
|
+
}
|
|
503
|
+
setOptions(options) {
|
|
504
|
+
if ("multiline" in options && options.multiline !== false !== this.multiline) {
|
|
505
|
+
throw new TypeError("multiline is fixed at creation; recreate or remount the field to change it.");
|
|
506
|
+
}
|
|
507
|
+
const previous = this.config;
|
|
508
|
+
this.config = { ...previous, ...options };
|
|
509
|
+
const editor = this.editor;
|
|
510
|
+
if (!editor || editor.isDestroyed) return;
|
|
511
|
+
if (previous.readOnly !== this.config.readOnly || previous.disabled !== this.config.disabled) {
|
|
512
|
+
editor.setEditable(!this.config.readOnly && !this.config.disabled, false);
|
|
513
|
+
}
|
|
514
|
+
if (options.content !== void 0) this.setContent(options.content);
|
|
515
|
+
if (previous.placeholder !== this.config.placeholder && !editor.view.composing) {
|
|
516
|
+
editor.view.dispatch(editor.state.tr);
|
|
517
|
+
}
|
|
518
|
+
const rubySignature = rubyOptionsSignature(this.config.ruby);
|
|
519
|
+
const annotationSignature = JSON.stringify([this.config.annotationBehavior?.scope, this.config.annotationBehavior?.validation]);
|
|
520
|
+
if (previous.annotate !== this.config.annotate || this.rubySignature !== rubySignature || this.annotationSignature !== annotationSignature) {
|
|
521
|
+
this.annotationSignature = annotationSignature;
|
|
522
|
+
this.rubySignature = rubySignature;
|
|
523
|
+
if (editor.view.composing) this.pendingRefresh = true;
|
|
524
|
+
else editor.view.dispatch(editor.state.tr.setMeta(refreshKey, "options"));
|
|
525
|
+
}
|
|
526
|
+
editor.view.setProps({});
|
|
527
|
+
}
|
|
528
|
+
flushComposition() {
|
|
529
|
+
if (this.pendingContent !== void 0) {
|
|
530
|
+
const text = this.pendingContent;
|
|
531
|
+
this.pendingContent = void 0;
|
|
532
|
+
this.setContent(text);
|
|
533
|
+
}
|
|
534
|
+
if (this.pendingRefresh && this.editor && !this.editor.isDestroyed) {
|
|
535
|
+
this.pendingRefresh = false;
|
|
536
|
+
this.editor.view.dispatch(this.editor.state.tr.setMeta(refreshKey, "options"));
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
destroy() {
|
|
540
|
+
this.editor?.destroy();
|
|
541
|
+
this.editor = null;
|
|
542
|
+
}
|
|
543
|
+
};
|
|
544
|
+
|
|
545
|
+
export {
|
|
546
|
+
segmentsToRanges,
|
|
547
|
+
BindingSession
|
|
548
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { A as Annotation, R as RubyfieldOptions, a as Rubyfield } from './types-B8H5PDW4.js';
|
|
2
|
+
export { b as Annotate, c as AnnotationBehaviorOptions, d as Attributes, E as ElementOptions, e as RPElementOptions, f as RubyOptions, g as RubyfieldHandle } from './types-B8H5PDW4.js';
|
|
3
|
+
import '@tiptap/extension-ruby-text';
|
|
4
|
+
|
|
5
|
+
/** Convert consecutive base text and annotation text pairs to UTF-16 ranges. */
|
|
6
|
+
declare function segmentsToRanges(pairs: readonly (readonly [text: string, rubyText: string | null | undefined])[]): Annotation[];
|
|
7
|
+
|
|
8
|
+
/** Mount a plain-text field with live, read-only ruby annotations in a DOM container. */
|
|
9
|
+
declare function createRubyfield(element: HTMLElement, options: RubyfieldOptions): Rubyfield;
|
|
10
|
+
|
|
11
|
+
export { Annotation, Rubyfield, RubyfieldOptions, createRubyfield, segmentsToRanges };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BindingSession,
|
|
3
|
+
segmentsToRanges
|
|
4
|
+
} from "./chunk-TFNIKGHG.js";
|
|
5
|
+
|
|
6
|
+
// src/index.ts
|
|
7
|
+
import { Editor } from "@tiptap/core";
|
|
8
|
+
function createRubyfield(element, options) {
|
|
9
|
+
const session = new BindingSession(options);
|
|
10
|
+
const editor = new Editor({ ...session.createOptions(), element });
|
|
11
|
+
session.attach(editor);
|
|
12
|
+
return Object.assign(session.handle, {
|
|
13
|
+
setOptions: (next) => session.setOptions(next),
|
|
14
|
+
destroy: () => session.destroy()
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
export {
|
|
18
|
+
createRubyfield,
|
|
19
|
+
segmentsToRanges
|
|
20
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { EditorOptions, Editor } from '@tiptap/core';
|
|
2
|
+
import { g as RubyfieldHandle, R as RubyfieldOptions } from './types-B8H5PDW4.js';
|
|
3
|
+
import '@tiptap/extension-ruby-text';
|
|
4
|
+
|
|
5
|
+
declare class BindingSession {
|
|
6
|
+
private editor;
|
|
7
|
+
private config;
|
|
8
|
+
private readonly multiline;
|
|
9
|
+
private lastText;
|
|
10
|
+
private pendingRefresh;
|
|
11
|
+
private pendingContent;
|
|
12
|
+
private rubySignature;
|
|
13
|
+
private annotationSignature;
|
|
14
|
+
readonly handle: RubyfieldHandle;
|
|
15
|
+
constructor(options: RubyfieldOptions);
|
|
16
|
+
createOptions(): Partial<EditorOptions>;
|
|
17
|
+
attach(editor: Editor): void;
|
|
18
|
+
private setContent;
|
|
19
|
+
setOptions(options: Partial<RubyfieldOptions>): void;
|
|
20
|
+
private flushComposition;
|
|
21
|
+
destroy(): void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export { BindingSession };
|
package/dist/session.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { RubyTextOptions } from '@tiptap/extension-ruby-text';
|
|
2
|
+
|
|
3
|
+
/** Ruby text for a half-open UTF-16 range in the supplied base text. */
|
|
4
|
+
type Annotation = readonly [startIndex: number, endIndex: number, rubyText: string];
|
|
5
|
+
/** Pure function producing annotations for the supplied line or full text. */
|
|
6
|
+
type Annotate = (text: string) => readonly Annotation[];
|
|
7
|
+
/** Raw HTML attributes using names such as `class`, not React's `className`. */
|
|
8
|
+
type Attributes = RubyTextOptions["HTMLAttributes"];
|
|
9
|
+
/** Attribute options for a rendered element. */
|
|
10
|
+
interface ElementOptions {
|
|
11
|
+
/**
|
|
12
|
+
* Raw HTML attributes applied to the element.
|
|
13
|
+
* @default {}
|
|
14
|
+
*/
|
|
15
|
+
attributes?: Attributes;
|
|
16
|
+
}
|
|
17
|
+
/** Optional ruby separator text and attributes. */
|
|
18
|
+
interface RPElementOptions extends ElementOptions {
|
|
19
|
+
/**
|
|
20
|
+
* Plain text inside <rp>; HTML is not interpreted.
|
|
21
|
+
* @default "(" before the annotation; ")" after the annotation
|
|
22
|
+
*/
|
|
23
|
+
text?: string;
|
|
24
|
+
}
|
|
25
|
+
/** Ruby rendering options shared by the live field and HTML export. */
|
|
26
|
+
interface RubyOptions extends ElementOptions {
|
|
27
|
+
/** Customize the annotation element; omitting this option still creates <rt>. */
|
|
28
|
+
rt?: ElementOptions;
|
|
29
|
+
/** Optional annotation separators; omitted sides create no <rp> element. */
|
|
30
|
+
rp?: {
|
|
31
|
+
/** Separator before the annotation; an empty object uses "(". */
|
|
32
|
+
before?: RPElementOptions;
|
|
33
|
+
/** Separator after the annotation; an empty object uses ")". */
|
|
34
|
+
after?: RPElementOptions;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** Annotation scope, validation policy, and error handling. */
|
|
38
|
+
interface AnnotationBehaviorOptions {
|
|
39
|
+
/**
|
|
40
|
+
* Annotation input scope: only new or changed lines, or the whole text.
|
|
41
|
+
* @default "line"
|
|
42
|
+
*/
|
|
43
|
+
scope?: "line" | "text";
|
|
44
|
+
/**
|
|
45
|
+
* Lenient clamps bounds and silently discards malformed or empty ranges.
|
|
46
|
+
* Strict additionally rejects overlaps and surrogate/grapheme splits, rejects
|
|
47
|
+
* out-of-bounds ranges instead of clamping, and reports validation errors.
|
|
48
|
+
* @default "lenient"
|
|
49
|
+
*/
|
|
50
|
+
validation?: "lenient" | "strict";
|
|
51
|
+
/** Callback for annotation errors after the edit commits; errors are thrown asynchronously when omitted. */
|
|
52
|
+
onError?: (error: unknown) => void;
|
|
53
|
+
}
|
|
54
|
+
/** Plain-text field configuration shared by core and framework bindings. */
|
|
55
|
+
interface RubyfieldOptions {
|
|
56
|
+
/** Pure annotation function for the base text. */
|
|
57
|
+
annotate: Annotate;
|
|
58
|
+
/** Annotation processing policy; defaults to line scope and lenient validation. */
|
|
59
|
+
annotationBehavior?: AnnotationBehaviorOptions;
|
|
60
|
+
/** Base text replaced by later option or prop updates. */
|
|
61
|
+
content?: string;
|
|
62
|
+
/**
|
|
63
|
+
* Initial base text; later changes are ignored. Mutually exclusive with content.
|
|
64
|
+
* @default ""
|
|
65
|
+
*/
|
|
66
|
+
defaultContent?: string;
|
|
67
|
+
/** Report base-text edits, excluding generated annotation changes. */
|
|
68
|
+
onUpdate?: (content: string) => void;
|
|
69
|
+
/** Rendering options for ruby text and annotation separators. */
|
|
70
|
+
ruby?: RubyOptions;
|
|
71
|
+
/**
|
|
72
|
+
* Raw HTML attributes applied to the element.
|
|
73
|
+
* @default {}
|
|
74
|
+
*/
|
|
75
|
+
attributes?: Attributes;
|
|
76
|
+
/**
|
|
77
|
+
* Allow line breaks; fixed at creation, so recreate or remount the field to change it.
|
|
78
|
+
* @default true
|
|
79
|
+
*/
|
|
80
|
+
multiline?: boolean;
|
|
81
|
+
/**
|
|
82
|
+
* Prevent editing while allowing focus, selection, and copying.
|
|
83
|
+
* @default false
|
|
84
|
+
*/
|
|
85
|
+
readOnly?: boolean;
|
|
86
|
+
/**
|
|
87
|
+
* Prevent editing and remove the field from keyboard tab navigation.
|
|
88
|
+
* @default false
|
|
89
|
+
*/
|
|
90
|
+
disabled?: boolean;
|
|
91
|
+
/**
|
|
92
|
+
* Text displayed while the base text is empty.
|
|
93
|
+
* @default ""
|
|
94
|
+
*/
|
|
95
|
+
placeholder?: string;
|
|
96
|
+
/**
|
|
97
|
+
* Focus the field when it mounts.
|
|
98
|
+
* @default false
|
|
99
|
+
*/
|
|
100
|
+
autoFocus?: boolean;
|
|
101
|
+
}
|
|
102
|
+
/** Access to the field DOM, base text, selection, and HTML export. */
|
|
103
|
+
interface RubyfieldHandle {
|
|
104
|
+
/** Editable element, or null before mounting or after destruction. */
|
|
105
|
+
readonly element: HTMLElement | null;
|
|
106
|
+
/** Current base text without annotations or annotation separators. */
|
|
107
|
+
readonly value: string;
|
|
108
|
+
/** Focus the field unless disabled. */
|
|
109
|
+
focus(): void;
|
|
110
|
+
/** Remove focus from the field. */
|
|
111
|
+
blur(): void;
|
|
112
|
+
/** Select all base text. */
|
|
113
|
+
select(): void;
|
|
114
|
+
/** Select a half-open range using UTF-16 offsets in the base text. */
|
|
115
|
+
setSelectionRange(start: number, end: number): void;
|
|
116
|
+
/** Export an HTML string containing the base text and ruby annotations. */
|
|
117
|
+
getHTML(): string;
|
|
118
|
+
}
|
|
119
|
+
/** Core field instance with runtime option updates and explicit cleanup. */
|
|
120
|
+
interface Rubyfield extends RubyfieldHandle {
|
|
121
|
+
/** Update runtime options; supplied content replaces the current base text. */
|
|
122
|
+
setOptions(options: Partial<Omit<RubyfieldOptions, "multiline">>): void;
|
|
123
|
+
/** Destroy the field and release its resources. */
|
|
124
|
+
destroy(): void;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export type { Annotation as A, ElementOptions as E, RubyfieldOptions as R, Rubyfield as a, Annotate as b, AnnotationBehaviorOptions as c, Attributes as d, RPElementOptions as e, RubyOptions as f, RubyfieldHandle as g };
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "rubyfield",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Plain-text field with live, read-only ruby annotations.",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/graphemecluster/rubyfield.git",
|
|
8
|
+
"directory": "packages/core"
|
|
9
|
+
},
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"sideEffects": false,
|
|
12
|
+
"type": "module",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"import": "./dist/index.js"
|
|
17
|
+
},
|
|
18
|
+
"./session": {
|
|
19
|
+
"types": "./dist/session.d.ts",
|
|
20
|
+
"import": "./dist/session.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"main": "./dist/index.js",
|
|
24
|
+
"module": "./dist/index.js",
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"files": [
|
|
27
|
+
"dist",
|
|
28
|
+
"README.md",
|
|
29
|
+
"LICENSE"
|
|
30
|
+
],
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsup src/index.ts src/session.ts --format esm --dts --clean"
|
|
33
|
+
},
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"@tiptap/core": "3.35.0",
|
|
36
|
+
"@tiptap/extension-document": "3.35.0",
|
|
37
|
+
"@tiptap/extension-paragraph": "3.35.0",
|
|
38
|
+
"@tiptap/extension-ruby-text": "3.35.0",
|
|
39
|
+
"@tiptap/extension-text": "3.35.0",
|
|
40
|
+
"@tiptap/extensions": "3.35.0",
|
|
41
|
+
"@tiptap/pm": "3.35.0"
|
|
42
|
+
},
|
|
43
|
+
"publishConfig": {
|
|
44
|
+
"access": "public"
|
|
45
|
+
}
|
|
46
|
+
}
|