@hozo/typography 0.3.0 → 0.5.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.
Files changed (53) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +1 -1
  3. package/dist/code/meta.d.ts +14 -0
  4. package/dist/code/meta.d.ts.map +1 -0
  5. package/dist/code/meta.js +62 -0
  6. package/dist/code/meta.js.map +1 -0
  7. package/dist/code/model.d.ts +66 -0
  8. package/dist/code/model.d.ts.map +1 -0
  9. package/dist/code/model.js +139 -0
  10. package/dist/code/model.js.map +1 -0
  11. package/dist/code/reuse.d.ts +22 -0
  12. package/dist/code/reuse.d.ts.map +1 -0
  13. package/dist/code/reuse.js +54 -0
  14. package/dist/code/reuse.js.map +1 -0
  15. package/dist/code/shiki.d.ts +12 -0
  16. package/dist/code/shiki.d.ts.map +1 -0
  17. package/dist/code/shiki.js +28 -0
  18. package/dist/code/shiki.js.map +1 -0
  19. package/dist/code-lines.d.ts +34 -0
  20. package/dist/code-lines.d.ts.map +1 -0
  21. package/dist/code-lines.js +192 -0
  22. package/dist/code-lines.js.map +1 -0
  23. package/dist/code-lines.native.d.ts +69 -0
  24. package/dist/code-lines.native.d.ts.map +1 -0
  25. package/dist/code-lines.native.js +138 -0
  26. package/dist/code-lines.native.js.map +1 -0
  27. package/dist/index.d.ts +3 -41
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +3 -69
  30. package/dist/index.js.map +1 -1
  31. package/dist/index.native.d.ts +3 -82
  32. package/dist/index.native.d.ts.map +1 -1
  33. package/dist/index.native.js +3 -140
  34. package/dist/index.native.js.map +1 -1
  35. package/dist/text.d.ts +43 -0
  36. package/dist/text.d.ts.map +1 -0
  37. package/dist/text.js +75 -0
  38. package/dist/text.js.map +1 -0
  39. package/dist/text.native.d.ts +84 -0
  40. package/dist/text.native.d.ts.map +1 -0
  41. package/dist/text.native.js +144 -0
  42. package/dist/text.native.js.map +1 -0
  43. package/package.json +30 -4
  44. package/src/code/meta.ts +69 -0
  45. package/src/code/model.ts +189 -0
  46. package/src/code/reuse.ts +70 -0
  47. package/src/code/shiki.ts +38 -0
  48. package/src/code-lines.native.tsx +236 -0
  49. package/src/code-lines.tsx +310 -0
  50. package/src/index.native.tsx +4 -245
  51. package/src/index.tsx +4 -164
  52. package/src/text.native.tsx +250 -0
  53. package/src/text.tsx +179 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hozo/typography",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Universal typography, semantic text formatting, and accessible CJK ruby primitives for Hozo.",
5
5
  "keywords": [
6
6
  "react-native",
@@ -33,6 +33,30 @@
33
33
  "types": "./dist/index.d.ts",
34
34
  "default": "./dist/index.js"
35
35
  },
36
+ "./code/model": {
37
+ "types": "./dist/code/model.d.ts",
38
+ "default": "./dist/code/model.js"
39
+ },
40
+ "./code/shiki": {
41
+ "types": "./dist/code/shiki.d.ts",
42
+ "default": "./dist/code/shiki.js"
43
+ },
44
+ "./code/meta": {
45
+ "types": "./dist/code/meta.d.ts",
46
+ "default": "./dist/code/meta.js"
47
+ },
48
+ "./code/lines": {
49
+ "react-native": {
50
+ "types": "./dist/code-lines.native.d.ts",
51
+ "default": "./dist/code-lines.native.js"
52
+ },
53
+ "types": "./dist/code-lines.d.ts",
54
+ "default": "./dist/code-lines.js"
55
+ },
56
+ "./code/lines/native": {
57
+ "types": "./dist/code-lines.native.d.ts",
58
+ "default": "./dist/code-lines.native.js"
59
+ },
36
60
  "./fonts": {
37
61
  "types": "./dist/fonts.d.ts",
38
62
  "default": "./dist/fonts.js"
@@ -68,12 +92,13 @@
68
92
  "provenance": true
69
93
  },
70
94
  "dependencies": {
71
- "@hozo/primitives": "^0.3.0",
72
- "@hozo/engine": "^0.3.0"
95
+ "@hozo/primitives": "^0.5.0",
96
+ "@hozo/engine": "^0.5.0",
97
+ "@hozo/behaviors": "^0.5.0"
73
98
  },
74
99
  "peerDependencies": {
75
100
  "react": "^19.0.0",
76
- "react-native": ">=0.86"
101
+ "react-native": ">=0.87"
77
102
  },
78
103
  "peerDependenciesMeta": {
79
104
  "react-native": {
@@ -81,6 +106,7 @@
81
106
  }
82
107
  },
