@portabletext/plugin-input-rule 0.3.1 → 0.3.3

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/README.md CHANGED
@@ -1,5 +1,245 @@
1
1
  # `@portabletext/plugin-input-rule`
2
2
 
3
- > Easily configure input rules in the Portable Text Editor
3
+ > Easily configure Input Rules in the Portable Text Editor
4
4
 
5
- This plugin is currently a work in progress. Docs to come with the APIs have settled.
5
+ > ⚠️ **Note:** `defineInputRule` and other APIs exposed by this plugin are still a work in progress and may change slightly. We are still ironing out some details before we can cut a stable release.
6
+
7
+ Listening for inserted text patterns and performing actions based on them is incredibly common, but it comes with many challenges:
8
+
9
+ 1. How do you implement undo functionality correctly?
10
+ 2. What about smart undo with <kbd>Backspace</kbd>?
11
+ 3. Have you considered `insert.text` events that carry more than one character? (Android, anyone?)
12
+
13
+ _This is why this plugin exists_. It brings the concept of "Input Rules" to the Portable Text Editor, allowing you to write text transformation logic as if they were Behaviors, without worrying about low-level details:
14
+
15
+ ```tsx
16
+ import type {EditorSchema} from '@portabletext/editor'
17
+ import {raise} from '@portabletext/editor/behaviors'
18
+ import {getPreviousInlineObject} from '@portabletext/editor/selectors'
19
+ import {defineInputRule} from '@portabletext/plugin-input-rule'
20
+
21
+ const unorderedListRule = defineInputRule({
22
+ // Listen for a RegExp pattern instead of a raw event
23
+ on: /^(-|\*) /,
24
+ // The `event` carries useful information like the offsets of RegExp matches
25
+ // as well as information about the focused text block
26
+ guard: ({snapshot, event}) => {
27
+ // In theory, an Input Rule could return multiple matches, but in this
28
+ // case we only expect one
29
+ const match = event.matches.at(0)
30
+
31
+ if (!match) {
32
+ return false
33
+ }
34
+
35
+ return {match}
36
+ },
37
+ actions: [
38
+ ({event}, {match}) => [
39
+ // Turn the text block into a paragraph
40
+ raise({
41
+ type: 'block.unset',
42
+ props: ['style'],
43
+ at: event.focusTextBlock.path,
44
+ }),
45
+ // Then, turn it into a list item
46
+ raise({
47
+ type: 'block.set',
48
+ props: {
49
+ listItem: 'bullet',
50
+ level: event.focusTextBlock.node.level ?? 1,
51
+ },
52
+ at: event.focusTextBlock.path,
53
+ }),
54
+ // Finally, delete the matched text
55
+ raise({
56
+ type: 'delete',
57
+ at: match.targetOffsets,
58
+ }),
59
+ ],
60
+ ],
61
+ })
62
+
63
+ export function MyMarkdownPlugin() {
64
+ return <InputRulePlugin rules={[unorderedListRule]} />
65
+ }
66
+ ```
67
+
68
+ > 💡 **Tip:** The [`@portabletext/plugin-markdown-shortcuts`](../plugin-markdown-shortcuts/) package is already built using Input Rules and provides common markdown shortcuts out of the box.
69
+
70
+ ## Text Transformation Rules
71
+
72
+ Text transformations are so common that the plugin provides a high-level `defineTextTransformRule` helper to configure them without any boilerplate:
73
+
74
+ ```tsx
75
+ const emDashRule = defineTextTransformRule({
76
+ on: /--/,
77
+ transform: () => '—',
78
+ })
79
+
80
+ export function MyTypographyPlugin() {
81
+ return <InputRulePlugin rules={[emDashRule]} />
82
+ }
83
+ ```
84
+
85
+ In fact, the production-ready [`@portabletext/plugin-typography`](../plugin-typography/) is built on top of Input Rules and comes packed with common text transformations like this.
86
+
87
+ ## Advanced Examples
88
+
89
+ Input Rules can handle more complex transformations. Here are two advanced examples:
90
+
91
+ 1. **Markdown Link**: Automatically convert `[text](url)` syntax into proper links
92
+ 2. **Stock Ticker**: Convert `{SYMBOL}` patterns into stock ticker objects
93
+
94
+ ### Markdown Link Rule
95
+
96
+ This example shows how to convert markdown-style link syntax `[text](url)` into proper link annotations:
97
+
98
+ ```tsx
99
+ const markdownLinkRule = defineInputRule({
100
+ on: /\[(.+)]\((.+)\)/,
101
+ actions: [
102
+ ({snapshot, event}) => {
103
+ const newText = event.textBefore + event.textInserted
104
+ let textLengthDelta = 0
105
+ const actions: Array<BehaviorAction> = []
106
+
107
+ for (const match of event.matches.reverse()) {
108
+ const textMatch = match.groupMatches.at(0)
109
+ const hrefMatch = match.groupMatches.at(1)
110
+
111
+ if (textMatch === undefined || hrefMatch === undefined) {
112
+ continue
113
+ }
114
+
115
+ textLengthDelta =
116
+ textLengthDelta -
117
+ (match.targetOffsets.focus.offset -
118
+ match.targetOffsets.anchor.offset -
119
+ textMatch.text.length)
120
+
121
+ const leftSideOffsets = {
122
+ anchor: match.targetOffsets.anchor,
123
+ focus: textMatch.targetOffsets.anchor,
124
+ }
125
+ const rightSideOffsets = {
126
+ anchor: textMatch.targetOffsets.focus,
127
+ focus: match.targetOffsets.focus,
128
+ }
129
+
130
+ actions.push(
131
+ raise({
132
+ type: 'select',
133
+ at: textMatch.targetOffsets,
134
+ }),
135
+ )
136
+ actions.push(
137
+ raise({
138
+ type: 'annotation.add',
139
+ annotation: {
140
+ name: 'link',
141
+ value: {
142
+ href: hrefMatch.text,
143
+ },
144
+ },
145
+ }),
146
+ )
147
+ actions.push(
148
+ raise({
149
+ type: 'delete',
150
+ at: rightSideOffsets,
151
+ }),
152
+ )
153
+ actions.push(
154
+ raise({
155
+ type: 'delete',
156
+ at: leftSideOffsets,
157
+ }),
158
+ )
159
+ }
160
+
161
+ const endCaretPosition = {
162
+ path: event.focusTextBlock.path,
163
+ offset: newText.length - textLengthDelta * -1,
164
+ }
165
+
166
+ return [
167
+ ...actions,
168
+ raise({
169
+ type: 'select',
170
+ at: {
171
+ anchor: endCaretPosition,
172
+ focus: endCaretPosition,
173
+ },
174
+ }),
175
+ ]
176
+ },
177
+ ],
178
+ })
179
+ ```
180
+
181
+ ### Stock Ticker Rule
182
+
183
+ This example demonstrates how to convert text patterns like `{AAPL}` into custom inline objects:
184
+
185
+ ```tsx
186
+ const stockTickerRule = defineInputRule({
187
+ on: /\{(.+)\}/,
188
+ guard: ({snapshot, event}) => {
189
+ const match = event.matches.at(0)
190
+
191
+ if (!match) {
192
+ return false
193
+ }
194
+
195
+ const symbolMatch = match.groupMatches.at(0)
196
+
197
+ if (symbolMatch === undefined) {
198
+ return false
199
+ }
200
+
201
+ return {match, symbolMatch}
202
+ },
203
+ actions: [
204
+ ({snapshot, event}, {match, symbolMatch}) => {
205
+ const stockTickerKey = snapshot.context.keyGenerator()
206
+
207
+ return [
208
+ raise({
209
+ type: 'delete',
210
+ at: match.targetOffsets,
211
+ }),
212
+ raise({
213
+ type: 'insert.child',
214
+ child: {
215
+ _key: stockTickerKey,
216
+ _type: 'stock-ticker',
217
+ symbol: symbolMatch.text,
218
+ },
219
+ }),
220
+ raise({
221
+ type: 'select',
222
+ at: {
223
+ anchor: {
224
+ path: [
225
+ {_key: event.focusTextBlock.node._key},
226
+ 'children',
227
+ {_key: stockTickerKey},
228
+ ],
229
+ offset: 0,
230
+ },
231
+ focus: {
232
+ path: [
233
+ {_key: event.focusTextBlock.node._key},
234
+ 'children',
235
+ {_key: stockTickerKey},
236
+ ],
237
+ offset: 0,
238
+ },
239
+ },
240
+ }),
241
+ ]
242
+ },
243
+ ],
244
+ })
245
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@portabletext/plugin-input-rule",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "Easily configure input rules in the Portable Text Editor",
5
5
  "keywords": [
6
6
  "portabletext",
@@ -53,12 +53,12 @@
53
53
  "typescript": "5.9.3",
54
54
  "typescript-eslint": "^8.41.0",
55
55
  "vitest": "^3.2.4",
56
- "@portabletext/editor": "2.14.1",
56
+ "@portabletext/editor": "2.14.2",
57
57
  "@portabletext/schema": "1.2.0",
58
58
  "racejar": "1.3.1"
59
59
  },
60
60
  "peerDependencies": {
61
- "@portabletext/editor": "^2.14.1",
61
+ "@portabletext/editor": "^2.14.2",
62
62
  "react": "^19.1.1"
63
63
  },
64
64
  "publishConfig": {
@@ -0,0 +1,16 @@
1
+ Feature: Stock Ticker Rule
2
+
3
+ Background:
4
+ Given the editor is focused
5
+ And a global keymap
6
+
7
+ Scenario Outline: Transforms plain text into stock ticker
8
+ Given the text <text>
9
+ When <inserted text> is inserted
10
+ And "{ArrowRight}" is pressed
11
+ And "new" is typed
12
+ Then the text is <new text>
13
+
14
+ Examples:
15
+ | text | inserted text | new text |
16
+ | "" | "{AAPL}" | ",{stock-ticker},new" |
@@ -8,14 +8,14 @@ import {defineSchema} from '@portabletext/schema'
8
8
  import {Before} from 'racejar'
9
9
  import {Feature} from 'racejar/vitest'
10
10
  import {InputRulePlugin} from './plugin.input-rule'
11
- import {createMarkdownLinkRule} from './rule.markdown-link'
12
- import markdownLinkFeature from './rule.markdown-link.feature?raw'
11
+ import {createStockTickerRule} from './rule.stock-ticker'
12
+ import stockTickerFeature from './rule.stock-ticker.feature?raw'
13
13
 
14
- const markdownLinkRule = createMarkdownLinkRule({
15
- linkObject: (context) => ({
16
- name: 'link',
14
+ const stockTickerRule = createStockTickerRule({
15
+ stockTickerObject: (context) => ({
16
+ name: 'stock-ticker',
17
17
  value: {
18
- href: context.href,
18
+ symbol: context.symbol,
19
19
  },
20
20
  }),
21
21
  })
@@ -26,7 +26,7 @@ Feature({
26
26
  const {editor, locator} = await createTestEditor({
27
27
  children: (
28
28
  <>
29
- <InputRulePlugin rules={[markdownLinkRule]} />
29
+ <InputRulePlugin rules={[stockTickerRule]} />
30
30
  </>
31
31
  ),
32
32
  schemaDefinition: defineSchema({
@@ -40,7 +40,7 @@ Feature({
40
40
  context.editor = editor
41
41
  }),
42
42
  ],
43
- featureText: markdownLinkFeature,
43
+ featureText: stockTickerFeature,
44
44
  stepDefinitions,
45
45
  parameterTypes,
46
46
  })
@@ -0,0 +1,79 @@
1
+ import type {EditorSchema} from '@portabletext/editor'
2
+ import {raise} from '@portabletext/editor/behaviors'
3
+ import {defineInputRule} from './input-rule'
4
+
5
+ export function createStockTickerRule(config: {
6
+ stockTickerObject: (context: {
7
+ schema: EditorSchema
8
+ symbol: string
9
+ }) => {name: string; value?: {[prop: string]: unknown}} | undefined
10
+ }) {
11
+ return defineInputRule({
12
+ on: /\{(.+)\}/,
13
+ guard: ({snapshot, event}) => {
14
+ const match = event.matches.at(0)
15
+
16
+ if (!match) {
17
+ return false
18
+ }
19
+
20
+ const symbolMatch = match.groupMatches.at(0)
21
+
22
+ if (symbolMatch === undefined) {
23
+ return false
24
+ }
25
+
26
+ const stockTickerObject = config.stockTickerObject({
27
+ schema: snapshot.context.schema,
28
+ symbol: symbolMatch.text,
29
+ })
30
+
31
+ if (!stockTickerObject) {
32
+ return false
33
+ }
34
+
35
+ return {match, stockTickerObject}
36
+ },
37
+ actions: [
38
+ ({snapshot, event}, {match, stockTickerObject}) => {
39
+ const stockTickerKey = snapshot.context.keyGenerator()
40
+
41
+ return [
42
+ raise({
43
+ type: 'delete',
44
+ at: match.targetOffsets,
45
+ }),
46
+ raise({
47
+ type: 'insert.child',
48
+ child: {
49
+ ...stockTickerObject.value,
50
+ _key: stockTickerKey,
51
+ _type: stockTickerObject.name,
52
+ },
53
+ }),
54
+ raise({
55
+ type: 'select',
56
+ at: {
57
+ anchor: {
58
+ path: [
59
+ {_key: event.focusTextBlock.node._key},
60
+ 'children',
61
+ {_key: stockTickerKey},
62
+ ],
63
+ offset: 0,
64
+ },
65
+ focus: {
66
+ path: [
67
+ {_key: event.focusTextBlock.node._key},
68
+ 'children',
69
+ {_key: stockTickerKey},
70
+ ],
71
+ offset: 0,
72
+ },
73
+ },
74
+ }),
75
+ ]
76
+ },
77
+ ],
78
+ })
79
+ }
@@ -1,54 +0,0 @@
1
- Feature: Markdown Link Rule
2
-
3
- Background:
4
- Given the editor is focused
5
- And a global keymap
6
-
7
- Scenario Outline: Transform markdown Link into annotation
8
- Given the text <text>
9
- When <inserted text> is inserted
10
- And "new" is typed
11
- Then the text is <new text>
12
- And <annotated> has marks "k4"
13
-
14
- Examples:
15
- | text | inserted text | new text | annotated |
16
- | "[foo](bar" | ")" | "foo,new" | "foo" |
17
-
18
- Scenario: Preserving decorator in link text
19
- Given the text "[foo](bar"
20
- And "strong" around "foo"
21
- When ")" is inserted
22
- And "new" is typed
23
- Then the text is "foo,new"
24
- And "foo" has marks "strong,k6"
25
-
26
- Scenario: Preserving decorators in link text
27
- Given the text "[foo](bar"
28
- And "strong" around "foo"
29
- And "em" around "oo"
30
- When ")" is inserted
31
- And "new" is typed
32
- Then the text is "f,oo,new"
33
- And "f" has marks "strong,k7"
34
- And "oo" has marks "strong,em,k7"
35
-
36
- Scenario: Overwriting other links
37
- Given the text "[foo](bar"
38
- And a "link" "l1" around "foo"
39
- When the caret is put after "bar"
40
- And ")" is inserted
41
- And "new" is typed
42
- Then the text is "foo,new"
43
- And "foo" has an annotation different than "l1"
44
-
45
- Scenario: Preserving other annotations
46
- Given the text "[foo](bar"
47
- And a "link" "l1" around "foo"
48
- And a "comment" "c1" around "foo"
49
- When the caret is put after "bar"
50
- And ")" is inserted
51
- And "new" is typed
52
- Then the text is "foo,new"
53
- And "foo" has an annotation different than "l1"
54
- And "foo" has marks "c1,k9"
@@ -1,98 +0,0 @@
1
- import type {EditorSchema} from '@portabletext/editor'
2
- import {raise, type BehaviorAction} from '@portabletext/editor/behaviors'
3
- import {defineInputRule} from './input-rule'
4
-
5
- export function createMarkdownLinkRule(config: {
6
- linkObject: (context: {
7
- schema: EditorSchema
8
- href: string
9
- }) => {name: string; value?: {[prop: string]: unknown}} | undefined
10
- }) {
11
- return defineInputRule({
12
- on: /\[(.+)]\((.+)\)/,
13
- actions: [
14
- ({snapshot, event}) => {
15
- const newText = event.textBefore + event.textInserted
16
- let textLengthDelta = 0
17
- const actions: Array<BehaviorAction> = []
18
-
19
- for (const match of event.matches.reverse()) {
20
- const textMatch = match.groupMatches.at(0)
21
- const hrefMatch = match.groupMatches.at(1)
22
-
23
- if (textMatch === undefined || hrefMatch === undefined) {
24
- continue
25
- }
26
-
27
- textLengthDelta =
28
- textLengthDelta -
29
- (match.targetOffsets.focus.offset -
30
- match.targetOffsets.anchor.offset -
31
- textMatch.text.length)
32
-
33
- const linkObject = config.linkObject({
34
- schema: snapshot.context.schema,
35
- href: hrefMatch.text,
36
- })
37
-
38
- if (!linkObject) {
39
- continue
40
- }
41
-
42
- const leftSideOffsets = {
43
- anchor: match.targetOffsets.anchor,
44
- focus: textMatch.targetOffsets.anchor,
45
- }
46
- const rightSideOffsets = {
47
- anchor: textMatch.targetOffsets.focus,
48
- focus: match.targetOffsets.focus,
49
- }
50
-
51
- actions.push(
52
- raise({
53
- type: 'select',
54
- at: textMatch.targetOffsets,
55
- }),
56
- )
57
- actions.push(
58
- raise({
59
- type: 'annotation.add',
60
- annotation: {
61
- name: linkObject.name,
62
- value: linkObject.value ?? {},
63
- },
64
- }),
65
- )
66
- actions.push(
67
- raise({
68
- type: 'delete',
69
- at: rightSideOffsets,
70
- }),
71
- )
72
- actions.push(
73
- raise({
74
- type: 'delete',
75
- at: leftSideOffsets,
76
- }),
77
- )
78
- }
79
-
80
- const endCaretPosition = {
81
- path: event.focusTextBlock.path,
82
- offset: newText.length - textLengthDelta * -1,
83
- }
84
-
85
- return [
86
- ...actions,
87
- raise({
88
- type: 'select',
89
- at: {
90
- anchor: endCaretPosition,
91
- focus: endCaretPosition,
92
- },
93
- }),
94
- ]
95
- },
96
- ],
97
- })
98
- }