@ember-formwright/tiptap 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ # @ember-formwright/tiptap
2
+
3
+ ## 1.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 5db314e: New package: a `rich-text` control on Tiptap 3's StarterKit. `registerTiptapControl()`
8
+ registers it. It has a toolbar (bold, italic, strikethrough, headings, lists, quote, undo,
9
+ redo; pick with `@toolbar`), stores HTML or, with `@output="json"`, Tiptap JSON, and
10
+ `toPlainText` formats either for inline forms. `RichTextHarness` lives at
11
+ `@ember-formwright/tiptap/test-support`, and `theme.css` follows the Formwright theme.
12
+
13
+ ### Patch Changes
14
+
15
+ - Updated dependencies [aad9026]
16
+ - Updated dependencies [abc6560]
17
+ - @ember-formwright/ember@1.3.0
18
+ - @ember-formwright/test-support@1.3.0
package/LICENSE.md ADDED
@@ -0,0 +1,9 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,74 @@
1
- # Temporary Holding Version
1
+ # @ember-formwright/tiptap
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A rich-text control for Formwright, powered by [Tiptap](https://tiptap.dev) 3 and its
4
+ StarterKit.
5
+
6
+ ```bash
7
+ npm install @ember-formwright/ember @ember-formwright/tiptap @tiptap/core @tiptap/pm @tiptap/starter-kit
8
+ ```
9
+
10
+ ```ts
11
+ // app/app.ts
12
+ import { registerTiptapControl } from '@ember-formwright/tiptap'
13
+ import '@ember-formwright/tiptap/theme.css' // optional; after the Formwright theme
14
+
15
+ registerTiptapControl() // @control="rich-text"
16
+ ```
17
+
18
+ ```gts
19
+ <f.Field @for="body" @control="rich-text" @label="Body" @placeholder="Write something" />
20
+
21
+ {{! a trimmed toolbar, storing Tiptap JSON }}
22
+ <f.Field @for="comment" @control="rich-text" @label="Comment" as |field|>
23
+ <field.Control @toolbar={{array "bold" "italic" "bullet-list"}} @output="json" />
24
+ </f.Field>
25
+
26
+ {{! inline forms show the value as text }}
27
+ <f.Field @for="body" @control="rich-text" @format={{toPlainText}} />
28
+ ```
29
+
30
+ The field stores HTML, or Tiptap's JSON document with `@output="json"`. An empty editor
31
+ stores `''` (`null` for JSON), so required checks work. `field.Control` also takes `@toolbar`
32
+ (the buttons to show, or `false`), `@extensions` (more Tiptap extensions) and `@starterKit`
33
+ (StarterKit's options); the last two are read once, when the editor is created.
34
+
35
+ Toolbar buttons: `bold`, `italic`, `strike`, `heading-2`, `heading-3`, `bullet-list`,
36
+ `ordered-list`, `blockquote`, `undo`, `redo`. Each has an accessible name, and the toggles
37
+ carry `aria-pressed`.
38
+
39
+ ## Testing
40
+
41
+ ```ts
42
+ import { RichTextHarness } from '@ember-formwright/tiptap/test-support'
43
+
44
+ class PostForm extends FormHarness {
45
+ @field(RichTextHarness) declare body: RichTextHarness
46
+ }
47
+
48
+ await post.body.typeText('Hello')
49
+ await post.body.selectAll()
50
+ await post.body.press('bold')
51
+ assert.true(post.body.isActive('bold'))
52
+ assert.strictEqual(post.body.html, '<p><strong>Hello</strong></p>')
53
+ ```
54
+
55
+ It also has `text`, `setContent(html)`, `tools`, `isEditable` and `editor` (the Tiptap
56
+ editor). Text goes in through Tiptap's commands: ProseMirror doesn't react to synthetic key
57
+ events.
58
+
59
+ ## Behaviour and known limits
60
+
61
+ - **Outside changes.** A new value from the model (reset, rollback, a reload) replaces the
62
+ document without a change event. Typing never re-sets the document.
63
+ - **Trailing paragraph.** StarterKit keeps an empty paragraph after a final list or heading,
64
+ so there is somewhere to type. It isn't stored.
65
+ - **Keyboard.** Enter starts a paragraph and doesn't reach the field, so in confirm and
66
+ inline modes it doesn't commit; use ✔. Escape cancels as usual.
67
+ - **Disabled and read-only.** The editor stops being editable and the toolbar is disabled.
68
+ - **Labels.** The editor is a `div role="textbox"`, which `<label for>` doesn't name; the
69
+ control passes `@label` as `aria-label`, and a click on the label focuses the editor.
70
+ - **Native submit.** There is no `<input name>`; the wrapper carries `data-fw-name` with the
71
+ field's path.
72
+ - **Sanitize.** Tiptap's schema limits what the editor produces, but the HTML is still user
73
+ input. Sanitize it on the server before rendering it elsewhere.
74
+ - **Versions.** Ember 6.12+ and Tiptap 3.
package/addon-main.cjs ADDED
@@ -0,0 +1,4 @@
1
+ 'use strict'
2
+
3
+ const { addonV1Shim } = require('@embroider/addon-shim')
4
+ module.exports = addonV1Shim(__dirname)
@@ -0,0 +1,97 @@
1
+ import Component from '@glimmer/component';
2
+ import type Owner from '@ember/owner';
3
+ import { Editor, type Extensions, type JSONContent } from '@tiptap/core';
4
+ import StarterKit from '@tiptap/starter-kit';
5
+ import { type ControlSignature } from '@ember-formwright/ember';
6
+ /** A toolbar button, by name. */
7
+ export type RichTextTool = 'bold' | 'italic' | 'strike' | 'heading-2' | 'heading-3' | 'bullet-list' | 'ordered-list' | 'blockquote' | 'undo' | 'redo';
8
+ /** What the control stores: HTML (a string), or Tiptap's JSON document. */
9
+ export type RichTextValue = string | JSONContent | null;
10
+ interface Tool {
11
+ name: RichTextTool;
12
+ label: string;
13
+ /** Toggles a mark or node, so it has a pressed state. */
14
+ toggle: boolean;
15
+ run: (editor: Editor) => void;
16
+ isActive: (editor: Editor) => boolean;
17
+ can: (editor: Editor) => boolean;
18
+ }
19
+ /** Every button, the default `@toolbar`. */
20
+ export declare const DEFAULT_TOOLBAR: readonly RichTextTool[];
21
+ export interface RichTextControlSignature {
22
+ /** The wrapper around the toolbar and the editor. */
23
+ Element: HTMLDivElement;
24
+ Args: ControlSignature<RichTextValue>['Args'] & {
25
+ /** `html` (default) stores an HTML string; `json` stores Tiptap's JSON document. */
26
+ output?: 'html' | 'json';
27
+ /** The buttons to show, in groups as listed; `false` hides the toolbar. */
28
+ toolbar?: readonly RichTextTool[] | false;
29
+ /** More Tiptap extensions, added after StarterKit. Read once, when the editor is created. */
30
+ extensions?: Extensions;
31
+ /** StarterKit's options, e.g. `{ heading: { levels: [2, 3] } }`. Read once. */
32
+ starterKit?: Parameters<typeof StarterKit.configure>[0];
33
+ };
34
+ }
35
+ /**
36
+ * A rich-text editor built on Tiptap's StarterKit, with a toolbar. Stores HTML, or Tiptap JSON
37
+ * with `@output="json"`; an empty document stores `''` (`null` for JSON).
38
+ */
39
+ export declare class RichTextControl extends Component<RichTextControlSignature> {
40
+ readonly editor: Editor;
41
+ /** The value this control last sent or was given, so it isn't set back into the editor. */
42
+ private current;
43
+ /** Bumped after each transaction, so the toolbar's pressed states re-render. */
44
+ revision: number;
45
+ constructor(owner: Owner, args: RichTextControlSignature['Args']);
46
+ get isJson(): boolean;
47
+ get editable(): boolean;
48
+ /** The toolbar's buttons, in groups; empty groups are left out. */
49
+ get groups(): Tool[][];
50
+ /**
51
+ * What the document stores as. StarterKit keeps an empty paragraph after a final list or
52
+ * heading, so there is somewhere to type; it isn't content, so it isn't stored.
53
+ */
54
+ serialize(): RichTextValue;
55
+ onUpdate(): void;
56
+ /** Transactions also happen while rendering (setting content), so re-render after it. */
57
+ refresh(): void;
58
+ isPressed: (tool: Tool, _revision: number) => boolean;
59
+ isDisabled: (tool: Tool, _revision: number) => boolean;
60
+ run: (tool: Tool) => void;
61
+ /** Keeps the editor's selection when a toolbar button is clicked. */
62
+ keepFocus: (event: MouseEvent) => void;
63
+ /** Mounts the editor on this element; a click on the field's label focuses it. */
64
+ mount: import("ember-modifier").FunctionBasedModifier<{
65
+ Args: {
66
+ Positional: unknown[];
67
+ Named: import("ember-modifier/-private/signature").EmptyObject;
68
+ };
69
+ Element: HTMLElement;
70
+ }>;
71
+ /** A new value from outside (a reset, a rollback) replaces the document, without a change. */
72
+ sync: import("ember-modifier").FunctionBasedModifier<{
73
+ Args: {
74
+ Positional: [unknown];
75
+ Named: import("ember-modifier/-private/signature").EmptyObject;
76
+ };
77
+ Element: HTMLElement;
78
+ }>;
79
+ setEditable: import("ember-modifier").FunctionBasedModifier<{
80
+ Args: {
81
+ Positional: [boolean];
82
+ Named: import("ember-modifier/-private/signature").EmptyObject;
83
+ };
84
+ Element: HTMLElement;
85
+ }>;
86
+ /** Enter makes a new paragraph; it doesn't reach the field, which would commit the edit. */
87
+ onKeydown: (event: KeyboardEvent) => void;
88
+ }
89
+ /**
90
+ * Plain text from a rich-text value (HTML or Tiptap JSON), for the field's `@format` in inline
91
+ * forms: `<f.Field @control="rich-text" @format={{toPlainText}} />`.
92
+ */
93
+ export declare function toPlainText(value: RichTextValue | undefined): string;
94
+ /** Makes `@control="rich-text"` available to every form. Call once, e.g. in app.ts. */
95
+ export declare function registerTiptapControl(name?: string): void;
96
+ export {};
97
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.gts"],"names":[],"mappings":"AAqXA,OAAO,SAAS,MAAM,oBAAoB,CAAA;AAE1C,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AAKrC,OAAO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A;KACxD,CAAA;CACF;AAYD;;;GAGG;AACH,qBAAa,eAAgB,SAAQ,SAAS,CAAC,wBAAwB,CAAC;IACtE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,2FAA2F;IAC3F,OAAO,CAAC,OAAO,CAAS;IACxB,gFAAgF;IACvE,QAAQ,SAAI;gBAET,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,wBAAwB,CAAC,MAAM,CAAC;IAkBhE,IAAI,MAAM,IAAI,OAAO,CAEpB;IAED,IAAI,QAAQ,IAAI,OAAO,CAEtB;IAED,mEAAmE;IACnE,IAAI,MAAM,IAAI,IAAI,EAAE,EAAE,CAOrB;IAED;;;OAGG;IACH,SAAS,IAAI,aAAa;IAS1B,QAAQ,IAAI,IAAI;IAMhB,yFAAyF;IACzF,OAAO,IAAI,IAAI;IAMf,SAAS,GAAI,MAAM,IAAI,EAAE,WAAW,MAAM,KAAG,OAAO,CAA8B;IAClF,UAAU,GAAI,MAAM,IAAI,EAAE,WAAW,MAAM,KAAG,OAAO,CAA4C;IAEjG,GAAG,GAAI,MAAM,IAAI,KAAG,IAAI,CAAyB;IAEjD,qEAAqE;IACrE,SAAS,GAAI,OAAO,UAAU,KAAG,IAAI,CAA0B;IAE/D,kFAAkF;IAClF,KAAK;;;;;;OAWH;IAEF,8FAA8F;IAC9F,IAAI;;;;;;OAQF;IAEF,WAAW;;;;;;OAET;IAEF,4FAA4F;IAC5F,SAAS,GAAI,OAAO,aAAa,KAAG,IAAI,CAEvC;CAoIF;AA4ND;;;GAGG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,aAAa,GAAG,SAAS,GAAG,MAAM,CAgBpE;AAED,uFAAuF;AACvF,wBAAgB,qBAAqB,CAAC,IAAI,SAAc,GAAG,IAAI,CAE9D"}
@@ -0,0 +1,42 @@
1
+ import { FieldHarness } from '@ember-formwright/test-support';
2
+ import type { Editor } from '@tiptap/core';
3
+ /**
4
+ * Drives a `rich-text` field. Text goes in through the editor's own commands (ProseMirror
5
+ * doesn't react to synthetic key events); formatting goes through the toolbar, as a user's
6
+ * would:
7
+ *
8
+ * class PostForm extends FormHarness {
9
+ * @field(RichTextHarness) declare body: RichTextHarness
10
+ * }
11
+ *
12
+ * await form.body.typeText('Hello')
13
+ * await form.body.selectAll()
14
+ * await form.body.press('bold')
15
+ * assert.strictEqual(form.body.html, '<p><strong>Hello</strong></p>')
16
+ */
17
+ export declare class RichTextHarness extends FieldHarness {
18
+ static controls: string[];
19
+ /** The editable element (the one with the field's id). */
20
+ get editorElement(): HTMLElement;
21
+ /** The Tiptap editor behind the field. */
22
+ get editor(): Editor;
23
+ /** The document as HTML. */
24
+ get html(): string;
25
+ /** The document as plain text, blocks separated by blank lines. */
26
+ get text(): string;
27
+ get isEditable(): boolean;
28
+ /** The toolbar's button names, in order. */
29
+ get tools(): string[];
30
+ /** Replaces the document, as pasting over all of it would; the cursor ends up at the end. */
31
+ setContent(html: string): Promise<void>;
32
+ /** Inserts text at the cursor (at the end, if the editor isn't focused). */
33
+ typeText(text: string): Promise<void>;
34
+ /** Selects the whole document, e.g. before pressing a button. */
35
+ selectAll(): Promise<void>;
36
+ /** Clicks a toolbar button: `bold`, `heading-2`, `bullet-list`, `undo`, ... */
37
+ press(tool: string): Promise<void>;
38
+ /** Whether a toolbar button is pressed (its mark or block is active at the cursor). */
39
+ isActive(tool: string): boolean;
40
+ private tool;
41
+ }
42
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/test-support/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAA;AAC7D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAE1C;;;;;;;;;;;;;GAaG;AACH,qBAAa,eAAgB,SAAQ,YAAY;IAC/C,OAAgB,QAAQ,WAAgB;IAExC,0DAA0D;IAC1D,IAAI,aAAa,IAAI,WAAW,CAE/B;IAED,0CAA0C;IAC1C,IAAI,MAAM,IAAI,MAAM,CAInB;IAED,4BAA4B;IAC5B,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,mEAAmE;IACnE,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,IAAI,UAAU,IAAI,OAAO,CAExB;IAED,4CAA4C;IAC5C,IAAI,KAAK,IAAI,MAAM,EAAE,CAIpB;IAED,6FAA6F;IACvF,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAK7C,4EAA4E;IACtE,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAU3C,iEAAiE;IAC3D,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;IAKhC,+EAA+E;IACzE,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIxC,uFAAuF;IACvF,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAI/B,OAAO,CAAC,IAAI;CAOb"}
package/dist/index.js ADDED
@@ -0,0 +1,217 @@
1
+ import Component from '@glimmer/component';
2
+ import { tracked } from '@glimmer/tracking';
3
+ import { fn } from '@ember/helper';
4
+ import { on } from '@ember/modifier';
5
+ import { modifier } from 'ember-modifier';
6
+ import { Editor } from '@tiptap/core';
7
+ import StarterKit from '@tiptap/starter-kit';
8
+ import { registerControl } from '@ember-formwright/ember';
9
+ import { precompileTemplate } from '@ember/template-compilation';
10
+ import { setComponentTemplate } from '@ember/component';
11
+ import templateOnly from '@ember/component/template-only';
12
+ import { g, i } from 'decorator-transforms/runtime';
13
+
14
+ const mark = (name, label, type, run) => ({
15
+ name,
16
+ label,
17
+ toggle: true,
18
+ run,
19
+ isActive: editor => editor.isActive(type),
20
+ can: () => true
21
+ });
22
+ const heading = level => ({
23
+ name: `heading-${level}`,
24
+ label: `Heading ${level}`,
25
+ toggle: true,
26
+ run: editor => editor.chain().focus().toggleHeading({
27
+ level
28
+ }).run(),
29
+ isActive: editor => editor.isActive('heading', {
30
+ level
31
+ }),
32
+ can: () => true
33
+ });
34
+ const TOOLS = [mark('bold', 'Bold', 'bold', e => e.chain().focus().toggleBold().run()), mark('italic', 'Italic', 'italic', e => e.chain().focus().toggleItalic().run()), mark('strike', 'Strikethrough', 'strike', e => e.chain().focus().toggleStrike().run()), heading(2), heading(3), mark('bullet-list', 'Bulleted list', 'bulletList', e => e.chain().focus().toggleBulletList().run()), mark('ordered-list', 'Numbered list', 'orderedList', e => e.chain().focus().toggleOrderedList().run()), mark('blockquote', 'Quote', 'blockquote', e => e.chain().focus().toggleBlockquote().run()), {
35
+ name: 'undo',
36
+ label: 'Undo',
37
+ toggle: false,
38
+ run: e => e.chain().focus().undo().run(),
39
+ isActive: () => false,
40
+ can: e => e.can().undo()
41
+ }, {
42
+ name: 'redo',
43
+ label: 'Redo',
44
+ toggle: false,
45
+ run: e => e.chain().focus().redo().run(),
46
+ isActive: () => false,
47
+ can: e => e.can().redo()
48
+ }];
49
+ /** Buttons are drawn in groups, with a divider between them. */
50
+ const GROUPS = [['bold', 'italic', 'strike'], ['heading-2', 'heading-3'], ['bullet-list', 'ordered-list', 'blockquote'], ['undo', 'redo']];
51
+ /** Every button, the default `@toolbar`. */
52
+ const DEFAULT_TOOLBAR = GROUPS.flat();
53
+ /** Whether a document is a single empty paragraph (or heading). */function isEmptyDoc(state) {
54
+ const {
55
+ doc
56
+ } = state;
57
+ return doc.childCount === 1 && doc.firstChild.isTextblock && doc.firstChild.content.size === 0;
58
+ }
59
+ const isEmptyParagraph = node => node.type === 'paragraph' && !node.content?.length;
60
+ const isBlank = value => value === null || value === undefined || value === '';
61
+ /**
62
+ * A rich-text editor built on Tiptap's StarterKit, with a toolbar. Stores HTML, or Tiptap JSON
63
+ * with `@output="json"`; an empty document stores `''` (`null` for JSON).
64
+ */
65
+ class RichTextControl extends Component {
66
+ editor;
67
+ /** The value this control last sent or was given, so it isn't set back into the editor. */
68
+ current;
69
+ /** Bumped after each transaction, so the toolbar's pressed states re-render. */
70
+ static {
71
+ g(this.prototype, "revision", [tracked], function () {
72
+ return 0;
73
+ });
74
+ }
75
+ #revision = (i(this, "revision"), void 0);
76
+ constructor(owner, args) {
77
+ super(owner, args);
78
+ this.current = args.value;
79
+ this.editor = new Editor({
80
+ element: null,
81
+ content: args.value ?? '',
82
+ extensions: [StarterKit.configure(args.starterKit), ...(args.extensions ?? [])],
83
+ editorProps: {
84
+ attributes: state => ({
85
+ class: 'fw-rich-text-editor',
86
+ ...(isEmptyDoc(state) ? {
87
+ 'data-empty': ''
88
+ } : {})
89
+ })
90
+ },
91
+ onUpdate: () => this.onUpdate(),
92
+ onTransaction: () => this.refresh()
93
+ });
94
+ }
95
+ get isJson() {
96
+ return this.args.output === 'json';
97
+ }
98
+ get editable() {
99
+ return !(this.args.disabled || this.args.readonly);
100
+ }
101
+ /** The toolbar's buttons, in groups; empty groups are left out. */
102
+ get groups() {
103
+ const wanted = this.args.toolbar;
104
+ if (wanted === false) return [];
105
+ const names = new Set(wanted ?? DEFAULT_TOOLBAR);
106
+ return GROUPS.map(group => TOOLS.filter(tool => group.includes(tool.name) && names.has(tool.name))).filter(group => group.length);
107
+ }
108
+ /**
109
+ * What the document stores as. StarterKit keeps an empty paragraph after a final list or
110
+ * heading, so there is somewhere to type; it isn't content, so it isn't stored.
111
+ */
112
+ serialize() {
113
+ if (this.editor.isEmpty) return this.isJson ? null : '';
114
+ if (!this.isJson) return this.editor.getHTML().replace(/(<p><\/p>)+$/, '');
115
+ const json = this.editor.getJSON();
116
+ const content = [...(json.content ?? [])];
117
+ while (content.length > 1 && isEmptyParagraph(content[content.length - 1])) content.pop();
118
+ return {
119
+ ...json,
120
+ content
121
+ };
122
+ }
123
+ onUpdate() {
124
+ const value = this.serialize();
125
+ this.current = value;
126
+ this.args.onChange(value);
127
+ }
128
+ /** Transactions also happen while rendering (setting content), so re-render after it. */
129
+ refresh() {
130
+ queueMicrotask(() => {
131
+ if (!this.isDestroying) this.revision++;
132
+ });
133
+ }
134
+ isPressed = (tool, _revision) => tool.isActive(this.editor);
135
+ isDisabled = (tool, _revision) => !this.editable || !tool.can(this.editor);
136
+ run = tool => tool.run(this.editor);
137
+ /** Keeps the editor's selection when a toolbar button is clicked. */
138
+ keepFocus = event => event.preventDefault();
139
+ /** Mounts the editor on this element; a click on the field's label focuses it. */
140
+ mount = modifier(element => {
141
+ this.editor.mount({
142
+ mount: element
143
+ });
144
+ const label = element.id ? document.querySelector(`label[for="${CSS.escape(element.id)}"]`) : null;
145
+ const focus = () => element.focus();
146
+ label?.addEventListener('click', focus);
147
+ return () => {
148
+ label?.removeEventListener('click', focus);
149
+ this.editor.destroy();
150
+ };
151
+ });
152
+ /** A new value from outside (a reset, a rollback) replaces the document, without a change. */
153
+ sync = modifier((_element, [value]) => {
154
+ if (value === this.current) return;
155
+ this.current = value;
156
+ if (isBlank(value) && this.editor.isEmpty) return;
157
+ const same = this.isJson ? JSON.stringify(value) === JSON.stringify(this.serialize()) : value === this.serialize();
158
+ if (!same) this.editor.commands.setContent(value ?? '', {
159
+ emitUpdate: false
160
+ });
161
+ });
162
+ setEditable = modifier((_element, [editable]) => {
163
+ if (this.editor.isEditable !== editable) this.editor.setEditable(editable, false);
164
+ });
165
+ /** Enter makes a new paragraph; it doesn't reach the field, which would commit the edit. */
166
+ onKeydown = event => {
167
+ if (event.key === 'Enter') event.stopPropagation();
168
+ };
169
+ static {
170
+ setComponentTemplate(precompileTemplate("<div class=\"fw-rich-text{{if @disabled \" fw-rich-text--disabled\"}}\" data-test-fw-control={{@type}} data-fw-name={{@name}} ...attributes>\n {{#if this.groups.length}}\n <div class=\"fw-rich-text-toolbar\" role=\"toolbar\" aria-label=\"Formatting\" aria-controls={{@id}}>\n {{#each this.groups as |group|}}\n <span class=\"fw-rich-text-group\">\n {{#each group as |tool|}}\n <button type=\"button\" class=\"fw-rich-text-tool fw-rich-text-tool--{{tool.name}}\" title={{tool.label}} aria-label={{tool.label}} aria-pressed={{if tool.toggle (if (this.isPressed tool this.revision) \"true\" \"false\")}} disabled={{this.isDisabled tool this.revision}} data-test-fw-tool={{tool.name}} {{on \"mousedown\" this.keepFocus}} {{on \"click\" (fn this.run tool)}}>\n <ToolIcon @name={{tool.name}} />\n </button>\n {{/each}}\n </span>\n {{/each}}\n </div>\n {{/if}}\n <div id={{@id}} aria-multiline=\"true\" aria-label={{@label}} aria-describedby={{@describedBy}} aria-invalid={{if @invalid \"true\"}} aria-required={{if @required \"true\"}} aria-readonly={{if @readonly \"true\"}} aria-disabled={{if @disabled \"true\"}} aria-placeholder={{@placeholder}} data-placeholder={{@placeholder}} {{this.mount}} {{this.sync @value}} {{this.setEditable this.editable}} {{on \"keydown\" this.onKeydown}}></div>\n</div>", {
171
+ strictMode: true,
172
+ scope: () => ({
173
+ on,
174
+ fn,
175
+ ToolIcon
176
+ })
177
+ }), this);
178
+ }
179
+ }
180
+ /** Each button's glyph: a letter for marks, a small SVG for the rest. Decorative. */
181
+ const ToolIcon = setComponentTemplate(precompileTemplate("{{#if (eq @name \"bold\")}}<b aria-hidden=\"true\">B</b>\n{{else if (eq @name \"italic\")}}<i aria-hidden=\"true\">I</i>\n{{else if (eq @name \"strike\")}}<s aria-hidden=\"true\">S</s>\n{{else}}\n <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" width=\"16\" height=\"16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n {{#if (eq @name \"heading-2\")}}\n <path d=\"M2 3.5v9M8 3.5v9M2 8h6\" />\n <path d=\"M10.5 9.2c0-.7.6-1.2 1.3-1.2s1.3.5 1.3 1.2c0 1-2.6 1.8-2.6 3.3h2.8\" />\n {{else if (eq @name \"heading-3\")}}\n <path d=\"M2 3.5v9M8 3.5v9M2 8h6\" />\n <path d=\"M10.6 8h2.4l-1.4 1.6c.9 0 1.5.5 1.5 1.3s-.7 1.4-1.5 1.4c-.6 0-1.1-.3-1.3-.7\" />\n {{else if (eq @name \"bullet-list\")}}\n <circle cx=\"2.5\" cy=\"4\" r=\"1\" fill=\"currentColor\" stroke=\"none\" />\n <circle cx=\"2.5\" cy=\"8\" r=\"1\" fill=\"currentColor\" stroke=\"none\" />\n <circle cx=\"2.5\" cy=\"12\" r=\"1\" fill=\"currentColor\" stroke=\"none\" />\n <path d=\"M6 4h8M6 8h8M6 12h8\" />\n {{else if (eq @name \"ordered-list\")}}\n <path d=\"M2 2.5h1v3M2 5.5h2M2 9.5c0-.6.5-1 1-1s1 .4 1 1c0 .8-2 1.5-2 2.5h2\" />\n <path d=\"M7 4h7M7 8h7M7 12h7\" />\n {{else if (eq @name \"blockquote\")}}\n <path d=\"M3 3v10M7 5h7M7 8h7M7 11h5\" />\n {{else if (eq @name \"undo\")}}\n <path d=\"M4 6h6.5a3 3 0 0 1 0 6H7\" /><path d=\"M6.5 3.5 4 6l2.5 2.5\" />\n {{else if (eq @name \"redo\")}}\n <path d=\"M12 6H5.5a3 3 0 0 0 0 6H9\" /><path d=\"M9.5 3.5 12 6l-2.5 2.5\" />\n {{/if}}\n </svg>\n{{/if}}", {
182
+ strictMode: true,
183
+ scope: () => ({
184
+ eq
185
+ })
186
+ }), templateOnly());
187
+ function eq(a, b) {
188
+ return a === b;
189
+ }
190
+ /**
191
+ * Plain text from a rich-text value (HTML or Tiptap JSON), for the field's `@format` in inline
192
+ * forms: `<f.Field @control="rich-text" @format={{toPlainText}} />`.
193
+ */
194
+ function toPlainText(value) {
195
+ if (isBlank(value)) return '';
196
+ if (typeof value === 'string') {
197
+ // Blocks end in a space, so "<p>a</p><p>b</p>" reads "a b", not "ab".
198
+ const spaced = value.replace(/<\/(p|h[1-6]|li|blockquote|pre)>|<br\s*\/?>/gi, '$& ');
199
+ const text = new DOMParser().parseFromString(spaced, 'text/html').body.textContent ?? '';
200
+ return text.replace(/\s+/g, ' ').trim();
201
+ }
202
+ const words = [];
203
+ const walk = node => {
204
+ if (node.text) words.push(node.text);
205
+ node.content?.forEach(walk);
206
+ if (node.type !== 'text') words.push(' ');
207
+ };
208
+ walk(value);
209
+ return words.join('').replace(/\s+/g, ' ').trim();
210
+ }
211
+ /** Makes `@control="rich-text"` available to every form. Call once, e.g. in app.ts. */
212
+ function registerTiptapControl(name = 'rich-text') {
213
+ registerControl(name, RichTextControl);
214
+ }
215
+
216
+ export { DEFAULT_TOOLBAR, RichTextControl, registerTiptapControl, toPlainText };
217
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../src/index.gts"],"sourcesContent":["import Component from '@glimmer/component'\nimport type { TOC } from '@ember/component/template-only'\nimport type Owner from '@ember/owner'\nimport { tracked } from '@glimmer/tracking'\nimport { fn } from '@ember/helper'\nimport { on } from '@ember/modifier'\nimport { modifier } from 'ember-modifier'\nimport { Editor, type Content, type Extensions, type JSONContent } from '@tiptap/core'\nimport type { EditorState } from '@tiptap/pm/state'\nimport StarterKit from '@tiptap/starter-kit'\nimport { registerControl, type ControlSignature } from '@ember-formwright/ember'\n\n/** A toolbar button, by name. */\nexport type RichTextTool =\n | 'bold'\n | 'italic'\n | 'strike'\n | 'heading-2'\n | 'heading-3'\n | 'bullet-list'\n | 'ordered-list'\n | 'blockquote'\n | 'undo'\n | 'redo'\n\n/** What the control stores: HTML (a string), or Tiptap's JSON document. */\nexport type RichTextValue = string | JSONContent | null\n\ninterface Tool {\n name: RichTextTool\n label: string\n /** Toggles a mark or node, so it has a pressed state. */\n toggle: boolean\n run: (editor: Editor) => void\n isActive: (editor: Editor) => boolean\n can: (editor: Editor) => boolean\n}\n\nconst mark = (\n name: RichTextTool,\n label: string,\n type: string,\n run: (editor: Editor) => void,\n): Tool => ({\n name,\n label,\n toggle: true,\n run,\n isActive: editor => editor.isActive(type),\n can: () => true,\n})\n\nconst heading = (level: 2 | 3): Tool => ({\n name: `heading-${level}`,\n label: `Heading ${level}`,\n toggle: true,\n run: editor => editor.chain().focus().toggleHeading({ level }).run(),\n isActive: editor => editor.isActive('heading', { level }),\n can: () => true,\n})\n\nconst TOOLS: Tool[] = [\n mark('bold', 'Bold', 'bold', e => e.chain().focus().toggleBold().run()),\n mark('italic', 'Italic', 'italic', e => e.chain().focus().toggleItalic().run()),\n mark('strike', 'Strikethrough', 'strike', e => e.chain().focus().toggleStrike().run()),\n heading(2),\n heading(3),\n mark('bullet-list', 'Bulleted list', 'bulletList', e =>\n e.chain().focus().toggleBulletList().run(),\n ),\n mark('ordered-list', 'Numbered list', 'orderedList', e =>\n e.chain().focus().toggleOrderedList().run(),\n ),\n mark('blockquote', 'Quote', 'blockquote', e => e.chain().focus().toggleBlockquote().run()),\n {\n name: 'undo',\n label: 'Undo',\n toggle: false,\n run: e => e.chain().focus().undo().run(),\n isActive: () => false,\n can: e => e.can().undo(),\n },\n {\n name: 'redo',\n label: 'Redo',\n toggle: false,\n run: e => e.chain().focus().redo().run(),\n isActive: () => false,\n can: e => e.can().redo(),\n },\n]\n\n/** Buttons are drawn in groups, with a divider between them. */\nconst GROUPS: RichTextTool[][] = [\n ['bold', 'italic', 'strike'],\n ['heading-2', 'heading-3'],\n ['bullet-list', 'ordered-list', 'blockquote'],\n ['undo', 'redo'],\n]\n\n/** Every button, the default `@toolbar`. */\nexport const DEFAULT_TOOLBAR: readonly RichTextTool[] = GROUPS.flat()\n\nexport interface RichTextControlSignature {\n /** The wrapper around the toolbar and the editor. */\n Element: HTMLDivElement\n Args: ControlSignature<RichTextValue>['Args'] & {\n /** `html` (default) stores an HTML string; `json` stores Tiptap's JSON document. */\n output?: 'html' | 'json'\n /** The buttons to show, in groups as listed; `false` hides the toolbar. */\n toolbar?: readonly RichTextTool[] | false\n /** More Tiptap extensions, added after StarterKit. Read once, when the editor is created. */\n extensions?: Extensions\n /** StarterKit's options, e.g. `{ heading: { levels: [2, 3] } }`. Read once. */\n starterKit?: Parameters<typeof StarterKit.configure>[0]\n }\n}\n\n/** Whether a document is a single empty paragraph (or heading). */\nfunction isEmptyDoc(state: EditorState): boolean {\n const { doc } = state\n return doc.childCount === 1 && doc.firstChild!.isTextblock && doc.firstChild!.content.size === 0\n}\n\nconst isEmptyParagraph = (node: JSONContent) => node.type === 'paragraph' && !node.content?.length\n\nconst isBlank = (value: unknown) => value === null || value === undefined || value === ''\n\n/**\n * A rich-text editor built on Tiptap's StarterKit, with a toolbar. Stores HTML, or Tiptap JSON\n * with `@output=\"json\"`; an empty document stores `''` (`null` for JSON).\n */\nexport class RichTextControl extends Component<RichTextControlSignature> {\n readonly editor: Editor\n /** The value this control last sent or was given, so it isn't set back into the editor. */\n private current: unknown\n /** Bumped after each transaction, so the toolbar's pressed states re-render. */\n @tracked revision = 0\n\n constructor(owner: Owner, args: RichTextControlSignature['Args']) {\n super(owner, args)\n this.current = args.value\n this.editor = new Editor({\n element: null,\n content: (args.value ?? '') as Content,\n extensions: [StarterKit.configure(args.starterKit), ...(args.extensions ?? [])],\n editorProps: {\n attributes: (state: EditorState) => ({\n class: 'fw-rich-text-editor',\n ...(isEmptyDoc(state) ? { 'data-empty': '' } : {}),\n }),\n },\n onUpdate: () => this.onUpdate(),\n onTransaction: () => this.refresh(),\n })\n }\n\n get isJson(): boolean {\n return this.args.output === 'json'\n }\n\n get editable(): boolean {\n return !(this.args.disabled || this.args.readonly)\n }\n\n /** The toolbar's buttons, in groups; empty groups are left out. */\n get groups(): Tool[][] {\n const wanted = this.args.toolbar\n if (wanted === false) return []\n const names = new Set(wanted ?? DEFAULT_TOOLBAR)\n return GROUPS.map(group =>\n TOOLS.filter(tool => group.includes(tool.name) && names.has(tool.name)),\n ).filter(group => group.length)\n }\n\n /**\n * What the document stores as. StarterKit keeps an empty paragraph after a final list or\n * heading, so there is somewhere to type; it isn't content, so it isn't stored.\n */\n serialize(): RichTextValue {\n if (this.editor.isEmpty) return this.isJson ? null : ''\n if (!this.isJson) return this.editor.getHTML().replace(/(<p><\\/p>)+$/, '')\n const json = this.editor.getJSON()\n const content = [...(json.content ?? [])]\n while (content.length > 1 && isEmptyParagraph(content[content.length - 1]!)) content.pop()\n return { ...json, content }\n }\n\n onUpdate(): void {\n const value = this.serialize()\n this.current = value\n this.args.onChange(value)\n }\n\n /** Transactions also happen while rendering (setting content), so re-render after it. */\n refresh(): void {\n queueMicrotask(() => {\n if (!this.isDestroying) this.revision++\n })\n }\n\n isPressed = (tool: Tool, _revision: number): boolean => tool.isActive(this.editor)\n isDisabled = (tool: Tool, _revision: number): boolean => !this.editable || !tool.can(this.editor)\n\n run = (tool: Tool): void => tool.run(this.editor)\n\n /** Keeps the editor's selection when a toolbar button is clicked. */\n keepFocus = (event: MouseEvent): void => event.preventDefault()\n\n /** Mounts the editor on this element; a click on the field's label focuses it. */\n mount = modifier((element: HTMLElement) => {\n this.editor.mount({ mount: element })\n const label = element.id\n ? document.querySelector<HTMLLabelElement>(`label[for=\"${CSS.escape(element.id)}\"]`)\n : null\n const focus = () => element.focus()\n label?.addEventListener('click', focus)\n return () => {\n label?.removeEventListener('click', focus)\n this.editor.destroy()\n }\n })\n\n /** A new value from outside (a reset, a rollback) replaces the document, without a change. */\n sync = modifier((_element: HTMLElement, [value]: [unknown]) => {\n if (value === this.current) return\n this.current = value\n if (isBlank(value) && this.editor.isEmpty) return\n const same = this.isJson\n ? JSON.stringify(value) === JSON.stringify(this.serialize())\n : value === this.serialize()\n if (!same) this.editor.commands.setContent((value ?? '') as Content, { emitUpdate: false })\n })\n\n setEditable = modifier((_element: HTMLElement, [editable]: [boolean]) => {\n if (this.editor.isEditable !== editable) this.editor.setEditable(editable, false)\n })\n\n /** Enter makes a new paragraph; it doesn't reach the field, which would commit the edit. */\n onKeydown = (event: KeyboardEvent): void => {\n if (event.key === 'Enter') event.stopPropagation()\n }\n\n <template>\n <div\n class=\"fw-rich-text{{if @disabled ' fw-rich-text--disabled'}}\"\n data-test-fw-control={{@type}}\n data-fw-name={{@name}}\n ...attributes\n >\n {{#if this.groups.length}}\n <div\n class=\"fw-rich-text-toolbar\"\n role=\"toolbar\"\n aria-label=\"Formatting\"\n aria-controls={{@id}}\n >\n {{#each this.groups as |group|}}\n <span class=\"fw-rich-text-group\">\n {{#each group as |tool|}}\n <button\n type=\"button\"\n class=\"fw-rich-text-tool fw-rich-text-tool--{{tool.name}}\"\n title={{tool.label}}\n aria-label={{tool.label}}\n aria-pressed={{if\n tool.toggle\n (if (this.isPressed tool this.revision) \"true\" \"false\")\n }}\n disabled={{this.isDisabled tool this.revision}}\n data-test-fw-tool={{tool.name}}\n {{on \"mousedown\" this.keepFocus}}\n {{on \"click\" (fn this.run tool)}}\n >\n <ToolIcon @name={{tool.name}} />\n </button>\n {{/each}}\n </span>\n {{/each}}\n </div>\n {{/if}}\n <div\n id={{@id}}\n aria-multiline=\"true\"\n aria-label={{@label}}\n aria-describedby={{@describedBy}}\n aria-invalid={{if @invalid \"true\"}}\n aria-required={{if @required \"true\"}}\n aria-readonly={{if @readonly \"true\"}}\n aria-disabled={{if @disabled \"true\"}}\n aria-placeholder={{@placeholder}}\n data-placeholder={{@placeholder}}\n {{this.mount}}\n {{this.sync @value}}\n {{this.setEditable this.editable}}\n {{on \"keydown\" this.onKeydown}}\n ></div>\n </div>\n </template>\n}\n\n/** Each button's glyph: a letter for marks, a small SVG for the rest. Decorative. */\nconst ToolIcon: TOC<{ Args: { name: RichTextTool } }> = <template>\n {{#if (eq @name \"bold\")}}<b aria-hidden=\"true\">B</b>\n {{else if (eq @name \"italic\")}}<i aria-hidden=\"true\">I</i>\n {{else if (eq @name \"strike\")}}<s aria-hidden=\"true\">S</s>\n {{else}}\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 16 16\"\n width=\"16\"\n height=\"16\"\n fill=\"none\"\n stroke=\"currentColor\"\n stroke-width=\"1.5\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n >\n {{#if (eq @name \"heading-2\")}}\n <path d=\"M2 3.5v9M8 3.5v9M2 8h6\" />\n <path d=\"M10.5 9.2c0-.7.6-1.2 1.3-1.2s1.3.5 1.3 1.2c0 1-2.6 1.8-2.6 3.3h2.8\" />\n {{else if (eq @name \"heading-3\")}}\n <path d=\"M2 3.5v9M8 3.5v9M2 8h6\" />\n <path d=\"M10.6 8h2.4l-1.4 1.6c.9 0 1.5.5 1.5 1.3s-.7 1.4-1.5 1.4c-.6 0-1.1-.3-1.3-.7\" />\n {{else if (eq @name \"bullet-list\")}}\n <circle cx=\"2.5\" cy=\"4\" r=\"1\" fill=\"currentColor\" stroke=\"none\" />\n <circle cx=\"2.5\" cy=\"8\" r=\"1\" fill=\"currentColor\" stroke=\"none\" />\n <circle cx=\"2.5\" cy=\"12\" r=\"1\" fill=\"currentColor\" stroke=\"none\" />\n <path d=\"M6 4h8M6 8h8M6 12h8\" />\n {{else if (eq @name \"ordered-list\")}}\n <path d=\"M2 2.5h1v3M2 5.5h2M2 9.5c0-.6.5-1 1-1s1 .4 1 1c0 .8-2 1.5-2 2.5h2\" />\n <path d=\"M7 4h7M7 8h7M7 12h7\" />\n {{else if (eq @name \"blockquote\")}}\n <path d=\"M3 3v10M7 5h7M7 8h7M7 11h5\" />\n {{else if (eq @name \"undo\")}}\n <path d=\"M4 6h6.5a3 3 0 0 1 0 6H7\" /><path d=\"M6.5 3.5 4 6l2.5 2.5\" />\n {{else if (eq @name \"redo\")}}\n <path d=\"M12 6H5.5a3 3 0 0 0 0 6H9\" /><path d=\"M9.5 3.5 12 6l-2.5 2.5\" />\n {{/if}}\n </svg>\n {{/if}}\n</template>\n\nfunction eq(a: unknown, b: unknown): boolean {\n return a === b\n}\n\n/**\n * Plain text from a rich-text value (HTML or Tiptap JSON), for the field's `@format` in inline\n * forms: `<f.Field @control=\"rich-text\" @format={{toPlainText}} />`.\n */\nexport function toPlainText(value: RichTextValue | undefined): string {\n if (isBlank(value)) return ''\n if (typeof value === 'string') {\n // Blocks end in a space, so \"<p>a</p><p>b</p>\" reads \"a b\", not \"ab\".\n const spaced = value.replace(/<\\/(p|h[1-6]|li|blockquote|pre)>|<br\\s*\\/?>/gi, '$& ')\n const text = new DOMParser().parseFromString(spaced, 'text/html').body.textContent ?? ''\n return text.replace(/\\s+/g, ' ').trim()\n }\n const words: string[] = []\n const walk = (node: JSONContent) => {\n if (node.text) words.push(node.text)\n node.content?.forEach(walk)\n if (node.type !== 'text') words.push(' ')\n }\n walk(value as JSONContent)\n return words.join('').replace(/\\s+/g, ' ').trim()\n}\n\n/** Makes `@control=\"rich-text\"` available to every form. Call once, e.g. in app.ts. */\nexport function registerTiptapControl(name = 'rich-text'): void {\n registerControl(name, RichTextControl)\n}\n"],"names":["mark","name","label","type","run","toggle","isActive","editor","can","heading","level","chain","focus","toggleHeading","TOOLS","e","toggleBold","toggleItalic","toggleStrike","toggleBulletList","toggleOrderedList","toggleBlockquote","undo","redo","GROUPS","DEFAULT_TOOLBAR","flat","isEmptyDoc","state","doc","childCount","firstChild","isTextblock","content","size","isEmptyParagraph","node","length","isBlank","value","undefined","RichTextControl","Component","current","g","prototype","tracked","i","constructor","owner","args","Editor","element","extensions","StarterKit","configure","starterKit","editorProps","attributes","class","onUpdate","onTransaction","refresh","isJson","output","editable","disabled","readonly","groups","wanted","toolbar","names","Set","map","group","filter","tool","includes","has","serialize","isEmpty","getHTML","replace","json","getJSON","pop","onChange","queueMicrotask","isDestroying","revision","isPressed","_revision","isDisabled","keepFocus","event","preventDefault","mount","modifier","id","document","querySelector","CSS","escape","addEventListener","removeEventListener","destroy","sync","_element","same","JSON","stringify","commands","setContent","emitUpdate","setEditable","isEditable","onKeydown","key","stopPropagation","setComponentTemplate","precompileTemplate","strictMode","scope","on","fn","ToolIcon","eq","templateOnly","a","b","toPlainText","spaced","text","DOMParser","parseFromString","body","textContent","trim","words","walk","push","forEach","join","registerTiptapControl","registerControl"],"mappings":";;;;;;;;;;;;;AAsCA,MAAMA,OAAOA,CACXC,IAAM,EACNC,KAAa,EACbC,IAAY,EACZC,GAA6B,MACnB;EACVH,IAAA;EACAC,KAAA;AACAG,EAAAA,MAAA,EAAQ,IAAA;EACRD,GAAA;EACAE,QAAA,EAA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A,CAAM2C,OAAO,CAAC,+CAAA,EAAiD,KAAA,CAAA;AAC9E,IAAA,MAAMkD,IAAA,GAAO,IAAIC,SAAA,EAAA,CAAYC,eAAe,CAACH,QAAQ,WAAA,CAAA,CAAaI,IAAI,CAACC,WAAW,IAAI,EAAA;IACtF,OAAOJ,IAAA,CAAKlD,OAAO,CAAC,MAAA,EAAQ,KAAKuD,IAAI,EAAA;AACvC,EAAA;EACA,MAAMC,KAAa,GAAK,EAAE;EAC1B,MAAMC,IAAA,GAAQvG,IAAM,IAAA;IAClB,IAAIA,KAAKgG,IAAI,EAAEM,MAAME,IAAI,CAACxG,KAAKgG,IAAI,CAAA;AACnChG,IAAAA,IAAA,CAAKH,OAAO,EAAE4G,OAAA,CAAQF,IAAA,CAAA;IACtB,IAAIvG,KAAKjC,IAAI,KAAK,MAAA,EAAQuI,KAAA,CAAME,IAAI,CAAC,GAAA,CAAA;EACvC,CAAA;EACAD,IAAA,CAAKpG,KAAS,CAAA;AACd,EAAA,OAAOmG,KAAA,CAAMI,IAAI,CAAC,EAAA,CAAA,CAAI5D,OAAO,CAAC,MAAA,EAAQ,KAAKuD,IAAI,EAAA;AACjD;AAEA;AACO,SAASM,sBAAsB9I,IAAA,GAAO,WAAW,EAAO;AAC7D+I,EAAAA,eAAA,CAAgB/I,IAAA,EAAMwC,eAAA,CAAA;AACxB;;"}
@@ -0,0 +1,87 @@
1
+ import { settled, click } from '@ember/test-helpers';
2
+ import { FieldHarness } from '@ember-formwright/test-support';
3
+
4
+ /**
5
+ * Drives a `rich-text` field. Text goes in through the editor's own commands (ProseMirror
6
+ * doesn't react to synthetic key events); formatting goes through the toolbar, as a user's
7
+ * would:
8
+ *
9
+ * class PostForm extends FormHarness {
10
+ * @field(RichTextHarness) declare body: RichTextHarness
11
+ * }
12
+ *
13
+ * await form.body.typeText('Hello')
14
+ * await form.body.selectAll()
15
+ * await form.body.press('bold')
16
+ * assert.strictEqual(form.body.html, '<p><strong>Hello</strong></p>')
17
+ */
18
+ class RichTextHarness extends FieldHarness {
19
+ static controls = ['rich-text'];
20
+
21
+ /** The editable element (the one with the field's id). */
22
+ get editorElement() {
23
+ return this.control;
24
+ }
25
+
26
+ /** The Tiptap editor behind the field. */
27
+ get editor() {
28
+ const editor = this.editorElement.editor;
29
+ if (!editor) throw new Error(`Formwright harness: no editor in "${this.path}"`);
30
+ return editor;
31
+ }
32
+
33
+ /** The document as HTML. */
34
+ get html() {
35
+ return this.editor.getHTML();
36
+ }
37
+
38
+ /** The document as plain text, blocks separated by blank lines. */
39
+ get text() {
40
+ return this.editor.getText();
41
+ }
42
+ get isEditable() {
43
+ return this.editor.isEditable;
44
+ }
45
+
46
+ /** The toolbar's button names, in order. */
47
+ get tools() {
48
+ return [...this.element.querySelectorAll('[data-test-fw-tool]')].map(button => button.getAttribute('data-test-fw-tool'));
49
+ }
50
+
51
+ /** Replaces the document, as pasting over all of it would; the cursor ends up at the end. */
52
+ async setContent(html) {
53
+ this.editor.chain().setContent(html).focus('end').run();
54
+ await settled();
55
+ }
56
+
57
+ /** Inserts text at the cursor (at the end, if the editor isn't focused). */
58
+ async typeText(text) {
59
+ const editor = this.editor;
60
+ editor.chain().focus(editor.isFocused ? undefined : 'end').insertContent(text).run();
61
+ await settled();
62
+ }
63
+
64
+ /** Selects the whole document, e.g. before pressing a button. */
65
+ async selectAll() {
66
+ this.editor.chain().focus().selectAll().run();
67
+ await settled();
68
+ }
69
+
70
+ /** Clicks a toolbar button: `bold`, `heading-2`, `bullet-list`, `undo`, ... */
71
+ async press(tool) {
72
+ await click(this.tool(tool));
73
+ }
74
+
75
+ /** Whether a toolbar button is pressed (its mark or block is active at the cursor). */
76
+ isActive(tool) {
77
+ return this.tool(tool).getAttribute('aria-pressed') === 'true';
78
+ }
79
+ tool(name) {
80
+ const button = this.element.querySelector(`[data-test-fw-tool="${CSS.escape(name)}"]`);
81
+ if (!button) throw new Error(`Formwright harness: no "${name}" button in "${this.path}"`);
82
+ return button;
83
+ }
84
+ }
85
+
86
+ export { RichTextHarness };
87
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../src/test-support/index.ts"],"sourcesContent":["import { click, settled } from '@ember/test-helpers'\nimport { FieldHarness } from '@ember-formwright/test-support'\nimport type { Editor } from '@tiptap/core'\n\n/**\n * Drives a `rich-text` field. Text goes in through the editor's own commands (ProseMirror\n * doesn't react to synthetic key events); formatting goes through the toolbar, as a user's\n * would:\n *\n * class PostForm extends FormHarness {\n * @field(RichTextHarness) declare body: RichTextHarness\n * }\n *\n * await form.body.typeText('Hello')\n * await form.body.selectAll()\n * await form.body.press('bold')\n * assert.strictEqual(form.body.html, '<p><strong>Hello</strong></p>')\n */\nexport class RichTextHarness extends FieldHarness {\n static override controls = ['rich-text']\n\n /** The editable element (the one with the field's id). */\n get editorElement(): HTMLElement {\n return this.control\n }\n\n /** The Tiptap editor behind the field. */\n get editor(): Editor {\n const editor = (this.editorElement as HTMLElement & { editor?: Editor }).editor\n if (!editor) throw new Error(`Formwright harness: no editor in \"${this.path}\"`)\n return editor\n }\n\n /** The document as HTML. */\n get html(): string {\n return this.editor.getHTML()\n }\n\n /** The document as plain text, blocks separated by blank lines. */\n get text(): string {\n return this.editor.getText()\n }\n\n get isEditable(): boolean {\n return this.editor.isEditable\n }\n\n /** The toolbar's button names, in order. */\n get tools(): string[] {\n return [...this.element.querySelectorAll('[data-test-fw-tool]')].map(button =>\n button.getAttribute('data-test-fw-tool')!,\n )\n }\n\n /** Replaces the document, as pasting over all of it would; the cursor ends up at the end. */\n async setContent(html: string): Promise<void> {\n this.editor.chain().setContent(html).focus('end').run()\n await settled()\n }\n\n /** Inserts text at the cursor (at the end, if the editor isn't focused). */\n async typeText(text: string): Promise<void> {\n const editor = this.editor\n editor\n .chain()\n .focus(editor.isFocused ? undefined : 'end')\n .insertContent(text)\n .run()\n await settled()\n }\n\n /** Selects the whole document, e.g. before pressing a button. */\n async selectAll(): Promise<void> {\n this.editor.chain().focus().selectAll().run()\n await settled()\n }\n\n /** Clicks a toolbar button: `bold`, `heading-2`, `bullet-list`, `undo`, ... */\n async press(tool: string): Promise<void> {\n await click(this.tool(tool))\n }\n\n /** Whether a toolbar button is pressed (its mark or block is active at the cursor). */\n isActive(tool: string): boolean {\n return this.tool(tool).getAttribute('aria-pressed') === 'true'\n }\n\n private tool(name: string): HTMLButtonElement {\n const button = this.element.querySelector<HTMLButtonElement>(\n `[data-test-fw-tool=\"${CSS.escape(name)}\"]`,\n )\n if (!button) throw new Error(`Formwright harness: no \"${name}\" button in \"${this.path}\"`)\n return button\n }\n}\n"],"names":["RichTextHarness","FieldHarness","controls","editorElement","control","editor","Error","path","html","getHTML","text","getText","isEditable","tools","element","querySelectorAll","map","button","getAttribute","setContent","chain","focus","run","settled","typeText","isFocused","undefined","insertContent","selectAll","press","tool","click","isActive","name","querySelector","CSS","escape"],"mappings":";;;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMA,eAAe,SAASC,YAAY,CAAC;AAChD,EAAA,OAAgBC,QAAQ,GAAG,CAAC,WAAW,CAAC;;AAExC;EACA,IAAIC,aAAaA,GAAgB;IAC/B,OAAO,IAAI,CAACC,OAAO;AACrB,EAAA;;AAEA;EACA,IAAIC,MAAMA,GAAW;AACnB,IAAA,MAAMA,MAAM,GAAI,IAAI,CAACF,aAAa,CAAuCE,MAAM;AAC/E,IAAA,IAAI,CAACA,MAAM,EAAE,MAAM,IAAIC,KAAK,CAAC,CAAA,kCAAA,EAAqC,IAAI,CAACC,IAAI,CAAA,CAAA,CAAG,CAAC;AAC/E,IAAA,OAAOF,MAAM;AACf,EAAA;;AAEA;EACA,IAAIG,IAAIA,GAAW;AACjB,IAAA,OAAO,IAAI,CAACH,MAAM,CAACI,OAAO,EAAE;AAC9B,EAAA;;AAEA;EACA,IAAIC,IAAIA,GAAW;AACjB,IAAA,OAAO,IAAI,CAACL,MAAM,CAACM,OAAO,EA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AAK,MAAM;AAChE,EAAA;EAEQY,IAAIA,CAACG,IAAY,EAAqB;AAC5C,IAAA,MAAMhB,MAAM,GAAG,IAAI,CAACH,OAAO,CAACoB,aAAa,CACvC,CAAA,oBAAA,EAAuBC,GAAG,CAACC,MAAM,CAACH,IAAI,CAAC,IACzC,CAAC;AACD,IAAA,IAAI,CAAChB,MAAM,EAAE,MAAM,IAAIX,KAAK,CAAC,CAAA,wBAAA,EAA2B2B,IAAI,CAAA,aAAA,EAAgB,IAAI,CAAC1B,IAAI,GAAG,CAAC;AACzF,IAAA,OAAOU,MAAM;AACf,EAAA;AACF;;"}
package/dist/theme.css ADDED
@@ -0,0 +1,185 @@
1
+ /*
2
+ * The rich-text control, on the Formwright theme's custom properties. Import it after the core
3
+ * theme:
4
+ *
5
+ * import '@ember-formwright/ember/theme.css'
6
+ * import '@ember-formwright/tiptap/theme.css'
7
+ *
8
+ * The box looks like a Formwright textarea: a toolbar on top, the document below.
9
+ */
10
+ .fw-rich-text {
11
+ flex: 1;
12
+ min-width: 0;
13
+ display: flex;
14
+ flex-direction: column;
15
+ background: var(--fw-bg);
16
+ border: 1px solid var(--fw-border);
17
+ border-radius: var(--fw-radius);
18
+ overflow: hidden;
19
+ }
20
+
21
+ .fw-rich-text:focus-within {
22
+ border-color: var(--fw-border-focus);
23
+ box-shadow: var(--fw-ring);
24
+ }
25
+
26
+ .fw-field[data-invalid] .fw-rich-text,
27
+ .fw-rich-text:has([aria-invalid='true']) {
28
+ border-color: var(--fw-error);
29
+ }
30
+
31
+ .fw-rich-text--disabled {
32
+ opacity: 0.6;
33
+ cursor: not-allowed;
34
+ }
35
+
36
+ /* ---- toolbar ---------------------------------------------------------------------- */
37
+
38
+ .fw-rich-text-toolbar {
39
+ display: flex;
40
+ flex-wrap: wrap;
41
+ align-items: center;
42
+ row-gap: 0.25rem;
43
+ /* No start padding: each line's first divider sits just outside, and is clipped. */
44
+ padding: 0.3rem 0.4rem 0.3rem 0;
45
+ overflow: hidden;
46
+ border-bottom: 1px solid var(--fw-border);
47
+ background: color-mix(in srgb, var(--fw-fg) 3%, var(--fw-bg));
48
+ }
49
+
50
+ /* A divider before every group; on a wrapped toolbar no line starts with one. */
51
+ .fw-rich-text-group {
52
+ display: inline-flex;
53
+ gap: 0.15rem;
54
+ margin-inline-start: -1px;
55
+ padding-inline: 0.4rem 0.1rem;
56
+ border-inline-start: 1px solid var(--fw-border);
57
+ }
58
+
59
+ .fw-rich-text-tool {
60
+ display: inline-grid;
61
+ place-items: center;
62
+ min-width: 2rem;
63
+ height: 2rem;
64
+ padding: 0 0.4rem;
65
+ font: inherit;
66
+ font-size: 0.85rem;
67
+ line-height: 1;
68
+ color: var(--fw-muted);
69
+ background: transparent;
70
+ border: 1px solid transparent;
71
+ border-radius: calc(var(--fw-radius) - 2px);
72
+ cursor: pointer;
73
+ }
74
+
75
+ .fw-rich-text-tool b,
76
+ .fw-rich-text-tool i,
77
+ .fw-rich-text-tool s,
78
+ .fw-rich-text-tool span {
79
+ font-family: Georgia, 'Times New Roman', serif;
80
+ font-size: 1rem;
81
+ }
82
+
83
+ .fw-rich-text-tool span {
84
+ font-family: inherit;
85
+ font-size: 0.8rem;
86
+ font-weight: 600;
87
+ }
88
+
89
+ .fw-rich-text-tool:hover:not(:disabled) {
90
+ color: var(--fw-fg);
91
+ background: color-mix(in srgb, var(--fw-fg) 7%, transparent);
92
+ }
93
+
94
+ .fw-rich-text-tool[aria-pressed='true'] {
95
+ color: var(--fw-accent);
96
+ background: color-mix(in srgb, var(--fw-accent) 12%, transparent);
97
+ border-color: color-mix(in srgb, var(--fw-accent) 30%, transparent);
98
+ }
99
+
100
+ .fw-rich-text-tool:focus-visible {
101
+ outline: none;
102
+ box-shadow: var(--fw-ring);
103
+ border-color: var(--fw-border-focus);
104
+ }
105
+
106
+ .fw-rich-text-tool:disabled {
107
+ opacity: 0.45;
108
+ cursor: default;
109
+ }
110
+
111
+ /* ---- document --------------------------------------------------------------------- */
112
+
113
+ .fw-rich-text-editor {
114
+ position: relative;
115
+ min-height: 8rem;
116
+ padding: 0.6rem 0.8rem;
117
+ color: var(--fw-fg);
118
+ line-height: 1.55;
119
+ outline: none;
120
+ overflow-wrap: anywhere;
121
+ }
122
+
123
+ .fw-rich-text .fw-rich-text-editor > :first-child {
124
+ margin-top: 0;
125
+ }
126
+
127
+ .fw-rich-text .fw-rich-text-editor > :last-child {
128
+ margin-bottom: 0;
129
+ }
130
+
131
+ .fw-rich-text-editor p {
132
+ margin: 0 0 0.6em;
133
+ }
134
+
135
+ /* Two classes deep, so a page's own prose styles (borders on h2, ...) don't reach in. */
136
+ .fw-rich-text .fw-rich-text-editor h2,
137
+ .fw-rich-text .fw-rich-text-editor h3 {
138
+ margin: 0.9em 0 0.4em;
139
+ padding: 0;
140
+ border: 0;
141
+ line-height: 1.25;
142
+ }
143
+
144
+ .fw-rich-text .fw-rich-text-editor h2 {
145
+ font-size: 1.3rem;
146
+ }
147
+
148
+ .fw-rich-text .fw-rich-text-editor h3 {
149
+ font-size: 1.1rem;
150
+ }
151
+
152
+ .fw-rich-text-editor ul,
153
+ .fw-rich-text-editor ol {
154
+ margin: 0 0 0.6em;
155
+ padding-inline-start: 1.4rem;
156
+ }
157
+
158
+ .fw-rich-text-editor li p {
159
+ margin: 0.15em 0;
160
+ }
161
+
162
+ .fw-rich-text-editor blockquote {
163
+ margin: 0 0 0.6em;
164
+ padding-inline-start: 0.8rem;
165
+ border-inline-start: 3px solid var(--fw-border);
166
+ color: var(--fw-muted);
167
+ }
168
+
169
+ .fw-rich-text-editor code {
170
+ font-size: 0.9em;
171
+ padding: 0.1em 0.3em;
172
+ border-radius: 4px;
173
+ background: color-mix(in srgb, var(--fw-fg) 8%, transparent);
174
+ }
175
+
176
+ .fw-rich-text-editor[data-empty]::before {
177
+ content: attr(data-placeholder);
178
+ position: absolute;
179
+ color: var(--fw-muted);
180
+ pointer-events: none;
181
+ }
182
+
183
+ .fw-rich-text-editor[contenteditable='false'] {
184
+ cursor: not-allowed;
185
+ }
package/package.json CHANGED
@@ -1,6 +1,114 @@
1
1
  {
2
2
  "name": "@ember-formwright/tiptap",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.3.0",
4
+ "description": "A rich-text control for Formwright, powered by Tiptap.",
5
+ "keywords": [
6
+ "ember-addon",
7
+ "ember",
8
+ "forms",
9
+ "formwright",
10
+ "rich-text",
11
+ "editor",
12
+ "tiptap",
13
+ "prosemirror"
14
+ ],
15
+ "license": "MIT",
16
+ "author": "Joe Gaudet <joe@joegaudet.com>",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/joegaudet/ember-formwright.git",
20
+ "directory": "packages/tiptap"
21
+ },
22
+ "homepage": "https://joegaudet.com/ember-formwright/",
23
+ "bugs": "https://github.com/joegaudet/ember-formwright/issues",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./declarations/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ },
29
+ "./test-support": {
30
+ "types": "./declarations/test-support/index.d.ts",
31
+ "default": "./dist/test-support/index.js"
32
+ },
33
+ "./theme.css": "./dist/theme.css",
34
+ "./addon-main.js": "./addon-main.cjs"
35
+ },
36
+ "typesVersions": {
37
+ "*": {
38
+ "*": [
39
+ "declarations/*"
40
+ ]
41
+ }
42
+ },
43
+ "files": [
44
+ "addon-main.cjs",
45
+ "declarations",
46
+ "dist",
47
+ "README.md",
48
+ "CHANGELOG.md"
49
+ ],
50
+ "dependencies": {
51
+ "@embroider/addon-shim": "^1.10.3",
52
+ "decorator-transforms": "^2.4.0",
53
+ "ember-modifier": "^4.3.0"
54
+ },
55
+ "peerDependencies": {
56
+ "@ember/test-helpers": ">= 5.0.0",
57
+ "@tiptap/core": ">= 3.0.0",
58
+ "@tiptap/pm": ">= 3.0.0",
59
+ "@tiptap/starter-kit": ">= 3.0.0",
60
+ "ember-source": ">= 6.12.0",
61
+ "@ember-formwright/ember": "^1.3.0",
62
+ "@ember-formwright/test-support": "^1.3.0"
63
+ },
64
+ "peerDependenciesMeta": {
65
+ "@ember-formwright/test-support": {
66
+ "optional": true
67
+ },
68
+ "@ember/test-helpers": {
69
+ "optional": true
70
+ }
71
+ },
72
+ "devDependencies": {
73
+ "@babel/core": "^7.29.7",
74
+ "@babel/plugin-transform-typescript": "^7.29.7",
75
+ "@babel/runtime": "^7.29.7",
76
+ "@ember/library-tsconfig": "^3.0.0",
77
+ "@ember/test-helpers": "^5.7.0",
78
+ "@embroider/addon-dev": "^8.4.2",
79
+ "@embroider/macros": "^1.21.1",
80
+ "@glimmer/component": "^2.1.1",
81
+ "@glimmer/tracking": "^1.1.2",
82
+ "@glint/ember-tsc": "^1.11.6",
83
+ "@glint/template": "^1.9.0",
84
+ "@rollup/plugin-babel": "^7.1.0",
85
+ "@tiptap/core": "^3.32.0",
86
+ "@tiptap/pm": "^3.32.0",
87
+ "@tiptap/starter-kit": "^3.32.0",
88
+ "babel-plugin-ember-template-compilation": "^4.0.1",
89
+ "ember-source": "~7.3.0",
90
+ "rollup": "^4.64.6",
91
+ "typescript": "~6.0.3",
92
+ "@ember-formwright/ember": "1.3.0",
93
+ "@ember-formwright/test-support": "1.3.0"
94
+ },
95
+ "publishConfig": {
96
+ "access": "public"
97
+ },
98
+ "engines": {
99
+ "node": ">=22.12.0"
100
+ },
101
+ "ember": {
102
+ "edition": "octane"
103
+ },
104
+ "ember-addon": {
105
+ "version": 2,
106
+ "type": "addon",
107
+ "main": "addon-main.cjs"
108
+ },
109
+ "scripts": {
110
+ "build": "rollup --config",
111
+ "start": "rollup --config --watch",
112
+ "typecheck": "ember-tsc --noEmit"
113
+ }
6
114
  }