notesoup 0.59.1 → 0.59.2

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.
@@ -0,0 +1,189 @@
1
+ // Manually mirrored between square and pi-context (notesoup):
2
+ // plugins/paseo/client/markdown-core.tsx. Keep both copies byte-identical.
3
+ // Mechanics only: palettes, attribution and preview controls belong to the adapters.
4
+ import type { ReactNode } from "react";
5
+ import { Linking, ScrollView, Text, View, type TextStyle, type ViewStyle } from "react-native";
6
+ import { Lexer, type Token, type Tokens } from "marked";
7
+
8
+ export interface MarkdownStyles {
9
+ text: TextStyle;
10
+ strong: TextStyle;
11
+ em: TextStyle;
12
+ del: TextStyle;
13
+ link: TextStyle;
14
+ // Keep nested Text backgrounds square; rounded inline backgrounds are unreliable on iOS.
15
+ inlineCode: TextStyle;
16
+ heading: TextStyle;
17
+ quoteText: TextStyle;
18
+ codeText: TextStyle;
19
+ bullet: TextStyle;
20
+ tableCell: TextStyle;
21
+ codeBlock: ViewStyle;
22
+ codeContent: ViewStyle;
23
+ quote: ViewStyle;
24
+ separator: ViewStyle;
25
+ list: ViewStyle;
26
+ listRow: ViewStyle;
27
+ listItem: ViewStyle;
28
+ table: ViewStyle;
29
+ tableHead: ViewStyle;
30
+ tableRow: ViewStyle;
31
+ }
32
+
33
+ /** Children of a token, if it has any: `Token` is a union, so the optional field needs one cast. */
34
+ const children = (node: Token | { tokens?: Token[] }): Token[] => (node as { tokens?: Token[] }).tokens ?? [];
35
+
36
+ const ENTITIES: Record<string, string> = {
37
+ lt: "<", gt: ">", quot: '"', apos: "'", amp: "&", nbsp: "\u00a0", mdash: "—", ndash: "–",
38
+ };
39
+ const HTML_BR = /^<br\s*\/?>$/i;
40
+ const SAFE_LINK = /^(?:https?:|mailto:)/i;
41
+
42
+ function unescape(text: string): string {
43
+ return text.replace(/&(?:#(\d+)|#x([0-9a-fA-F]+)|([a-zA-Z0-9]+));/g, (raw, dec?: string, hex?: string, named?: string) => {
44
+ if (dec !== undefined || hex !== undefined) {
45
+ const code = Number.parseInt((dec ?? hex)!, dec !== undefined ? 10 : 16);
46
+ return code > 0 && code <= 0x10ffff && (code < 0xd800 || code > 0xdfff) ? String.fromCodePoint(code) : raw;
47
+ }
48
+ return ENTITIES[named!] ?? raw;
49
+ });
50
+ }
51
+
52
+ function linkPress(href: string, openLinks: boolean): (() => void) | undefined {
53
+ const url = unescape(href);
54
+ return openLinks && SAFE_LINK.test(url) ? () => { void Promise.resolve(Linking.openURL(url)).catch(() => {}); } : undefined;
55
+ }
56
+
57
+ function inlinePlain(tokens: Token[]): string {
58
+ return tokens.map(token => {
59
+ switch (token.type) {
60
+ case "checkbox": return "";
61
+ case "br": return "\n";
62
+ case "html": return HTML_BR.test(token.raw.trim()) ? "\n" : token.raw;
63
+ case "codespan": return token.text;
64
+ case "image": return inlinePlain(children(token)) || token.text || "[image]";
65
+ default: {
66
+ const inline = token as Tokens.Generic;
67
+ return inline.tokens !== undefined ? inlinePlain(inline.tokens) : unescape(inline.text ?? inline.raw);
68
+ }
69
+ }
70
+ }).join("");
71
+ }
72
+
73
+ function cellWidth(cell: Tokens.TableCell | undefined): number {
74
+ if (!cell) return 56;
75
+ const widest = Math.max(...inlinePlain(children(cell)).split("\n").map(line =>
76
+ [...line].reduce((sum, ch) => sum + (ch.codePointAt(0)! > 0x2e7f ? 14 : 7.5), 16)));
77
+ return Math.min(240, Math.max(56, widest));
78
+ }
79
+
80
+ /** Inline runs nest inside their block's Text, so they carry only what differs from it. */
81
+ export function renderInlines(tokens: Token[], styles: MarkdownStyles, prefix: string, openLinks = false): ReactNode[] {
82
+ return tokens.map((token, index) => {
83
+ const key = `${prefix}-${index}`;
84
+ const nested = (style?: TextStyle, onPress?: () => void): ReactNode => (
85
+ <Text key={key} style={style} onPress={onPress}>{renderInlines(children(token), styles, key, openLinks)}</Text>
86
+ );
87
+ switch (token.type) {
88
+ case "checkbox": return null;
89
+ case "strong": return nested(styles.strong);
90
+ case "em": return nested(styles.em);
91
+ case "del": return nested(styles.del);
92
+ case "link": return nested(styles.link, linkPress((token as Tokens.Link).href, openLinks));
93
+ case "codespan": return <Text key={key} style={styles.inlineCode}>{token.text}</Text>;
94
+ case "br": return "\n";
95
+ case "html": return HTML_BR.test(token.raw.trim()) ? "\n" : token.raw;
96
+ case "image": {
97
+ const image = token as Tokens.Image;
98
+ const label = inlinePlain(children(image)) || image.text || "[image]";
99
+ return <Text key={key} style={styles.link} onPress={linkPress(image.href, openLinks)}>{label}</Text>;
100
+ }
101
+ default: {
102
+ const inline = token as Tokens.Generic;
103
+ if (inline.tokens !== undefined) return nested();
104
+ return unescape(inline.text ?? inline.raw);
105
+ }
106
+ }
107
+ });
108
+ }
109
+
110
+ export function renderBlocks(tokens: Token[], styles: MarkdownStyles, prefix: string, textStyle?: TextStyle, openLinks = true): ReactNode[] {
111
+ const visible = tokens.filter(token =>
112
+ token.type !== "space" && token.type !== "checkbox" && token.type !== "def"
113
+ && !(token.type === "html" && HTML_BR.test(token.raw.trim())));
114
+ return visible.map((token, index) => {
115
+ const key = `${prefix}-${index}`;
116
+ switch (token.type) {
117
+ case "html":
118
+ return <Text key={key} selectable style={[styles.text, textStyle]}>{token.raw}</Text>;
119
+ case "hr":
120
+ return <View key={key} style={styles.separator} />;
121
+ case "code":
122
+ return (
123
+ <ScrollView key={key} horizontal style={styles.codeBlock} contentContainerStyle={styles.codeContent}>
124
+ <Text selectable style={styles.codeText}>{token.text}</Text>
125
+ </ScrollView>
126
+ );
127
+ case "heading": {
128
+ // Headings sit closer to the section they introduce than to whatever preceded them.
129
+ const rhythm = { marginTop: index > 0 ? 4 : 0, marginBottom: index < visible.length - 1 ? -2 : 0 };
130
+ return (
131
+ <Text key={key} selectable style={[styles.text, textStyle, styles.heading, rhythm]}>
132
+ {renderInlines(children(token), styles, key, openLinks)}
133
+ </Text>
134
+ );
135
+ }
136
+ case "blockquote":
137
+ return <View key={key} style={styles.quote}>{renderBlocks(children(token), styles, key, styles.quoteText, openLinks)}</View>;
138
+ case "list": {
139
+ const list = token as Tokens.List;
140
+ const start = typeof list.start === "number" ? list.start : 1;
141
+ return (
142
+ <View key={key} style={styles.list}>
143
+ {list.items.map((item, itemIndex) => (
144
+ <View key={`${key}-${itemIndex}`} style={styles.listRow}>
145
+ <Text style={styles.bullet}>
146
+ {item.task ? (item.checked === true ? "☑" : "☐") : list.ordered ? `${start + itemIndex}.` : "•"}
147
+ </Text>
148
+ <View style={styles.listItem}>{renderBlocks(children(item), styles, `${key}-${itemIndex}`, textStyle, openLinks)}</View>
149
+ </View>
150
+ ))}
151
+ </View>
152
+ );
153
+ }
154
+ case "table": {
155
+ const table = token as Tokens.Table;
156
+ const rows = [table.header, ...table.rows];
157
+ // Columns size to their widest cell (within reason) and the table scrolls sideways
158
+ // on narrow screens instead of crushing every cell to a sliver.
159
+ const widths = table.header.map((_, column) => Math.max(...rows.map(cells => cellWidth(cells[column]))));
160
+ return (
161
+ <ScrollView key={key} horizontal>
162
+ <View style={styles.table}>
163
+ {rows.map((cells, rowIndex) => (
164
+ <View key={`${key}-${rowIndex}`} style={rowIndex === 0 ? [styles.tableRow, styles.tableHead, { borderTopWidth: 0 }] : styles.tableRow}>
165
+ {cells.map((cell, cellIndex) => (
166
+ <Text
167
+ key={`${key}-${rowIndex}-${cellIndex}`}
168
+ selectable
169
+ style={[styles.text, textStyle, styles.tableCell, { width: widths[cellIndex], textAlign: table.align[cellIndex] ?? "left" },
170
+ rowIndex === 0 ? styles.strong : undefined]}
171
+ >{renderInlines(children(cell), styles, `${key}-${rowIndex}-${cellIndex}`, openLinks)}</Text>
172
+ ))}
173
+ </View>
174
+ ))}
175
+ </View>
176
+ </ScrollView>
177
+ );
178
+ }
179
+ default: {
180
+ const block = token as Tokens.Generic;
181
+ return (
182
+ <Text key={key} selectable style={[styles.text, textStyle]}>
183
+ {renderInlines(block.tokens ?? Lexer.lexInline(block.text ?? block.raw), styles, key, openLinks)}
184
+ </Text>
185
+ );
186
+ }
187
+ }
188
+ });
189
+ }
@@ -1,160 +1,63 @@
1
- import { Lexer, lexer, type Token, type Tokens } from "marked";
2
- import type { ReactNode } from "react";
1
+ import { useMemo } from "react";
2
+ import { Lexer, lexer } from "marked";
3
+ import { renderBlocks, renderInlines, type MarkdownStyles } from "./markdown-core.tsx";
3
4
  import { StyleSheet, Text, View, type TextStyle, type ViewStyle } from "react-native";
