-
Notifications
You must be signed in to change notification settings - Fork 249
Expand file tree
/
Copy pathTokenizedText.tsx
More file actions
230 lines (211 loc) · 5.89 KB
/
TokenizedText.tsx
File metadata and controls
230 lines (211 loc) · 5.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import {Command} from './Command.js'
import {Link} from './Link.js'
import {List} from './List.js'
import {UserInput} from './UserInput.js'
import {FilePath} from './FilePath.js'
import {Subdued} from './Subdued.js'
import React, {FunctionComponent} from 'react'
import {Box, Text} from 'ink'
export interface LinkToken {
link: {
label?: string
url: string
}
}
export interface UserInputToken {
userInput: string
}
export interface ListToken {
list: {
title?: TokenItem<InlineToken>
items: TokenItem<InlineToken>[]
ordered?: boolean
}
}
export interface BoldToken {
bold: string
}
export type Token =
| string
| {
command: string
}
| LinkToken
| {
char: string
}
| UserInputToken
| {
subdued: string
}
| {
filePath: string
}
| ListToken
| BoldToken
| {
info: string
}
| {
warn: string
}
| {
error: string
}
export type InlineToken = Exclude<Token, ListToken>
export type TokenItem<T extends Token = Token> = T | T[]
type DisplayType = 'block' | 'inline'
interface Block {
display: DisplayType
value: Token
}
function tokenToBlock(token: Token): Block {
return {
display: typeof token !== 'string' && 'list' in token ? 'block' : 'inline',
value: token,
}
}
export function tokenItemToString(token: TokenItem): string {
if (typeof token === 'string') {
return token
} else if ('command' in token) {
return token.command
} else if ('link' in token) {
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- empty label should fall through to url
return token.link.label || token.link.url
} else if ('char' in token) {
return token.char
} else if ('userInput' in token) {
return token.userInput
} else if ('subdued' in token) {
return token.subdued
} else if ('filePath' in token) {
return token.filePath
} else if ('list' in token) {
return token.list.items.map(tokenItemToString).join(' ')
} else if ('bold' in token) {
return token.bold
} else if ('info' in token) {
return token.info
} else if ('warn' in token) {
return token.warn
} else if ('error' in token) {
return token.error
} else {
return token
.map((item, index) => {
if (index !== 0 && !(typeof item !== 'string' && 'char' in item)) {
return ` ${tokenItemToString(item)}`
} else {
return tokenItemToString(item)
}
})
.join('')
}
}
export function appendToTokenItem(token: TokenItem, suffix: string): TokenItem {
return Array.isArray(token) ? [...token, {char: suffix}] : [token, {char: suffix}]
}
function splitByDisplayType(acc: Block[][], item: Block) {
if (item.display === 'block') {
acc.push([item])
} else {
const last = acc[acc.length - 1]
if (last && last[0]!.display === 'inline') {
last.push(item)
} else {
acc.push([item])
}
}
return acc
}
const InlineBlocks: React.FC<{blocks: Block[]}> = ({blocks}) => {
return (
<Text>
{blocks.map((block, blockIndex) => (
<Text key={blockIndex}>
{blockIndex !== 0 && !(typeof block.value !== 'string' && 'char' in block.value) && <Text> </Text>}
<TokenizedText item={block.value} />
</Text>
))}
</Text>
)
}
interface TokenizedTextProps {
item: TokenItem
}
/**
* `TokenizedText` renders a text string with tokens that can be either strings,
* links, and commands.
*/
const URL_REGEX = /https?:\/\/\S+/g
const URL_TRAILING_PUNCTUATION = /[.,;:!?)\]}>'"]+$/
function renderStringWithLinks(str: string): JSX.Element {
const matches = Array.from(str.matchAll(URL_REGEX))
if (matches.length === 0) {
return <Text>{str}</Text>
}
const parts: JSX.Element[] = []
let cursor = 0
matches.forEach((match, index) => {
let url = match[0]
const trailing = url.match(URL_TRAILING_PUNCTUATION)
if (trailing) {
url = url.slice(0, url.length - trailing[0].length)
}
const start = match.index
const end = start + url.length
if (start > cursor) {
parts.push(<Text key={`t${index}`}>{str.slice(cursor, start)}</Text>)
}
parts.push(<Link key={`l${index}`} url={url} />)
cursor = end
})
if (cursor < str.length) {
parts.push(<Text key="tail">{str.slice(cursor)}</Text>)
}
return <Text>{parts}</Text>
}
const TokenizedText: FunctionComponent<TokenizedTextProps> = ({item}) => {
if (typeof item === 'string') {
return renderStringWithLinks(item)
} else if ('command' in item) {
return <Command command={item.command} />
} else if ('link' in item) {
return <Link {...item.link} />
} else if ('char' in item) {
return <Text>{item.char[0]}</Text>
} else if ('userInput' in item) {
return <UserInput userInput={item.userInput} />
} else if ('subdued' in item) {
return <Subdued subdued={item.subdued} />
} else if ('filePath' in item) {
return <FilePath filePath={item.filePath} />
} else if ('list' in item) {
return <List {...item.list} />
} else if ('bold' in item) {
return <Text bold>{item.bold}</Text>
} else if ('info' in item) {
return <Text color="blue">{item.info}</Text>
} else if ('warn' in item) {
return <Text color="yellow">{item.warn}</Text>
} else if ('error' in item) {
return <Text color="red">{item.error}</Text>
} else {
const groupedItems = item.map(tokenToBlock).reduce(splitByDisplayType, [])
return groupedItems.length === 1 && groupedItems[0]!.every((item) => item.display === 'inline') ? (
<InlineBlocks blocks={groupedItems[0]!} />
) : (
<Box flexDirection="column">
{groupedItems.map((items, groupIndex) => {
if (items[0]!.display === 'inline') {
return <InlineBlocks blocks={items} key={groupIndex} />
} else {
return <List key={groupIndex} {...(items[0]!.value as ListToken).list} />
}
})}
</Box>
)
}
}
export {TokenizedText}