83
108
  "devDependencies": {
109
+ "shiki": "4.4.3",
84
110
  "@types/react": "^19.2.18",
85
111
  "@types/react-dom": "^19.2.4",
86
112
  "react-dom": "^19.2.8",
@@ -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,236 @@
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 type CodeMarkFacts = Readonly<{
28
+ 'data-code-mark': boolean
29
+ 'data-code-mark=ins': boolean
30
+ 'data-code-mark=del': boolean
31
+ 'data-code-mark=mark': boolean
32
+ }>
33
+
34
+ export interface CodeLinesProps {
35
+ lines: readonly CodeLine[] | string
36
+ tabSize?: number
37
+ theme?: string
38
+ wrap?: boolean
39
+ className?: string
40
+ lineClassName?: string
41
+ insClassName?: string
42
+ delClassName?: string
43
+ markClassName?: string
44
+ /** @internal Complete prepared line class contribution (RFC 010). */
45
+ hozoLineStyle?: (facts: CodeMarkFacts) => CodeStyle
46
+ /** @internal Complete prepared inserted-line class contribution (RFC 010). */
47
+ hozoInsStyle?: (facts: CodeMarkFacts) => CodeStyle
48
+ /** @internal Complete prepared deleted-line class contribution (RFC 010). */
49
+ hozoDelStyle?: (facts: CodeMarkFacts) => CodeStyle
50
+ /** @internal Complete prepared highlighted-line class contribution (RFC 010). */
51
+ hozoMarkStyle?: (facts: CodeMarkFacts) => CodeStyle
52
+ style?: CodeStyle
53
+ lineStyle?: CodeStyle
54
+ insStyle?: CodeStyle
55
+ delStyle?: CodeStyle
56
+ markStyle?: CodeStyle
57
+ /** @internal A separate gutter supplied by CodeBlock. */
58
+ renderGutter?: (line: CodeLine, index: number) => ReactNode
59
+ /**
60
+ * @internal Everything `renderGutter` draws from besides the line and its
61
+ * index, as `codeRowKey` gives it. Without it, a gutter's rows are not reused.
62
+ */
63
+ gutterKey?: string
64
+ }
65
+
66
+ export const CODE_MARK_FACTS: readonly CodeMarkFacts[] = [undefined, 'ins', 'del', 'mark'].map(
67
+ (mark) => ({
68
+ 'data-code-mark': Boolean(mark),
69
+ 'data-code-mark=ins': mark === 'ins',
70
+ 'data-code-mark=del': mark === 'del',
71
+ 'data-code-mark=mark': mark === 'mark',
72
+ }),
73
+ )
74
+
75
+ /**
76
+ * @internal One string for everything a row is drawn from besides its line
77
+ * and index, with styles flattened and classes resolved under each mark, so
78
+ * an equal key means an equal row. `undefined` when a value cannot be written
79
+ * out (an animated style, say): then nothing is reused.
80
+ */
81
+ export function codeRowKey(
82
+ values: readonly unknown[],
83
+ classNames: readonly (string | undefined)[] = [],
84
+ ): string | undefined {
85
+ return codeKey([
86
+ values,
87
+ classNames.map((name) =>
88
+ name ? CODE_MARK_FACTS.map((facts) => hozoClasses(name, facts)) : null,
89
+ ),
90
+ ])
91
+ }
92
+
93
+ const split = (style: CodeStyle) =>
94
+ hozoSplitTextStyle(StyleSheet.flatten(style) ?? {}) as [ViewStyle, TextStyle]
95
+
96
+ // Only what the run sets, so that on the line itself an unset colour still
97
+ // leaves the line's own.
98
+ function runStyle(run: DrawnCodeToken | undefined): TextStyle {
99
+ return {
100
+ ...(run?.color ? { color: run.color } : {}),
101
+ ...(run?.italic ? { fontStyle: 'italic' } : {}),
102
+ ...(run?.bold ? { fontWeight: '700' } : {}),
103
+ ...(run?.underline ? { textDecorationLine: 'underline' } : {}),
104
+ }
105
+ }
106
+
107
+ /** A line after `normalizeCodeLines`: its tokens are always a list. */
108
+ export type NormalizedCodeLine = ReturnType<typeof normalizeCodeLines>[number]
109
+
110
+ export interface CodeLineRows {
111
+ lines: readonly NormalizedCodeLine[]
112
+ style: StyleProp<ViewStyle>
113
+ renderLine: (line: NormalizedCodeLine, index: number) => ReactNode
114
+ }
115
+
116
+ /**
117
+ * @internal What `CodeLines` draws, one line at a time: the normalized lines,
118
+ * the box around them, and the row for any one line.
119
+ *
120
+ * Separate from `CodeLines` so that `CodeBlock` can hand the rows to a
121
+ * `FlatList` and mount only the lines near the visible ones (#1289), with
122
+ * each row the same element the full list draws.
123
+ */
124
+ export function useCodeLineRows(props: CodeLinesProps): CodeLineRows {
125
+ const message = useHozoMessage()
126
+ const dark = useHozoDark()
127
+ const inheritedSize = useContext(HozoTextSizeContext)
128
+ const theme = props.theme ?? (dark ? 'dark' : 'light')
129
+ const lines = useNormalizedCodeLines(props.lines, props.tabSize)
130
+ const [box, text] = split([
131
+ props.className ? hozoClasses(props.className) : undefined,
132
+ props.style,
133
+ ])
134
+ const labels: Record<CodeMark, string> = {
135
+ ins: message('hozo.code.added'),
136
+ del: message('hozo.code.removed'),
137
+ mark: message('hozo.code.highlighted'),
138
+ }
139
+ const fontSize = typeof text.fontSize === 'number' ? text.fontSize : inheritedSize
140
+ const lineHeight = text.lineHeight ?? fontSize * 1.5
141
+ const preparedMarks: Record<CodeMark, ((facts: CodeMarkFacts) => CodeStyle) | undefined> = {
142
+ ins: props.hozoInsStyle,
143
+ del: props.hozoDelStyle,
144
+ mark: props.hozoMarkStyle,
145
+ }
146
+ const key =
147
+ props.renderGutter && props.gutterKey === undefined
148
+ ? undefined
149
+ : codeRowKey(
150
+ [
151
+ theme,
152
+ fontSize,
153
+ lineHeight,
154
+ props.wrap,
155
+ text,
156
+ labels,
157
+ props.gutterKey,
158
+ ...[props.lineStyle, props.insStyle, props.delStyle, props.markStyle].map((style) =>
159
+ StyleSheet.flatten(style),
160
+ ),
161
+ ...[
162
+ props.hozoLineStyle,
163
+ props.hozoInsStyle,
164
+ props.hozoDelStyle,
165
+ props.hozoMarkStyle,
166
+ ].map((prepared) =>
167
+ prepared ? CODE_MARK_FACTS.map((facts) => StyleSheet.flatten(prepared(facts))) : null,
168
+ ),
169
+ ],
170
+ [props.lineClassName, props.insClassName, props.delClassName, props.markClassName],
171
+ )
172
+ const renderLine = useCodeRows(lines, key, drawLine)
173
+ function drawLine(line: NormalizedCodeLine, index: number) {
174
+ const facts: CodeMarkFacts = {
175
+ 'data-code-mark': Boolean(line.mark),
176
+ 'data-code-mark=ins': line.mark === 'ins',
177
+ 'data-code-mark=del': line.mark === 'del',
178
+ 'data-code-mark=mark': line.mark === 'mark',
179
+ }
180
+ const markPrepared = line.mark ? preparedMarks[line.mark] : undefined
181
+ const markClassName = line.mark ? props[`${line.mark}ClassName`] : undefined
182
+ const [lineBox, lineText] = split([
183
+ props.hozoLineStyle
184
+ ? props.hozoLineStyle(facts)
185
+ : props.lineClassName
186
+ ? hozoClasses(props.lineClassName, facts)
187
+ : undefined,
188
+ markPrepared
189
+ ? markPrepared(facts)
190
+ : markClassName
191
+ ? hozoClasses(markClassName, facts)
192
+ : undefined,
193
+ props.lineStyle,
194
+ line.mark ? props[`${line.mark}Style`] : undefined,
195
+ ])
196
+ const tokens = line.tokens
197
+ const content = tokens.map((token) => token.text).join('')
198
+ const runs = drawnCodeTokens(tokens, theme)
199
+ return (
200
+ <View key={index} style={[{ flexDirection: 'row', minHeight: lineHeight }, lineBox]}>
201
+ {props.renderGutter?.(line, index)}
202
+ <Text
203
+ accessible
204
+ accessibilityLabel={line.mark ? `${labels[line.mark]}: ${content}` : content}
205
+ style={[
206
+ { fontFamily: 'monospace', fontSize, lineHeight },
207
+ text,
208
+ lineText,
209
+ // A line drawn in one style needs no nested Text: the run's style
210
+ // goes on the line itself, which is the same drawing (#1431).
211
+ runs.length === 1 ? runStyle(runs[0]) : undefined,
212
+ { flexGrow: 1, flexShrink: props.wrap ? 1 : 0, minWidth: 0 },
213
+ ]}
214
+ >
215
+ {runs.length === 1
216
+ ? runs[0]?.text
217
+ : runs.map((run, at) => (
218
+ <Text key={at} style={runStyle(run)}>
219
+ {run.text}
220
+ </Text>
221
+ ))}
222
+ </Text>
223
+ </View>
224
+ )
225
+ }
226
+ return {
227
+ lines,
228
+ style: [box, props.wrap ? { alignSelf: 'stretch', minWidth: 0 } : undefined],
229
+ renderLine,
230
+ }
231
+ }
232
+
233
+ export function CodeLines(props: CodeLinesProps) {
234
+ const { lines, style, renderLine } = useCodeLineRows(props)
235
+ return <View style={style}>{lines.map(renderLine)}</View>
236
+ }