@hozo/typography 0.3.0 → 0.4.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 +26 -0
- package/README.md +1 -1
- package/dist/code/meta.d.ts +14 -0
- package/dist/code/meta.d.ts.map +1 -0
- package/dist/code/meta.js +62 -0
- package/dist/code/meta.js.map +1 -0
- package/dist/code/model.d.ts +66 -0
- package/dist/code/model.d.ts.map +1 -0
- package/dist/code/model.js +139 -0
- package/dist/code/model.js.map +1 -0
- package/dist/code/reuse.d.ts +22 -0
- package/dist/code/reuse.d.ts.map +1 -0
- package/dist/code/reuse.js +54 -0
- package/dist/code/reuse.js.map +1 -0
- package/dist/code/shiki.d.ts +12 -0
- package/dist/code/shiki.d.ts.map +1 -0
- package/dist/code/shiki.js +28 -0
- package/dist/code/shiki.js.map +1 -0
- package/dist/code-lines.d.ts +34 -0
- package/dist/code-lines.d.ts.map +1 -0
- package/dist/code-lines.js +192 -0
- package/dist/code-lines.js.map +1 -0
- package/dist/code-lines.native.d.ts +54 -0
- package/dist/code-lines.native.d.ts.map +1 -0
- package/dist/code-lines.native.js +114 -0
- package/dist/code-lines.native.js.map +1 -0
- package/dist/index.d.ts +3 -41
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -69
- package/dist/index.js.map +1 -1
- package/dist/index.native.d.ts +3 -82
- package/dist/index.native.d.ts.map +1 -1
- package/dist/index.native.js +3 -140
- package/dist/index.native.js.map +1 -1
- package/dist/text.d.ts +43 -0
- package/dist/text.d.ts.map +1 -0
- package/dist/text.js +75 -0
- package/dist/text.js.map +1 -0
- package/dist/text.native.d.ts +84 -0
- package/dist/text.native.d.ts.map +1 -0
- package/dist/text.native.js +144 -0
- package/dist/text.native.js.map +1 -0
- package/package.json +30 -4
- package/src/code/meta.ts +69 -0
- package/src/code/model.ts +189 -0
- package/src/code/reuse.ts +70 -0
- package/src/code/shiki.ts +38 -0
- package/src/code-lines.native.tsx +191 -0
- package/src/code-lines.tsx +310 -0
- package/src/index.native.tsx +4 -245
- package/src/index.tsx +4 -164
- package/src/text.native.tsx +250 -0
- package/src/text.tsx +179 -0
package/src/code/meta.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import type { CodeMark, CodeRange } from './model.ts'
|
|
2
|
+
|
|
3
|
+
export interface CodeMeta {
|
|
4
|
+
language: string
|
|
5
|
+
title?: string
|
|
6
|
+
wrap?: boolean
|
|
7
|
+
lineNumbers?: boolean | { start: number }
|
|
8
|
+
marks: CodeRange[]
|
|
9
|
+
unknown: string[]
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Fence metadata is data: unknown syntax is preserved, never executed. */
|
|
13
|
+
export function parseCodeMeta(language: string, meta = ''): CodeMeta {
|
|
14
|
+
const result: CodeMeta = { language, marks: [], unknown: [] }
|
|
15
|
+
const tokens = meta.match(/(?:[^\s"'{}]+|"(?:\\.|[^"\\])*"|'[^']*'|\{[^}]*\})+|\S+/g) ?? []
|
|
16
|
+
let start: number | undefined
|
|
17
|
+
for (const token of tokens) {
|
|
18
|
+
if (token === 'wrap') {
|
|
19
|
+
result.wrap = true
|
|
20
|
+
continue
|
|
21
|
+
}
|
|
22
|
+
if (token === 'showLineNumbers') {
|
|
23
|
+
result.lineNumbers = true
|
|
24
|
+
continue
|
|
25
|
+
}
|
|
26
|
+
if (token.startsWith('title=')) {
|
|
27
|
+
const value = token.slice(6)
|
|
28
|
+
try {
|
|
29
|
+
result.title = value.startsWith('"') ? JSON.parse(value) : value.replace(/^'|'$/g, '')
|
|
30
|
+
} catch {
|
|
31
|
+
result.unknown.push(token)
|
|
32
|
+
}
|
|
33
|
+
continue
|
|
34
|
+
}
|
|
35
|
+
if (/^startLineNumber=\d+$/.test(token)) {
|
|
36
|
+
const value = Number(token.slice(16))
|
|
37
|
+
if (Number.isSafeInteger(value)) start = value
|
|
38
|
+
else result.unknown.push(token)
|
|
39
|
+
continue
|
|
40
|
+
}
|
|
41
|
+
const range = /^(?:(ins|del)=)?\{([\d,\s-]+)\}$/.exec(token)
|
|
42
|
+
if (range) {
|
|
43
|
+
const mark = (range[1] ?? 'mark') as CodeMark
|
|
44
|
+
const parsed: CodeRange[] = []
|
|
45
|
+
for (const part of range[2]!.split(',')) {
|
|
46
|
+
const match = /^(\d+)(?:-(\d+))?$/.exec(part.trim())
|
|
47
|
+
const from = Number(match?.[1]),
|
|
48
|
+
to = Number(match?.[2] ?? match?.[1])
|
|
49
|
+
if (
|
|
50
|
+
!match ||
|
|
51
|
+
!Number.isSafeInteger(from) ||
|
|
52
|
+
!Number.isSafeInteger(to) ||
|
|
53
|
+
from < 1 ||
|
|
54
|
+
to < from
|
|
55
|
+
) {
|
|
56
|
+
parsed.length = 0
|
|
57
|
+
break
|
|
58
|
+
}
|
|
59
|
+
parsed.push({ from, to, mark })
|
|
60
|
+
}
|
|
61
|
+
if (parsed.length) result.marks.push(...parsed)
|
|
62
|
+
else result.unknown.push(token)
|
|
63
|
+
continue
|
|
64
|
+
}
|
|
65
|
+
result.unknown.push(token)
|
|
66
|
+
}
|
|
67
|
+
if (start !== undefined) result.lineNumbers = { start }
|
|
68
|
+
return result
|
|
69
|
+
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
export interface CodeToken {
|
|
2
|
+
text: string
|
|
3
|
+
color?: string | Readonly<Record<string, string>>
|
|
4
|
+
italic?: boolean
|
|
5
|
+
bold?: boolean
|
|
6
|
+
underline?: boolean
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export type CodeMark = 'ins' | 'del' | 'mark'
|
|
10
|
+
|
|
11
|
+
export interface CodeLine {
|
|
12
|
+
tokens: string | readonly CodeToken[]
|
|
13
|
+
mark?: CodeMark
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface CodeRange {
|
|
17
|
+
from: number
|
|
18
|
+
to: number
|
|
19
|
+
mark: CodeMark
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function codeText(lines: readonly CodeLine[] | string): string {
|
|
23
|
+
return typeof lines === 'string'
|
|
24
|
+
? lines
|
|
25
|
+
: lines
|
|
26
|
+
.map((line) =>
|
|
27
|
+
typeof line.tokens === 'string'
|
|
28
|
+
? line.tokens
|
|
29
|
+
: line.tokens.map((token) => token.text).join(''),
|
|
30
|
+
)
|
|
31
|
+
.join('\n')
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
type NormalizedLine = Omit<CodeLine, 'tokens'> & { tokens: CodeToken[] }
|
|
35
|
+
|
|
36
|
+
/** Tab stops cross token boundaries, so highlighting cannot change indentation. */
|
|
37
|
+
export function normalizeCodeLines(
|
|
38
|
+
lines: readonly CodeLine[] | string,
|
|
39
|
+
tabSize = 2,
|
|
40
|
+
): NormalizedLine[] {
|
|
41
|
+
return normalizeCodeLinesFrom(lines, tabSize, new Map())[0]
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* @internal `normalizeCodeLines`, handing back what a line object came out as
|
|
46
|
+
* in `previous` (the map the last call returned, at the same tab size) when it
|
|
47
|
+
* is passed again. A renderer can then tell the lines an edit left alone from
|
|
48
|
+
* the one it changed by identity (#1289); lines are read as immutable, as
|
|
49
|
+
* React reads props.
|
|
50
|
+
*/
|
|
51
|
+
export function normalizeCodeLinesFrom(
|
|
52
|
+
lines: readonly CodeLine[] | string,
|
|
53
|
+
tabSize: number,
|
|
54
|
+
previous: ReadonlyMap<CodeLine, NormalizedLine[]>,
|
|
55
|
+
): [NormalizedLine[], Map<CodeLine, NormalizedLine[]>] {
|
|
56
|
+
if (!Number.isSafeInteger(tabSize) || tabSize < 1)
|
|
57
|
+
throw new RangeError('tabSize must be a positive safe integer')
|
|
58
|
+
const next = new Map<CodeLine, NormalizedLine[]>()
|
|
59
|
+
if (typeof lines === 'string')
|
|
60
|
+
return [
|
|
61
|
+
lines
|
|
62
|
+
.replace(/\r\n?/g, '\n')
|
|
63
|
+
.split('\n')
|
|
64
|
+
.flatMap((tokens) => normalizeLine({ tokens }, tabSize)),
|
|
65
|
+
next,
|
|
66
|
+
]
|
|
67
|
+
const result = lines.flatMap((line) => {
|
|
68
|
+
const normalized = next.get(line) ?? previous.get(line) ?? normalizeLine(line, tabSize)
|
|
69
|
+
next.set(line, normalized)
|
|
70
|
+
return normalized
|
|
71
|
+
})
|
|
72
|
+
return [result, next]
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function normalizeLine(line: CodeLine, tabSize: number): NormalizedLine[] {
|
|
76
|
+
const parts = typeof line.tokens === 'string' ? [{ text: line.tokens }] : line.tokens
|
|
77
|
+
const result: NormalizedLine[] = []
|
|
78
|
+
let tokens: CodeToken[] = []
|
|
79
|
+
let column = 0
|
|
80
|
+
for (const token of parts) {
|
|
81
|
+
const pieces = token.text.replace(/\r\n?/g, '\n').split('\n')
|
|
82
|
+
pieces.forEach((piece, index) => {
|
|
83
|
+
if (index > 0) {
|
|
84
|
+
result.push({ tokens, mark: line.mark })
|
|
85
|
+
tokens = []
|
|
86
|
+
column = 0
|
|
87
|
+
}
|
|
88
|
+
let text = ''
|
|
89
|
+
for (const character of piece) {
|
|
90
|
+
const expanded = character === '\t' ? ' '.repeat(tabSize - (column % tabSize)) : character
|
|
91
|
+
text += expanded
|
|
92
|
+
column += expanded.length
|
|
93
|
+
}
|
|
94
|
+
tokens.push({ ...token, text })
|
|
95
|
+
})
|
|
96
|
+
}
|
|
97
|
+
result.push({ tokens, mark: line.mark })
|
|
98
|
+
return result
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** A token as one theme draws it. */
|
|
102
|
+
export interface DrawnCodeToken {
|
|
103
|
+
text: string
|
|
104
|
+
color?: string
|
|
105
|
+
italic?: boolean
|
|
106
|
+
bold?: boolean
|
|
107
|
+
underline?: boolean
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The tokens as `theme` draws them, with each run of neighbours that would be
|
|
112
|
+
* drawn the same joined into one, so a Native line nests one `Text` per run
|
|
113
|
+
* rather than per token (#1431). Highlighters split far finer than they
|
|
114
|
+
* colour: punctuation, whitespace and plain identifiers often share a style.
|
|
115
|
+
*
|
|
116
|
+
* Only an unchanged look is joined. Colour, italic, bold and underline must
|
|
117
|
+
* all match, with one exception: whitespace with no underline draws nothing,
|
|
118
|
+
* so its colour is not compared. Its weight and slant still are, since a
|
|
119
|
+
* font's bold or italic space is not always as wide.
|
|
120
|
+
*/
|
|
121
|
+
export function drawnCodeTokens(tokens: readonly CodeToken[], theme: string): DrawnCodeToken[] {
|
|
122
|
+
const result: DrawnCodeToken[] = []
|
|
123
|
+
for (const token of tokens) {
|
|
124
|
+
if (!token.text) continue
|
|
125
|
+
const drawn: DrawnCodeToken = {
|
|
126
|
+
text: token.text,
|
|
127
|
+
color:
|
|
128
|
+
typeof token.color === 'string'
|
|
129
|
+
? token.color
|
|
130
|
+
: (token.color?.[theme] ?? token.color?.light),
|
|
131
|
+
italic: token.italic || undefined,
|
|
132
|
+
bold: token.bold || undefined,
|
|
133
|
+
underline: token.underline || undefined,
|
|
134
|
+
}
|
|
135
|
+
const last = result.at(-1)
|
|
136
|
+
if (
|
|
137
|
+
last &&
|
|
138
|
+
last.italic === drawn.italic &&
|
|
139
|
+
last.bold === drawn.bold &&
|
|
140
|
+
last.underline === drawn.underline &&
|
|
141
|
+
(last.color === drawn.color || (!drawn.underline && (blank(last.text) || blank(drawn.text))))
|
|
142
|
+
) {
|
|
143
|
+
if (blank(last.text)) last.color = drawn.color
|
|
144
|
+
last.text += drawn.text
|
|
145
|
+
} else result.push(drawn)
|
|
146
|
+
}
|
|
147
|
+
return result
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const blank = (text: string) => /^\s+$/.test(text)
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The line that needs the most columns, for a windowed block to hold its
|
|
154
|
+
* scrolling width open with before the line itself is mounted.
|
|
155
|
+
*
|
|
156
|
+
* The text is monospaced, so columns are the width; a wide character (CJK,
|
|
157
|
+
* full-width forms, most emoji) takes two, which is approximated by code
|
|
158
|
+
* point rather than read from Unicode's East Asian Width table.
|
|
159
|
+
*/
|
|
160
|
+
export function widestCodeLine<T extends Pick<CodeLine, 'tokens'>>(
|
|
161
|
+
lines: readonly T[],
|
|
162
|
+
): { line: T; index: number } | undefined {
|
|
163
|
+
let widest: { line: T; index: number; columns: number } | undefined
|
|
164
|
+
lines.forEach((line, index) => {
|
|
165
|
+
let columns = 0
|
|
166
|
+
const tokens = typeof line.tokens === 'string' ? [{ text: line.tokens }] : line.tokens
|
|
167
|
+
for (const token of tokens)
|
|
168
|
+
for (const char of token.text) columns += (char.codePointAt(0) ?? 0) >= 0x2e80 ? 2 : 1
|
|
169
|
+
if (!widest || columns > widest.columns) widest = { line, index, columns }
|
|
170
|
+
})
|
|
171
|
+
return widest
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function markCodeLines(
|
|
175
|
+
lines: readonly CodeLine[] | string,
|
|
176
|
+
ranges: readonly CodeRange[],
|
|
177
|
+
): CodeLine[] {
|
|
178
|
+
const normalized =
|
|
179
|
+
typeof lines === 'string'
|
|
180
|
+
? lines
|
|
181
|
+
.replace(/\r\n?/g, '\n')
|
|
182
|
+
.split('\n')
|
|
183
|
+
.map((tokens) => ({ tokens }))
|
|
184
|
+
: lines
|
|
185
|
+
return normalized.map((line, index) => {
|
|
186
|
+
const mark = ranges.findLast((range) => range.from <= index + 1 && range.to >= index + 1)?.mark
|
|
187
|
+
return mark ? { ...line, mark } : { ...line }
|
|
188
|
+
})
|
|
189
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { type ReactNode, useRef } from 'react'
|
|
2
|
+
import { type CodeLine, normalizeCodeLinesFrom } from './model.ts'
|
|
3
|
+
|
|
4
|
+
type NormalizedCodeLine = ReturnType<typeof normalizeCodeLinesFrom>[0][number]
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @internal `normalizeCodeLines`, keeping a line's normalized objects from the
|
|
8
|
+
* last render while the same line object is passed.
|
|
9
|
+
*/
|
|
10
|
+
export function useNormalizedCodeLines(
|
|
11
|
+
lines: readonly CodeLine[] | string,
|
|
12
|
+
tabSize = 2,
|
|
13
|
+
): NormalizedCodeLine[] {
|
|
14
|
+
const last = useRef<{ tabSize: number; byLine: ReadonlyMap<CodeLine, NormalizedCodeLine[]> }>(
|
|
15
|
+
undefined,
|
|
16
|
+
)
|
|
17
|
+
const [result, byLine] = normalizeCodeLinesFrom(
|
|
18
|
+
lines,
|
|
19
|
+
tabSize,
|
|
20
|
+
last.current?.tabSize === tabSize ? last.current.byLine : new Map(),
|
|
21
|
+
)
|
|
22
|
+
last.current = { tabSize, byLine }
|
|
23
|
+
return result
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @internal Rows already drawn, by line object. A line an edit left alone
|
|
28
|
+
* comes back from `useNormalizedCodeLines` as the same object, and is handed
|
|
29
|
+
* back here as the same element, which React skips; without this, changing
|
|
30
|
+
* one line re-rendered every mounted one (#1289). A `FlatList` asks for rows
|
|
31
|
+
* after the render too, so the map outlives it, holding only the current
|
|
32
|
+
* lines. `key` is everything else a row is drawn from; `undefined` reuses
|
|
33
|
+
* nothing.
|
|
34
|
+
*/
|
|
35
|
+
export function useCodeRows<Line extends object>(
|
|
36
|
+
lines: readonly Line[],
|
|
37
|
+
key: string | undefined,
|
|
38
|
+
draw: (line: Line, index: number) => ReactNode,
|
|
39
|
+
): (line: Line, index: number) => ReactNode {
|
|
40
|
+
const drawn = useRef<{
|
|
41
|
+
lines?: readonly Line[]
|
|
42
|
+
rows: Map<Line, { index: number; key: string; row: ReactNode }>
|
|
43
|
+
}>({ rows: new Map() })
|
|
44
|
+
if (drawn.current.lines !== lines) {
|
|
45
|
+
const rows: typeof drawn.current.rows = new Map()
|
|
46
|
+
for (const line of lines) {
|
|
47
|
+
const hit = drawn.current.rows.get(line)
|
|
48
|
+
if (hit) rows.set(line, hit)
|
|
49
|
+
}
|
|
50
|
+
drawn.current = { lines, rows }
|
|
51
|
+
}
|
|
52
|
+
const { rows } = drawn.current
|
|
53
|
+
return (line, index) => {
|
|
54
|
+
if (key === undefined) return draw(line, index)
|
|
55
|
+
const hit = rows.get(line)
|
|
56
|
+
if (hit && hit.index === index && hit.key === key) return hit.row
|
|
57
|
+
const row = draw(line, index)
|
|
58
|
+
rows.set(line, { index, key, row })
|
|
59
|
+
return row
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** @internal JSON for a row key, or `undefined` for a value it cannot write out. */
|
|
64
|
+
export function codeKey(value: unknown): string | undefined {
|
|
65
|
+
try {
|
|
66
|
+
return JSON.stringify(value)
|
|
67
|
+
} catch {
|
|
68
|
+
return undefined
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { CodeLine, CodeToken } from './model.ts'
|
|
2
|
+
|
|
3
|
+
export interface ShikiTokenLike {
|
|
4
|
+
content: string
|
|
5
|
+
color?: string
|
|
6
|
+
fontStyle?: number
|
|
7
|
+
htmlStyle?: Readonly<Record<string, string>>
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Maps output theme slots to Shiki's htmlStyle suffixes (for example dark -> dark). */
|
|
11
|
+
export function fromShiki(
|
|
12
|
+
lines: readonly (readonly ShikiTokenLike[])[],
|
|
13
|
+
options?: { themes?: Readonly<Record<string, string>> },
|
|
14
|
+
): CodeLine[] {
|
|
15
|
+
return lines.map((line) => ({
|
|
16
|
+
tokens: line.map((token): CodeToken => {
|
|
17
|
+
let color: CodeToken['color'] = token.color ?? token.htmlStyle?.color
|
|
18
|
+
if (options?.themes) {
|
|
19
|
+
const colors: Record<string, string> = {}
|
|
20
|
+
for (const [slot, key] of Object.entries(options.themes)) {
|
|
21
|
+
const value =
|
|
22
|
+
token.htmlStyle?.[key.startsWith('--') ? key : `--shiki-${key}`] ??
|
|
23
|
+
(slot === 'light' ? (token.color ?? token.htmlStyle?.color) : undefined)
|
|
24
|
+
if (value) colors[slot] = value
|
|
25
|
+
}
|
|
26
|
+
if (Object.keys(colors).length) color = colors
|
|
27
|
+
}
|
|
28
|
+
const flags = token.fontStyle !== undefined && token.fontStyle > 0 ? token.fontStyle : 0
|
|
29
|
+
return {
|
|
30
|
+
text: token.content,
|
|
31
|
+
...(color ? { color } : {}),
|
|
32
|
+
...(flags & 1 ? { italic: true } : {}),
|
|
33
|
+
...(flags & 2 ? { bold: true } : {}),
|
|
34
|
+
...(flags & 4 ? { underline: true } : {}),
|
|
35
|
+
}
|
|
36
|
+
}),
|
|
37
|
+
}))
|
|
38
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// biome-ignore-all lint/suspicious/noArrayIndexKey: code lines and tokens use source-position identity
|
|
2
|
+
import { useHozoMessage } from '@hozo/behaviors'
|
|
3
|
+
import { HozoTextSizeContext, hozoSplitTextStyle } from '@hozo/engine'
|
|
4
|
+
import { useHozoDark } from '@hozo/engine/generated/environment'
|
|
5
|
+
import { hozoClasses } from '@hozo/engine/project'
|
|
6
|
+
import { type ReactNode, useContext } from 'react'
|
|
7
|
+
import {
|
|
8
|
+
type StyleProp,
|
|
9
|
+
StyleSheet,
|
|
10
|
+
Text,
|
|
11
|
+
type TextStyle,
|
|
12
|
+
View,
|
|
13
|
+
type ViewStyle,
|
|
14
|
+
} from 'react-native'
|
|
15
|
+
import {
|
|
16
|
+
type CodeLine,
|
|
17
|
+
type CodeMark,
|
|
18
|
+
type DrawnCodeToken,
|
|
19
|
+
drawnCodeTokens,
|
|
20
|
+
type normalizeCodeLines,
|
|
21
|
+
} from './code/model.ts'
|
|
22
|
+
import { codeKey, useCodeRows, useNormalizedCodeLines } from './code/reuse.ts'
|
|
23
|
+
|
|
24
|
+
export { useNormalizedCodeLines }
|
|
25
|
+
|
|
26
|
+
type CodeStyle = StyleProp<ViewStyle | TextStyle>
|
|
27
|
+
export interface CodeLinesProps {
|
|
28
|
+
lines: readonly CodeLine[] | string
|
|
29
|
+
tabSize?: number
|
|
30
|
+
theme?: string
|
|
31
|
+
wrap?: boolean
|
|
32
|
+
className?: string
|
|
33
|
+
lineClassName?: string
|
|
34
|
+
insClassName?: string
|
|
35
|
+
delClassName?: string
|
|
36
|
+
markClassName?: string
|
|
37
|
+
style?: CodeStyle
|
|
38
|
+
lineStyle?: CodeStyle
|
|
39
|
+
insStyle?: CodeStyle
|
|
40
|
+
delStyle?: CodeStyle
|
|
41
|
+
markStyle?: CodeStyle
|
|
42
|
+
/** @internal A separate gutter supplied by CodeBlock. */
|
|
43
|
+
renderGutter?: (line: CodeLine, index: number) => ReactNode
|
|
44
|
+
/**
|
|
45
|
+
* @internal Everything `renderGutter` draws from besides the line and its
|
|
46
|
+
* index, as `codeRowKey` gives it. Without it, a gutter's rows are not reused.
|
|
47
|
+
*/
|
|
48
|
+
gutterKey?: string
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const MARK_FACTS = [undefined, 'ins', 'del', 'mark'].map((mark) => ({
|
|
52
|
+
'data-code-mark': Boolean(mark),
|
|
53
|
+
'data-code-mark=ins': mark === 'ins',
|
|
54
|
+
'data-code-mark=del': mark === 'del',
|
|
55
|
+
'data-code-mark=mark': mark === 'mark',
|
|
56
|
+
}))
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @internal One string for everything a row is drawn from besides its line
|
|
60
|
+
* and index, with styles flattened and classes resolved under each mark, so
|
|
61
|
+
* an equal key means an equal row. `undefined` when a value cannot be written
|
|
62
|
+
* out (an animated style, say): then nothing is reused.
|
|
63
|
+
*/
|
|
64
|
+
export function codeRowKey(
|
|
65
|
+
values: readonly unknown[],
|
|
66
|
+
classNames: readonly (string | undefined)[] = [],
|
|
67
|
+
): string | undefined {
|
|
68
|
+
return codeKey([
|
|
69
|
+
values,
|
|
70
|
+
classNames.map((name) => MARK_FACTS.map((facts) => hozoClasses(name, facts))),
|
|
71
|
+
])
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const split = (style: CodeStyle) =>
|
|
75
|
+
hozoSplitTextStyle(StyleSheet.flatten(style) ?? {}) as [ViewStyle, TextStyle]
|
|
76
|
+
|
|
77
|
+
// Only what the run sets, so that on the line itself an unset colour still
|
|
78
|
+
// leaves the line's own.
|
|
79
|
+
function runStyle(run: DrawnCodeToken | undefined): TextStyle {
|
|
80
|
+
return {
|
|
81
|
+
...(run?.color ? { color: run.color } : {}),
|
|
82
|
+
...(run?.italic ? { fontStyle: 'italic' } : {}),
|
|
83
|
+
...(run?.bold ? { fontWeight: '700' } : {}),
|
|
84
|
+
...(run?.underline ? { textDecorationLine: 'underline' } : {}),
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** A line after `normalizeCodeLines`: its tokens are always a list. */
|
|
89
|
+
export type NormalizedCodeLine = ReturnType<typeof normalizeCodeLines>[number]
|
|
90
|
+
|
|
91
|
+
export interface CodeLineRows {
|
|
92
|
+
lines: readonly NormalizedCodeLine[]
|
|
93
|
+
style: StyleProp<ViewStyle>
|
|
94
|
+
renderLine: (line: NormalizedCodeLine, index: number) => ReactNode
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* @internal What `CodeLines` draws, one line at a time: the normalized lines,
|
|
99
|
+
* the box around them, and the row for any one line.
|
|
100
|
+
*
|
|
101
|
+
* Separate from `CodeLines` so that `CodeBlock` can hand the rows to a
|
|
102
|
+
* `FlatList` and mount only the lines near the visible ones (#1289), with
|
|
103
|
+
* each row the same element the full list draws.
|
|
104
|
+
*/
|
|
105
|
+
export function useCodeLineRows(props: CodeLinesProps): CodeLineRows {
|
|
106
|
+
const message = useHozoMessage()
|
|
107
|
+
const dark = useHozoDark()
|
|
108
|
+
const inheritedSize = useContext(HozoTextSizeContext)
|
|
109
|
+
const theme = props.theme ?? (dark ? 'dark' : 'light')
|
|
110
|
+
const lines = useNormalizedCodeLines(props.lines, props.tabSize)
|
|
111
|
+
const [box, text] = split([hozoClasses(props.className), props.style])
|
|
112
|
+
const labels: Record<CodeMark, string> = {
|
|
113
|
+
ins: message('hozo.code.added'),
|
|
114
|
+
del: message('hozo.code.removed'),
|
|
115
|
+
mark: message('hozo.code.highlighted'),
|
|
116
|
+
}
|
|
117
|
+
const fontSize = typeof text.fontSize === 'number' ? text.fontSize : inheritedSize
|
|
118
|
+
const lineHeight = text.lineHeight ?? fontSize * 1.5
|
|
119
|
+
const key =
|
|
120
|
+
props.renderGutter && props.gutterKey === undefined
|
|
121
|
+
? undefined
|
|
122
|
+
: codeRowKey(
|
|
123
|
+
[
|
|
124
|
+
theme,
|
|
125
|
+
fontSize,
|
|
126
|
+
lineHeight,
|
|
127
|
+
props.wrap,
|
|
128
|
+
text,
|
|
129
|
+
labels,
|
|
130
|
+
props.gutterKey,
|
|
131
|
+
...[props.lineStyle, props.insStyle, props.delStyle, props.markStyle].map((style) =>
|
|
132
|
+
StyleSheet.flatten(style),
|
|
133
|
+
),
|
|
134
|
+
],
|
|
135
|
+
[props.lineClassName, props.insClassName, props.delClassName, props.markClassName],
|
|
136
|
+
)
|
|
137
|
+
const renderLine = useCodeRows(lines, key, drawLine)
|
|
138
|
+
function drawLine(line: NormalizedCodeLine, index: number) {
|
|
139
|
+
const facts = {
|
|
140
|
+
'data-code-mark': Boolean(line.mark),
|
|
141
|
+
'data-code-mark=ins': line.mark === 'ins',
|
|
142
|
+
'data-code-mark=del': line.mark === 'del',
|
|
143
|
+
'data-code-mark=mark': line.mark === 'mark',
|
|
144
|
+
}
|
|
145
|
+
const [lineBox, lineText] = split([
|
|
146
|
+
hozoClasses(props.lineClassName, facts),
|
|
147
|
+
line.mark ? hozoClasses(props[`${line.mark}ClassName`], facts) : undefined,
|
|
148
|
+
props.lineStyle,
|
|
149
|
+
line.mark ? props[`${line.mark}Style`] : undefined,
|
|
150
|
+
])
|
|
151
|
+
const tokens = line.tokens
|
|
152
|
+
const content = tokens.map((token) => token.text).join('')
|
|
153
|
+
const runs = drawnCodeTokens(tokens, theme)
|
|
154
|
+
return (
|
|
155
|
+
<View key={index} style={[{ flexDirection: 'row', minHeight: lineHeight }, lineBox]}>
|
|
156
|
+
{props.renderGutter?.(line, index)}
|
|
157
|
+
<Text
|
|
158
|
+
accessible
|
|
159
|
+
accessibilityLabel={line.mark ? `${labels[line.mark]}: ${content}` : content}
|
|
160
|
+
style={[
|
|
161
|
+
{ fontFamily: 'monospace', fontSize, lineHeight },
|
|
162
|
+
text,
|
|
163
|
+
lineText,
|
|
164
|
+
// A line drawn in one style needs no nested Text: the run's style
|
|
165
|
+
// goes on the line itself, which is the same drawing (#1431).
|
|
166
|
+
runs.length === 1 ? runStyle(runs[0]) : undefined,
|
|
167
|
+
{ flexGrow: 1, flexShrink: props.wrap ? 1 : 0, minWidth: 0 },
|
|
168
|
+
]}
|
|
169
|
+
>
|
|
170
|
+
{runs.length === 1
|
|
171
|
+
? runs[0]?.text
|
|
172
|
+
: runs.map((run, at) => (
|
|
173
|
+
<Text key={at} style={runStyle(run)}>
|
|
174
|
+
{run.text}
|
|
175
|
+
</Text>
|
|
176
|
+
))}
|
|
177
|
+
</Text>
|
|
178
|
+
</View>
|
|
179
|
+
)
|
|
180
|
+
}
|
|
181
|
+
return {
|
|
182
|
+
lines,
|
|
183
|
+
style: [box, props.wrap ? { alignSelf: 'stretch', minWidth: 0 } : undefined],
|
|
184
|
+
renderLine,
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function CodeLines(props: CodeLinesProps) {
|
|
189
|
+
const { lines, style, renderLine } = useCodeLineRows(props)
|
|
190
|
+
return <View style={style}>{lines.map(renderLine)}</View>
|
|
191
|
+
}
|