4
- import { MONO } from "./paper-card.tsx";
5
5
  import type { PaperPalette } from "./paper-palette.ts";
6
+ import type { Typography } from "./typography.ts";
6
7
 
7
- type Styles = {
8
- block: ViewStyle;
9
- text: TextStyle; muted: TextStyle; strong: TextStyle; em: TextStyle; del: TextStyle;
10
- codespan: TextStyle; link: TextStyle; heading: TextStyle; quoteText: TextStyle;
11
- code: TextStyle; marker: TextStyle; tableCell: TextStyle;
12
- quote: ViewStyle; hr: ViewStyle; list: ViewStyle; listItem: ViewStyle;
13
- table: ViewStyle; tableRow: ViewStyle;
14
- };
8
+ type Styles = MarkdownStyles & { block: ViewStyle; muted: TextStyle };
15
9
 
16
- function markdownStyles(paper: PaperPalette): Styles {
10
+ function markdownStyles(paper: PaperPalette, type: Typography): Styles {
11
+ const hairline = { borderWidth: StyleSheet.hairlineWidth, borderColor: paper.edge };
17
12
  return {
18
13
  block: { gap: 8 },
19
- text: { color: paper.ink, fontSize: 12, lineHeight: 19 },
20
- muted: { color: paper.inkMuted, fontSize: 12, lineHeight: 19 },
14
+ text: { ...type.body, color: paper.ink },
15
+ muted: { ...type.body, color: paper.inkMuted },
21
16
  strong: { fontWeight: "600" },
22
- em: { color: paper.inkMuted, fontStyle: "italic" },
17
+ em: { fontStyle: "italic" },
23
18
  del: { color: paper.inkMuted, textDecorationLine: "line-through" },
24
- codespan: { fontFamily: MONO, fontSize: 12, backgroundColor: paper.crumpled },
19
+ // No borderRadius here: nested rounded Text backgrounds paint a wrapped slab on iOS Fabric.
20
+ // A faint ink wash keeps flush glyph edges gentle and stays visible on crumpled paper too.
21
+ inlineCode: { ...type.inlineCode, backgroundColor: `${paper.ink}10` },
25
22
  link: { color: paper.added, textDecorationLine: "underline" },
26
- heading: { fontWeight: "600" },
27
- quote: { borderLeftWidth: 2, borderLeftColor: paper.edge, paddingLeft: 10, gap: 4, marginTop: 4 },
28
- quoteText: { color: paper.inkMuted, fontSize: 12, lineHeight: 19 },
29
- code: {
30
- fontFamily: MONO, fontSize: 12, lineHeight: 18, color: paper.ink,
31
- backgroundColor: paper.crumpled, borderRadius: 3, paddingVertical: 6, paddingHorizontal: 8,
32
- },
33
- hr: { height: StyleSheet.hairlineWidth, backgroundColor: paper.edge },
34
- list: { gap: 8 },
35
- listItem: { flexDirection: "row" },
36
- marker: { color: paper.inkMuted, minWidth: 14, paddingRight: 4 },
37
- table: { gap: 2 },
38
- tableRow: { flexDirection: "row", gap: 8 },
39
- tableCell: { flex: 1 },
23
+ heading: { ...type.base, fontWeight: "600", color: paper.ink, letterSpacing: -0.1 },
24
+ quote: { borderLeftWidth: 2, borderLeftColor: paper.edge, paddingLeft: 10, gap: 4 },
25
+ quoteText: { color: paper.inkMuted },
26
+ codeBlock: { ...hairline, backgroundColor: paper.crumpled, borderRadius: 4 },
27
+ codeContent: { paddingVertical: 6, paddingHorizontal: 8 },
28
+ codeText: { ...type.code, color: paper.ink },
29
+ separator: { height: StyleSheet.hairlineWidth, backgroundColor: paper.edge, marginVertical: 2 },
30
+ list: { gap: 4 },
31
+ listRow: { flexDirection: "row" },
32
+ listItem: { flex: 1, gap: 4 },
33
+ bullet: { ...type.body, color: paper.inkMuted, minWidth: 18, paddingRight: 6,
34
+ textAlign: "right", fontVariant: ["tabular-nums"] },
35
+ table: { ...hairline, borderRadius: 4, overflow: "hidden" },
36
+ tableHead: { backgroundColor: paper.crumpled },
37
+ tableRow: { flexDirection: "row", borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: paper.edge },
38
+ tableCell: { paddingVertical: 4, paddingHorizontal: 8 },
40
39
  };
41
40
  }
42
41
 
43
- /** Inline tokens keep their nesting: strong/em/del/link hold the tokens they wrap. */
44
- function renderInlines(tokens: Token[] | undefined, styles: Styles, keyPrefix: string): ReactNode[] {
45
- if (!tokens) return [];
46
- return tokens.map((token, index) => {
47
- const key = `${keyPrefix}.${index}`;
48
- switch (token.type) {
49
- case "strong":
50
- return <Text key={key} style={styles.strong}>{renderInlines(token.tokens, styles, key)}</Text>;
51
- case "em":
52
- return <Text key={key} style={styles.em}>{renderInlines(token.tokens, styles, key)}</Text>;
53
- case "del":
54
- return <Text key={key} style={styles.del}>{renderInlines(token.tokens, styles, key)}</Text>;
55
- case "codespan":
56
- return <Text key={key} style={styles.codespan}>{token.text}</Text>;
57
- case "link":
58
- return <Text key={key} style={styles.link}>{renderInlines(token.tokens, styles, key)}</Text>;
59
- case "br":
60
- return "\n";
61
- case "image":
62
- return <Text key={key} style={styles.link}>{token.text}</Text>;
63
- default: {
64
- const nested = (token as Tokens.Generic).tokens;
65
- if (nested?.length) return <Text key={key}>{renderInlines(nested, styles, key)}</Text>;
66
- const { text } = token as Tokens.Text;
67
- return text ?? token.raw;
68
- }
69
- }
70
- });
71
- }
72
-
73
- function renderListItem(item: Tokens.ListItem, marker: string, key: string, styles: Styles, textStyle: TextStyle): ReactNode {
74
- return (
75
- <View key={key} style={styles.listItem}>
76
- <Text style={[styles.marker, textStyle]}>{item.task ? (item.checked ? "☑" : "☐") : marker}</Text>
77
- <View style={{ flex: 1, gap: 4 }}>{renderBlocks(item.tokens, styles, key, textStyle)}</View>
78
- </View>
79
- );
80
- }
81
-
82
- function renderBlocks(tokens: Token[] | undefined, styles: Styles, keyPrefix: string, textStyle: TextStyle): ReactNode[] {
83
- if (!tokens) return [];
84
- return tokens.map((token, index) => {
85
- const key = `${keyPrefix}.${index}`;
86
- switch (token.type) {
87
- case "space":
88
- case "checkbox":
89
- case "def":
90
- return null;
91
- case "hr":
92
- return <View key={key} style={styles.hr} />;
93
- case "code":
94
- return <Text key={key} selectable style={styles.code}>{token.text}</Text>;
95
- case "heading":
96
- return <Text key={key} selectable style={[textStyle, styles.heading,
97
- { marginTop: index === 0 ? 2 : token.depth === 1 ? 2 : 6 }]}>{renderInlines(token.tokens, styles, key)}</Text>;
98
- case "blockquote":
99
- return <View key={key} style={styles.quote}>{renderBlocks(token.tokens, styles, key, styles.quoteText)}</View>;
100
- case "list": {
101
- const list = token as Tokens.List;
102
- const start = typeof list.start === "number" ? list.start : 1;
103
- return (
104
- <View key={key} style={styles.list}>
105
- {list.items.map((item, itemIndex) =>
106
- renderListItem(item, list.ordered ? `${start + itemIndex}.` : "•", `${key}.${itemIndex}`, styles, textStyle))}
107
- </View>
108
- );
109
- }
110
- case "table": {
111
- const table = token as Tokens.Table;
112
- return (
113
- <View key={key} style={styles.table}>
114
- {[table.header, ...table.rows].map((row, rowIndex) => (
115
- <View key={`${key}.${rowIndex}`} style={styles.tableRow}>
116
- {row.map((cell, cellIndex) => (
117
- <Text
118
- key={`${key}.${rowIndex}.${cellIndex}`}
119
- selectable
120
- style={[textStyle, styles.tableCell, { textAlign: cell.align ?? "left" }, cell.header && styles.strong]}
121
- >
122
- {renderInlines(cell.tokens, styles, `${key}.${rowIndex}.${cellIndex}`)}
123
- </Text>
124
- ))}
125
- </View>
126
- ))}
127
- </View>
128
- );
129
- }
130
- default: {
131
- const generic = token as Tokens.Generic;
132
- return (
133
- <Text key={key} selectable style={textStyle}>
134
- {generic.tokens?.length ? renderInlines(generic.tokens, styles, key) : generic.text ?? generic.raw}
135
- </Text>
136
- );
137
- }
138
- }
139
- });
140
- }
141
-
142
- export function NoteInline({ text, paper, color, numberOfLines }: {
42
+ export function NoteInline({ text, paper, type, color, numberOfLines }: {
143
43
  text: string;
144
44
  paper: PaperPalette;
45
+ type: Typography;
145
46
  color?: string;
146
47
  numberOfLines?: number;
147
48
  }) {
148
- const styles = markdownStyles(paper);
49
+ const styles = useMemo(() => markdownStyles(paper, type), [paper, type]);
50
+ const tokens = useMemo(() => Lexer.lexInline(text), [text]);
149
51
  return (
150
52
  <Text numberOfLines={numberOfLines} style={{ ...styles.text, color: color ?? paper.ink }}>
151
- {renderInlines(Lexer.lexInline(text), styles, "inline")}
53
+ {renderInlines(tokens, styles, "inline")}
152
54
  </Text>
153
55
  );
154
56
  }
155
57
 
156
- export function NoteMarkdown({ text, paper, muted = false }: { text: string; paper: PaperPalette; muted?: boolean }) {
157
- const styles = markdownStyles(paper);
58
+ export function NoteMarkdown({ text, paper, type, muted = false }: { text: string; paper: PaperPalette; type: Typography; muted?: boolean }) {
59
+ const styles = useMemo(() => markdownStyles(paper, type), [paper, type]);
60
+ const tokens = useMemo(() => lexer(text), [text]);
158
61
  const textStyle = muted ? styles.muted : styles.text;
159
- return <View style={styles.block}>{renderBlocks(lexer(text), styles, "block", textStyle)}</View>;
62
+ return <View style={styles.block}>{renderBlocks(tokens, styles, "block", textStyle)}</View>;
160
63
  }
@@ -1,11 +1,12 @@
1
1
  import type { PluginTimelineItemProps } from "@getpaseo/plugin/client";
2
2
  import { Icon } from "@getpaseo/plugin/client/react-native";
3
- import { useState } from "react";
3
+ import { useMemo, useState } from "react";
4
4
  import { Pressable, ScrollView, Text, View } from "react-native";
5
5
  import { COLLAPSED_PREVIEW_MAX_CHARS, outputPreview, type NotesOp } from "../shared/notes-op.ts";
6
6
  import { NoteInline, NoteMarkdown } from "./markdown.tsx";
7
- import { MONO, PaperCard } from "./paper-card.tsx";
7
+ import { PaperCard } from "./paper-card.tsx";
8
8
  import { paperPalette, type PaperPalette } from "./paper-palette.ts";
9
+ import { typography, type Typography } from "./typography.ts";
9
10
 
10
11
  const OP_LABEL: Record<NotesOp["op"], string> = { read: "read", write: "wrote", update: "edited" };
11
12
  const OP_LABEL_RUNNING: Record<NotesOp["op"], string> = { read: "reading", write: "writing", update: "editing" };
@@ -15,7 +16,7 @@ function addedLine(diff: string): string | undefined {
15
16
  return /^\+.*/m.exec(diff)?.[0].replace(/^\+(?:\s*\d+\s+\+|\s*\d+)?\s?/, "");
16
17
  }
17
18
 
18
- function DiffBody({ diff, paper }: { diff: string; paper: PaperPalette }) {
19
+ function DiffBody({ diff, paper, style }: { diff: string; paper: PaperPalette; style: Typography["code"] }) {
19
20
  const runs: { color: string; lines: string[] }[] = [];
20
21
  for (const line of diff.split("\n")) {
21
22
  const color = line.startsWith("+") ? paper.added : line.startsWith("-") ? paper.removed : paper.inkMuted;
@@ -24,7 +25,7 @@ function DiffBody({ diff, paper }: { diff: string; paper: PaperPalette }) {
24
25
  else runs.push({ color, lines: [line] });
25
26
  }
26
27
  return (
27
- <Text selectable style={{ fontSize: 12, lineHeight: 18, fontFamily: MONO }}>
28
+ <Text selectable style={style}>
28
29
  {runs.map((run, index) => <Text key={index} style={{ color: run.color }}>{index > 0 ? "\n" : ""}{run.lines.join("\n")}</Text>)}
29
30
  </Text>
30
31
  );
@@ -33,6 +34,7 @@ function DiffBody({ diff, paper }: { diff: string; paper: PaperPalette }) {
33
34
  export function NotesOpCard({ item, layout, theme }: PluginTimelineItemProps<NotesOp>) {
34
35
  const [expanded, setExpanded] = useState(false);
35
36
  const paper = paperPalette(theme);
37
+ const type = useMemo(() => typography(theme), [theme]);
36
38
  const data = item.data;
37
39
  const title = data.status === "running" ? OP_LABEL_RUNNING[data.op] : OP_LABEL[data.op];
38
40
  const hasBody = Boolean(data.text || data.preview || data.diff);
@@ -51,30 +53,31 @@ export function NotesOpCard({ item, layout, theme }: PluginTimelineItemProps<Not
51
53
  style={({ pressed }) => ({ gap: 4, opacity: pressed && hasBody ? 0.7 : 1 })}
52
54
  >
53
55
  <View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
54
- <Text style={{ color: paper.inkMuted, fontSize: 12 }}>
56
+ <Text style={{ ...type.sm, color: paper.inkMuted }}>
55
57
  {data.crumpled ? "crumpled" : title}{data.status === "running" ? " …" : ""}
56
58
  </Text>
57
- <Text numberOfLines={1} style={{ color: data.crumpled ? paper.inkMuted : paper.ink, fontSize: 12, flex: 1, textDecorationLine: data.crumpled ? "line-through" : "none" }}>
59
+ <Text numberOfLines={1} style={{ ...type.base, color: data.crumpled ? paper.inkMuted : paper.ink, flex: 1, textDecorationLine: data.crumpled ? "line-through" : "none" }}>
58
60
  {data.address}
59
61
  </Text>
60
- {hasBody && <Icon name={expanded ? "ChevronUp" : "ChevronDown"} size={16} color={paper.inkMuted} />}
62
+ {hasBody && <Icon name={expanded ? "ChevronUp" : "ChevronDown"} size={12} color={paper.inkMuted} />}
61
63
  </View>
62
64
  {peek !== undefined && (
63
65
  <NoteInline
64
66
  text={`${data.diff !== undefined ? "+ " : ""}${outputPreview(peek, COLLAPSED_PREVIEW_MAX_CHARS).replace(/\s+/g, " ")}`}
65
67
  paper={paper}
68
+ type={type}
66
69
  color={data.diff !== undefined ? paper.added : paper.ink}
67
70
  numberOfLines={2}
68
71
  />
69
72
  )}
70
- {data.error !== undefined && <Text selectable style={{ color: paper.removed, fontSize: 12, lineHeight: 18 }}>{data.error}</Text>}
73
+ {data.error !== undefined && <Text selectable style={{ ...type.sm, color: paper.removed }}>{data.error}</Text>}
71
74
  </Pressable>
72
75
  {expanded && hasBody && (
73
76
  <ScrollView style={{ maxHeight: layout.compact ? 280 : 400, marginTop: 2, borderTopWidth: 1, borderTopColor: paper.edge }} contentContainerStyle={{ gap: 5, paddingTop: 8 }} nestedScrollEnabled>
74
- {data.text !== undefined && <NoteMarkdown text={outputPreview(data.text)} paper={paper} />}
75
- {data.preview !== undefined && <NoteMarkdown text={outputPreview(data.preview)} paper={paper} />}
76
- {data.diff !== undefined && <DiffBody diff={outputPreview(data.diff)} paper={paper} />}
77
- {data.renamedFrom !== undefined && <Text style={{ color: paper.inkMuted, fontSize: 12 }}>renamed from {data.renamedFrom}</Text>}
77
+ {data.text !== undefined && <NoteMarkdown text={outputPreview(data.text)} paper={paper} type={type} />}
78
+ {data.preview !== undefined && <NoteMarkdown text={outputPreview(data.preview)} paper={paper} type={type} />}
79
+ {data.diff !== undefined && <DiffBody diff={outputPreview(data.diff)} paper={paper} style={type.code} />}
80
+ {data.renamedFrom !== undefined && <Text style={{ ...type.sm, color: paper.inkMuted }}>renamed from {data.renamedFrom}</Text>}
78
81
  </ScrollView>
79
82
  )}
80
83
  </PaperCard>
@@ -1,9 +1,7 @@
1
1
  import type { ReactNode } from "react";
2
- import { Platform, StyleSheet, View } from "react-native";
2
+ import { StyleSheet, View } from "react-native";
3
3
  import type { PaperPalette } from "./paper-palette.ts";
4
4
 
5
- export const MONO = Platform.select({ ios: "Menlo", android: "monospace", default: "ui-monospace, Menlo, monospace" });
6
-
7
5
  function Tape({ paper }: { paper: PaperPalette }) {
8
6
  return (
9
7
  <View style={{
@@ -3,13 +3,14 @@ import { Text } from "react-native";
3
3
  import type { LastWord } from "../shared/last-word.ts";
4
4
  import { PaperCard } from "./paper-card.tsx";
5
5
  import { paperPalette } from "./paper-palette.ts";
6
+ import { typography } from "./typography.ts";
6
7
 
7
8
  export function StickyCard({ item, layout, theme }: PluginTimelineItemProps<LastWord>) {
8
9
  const paper = paperPalette(theme);
9
10
  const text = item.data.text.replace(/^\*You peel a sticky note off your forehead\.\*\n/, "");
10
11
  return (
11
12
  <PaperCard paper={paper} compact={layout.compact}>
12
- <Text selectable style={{ color: paper.ink, fontSize: 13, lineHeight: 19, flexShrink: 1 }}>{text}</Text>
13
+ <Text selectable style={{ ...typography(theme).body, color: paper.ink, flexShrink: 1 }}>{text}</Text>
13
14
  </PaperCard>
14
15
  );
15
16
  }
@@ -0,0 +1,24 @@
1
+ import type { PluginTheme } from "@getpaseo/plugin";
2
+ import { Platform } from "react-native";
3
+
4
+ type ThemeTypography = {
5
+ fontSize?: Partial<Record<"sm" | "base" | "code", number>>;
6
+ fontFamily?: Partial<Record<"ui" | "mono", string>>;
7
+ };
8
+
9
+ const MONO = Platform.select({ ios: "Menlo", android: "monospace", default: "ui-monospace, Menlo, monospace" });
10
+ const lineHeight = (size: number, ratio: number) => Math.round(size * ratio * 2) / 2;
11
+
12
+ export function typography(theme: PluginTheme) {
13
+ // The host can supply these roles before the SDK exposes them (#6600).
14
+ const { fontSize, fontFamily } = (theme as PluginTheme & { typography?: ThemeTypography }).typography ?? {};
15
+ const text = (size: number) => ({ fontSize: size, lineHeight: lineHeight(size, 1.5), fontFamily: fontFamily?.ui });
16
+ const size = fontSize?.code ?? 13;
17
+ const inlineCode = { fontSize: size, fontFamily: fontFamily?.mono ?? MONO };
18
+ return {
19
+ sm: text(fontSize?.sm ?? 11.5), base: text(fontSize?.base ?? 13), body: text(size),
20
+ inlineCode, code: { ...inlineCode, lineHeight: lineHeight(size, 1.4) },
21
+ };
22
+ }
23
+
24
+ export type Typography = ReturnType<typeof typography>;
@@ -0,0 +1,75 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { readFileSync } from "node:fs";
4
+ import { createRequire } from "node:module";
5
+ import ts from "typescript";
6
+
7
+ // Exercise the actual renderer with RN host primitives, not a native layout emulator.
8
+ const require = createRequire(import.meta.url);
9
+ const opened: string[] = [];
10
+ const source = readFileSync(new URL("../client/markdown-core.tsx", import.meta.url), "utf8");
11
+ const { outputText } = ts.transpileModule(source, {
12
+ compilerOptions: { jsx: ts.JsxEmit.ReactJSX, module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
13
+ });
14
+ const compiled = { exports: {} as any };
15
+ new Function("require", "module", "exports", outputText)(
16
+ (id: string) => id === "react-native"
17
+ ? { Text: "Text", View: "View", ScrollView: "ScrollView", Linking: { openURL: (url: string) => { opened.push(url); return Promise.resolve(); } } }
18
+ : require(id),
19
+ compiled, compiled.exports,
20
+ );
21
+ const { renderBlocks, renderInlines } = compiled.exports;
22
+ const { lexer, Lexer } = require("marked");
23
+ const styles = new Proxy({}, { get: () => ({}) });
24
+ function elements(node: any): any[] {
25
+ if (Array.isArray(node)) return node.flatMap(elements);
26
+ if (!node || typeof node !== "object") return [];
27
+ return [node, ...elements(node.props?.children)];
28
+ }
29
+ function text(node: any): string {
30
+ if (Array.isArray(node)) return node.map(text).join("");
31
+ if (node == null) return "";
32
+ return typeof node === "object" ? text(node.props?.children) : String(node);
33
+ }
34
+ const render = (markdown: string, openLinks?: boolean) => renderBlocks(lexer(markdown), styles, "test", undefined, openLinks);
35
+
36
+ test("inline nesting, entities, br and empty-alt images render cleanly", () => {
37
+ const result = renderInlines(Lexer.lexInline("**bold *nested*** &mdash; &#65; `a < b & c`<br>![](https://example.com/a.png)"), styles, "inline");
38
+ assert.equal(text(result), "bold nested — A a < b & c\n[image]");
39
+ });
40
+
41
+ test("ordered starts, tight and loose task markers survive without duplicate checkboxes", () => {
42
+ assert.match(text(render("3. third\n4. fourth")), /3\.third4\.fourth/);
43
+ const tight = text(render("- [x] done\n- [ ] pending\n - child"));
44
+ assert.match(tight, /☑done/);
45
+ assert.match(tight, /☐pending/);
46
+ assert.match(tight, /•child/);
47
+ const loose = text(render("- [x] first\n\n- [ ] second"));
48
+ assert.equal(loose, "☑first☐second");
49
+ });
50
+
51
+ test("safe links open only when enabled and block unsafe schemes", () => {
52
+ opened.length = 0;
53
+ const disabled = elements(render("[ok](https://example.com?a=1&amp;b=2)", false)).find(n => typeof n.props?.onPress === "function");
54
+ assert.equal(disabled, undefined);
55
+ const inlineDefault = elements(renderInlines(Lexer.lexInline("[peek](https://example.com)"), styles, "peek")).find(n => typeof n.props?.onPress === "function");
56
+ assert.equal(inlineDefault, undefined);
57
+
58
+ const active = elements(render("[ok](https://example.com?a=1&amp;b=2) [bad](javascript:alert(1)) [mail](mailto:hi@example.com)"));
59
+ const handlers = active.filter(n => typeof n.props?.onPress === "function");
60
+ assert.equal(handlers.length, 2);
61
+ handlers.forEach(n => n.props.onPress());
62
+ assert.deepEqual(opened, ["https://example.com?a=1&b=2", "mailto:hi@example.com"]);
63
+ });
64
+
65
+ test("tables size by visible CJK/link text and stay horizontally scrollable", () => {
66
+ const md = "# Heading\n\n| [详情](https://very-long.example.com/path/to/doc) | 状态说明 |\n| :--- | ---: |\n| x<br>y | 值 |\n\n```\n&amp;\n```";
67
+ const nodes = elements(render(md));
68
+ assert.equal(nodes.filter(n => n.type === "ScrollView" && n.props.horizontal).length, 2);
69
+ assert.ok(nodes.filter(n => n.type === "Text" && n.props.selectable !== undefined).every(n => n.props.selectable));
70
+ const headerCells = nodes.filter(n => Array.isArray(n.props.style) && n.props.style.some((s: any) => typeof s?.width === "number")).slice(0, 2);
71
+ const [linkColWidth, cjkColWidth] = headerCells.map(n => n.props.style.find((s: any) => typeof s?.width === "number").width);
72
+ assert.ok(linkColWidth < 80, `expected visible link text width, got ${linkColWidth}`);
73
+ assert.ok(cjkColWidth > 64, `expected CJK header width above ASCII floor, got ${cjkColWidth}`);
74
+ assert.ok(nodes.some(n => n.type === "Text" && text(n) === "&amp;"));
75
+ });
@@ -1,8 +1,13 @@
1
1
  /** Claude's persisted main transcript -> the shared history projection. No inference-context API. */
2
- import { readFile } from "node:fs/promises";
2
+ import { readFile, stat } from "node:fs/promises";
3
+ import { setTimeout as sleep } from "node:timers/promises";
3
4
  import { isDeepStrictEqual } from "node:util";
4
5
  import { contentText, projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection } from "./history.js";
5
6
 
7
+ class UnpersistedClaudeHead extends Error {
8
+ constructor() { super("Claude history active head is not persisted yet; retry after the transcript write"); }
9
+ }
10
+
6
11
  type Row = Record<string, unknown>;
7
12
  type WindowPosition = { ordinal: number } | { unknownAncestor: string };
8
13
  type Version = { row: Row; ancestorUuid?: string; ancestor?: Version; position?: WindowPosition };
@@ -180,7 +185,7 @@ function claudeHistoryFromRows(rows: Row[], source: Omit<ClaudeHistorySource, "t
180
185
  return version.position!;
181
186
  }
182
187
  if (!source.headUuid) throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
183
- if (!nodes.has(source.headUuid)) throw new Error("Claude history active head is not persisted yet; retry after the transcript write");
188
+ if (!nodes.has(source.headUuid)) throw new UnpersistedClaudeHead();
184
189
 
185
190
  // The inference tree uses the latest rewritten parents. At a compact boundary the logical
186
191
  // parent and preserved segments use ORIGINAL ancestry: the old context is still history.
@@ -299,7 +304,29 @@ export function offlineClaudeHistoryFromJsonl(text: string, sessionId: string):
299
304
  return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
300
305
  }
301
306
 
302
- export async function readClaudeHistory(source: ClaudeHistorySource): Promise<ClaudeHistoryProjection> {
307
+ export async function readClaudeHistory(source: ClaudeHistorySource, { waitForHead = false } = {}): Promise<ClaudeHistoryProjection> {
303
308
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string") throw new Error("Claude history transcript_path is unavailable");
304
- return claudeHistoryFromJsonl(await readFile(source.transcriptPath, "utf8"), source);
309
+ const snapshot = { ...source };
310
+ const read = async () => claudeHistoryFromJsonl(await readFile(snapshot.transcriptPath, "utf8"), snapshot);
311
+ if (!waitForHead || !snapshot.headUuid) return read();
312
+ const revision = async () => {
313
+ const { dev, ino, size, mtimeNs, ctimeNs } = await stat(snapshot.transcriptPath, { bigint: true });
314
+ return `${dev}:${ino}:${size}:${mtimeNs}:${ctimeNs}`;
315
+ };
316
+ let seen = await revision();
317
+ try { return await read(); }
318
+ catch (error) {
319
+ if (!(error instanceof UnpersistedClaudeHead)) throw error;
320
+ // A kept append can reach the tool before its disk write. Only retry that same
321
+ // head, and only reparse on file changes. Never fall back to an offline leaf.
322
+ for (const delay of [50, 100, 200, 300, 350]) {
323
+ await sleep(delay);
324
+ const current = await revision();
325
+ if (current === seen) continue;
326
+ seen = current;
327
+ try { return await read(); }
328
+ catch (retry) { if (!(retry instanceof UnpersistedClaudeHead)) throw retry; }
329
+ }
330
+ throw error;
331
+ }
305
332
  }