Right-to-left for Claude Code mods: one file to copy into a mod that orders Hebrew and Arabic right on every surface, aligns wrapped text right, draws…

Right-to-left for Claude Code mods. One file you copy into a mod, so Hebrew and Arabic read right in a pane, a band or a status line.
A mod draws with Claude Code's own elements. On the desktop app every element is laid out left to right, so a line that mixes Hebrew with English or numbers comes out scrambled, a long line wraps starting at the left, and Markdown is both. On the macOS terminals Claude Code prints Hebrew in stored order, so it reads reversed. The kit fixes each of these:
לבקש מ-Claude: 3 בקשות, 10:00–12:00 reads right, in text and in button labels.k.md() draws headings, paragraphs, nested lists, quotes and tables with the pieces above.Svg.TERM_PROGRAM=vscode or WT_SESSION set), pass { terminal: 'logical' }, or it is reversed twice. The gallery reads both variables when the session starts and does this itself.claude plugin install rtl-kit@bar-mods
The plugin brings a skill, rtl-kit, that copies hooks/rtl.tsx into the mod you are building and uses it (with Read and Write: a shell cp out of ~/.claude/ is refused). By hand:
cp ~/.claude/plugins/marketplaces/bar-mods/rtl-kit/hooks/rtl.tsx <your-mod>/hooks/rtl.tsx
import { kit } from './rtl'
on('ui.render', { component: 'Pane', requestId: 'mine' }, async ($, e) => {
const k = kit($.ui.resolve(e), e)
return k.col('page', [
k.heading('h', 'שלום'),
k.para('p', 'טקסט ארוך בעברית עם Claude באמצע, שעובר כמה שורות ונשאר מיושר לימין.'),
k.row('buttons', [k.primary('ok', 'לאשר', () => approve($)), k.action('no', 'לדחות', () => decline($))]),
])
})
The copied file has no run-time imports and takes no $, so the mod needs nothing else installed. Re-copy it to upgrade; its first line names the version.
/rtl-gallery opens a gallery of every piece on the current surface, and a ruler to see how many characters fit a line.
Nothing. The gallery draws, remembers which tab is open, reads Claude Code's theme setting, and reads TERM_PROGRAM and WT_SESSION to know whether Claude Code orders the terminal's text itself. No files, processes, network or model calls. The copied rtl.tsx makes no calls at all.
From claude plugin validate:
session.start, command.run{command=rtl-gallery}, ui.render{component=Pane, requestId=rtl-kit}$.command.register, $.config.list, $.env.get, $.state.get, $.state.set, $.ui.open, $.ui.resolveTERM_PROGRAM, WT_SESSIONClaude Code 2.1.300 gave Text a dir prop: dir="rtl" sets the base direction, and where Claude Code orders the letters itself (VS Code's terminal, Windows Terminal) the rows also sit flush right. It does not replace the kit yet:
dir. The kit is the desktop's answer until the app moves; then dir on the desktop gets measured.dir changes nothing there (Claude Code leaves the order to the terminal), so the kit's visual order is still what makes Hebrew read right.WT_SESSION set or TERM_PROGRAM=vscode; plain conhost sets neither), so use { terminal: 'logical' } there, and dir="rtl" on a Text once every engine you target has it.charsPerColumn changes it.theme setting describes the terminal, not the desktop app, so SVG on the desktop follows the system's colour scheme.Looked at in the desktop app's Code tab, every gallery tab. On the terminal, the gallery was read off the terminal buffer with TERM_PROGRAM=vscode (Claude Code's order) and without it (the kit's), and the tests cover both, Windows Terminal's WT_SESSION too. The VS Code extension's panel and the phone use the desktop's path and have not been looked at yet. In claude -p and the SDK its hooks run and nothing draws.
Tested on Claude Code 2.1.289; tests re-run on 2.1.295, 2.1.300 and 2.1.301, and the terminal path read on 2.1.301 (2026-10-16).
hooks/register.tsx 172 lines1// rtl-kit's demo: /rtl-gallery opens a gallery of every piece of the kit on this surface, and a ruler
2// to measure how many characters fit a line. The kit itself is ./rtl.tsx, the file a mod copies.
3import { atom, read, update } from 'claude-code'
4import type { Register } from 'claude-code'
5
6import type { RtlKitDemo, RtlKitTerminal } from '../types'
7import { asStored, kit, schemeOf, svgHeader, svgTimeline, visual } from './rtl'
8
9const PANE = 'rtl-kit'
10const demo = atom({ plugin: 'rtl-kit', key: 'demo' } as const, { section: 'text', pressed: null } as RtlKitDemo)
11// Who orders right-to-left text on the terminal: the kit ('visual') or Claude Code ('logical').
12const terminal = atom({ plugin: 'rtl-kit', key: 'terminal' } as const, 'visual' as RtlKitTerminal)
13
14const SECTIONS = [
15 { id: 'text', label: 'טקסט' },
16 { id: 'parts', label: 'רכיבים' },
17 { id: 'md', label: 'Markdown' },
18 { id: 'svg', label: 'SVG' },
19 { id: 'terminal', label: 'טרמינל' },
20 { id: 'ruler', label: 'סרגל' },
21]
22
23// Invented sample text only.
24const MIXED = 'לבקש מ-Claude: 3 בקשות, 10:00–12:00'
25const LONG = 'פסקה ארוכה בעברית שעוברת כמה שורות: כל שורה צריכה להתחיל בצד ימין, גם כשיש בה מילה באנגלית כמו Claude, תאריך כמו 7.10.2026, או מספר כמו 42. בלי הערכה, השורה השנייה מתחילה משמאל.'
26const ARABIC = 'مرحبا: هذا سطر بالعربية مع Claude و 3 أرقام.'
27const SAMPLE_MD = `# נוהל לדוגמה
28
29פסקה ראשונה עם **הדגשה**, [קישור](https://example.com) ו-\`קוד\`, שמספיק ארוכה כדי לעבור שורה בחלונית צרה.
30
31## שלבים
32
331. לפתוח את החדר
342. לבדוק את הציוד:
35 - מגבות
36 - חיטוי
373. לסגור ביומן
38
39> הערה: זה ציטוט, והוא נראה ככרטיס.
40
41| פריט | מחיר | הערות |
42|---|---|---|
43| טיפול לדוגמה | 100 ₪ | כולל מע"מ |
44| מוצר \\| מיוחד | 25 ₪ | |
45`
46
47export const register: Register = on => {
48 on('session.start', async ($, e, next) => {
49 // Not /rtl-kit: the plugin's skill, rtl-kit, holds that name (a register refuses it).
50 await $.command.register({ name: 'rtl-gallery', description: 'Open the RTL kit gallery: every piece of the kit on this surface' })
51 // Claude Code's own test (2.1.300): it reorders in Windows Terminal and VS Code's terminal, so
52 // the kit computing the visual order there too would reverse it twice.
53 const engineOrders = (await $.env.get('WT_SESSION')) !== undefined || (await $.env.get('TERM_PROGRAM')) === 'vscode'
54 await update($, terminal, () => (engineOrders ? 'logical' : 'visual'))
55 return next(e)
56 })
57
58 // Opened without `focus`: a pane holding the keyboard can hold back queued prompts.
59 on('command.run', { command: 'rtl-gallery' }, async $ => {
60 const r = await $.ui.open({ id: PANE, title: 'rtl-kit', columns: 200 })
61 return { text: r.isPlaced ? 'rtl-kit is open.' : `rtl-kit did not open: ${r.reason}` }
62 })
63
64 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
65 const el = $.ui.resolve(e)
66 const order = await read($, terminal)
67 const k = kit(el, e, { terminal: order })
68 const d = await read($, demo)
69 // The theme setting is the terminal's; the desktop follows the system's colour scheme.
70 const scheme = e.surface === 'terminal' ? schemeOf((await $.config.list()).find(r => r.key === 'theme')?.value) : 'auto'
71 const pick = (id: string) => update($, demo, x => ({ ...x, section: id }))
72 const pressed = (what: string) => update($, demo, x => ({ ...x, pressed: what }))
73 const { Box, Text } = el
74
75 let body
76 if (d.section === 'text') {
77 body = k.col('text', [
78 k.heading('t:h', 'שורות מעורבות'),
79 k.text(MIXED),
80 k.text(ARABIC),
81 k.heading('t:h2', 'פסקה ארוכה', 2),
82 k.para('t:long', LONG),
83 k.heading('t:h3', 'כפתורים', 2),
84 k.row('t:btns', [
85 k.primary('t:primary', 'פעולה ראשית', () => pressed('primary')),
86 k.action('t:action', 'לבקש מ-Claude', () => pressed('action')),
87 k.quiet('t:quiet', 'ביטול', () => pressed('quiet')),
88 ]),
89 d.pressed ? k.muted('t:pressed', `נלחץ: ${d.pressed}`) : null,
90 ])
91 } else if (d.section === 'parts') {
92 body = k.col('parts', [
93 k.row('p:stats', [
94 k.stat('p:s1', 3, 'בקשות ממתינות', 'warn'),
95 k.stat('p:s2', 9, 'הזמנות היום', 'info'),
96 k.stat('p:s3', 2, 'באיחור', 'bad'),
97 ]),
98 k.card('p:card', {
99 title: 'חדר 4 · יום שני 5.10 · 10:00–12:00',
100 meta: 'בקשה של מטפלת לדוגמה. מתנגשת עם הזמנה אחת קיימת.',
101 tone: 'warn',
102 actions: [
103 k.primary('p:approve', 'לאשר', () => pressed('approve')),
104 k.action('p:decline', 'לדחות', () => pressed('decline')),
105 ],
106 }, [k.chips('p:chips', [{ label: 'בקשה', tone: 'warn' }, { label: 'מייל לשוכר', tone: 'info' }])]),
107 k.card('p:card2', { title: 'כרטיס שקט', meta: 'גבול עדין, ומודגש במעבר עכבר.' }),
108 k.heading('p:list', 'רשימה', 2),
109 k.list('p:l', ['פריט ראשון', { text: 'פריט מקונן עם Claude', depth: 1 }, 'פריט שלישי ארוך מספיק כדי לעבור שורה ולהראות שהשורה השנייה מיושרת לימין גם היא']),
110 k.heading('p:items', 'שורות ללחיצה', 2),
111 k.item('p:i1', 'הכנת שישי', () => pressed('item 1'), 'שבעה שלבים · נשמר להיום'),
112 k.item('p:i2', 'קביעת תור', () => pressed('item 2'), 'workflows/booking.md'),
113 k.heading('p:table', 'טבלה', 2),
114 k.table('p:t', ['שירות', 'מחיר', 'הערות'], [['טיפול לדוגמה', '100 ₪', 'כולל מע"מ'], ['ייעוץ', '180 ₪', 'הערה ארוכה שעוברת שורה בתוך התא']], { widths: [40, 20, 40] }),
115 d.pressed ? k.muted('p:pressed', `נלחץ: ${d.pressed}`) : null,
116 ])
117 } else if (d.section === 'md') {
118 body = k.md('md', SAMPLE_MD)
119 } else if (d.section === 'svg') {
120 if (k.isTerminal) {
121 body = k.para('svg:none', 'בטרמינל אין SVG: הכותרת והציר נשארים לחלונית בדסקטופ.')
122 } else {
123 const head = svgHeader({
124 title: 'חדרים · יום שני 5.10', subtitle: '3 בקשות ממתינות · 9 הזמנות · ניסוי', scheme, width: k.svgWidth,
125 chips: [{ label: '3 ממתינות', tone: 'warn' }, { label: '9 היום', tone: 'info' }, { label: '1 התנגשות', tone: 'bad' }],
126 })
127 const day = svgTimeline({
128 scheme, width: k.svgWidth, from: 8, to: 21, now: '13:20',
129 lanes: [{ id: 'r1', label: 'חדר 1' }, { id: 'r2', label: 'חדר 2' }, { id: 'r4', label: 'חדר 4' }, { id: 'hall', label: 'החלל הקהילתי' }],
130 blocks: [
131 { lane: 'r1', start: '09:00', end: '11:00', label: 'מטפלת א', tone: 'info' },
132 { lane: 'r2', start: '13:00', end: '14:00', label: 'מטפל ב', tone: 'info' },
133 { lane: 'r4', start: '10:00', end: '12:00', label: 'בקשה', tone: 'warn' },
134 { lane: 'r4', start: '16:00', end: '18:00', label: 'סגור: ניקיון', tone: 'muted' },
135 { lane: 'hall', start: '16:00', end: '20:00', label: 'קהילתי', tone: 'ok' },
136 ],
137 })
138 body = k.col('svg', [
139 k.svg('svg:head', head, 'כותרת: חדרים, יום שני'),
140 <Box key="svg:gap" height={1} />,
141 k.svg('svg:day', day, 'ציר זמן של החדרים היום'),
142 k.muted('svg:scheme', `ערכת צבעים: ${scheme} (לפי ערכת הצבעים של המערכת)`),
143 ])
144 }
145 } else if (d.section === 'terminal') {
146 const lines = [MIXED, ARABIC, 'סוגריים (בתוך) משפט · 10:00–12:00']
147 body = k.col('term', [
148 k.isTerminal && order === 'logical'
149 ? k.para('term:what', 'בטרמינל הזה Claude Code מסדר את הטקסט מימין לשמאל בעצמו, אז הוא נשלח בסדר השמור.')
150 : k.para('term:what', 'כך נשלח לטרמינל: הסדר החזותי מחושב, כי הטרמינל מדפיס תווים לפי הסדר השמור. כאן זה מוצג בדיוק כפי שהטרמינל ידפיס, ובטרמינל זה ייקרא נכון.'),
151 ...lines.map((l, i) => <Text key={`term:${i}`}>{k.isTerminal ? k.bidi(l) : asStored(visual(l))}</Text>),
152 ])
153 } else {
154 const ruler = (n: number) => Array.from({ length: n }, (_, i) => String((i + 1) % 10)).join('')
155 body = k.col('ruler', [
156 k.para('r:what', `bodyColumns ${k.cols} · רוחב השבירה ${k.width} תווים. השורה הארוכה ביותר שלא נשברת היא היחס הנכון.`),
157 <Text key="r:w">{ruler(k.width)}</Text>,
158 <Text key="r:c">{ruler(k.cols)}</Text>,
159 <Text key="r:c11">{ruler(Math.round(k.cols * 1.1))}</Text>,
160 <Text key="r:he">{k.bidi('א'.repeat(k.cols))}</Text>,
161 ])
162 }
163
164 return (
165 <Box flexDirection="column">
166 {k.tabs('tabs', SECTIONS, d.section, pick)}
167 {body}
168 </Box>
169 )
170 })
171}
172hooks/rtl.tsx 573 lines1// rtl-kit 0.1.3: right-to-left text and a small design language for Claude Code mods.
2// https://github.com/barmoshe/bar-mods/tree/main/rtl-kit
3//
4// Copy this one file into your mod's hooks/ folder and import from './rtl'. It imports nothing at
5// run time, takes no `$`, and works on every surface:
6//
7// const k = kit($.ui.resolve(e), e)
8// return k.col('page', [k.heading('h', 'שלום'), k.para('p', 'טקסט ארוך בעברית עם Claude באמצע…')])
9//
10// Why it exists (measured on the desktop app, Claude Code 2.1.288-2.1.289):
11// - every element is laid out left to right, so a line that mixes Hebrew with Latin or digits is
12// scrambled; wrapping it in RLE…PDF fixes the order, in a Text and in a Button label;
13// - a line that wraps still starts at the left, so long text is wrapped here, one Text per line,
14// each aligned right;
15// - Markdown is scrambled and left-aligned, so md() renders markdown with these builders instead;
16// - on the macOS terminals Claude Code prints Hebrew in stored order, so it reads reversed, and the
17// terminal gets the visual order computed here. Claude Code reorders it itself in Windows
18// Terminal and VS Code's terminal (since 2.1.74; on 2.1.300 its test is WT_SESSION set or
19// TERM_PROGRAM=vscode): pass { terminal: 'logical' } there, or it is reversed twice.
20// - Text's `dir` (Claude Code 2.1.300) does not replace this yet: an engine older than 2.1.300 (the
21// desktop app's, on 2026-10-15) refuses the whole tree over it.
22//
23// Never name a variable `h` in a .tsx file: JSX compiles to the global h().
24
25// ---------- characters and lines ----------
26
27export type Surface = 'terminal' | 'desktop' | 'vscode' | 'mobile' | string
28
29const RTL_CHAR = /[\u0590-\u05FF\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF]/
30const LATIN_CHAR = /[A-Za-z\u00C0-\u024F\u0370-\u03FF\u0400-\u04FF]/
31const DIGIT = /[0-9\u0660-\u0669\u06F0-\u06F9]/
32const MARKS = /[\u200E\u200F\u202A-\u202E\u2066-\u2069]/g
33const RLE = '\u202B'
34const PDF = '\u202C'
35
36export const hasRtl = (s: string) => RTL_CHAR.test(s)
37// Shows a string exactly in stored order on a surface that does bidi (a preview of terminal output).
38export const asStored = (s: string) => `\u202D${s}\u202C`
39export const stripMarks = (s: string) => s.replace(MARKS, '')
40
41export type BidiOptions = {
42 // 'visual' (the default) reorders right-to-left text for a terminal that draws characters in
43 // stored order; 'logical' leaves it for a terminal that does its own bidi.
44 terminal?: 'visual' | 'logical'
45}
46
47// What to hand an element so a right-to-left string reads right on this surface.
48export function bidi(s: string, surface: Surface, opts: BidiOptions = {}): string {
49 if (!hasRtl(s)) return s
50 if (surface === 'terminal') {
51 return opts.terminal === 'logical' ? s : s.split('\n').map(visual).join('\n')
52 }
53 return `${RLE}${stripMarks(s)}${PDF}`
54}
55
56const MIRROR: Record<string, string> = { '(': ')', ')': '(', '[': ']', ']': '[', '{': '}', '}': '{', '<': '>', '>': '<', '«': '»', '»': '«' }
57
58type Dir = 'R' | 'L' | 'N'
59
60function strong(ch: string): Dir {
61 if (RTL_CHAR.test(ch)) return 'R'
62 if (LATIN_CHAR.test(ch) || DIGIT.test(ch)) return 'L'
63 return 'N'
64}
65
66// One line in the order a terminal must print it so it reads right to left. A simplified Unicode
67// bidi: Latin words and numbers stay left to right (with what sits between them, so "Claude: 3"
68// and "10:00–12:00" stay whole), everything else follows the line's direction, set by its first
69// letter. Brackets in right-to-left runs are mirrored. Combining marks are not handled.
70export function visual(line: string): string {
71 const chars = Array.from(stripMarks(line))
72 if (!chars.some(c => RTL_CHAR.test(c))) return chars.join('')
73 const dirs = chars.map(strong)
74 // The line's direction comes from its first letter (digits are weak, as in Unicode's bidi).
75 const firstLetter = chars.find(c => RTL_CHAR.test(c) || LATIN_CHAR.test(c)) ?? ''
76 const base: Dir = LATIN_CHAR.test(firstLetter) ? 'L' : 'R'
77 // A neutral between two left-to-right characters joins them; any other neutral takes the base.
78 const resolved = dirs.map((d, i) => {
79 if (d !== 'N') return d
80 let p = i - 1
81 while (p >= 0 && dirs[p] === 'N') p--
82 let q = i + 1
83 while (q < dirs.length && dirs[q] === 'N') q++
84 const before = p >= 0 ? dirs[p] : null
85 const after = q < dirs.length ? dirs[q] : null
86 return before === 'L' && after === 'L' ? 'L' : base
87 })
88 const runs: { dir: Dir; text: string[] }[] = []
89 chars.forEach((c, i) => {
90 const d = resolved[i] ?? base
91 const last = runs[runs.length - 1]
92 if (last && last.dir === d) last.text.push(c)
93 else runs.push({ dir: d, text: [c] })
94 })
95 const flip = (r: { dir: Dir; text: string[] }) =>
96 r.dir === 'R' ? [...r.text].reverse().map(c => MIRROR[c] ?? c).join('') : r.text.join('')
97 return (base === 'R' ? [...runs].reverse() : runs).map(flip).join('')
98}
99
100// Word-wrap to `width` characters; a word longer than the width is cut.
101export function wrap(s: string, width: number): string[] {
102 const w = Math.max(8, Math.floor(width))
103 const out: string[] = []
104 for (const para of s.split('\n')) {
105 let line = ''
106 for (const word of para.split(/\s+/).filter(Boolean)) {
107 let rest = word
108 while (Array.from(rest).length > w) {
109 if (line) {
110 out.push(line)
111 line = ''
112 }
113 out.push(Array.from(rest).slice(0, w).join(''))
114 rest = Array.from(rest).slice(w).join('')
115 }
116 if (!line) line = rest
117 else if (Array.from(line).length + 1 + Array.from(rest).length <= w) line = `${line} ${rest}`
118 else {
119 out.push(line)
120 line = rest
121 }
122 }
123 out.push(line)
124 }
125 return out
126}
127
128// ---------- the design language ----------
129
130// Theme keys, so colours follow the app's light and dark themes.
131export const tone = {
132 accent: 'claude',
133 ok: 'success',
134 warn: 'warning',
135 bad: 'error',
136 info: 'permission',
137 muted: 'secondaryText',
138 line: 'subtle',
139 fill: 'userMessageBackground',
140} as const
141export type Tone = keyof typeof tone
142
143// ---------- markdown, parsed ----------
144
145export type MdBlock =
146 | { kind: 'heading'; level: number; text: string }
147 | { kind: 'para'; text: string }
148 | { kind: 'item'; depth: number; marker: string; text: string }
149 | { kind: 'quote'; text: string }
150 | { kind: 'table'; headers: string[]; rows: string[][] }
151 | { kind: 'code'; text: string }
152 | { kind: 'rule' }
153
154// Inline markdown to plain text: links to their text, emphasis and code marks off.
155export function inline(s: string): string {
156 return s
157 .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
158 .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
159 .replace(/\*\*(.+?)\*\*/g, '$1')
160 .replace(/__(.+?)__/g, '$1')
161 .replace(/~~(.+?)~~/g, '$1')
162 .replace(/(^|[^*])\*([^*\s][^*]*)\*/g, '$1$2')
163 .replace(/`([^`]*)`/g, '$1')
164 .replace(/\s+/g, ' ')
165 .trim()
166}
167
168// A table line to its cells: a pipe splits unless escaped (\|) or inside a code span.
169export function cells(line: string): string[] {
170 const out: string[] = []
171 let cur = ''
172 let isCode = false
173 const s = line.trim()
174 for (let i = 0; i < s.length; i++) {
175 const ch = s[i]
176 if (ch === '\\' && s[i + 1] === '|') {
177 cur += '|'
178 i++
179 continue
180 }
181 if (ch === '`') isCode = !isCode
182 if (ch === '|' && !isCode) {
183 out.push(cur)
184 cur = ''
185 continue
186 }
187 cur += ch
188 }
189 out.push(cur)
190 if (s.startsWith('|')) out.shift()
191 if (s.endsWith('|') && !s.endsWith('\\|')) out.pop()
192 return out.map(c => c.trim())
193}
194
195const SEPARATOR = /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/
196
197export function parseMd(src: string): MdBlock[] {
198 let lines = src.replace(/\r/g, '').split('\n')
199 if (lines[0]?.trim() === '---') {
200 const end = lines.findIndex((l, i) => i > 0 && l.trim() === '---')
201 if (end > 0) lines = lines.slice(end + 1)
202 }
203 const out: MdBlock[] = []
204 let para: string[] = []
205 const flush = () => {
206 if (para.length) out.push({ kind: 'para', text: inline(para.join(' ')) })
207 para = []
208 }
209 for (let i = 0; i < lines.length; i++) {
210 const l = lines[i] ?? ''
211 if (/^\s*```/.test(l)) {
212 flush()
213 const code: string[] = []
214 for (i++; i < lines.length && !/^\s*```/.test(lines[i] ?? ''); i++) code.push(lines[i] ?? '')
215 out.push({ kind: 'code', text: code.join('\n') })
216 continue
217 }
218 if (l.trim() === '') {
219 flush()
220 continue
221 }
222 const hd = /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(l)
223 if (hd) {
224 flush()
225 out.push({ kind: 'heading', level: (hd[1] ?? '#').length, text: inline(hd[2] ?? '') })
226 continue
227 }
228 if (/^\s*(-{3,}|\*{3,})\s*$/.test(l)) {
229 flush()
230 out.push({ kind: 'rule' })
231 continue
232 }
233 if (l.trim().startsWith('|') && SEPARATOR.test(lines[i + 1] ?? '')) {
234 flush()
235 const headers = cells(l).map(inline)
236 const rows: string[][] = []
237 for (i += 2; i < lines.length && (lines[i] ?? '').trim().startsWith('|'); i++) {
238 if (!SEPARATOR.test(lines[i] ?? '')) rows.push(cells(lines[i] ?? '').map(inline))
239 }
240 i--
241 out.push({ kind: 'table', headers, rows })
242 continue
243 }
244 const q = /^\s*>\s?(.*)$/.exec(l)
245 if (q) {
246 flush()
247 const quote = [q[1] ?? '']
248 while (i + 1 < lines.length && /^\s*>/.test(lines[i + 1] ?? '')) quote.push((lines[++i] ?? '').replace(/^\s*>\s?/, ''))
249 out.push({ kind: 'quote', text: inline(quote.join(' ')) })
250 continue
251 }
252 const it = /^(\s*)(\d+[.)]|[-*+])\s+(?:\[[ xX]\]\s+)?(.*)$/.exec(l)
253 if (it) {
254 flush()
255 const indent = (it[1] ?? '').replace(/\t/g, ' ').length
256 const raw = it[2] ?? '-'
257 out.push({ kind: 'item', depth: Math.min(3, Math.floor(indent / 2)), marker: /\d/.test(raw) ? raw.replace(')', '.') : '•', text: inline(it[3] ?? '') })
258 continue
259 }
260 const last = out[out.length - 1]
261 if (para.length === 0 && last?.kind === 'item' && /^\s{2,}\S/.test(l)) {
262 last.text = `${last.text} ${inline(l)}`
263 continue
264 }
265 para.push(l.trim())
266 }
267 flush()
268 return out
269}
270
271// ---------- SVG pieces (strings for el.Svg; not drawn on the terminal) ----------
272
273export type Scheme = 'light' | 'dark' | 'auto'
274
275export const escapeXml = (s: string) =>
276 s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''')
277
278const PALETTE = {
279 light: { bg: '#faf9f5', panel: '#f0eee6', text: '#141413', muted: '#6b6a64', grid: '#e3e0d6', accent: '#d97757', info: '#6a9bcc', ok: '#788c5d', warn: '#d4a017', bad: '#c4554d', line: '#b0aea5', fill: '#e8e6dc', onTone: '#ffffff' },
280 dark: { bg: '#262624', panel: '#30302e', text: '#f5f4ef', muted: '#a8a69e', grid: '#3d3d3a', accent: '#d97757', info: '#7fb0de', ok: '#94ab72', warn: '#e0b33a', bad: '#d9746c', line: '#6b6a64', fill: '#3a3a37', onTone: '#141413' },
281}
282type Paint = keyof typeof PALETTE.light
283
284// Fills by class, so 'auto' can switch with the viewer's colour scheme.
285function styleFor(scheme: Scheme): string {
286 const rules = (p: typeof PALETTE.light) =>
287 (Object.keys(p) as Paint[]).map(k => `.f-${k}{fill:${p[k]}}.s-${k}{stroke:${p[k]}}`).join('')
288 if (scheme === 'light') return `<style>${rules(PALETTE.light)}</style>`
289 if (scheme === 'dark') return `<style>${rules(PALETTE.dark)}</style>`
290 return `<style>${rules(PALETTE.light)}@media (prefers-color-scheme: dark){${rules(PALETTE.dark)}}</style>`
291}
292
293const FONT = `font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, 'Noto Sans Hebrew', 'Noto Sans Arabic', sans-serif"`
294const clampWidth = (w: number | undefined) => Math.max(280, Math.min(720, Math.round(w ?? 520)))
295// A rough text width, enough to size chips and cut labels: Hebrew and Arabic letters are narrower
296// than Latin capitals, digits in between.
297export const textWidth = (s: string, size: number) => Array.from(s).reduce((sum, c) => sum + (c === ' ' ? 0.3 : /[A-Z]/.test(c) ? 0.66 : 0.56) * size, 0)
298const toneFill = (t: Tone | undefined): Paint =>
299 t === 'ok' ? 'ok' : t === 'warn' ? 'warn' : t === 'bad' ? 'bad' : t === 'info' ? 'info' : t === 'muted' || t === 'line' ? 'line' : 'accent'
300
301function fitText(s: string, size: number, max: number): string {
302 if (textWidth(s, size) <= max) return s
303 const chars = Array.from(s)
304 while (chars.length > 1 && textWidth(`${chars.join('')}…`, size) > max) chars.pop()
305 return `${chars.join('')}…`
306}
307
308export type SvgChip = { label: string; tone?: Tone }
309
310export function svgHeader(o: { title: string; subtitle?: string; chips?: SvgChip[]; scheme?: Scheme; width?: number }): { source: string; width: number; height: number } {
311 const width = clampWidth(o.width)
312 const chips = o.chips ?? []
313 const height = chips.length ? 118 : 78
314 const right = width - 22
315 let x = right
316 const chipSvg = chips.map(c => {
317 const w = Math.ceil(textWidth(c.label, 12)) + 22
318 const left = x - w
319 const out = `<rect class="f-${toneFill(c.tone)}" x="${left}" y="80" width="${w}" height="24" rx="12"/><text class="f-onTone" x="${x - 11}" y="96" direction="rtl" font-size="12" font-weight="600">${escapeXml(c.label)}</text>`
320 x = left - 8
321 return left > 10 ? out : ''
322 }).join('')
323 const source = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" ${FONT}>${styleFor(o.scheme ?? 'auto')}
324<rect class="f-bg" width="${width}" height="${height}" rx="14"/>
325<rect class="f-accent" x="${width - 6}" y="16" width="4" height="${o.subtitle ? 44 : 26}" rx="2"/>
326<text class="f-text" x="${right}" y="38" direction="rtl" font-size="20" font-weight="700">${escapeXml(fitText(o.title, 20, width - 44))}</text>
327${o.subtitle ? `<text class="f-muted" x="${right}" y="62" direction="rtl" font-size="13">${escapeXml(fitText(o.subtitle, 13, width - 44))}</text>` : ''}
328${chipSvg}</svg>`
329 return { source, width, height }
330}
331
332export type Lane = { id: string; label: string }
333export type Block = { lane: string; start: string; end: string; label?: string; tone?: Tone }
334
335const minutes = (hm: string) => Number(hm.slice(0, 2)) * 60 + Number(hm.slice(3, 5))
336
337// Lanes (rooms, people) against the hours of one day, read right to left: the first hour at the
338// right edge. Blocks outside the hours are clipped.
339export function svgTimeline(o: { lanes: Lane[]; blocks: Block[]; from?: number; to?: number; now?: string; scheme?: Scheme; width?: number }): { source: string; width: number; height: number } {
340 const width = clampWidth(o.width)
341 const from = o.from ?? 8
342 const to = Math.max(from + 1, o.to ?? 21)
343 const labelW = 86
344 const top = 28
345 const laneH = 26
346 const height = top + o.lanes.length * laneH + 12
347 const plotRight = width - labelW - 10
348 const plotLeft = 14
349 const span = (to - from) * 60
350 const xAt = (m: number) => plotRight - ((Math.min(Math.max(m, from * 60), to * 60) - from * 60) / span) * (plotRight - plotLeft)
351 const ticks: string[] = []
352 const step = to - from > 8 ? 2 : 1
353 for (let hr = from; hr <= to; hr += step) {
354 const x = xAt(hr * 60)
355 ticks.push(`<line class="s-grid" x1="${x}" y1="${top - 6}" x2="${x}" y2="${height - 10}" stroke-width="1"/><text class="f-muted" x="${x}" y="16" text-anchor="middle" font-size="10">${hr}</text>`)
356 }
357 const lanes = o.lanes.map((l, i) => {
358 const y = top + i * laneH
359 return `<rect class="f-panel" x="${plotLeft}" y="${y + 3}" width="${plotRight - plotLeft}" height="${laneH - 6}" rx="6"/><text class="f-text" x="${width - 12}" y="${y + laneH / 2 + 4}" direction="rtl" font-size="12" font-weight="600">${escapeXml(fitText(l.label, 12, labelW - 6))}</text>`
360 }).join('')
361 const blocks = o.blocks.map(b => {
362 const i = o.lanes.findIndex(l => l.id === b.lane)
363 if (i < 0) return ''
364 const y = top + i * laneH
365 const x1 = xAt(minutes(b.end))
366 const x2 = xAt(minutes(b.start))
367 const w = x2 - x1
368 if (w <= 1) return ''
369 const label = b.label ? fitText(b.label, 11, w - 10) : ''
370 return `<rect class="f-${toneFill(b.tone)}" x="${x1 + 1}" y="${y + 4}" width="${w - 2}" height="${laneH - 8}" rx="5"/>${label && w > 26 ? `<text class="f-onTone" x="${x2 - 6}" y="${y + laneH / 2 + 4}" direction="rtl" font-size="11" font-weight="600">${escapeXml(label)}</text>` : ''}`
371 }).join('')
372 const now = o.now ? (() => {
373 const m = minutes(o.now)
374 if (m < from * 60 || m > to * 60) return ''
375 const x = xAt(m)
376 return `<line class="s-bad" x1="${x}" y1="${top - 4}" x2="${x}" y2="${height - 10}" stroke-width="2"/>`
377 })() : ''
378 const source = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" ${FONT}>${styleFor(o.scheme ?? 'auto')}
379<rect class="f-bg" width="${width}" height="${height}" rx="14"/>${ticks.join('')}${lanes}${blocks}${now}</svg>`
380 return { source, width, height }
381}
382
383// Claude Code's `theme` setting, from `(await $.config.list()).find(r => r.key === 'theme')?.value`.
384// It is the terminal's theme: the desktop app can be light while it says dark (seen 05/10), so on
385// the desktop leave the scheme 'auto' and let the system's colour scheme decide.
386export function schemeOf(theme: unknown): Scheme {
387 const t = typeof theme === 'string' ? theme : ''
388 return t.includes('dark') ? 'dark' : t.includes('light') ? 'light' : 'auto'
389}
390
391// ---------- the builders ----------
392
393// The element constructors are the engine's; the kit only passes props through.
394// eslint-disable-next-line @typescript-eslint/no-explicit-any
395type Els = Record<string, any>
396// eslint-disable-next-line @typescript-eslint/no-explicit-any
397type Node = any
398type Press = () => unknown
399
400export type KitOptions = BidiOptions & {
401 // How many characters fit in one of the pane's columns, for wrapping long text yourself
402 // (measured with the /rtl-gallery ruler; proportional fonts make this an estimate).
403 charsPerColumn?: number
404}
405
406export type Kit = ReturnType<typeof kit>
407
408export function kit(el: Els, e: { surface: Surface; props?: { bodyColumns?: number } }, opts: KitOptions = {}) {
409 const { Box, Text, Button } = el
410 const surface = e.surface
411 const isTerminal = surface === 'terminal'
412 const cols = e.props?.bodyColumns ?? 80
413 const width = Math.max(16, Math.floor(cols * (opts.charsPerColumn ?? (isTerminal ? 1 : 0.9))))
414 const b = (s: string) => bidi(s, surface, opts)
415 // The press hands back what the handler returns, so the engine (and a test's press) can wait for
416 // it; dropping the promise lets work run on after the press and its errors go unhandled.
417 const run = (f: Press) => () => f()
418
419 const text = (s: string, props: Record<string, unknown> = {}) => <Text {...props}>{b(s)}</Text>
420
421 const para = (key: string, s: string, props: Record<string, unknown> = {}, w = width) => (
422 <Box key={key} flexDirection="column" alignItems="flex-end">
423 {wrap(s, w).map((l, i) => <Text key={`${key}:${i}`} {...props}>{b(l || ' ')}</Text>)}
424 </Box>
425 )
426
427 const heading = (key: string, s: string, level = 1) => (
428 <Box key={key} flexDirection="column" alignItems="flex-end" marginTop={level > 1 ? 1 : 0}>
429 <Text bold color={level === 1 ? tone.accent : undefined}>{b(s)}</Text>
430 </Box>
431 )
432
433 const muted = (key: string, s: string) => para(key, s, { color: tone.muted })
434
435 const row = (key: string, children: Node[], props: Record<string, unknown> = {}) => (
436 <Box key={key} flexDirection="row-reverse" flexWrap="wrap" gap={1} alignItems="center" {...props}>{children}</Box>
437 )
438
439 const col = (key: string, children: Node[], props: Record<string, unknown> = {}) => (
440 <Box key={key} flexDirection="column" alignItems="flex-end" {...props}>{children}</Box>
441 )
442
443 const action = (key: string, label: string, onPress: Press, props: Record<string, unknown> = {}) =>
444 <Button key={key} label={b(label)} variant="secondary" onPress={run(onPress)} {...props} />
445 const primary = (key: string, label: string, onPress: Press, props: Record<string, unknown> = {}) =>
446 <Button key={key} label={b(label)} variant="primary" onPress={run(onPress)} {...props} />
447 const quiet = (key: string, label: string, onPress: Press, props: Record<string, unknown> = {}) =>
448 <Button key={key} label={b(label)} dimColor onPress={run(onPress)} {...props} />
449
450 // A list row you press: the label as a plain button, a muted line under it.
451 // The button carries `key`, so the caller presses the key it passed.
452 const item = (key: string, label: string, onPress: Press, meta?: string) => (
453 <Box key={`${key}:item`} flexDirection="column" alignItems="flex-end">
454 <Button key={key} label={b(label)} plain onPress={run(onPress)} />
455 {meta ? para(`${key}:meta`, meta, { color: tone.muted }) : null}
456 </Box>
457 )
458
459 const chip = (key: string, label: string, t: Tone = 'accent') => (isTerminal
460 ? <Text key={key} color={tone[t]}>{b(`[${label}]`)}</Text>
461 : <Text key={key} color={tone[t]} backgroundColor={tone.fill} bold>{b(` ${label} `)}</Text>)
462
463 const chips = (key: string, items: SvgChip[]) => row(key, items.map((c, i) => chip(`${key}:${i}`, c.label, c.tone)))
464
465 const stat = (key: string, value: string | number, label: string, t: Tone = 'accent') => (isTerminal
466 ? <Text key={key}>{b(`${label}: ${value}`)}</Text>
467 : (
468 <Box key={key} flexDirection="column" alignItems="flex-end" paddingX={1}>
469 <Text bold color={tone[t]}>{String(value)}</Text>
470 <Text color={tone.muted}>{b(label)}</Text>
471 </Box>
472 ))
473
474 const card = (key: string, o: { title?: string; meta?: string; tone?: Tone; actions?: Node[] }, children: Node[] = []) => (
475 <Box key={key} flexDirection="column" alignItems="flex-end" borderStyle="round"
476 borderColor={o.tone ? tone[o.tone] : tone.line} hover={{ borderColor: tone.accent }} paddingX={1} marginBottom={1}>
477 {o.title ? <Text bold>{b(o.title)}</Text> : null}
478 {o.meta ? para(`${key}:meta`, o.meta, { color: tone.muted }, width - 4) : null}
479 {children}
480 {o.actions && o.actions.length ? row(`${key}:actions`, o.actions, { marginTop: 1 }) : null}
481 </Box>
482 )
483
484 const tabs = (key: string, items: { id: string; label: string }[], current: string, onPick: (id: string) => unknown) =>
485 row(key, items.map(t => (t.id === current
486 ? <Button key={`${key}:${t.id}`} label={b(t.label)} variant="primary" onPress={run(() => onPick(t.id))} />
487 : <Button key={`${key}:${t.id}`} label={b(t.label)} plain onPress={run(() => onPick(t.id))} />)), { marginBottom: 1 })
488
489 // Items with the marker on the right; depth indents from the right.
490 const list = (key: string, items: (string | { text: string; depth?: number })[], o: { ordered?: boolean } = {}) => (
491 <Box key={key} flexDirection="column" alignItems="flex-end">
492 {items.map((x, i) => {
493 const it = typeof x === 'string' ? { text: x, depth: 0 } : { text: x.text, depth: x.depth ?? 0 }
494 const marker = o.ordered ? `${i + 1}.` : '•'
495 return listRow(`${key}:${i}`, marker, it.text, it.depth)
496 })}
497 </Box>
498 )
499
500 const listRow = (key: string, marker: string, s: string, depth: number) => {
501 const w = Math.max(12, width - 3 - depth * 2)
502 const lines = wrap(s, w)
503 return (
504 <Box key={key} flexDirection="row-reverse" gap={1} paddingRight={depth * 2}>
505 <Text color={tone.muted}>{marker}</Text>
506 <Box flexDirection="column" alignItems="flex-end">
507 {lines.map((l, i) => <Text key={`${key}:${i}`}>{b(l || ' ')}</Text>)}
508 </Box>
509 </Box>
510 )
511 }
512
513 // Columns right to left; each cell wraps inside its share of the width.
514 const table = (key: string, headers: string[], rows: string[][], o: { widths?: number[] } = {}) => {
515 const n = Math.max(headers.length, ...rows.map(r => r.length), 1)
516 const widths = o.widths && o.widths.length === n ? o.widths : Array.from({ length: n }, () => 100 / n)
517 const cell = (rk: string, c: string, i: number, props: Record<string, unknown>) => (
518 <Box key={`${rk}:${i}`} width={`${Math.round(widths[i] ?? 0)}%`} flexDirection="column" alignItems="flex-end" paddingX={1}>
519 {wrap(c, Math.max(6, Math.floor(((width - 2) * (widths[i] ?? 0)) / 100) - 2)).map((l, j) => <Text key={`${rk}:${i}:${j}`} {...props}>{b(l || ' ')}</Text>)}
520 </Box>
521 )
522 return (
523 <Box key={key} flexDirection="column" width="100%" borderStyle="round" borderColor={tone.line} marginBottom={1}>
524 <Box key={`${key}:head`} flexDirection="row-reverse">
525 {Array.from({ length: n }, (_, i) => cell(`${key}:head`, headers[i] ?? '', i, { bold: true, color: tone.muted }))}
526 </Box>
527 {rows.map((r, ri) => (
528 <Box key={`${key}:r${ri}`} flexDirection="row-reverse">
529 {Array.from({ length: n }, (_, i) => cell(`${key}:r${ri}`, r[i] ?? '', i, {}))}
530 </Box>
531 ))}
532 </Box>
533 )
534 }
535
536 // Markdown drawn with the builders above, because the Markdown element cannot do right to left.
537 const md = (key: string, src: string) => (
538 <Box key={key} flexDirection="column" alignItems="flex-end">
539 {parseMd(src).map((blk, i) => {
540 const k = `${key}:${i}`
541 switch (blk.kind) {
542 case 'heading':
543 return heading(k, blk.text, blk.level)
544 case 'para':
545 return <Box key={k} marginBottom={1}>{para(`${k}:p`, blk.text)}</Box>
546 case 'item':
547 return listRow(k, blk.marker, blk.text, blk.depth)
548 case 'quote':
549 return card(k, { tone: 'line' }, [para(`${k}:q`, blk.text, {}, width - 4)])
550 case 'table':
551 return table(k, blk.headers, blk.rows)
552 case 'code':
553 return <Box key={k} marginBottom={1} borderStyle="round" borderColor={tone.line} paddingX={1}><Text>{blk.text}</Text></Box>
554 case 'rule':
555 return <Text key={k} color={tone.line}>{'─'.repeat(Math.min(40, width))}</Text>
556 }
557 })}
558 </Box>
559 )
560
561 // An SVG piece, or nothing on a surface without Svg.
562 const svg = (key: string, piece: { source: string; width: number; height: number }, alt: string) =>
563 (!isTerminal && 'Svg' in el ? <el.Svg key={key} source={piece.source} alt={alt} width={piece.width} height={piece.height} /> : null)
564
565 // Pixels for an SVG that spans the pane: an estimate from the columns.
566 const svgWidth = Math.max(280, Math.min(720, Math.round(cols * 7.2)))
567
568 return {
569 surface, isTerminal, cols, width, svgWidth, bidi: b,
570 text, para, heading, muted, row, col, action, primary, quiet, item, chip, chips, stat, card, tabs, list, table, md, svg,
571 }
572}
573types/index.d.ts 9 lines1export type RtlKitDemo = { section: string; pressed: string | null }
2export type RtlKitTerminal = 'visual' | 'logical'
3
4declare module 'claude-code' {
5 interface PluginState {
6 'rtl-kit': { demo: RtlKitDemo; terminal: RtlKitTerminal }
7 }
8}
9