Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat(mobile): Render Markdown tables in notes and note chat (#2364)
Chad Piha8d2942368406
diff --git a/openwhispr-mobile/src/components/notes/MarkdownRenderer.tsx b/openwhispr-mobile/src/components/notes/MarkdownRenderer.tsxindex ea1239b54..c702689fa 100644--- a/openwhispr-mobile/src/components/notes/MarkdownRenderer.tsx+++ b/openwhispr-mobile/src/components/notes/MarkdownRenderer.tsx@@ -1,6 +1,15 @@import { useMemo } from 'react';-import { View, PlatformColor } from 'react-native';+import {+ View,+ PlatformColor,+ ScrollView,+ StyleSheet,+ type StyleProp,+ type TextStyle,+} from 'react-native';import { Text } from '@/components/ui/Text';+import { parseMarkdownBlocks, type MarkdownBlock } from './markdownBlocks';+import { NOTES_GROUP_RADIUS } from './tokens';interface MarkdownRendererProps {content: string;@@ -44,12 +53,17 @@ function parseInline(text: string): InlineSegment[] {function InlineText({segments,selectable = false,+ style,}: {segments: InlineSegment[];selectable?: boolean;+ style?: StyleProp<TextStyle>;}) {return (- <Text selectable={selectable} style={{ fontSize: 16, lineHeight: 24, color: labelColor }}>+ <Text+ selectable={selectable}+ style={[{ fontSize: 16, lineHeight: 24, color: labelColor }, style]}+ >{segments.map((seg, i) => {if (seg.code) {return (@@ -83,33 +97,70 @@ function InlineText({);}-interface ParsedLine {- type: 'h1' | 'h2' | 'h3' | 'bullet' | 'numbered' | 'paragraph' | 'empty';- content: string;- number?: number;-}+// Sized from the longest cell so no measuring pass is needed; wide tables+// scroll sideways rather than squeezing every column into the screen.+const CELL_CHAR_WIDTH = 8;+const CELL_PADDING = 20;+const MIN_COLUMN_WIDTH = 80;+const MAX_COLUMN_WIDTH = 220;-function parseLine(line: string): ParsedLine {- if (line.trim() === '') return { type: 'empty', content: '' };- if (line.startsWith('### ')) return { type: 'h3', content: line.slice(4) };- if (line.startsWith('## ')) return { type: 'h2', content: line.slice(3) };- if (line.startsWith('# ')) return { type: 'h1', content: line.slice(2) };+type TableBlock = Extract<MarkdownBlock, { type: 'table' }>;- const bulletMatch = line.match(/^[-*]\s+(.*)/);- if (bulletMatch) return { type: 'bullet', content: bulletMatch[1] };+function columnWidths(table: TableBlock): number[] {+ return table.header.map((label, column) => {+ const longest = Math.max(label.length, ...table.rows.map((row) => row[column].length));+ const width = longest * CELL_CHAR_WIDTH + CELL_PADDING;+ return Math.min(MAX_COLUMN_WIDTH, Math.max(MIN_COLUMN_WIDTH, width));+ });+}- const numberedMatch = line.match(/^(\d+)\.\s+(.*)/);- if (numberedMatch)- return { type: 'numbered', content: numberedMatch[2], number: parseInt(numberedMatch[1], 10) };+function MarkdownTable({ table, selectable }: { table: TableBlock; selectable: boolean }) {+ const widths = columnWidths(table);+ const allRows = [table.header, ...table.rows];- return { type: 'paragraph', content: line };+ return (+ <ScrollView+ testID="markdown-table"+ horizontal+ showsHorizontalScrollIndicator={false}+ style={styles.tableScroller}+ >+ <View className="overflow-hidden border-separator" style={styles.table}>+ {allRows.map((row, rowIndex) => {+ const isHeader = rowIndex === 0;+ return (+ <View+ key={rowIndex}+ className={`flex-row border-separator ${isHeader ? 'bg-secondarySystemBackground' : ''}`}+ style={!isHeader && styles.rowDivider}+ >+ {row.map((cell, column) => {+ const width = widths[column];+ const textAlign = table.alignments[column] ?? 'auto';+ return (+ <View+ key={column}+ className="border-separator px-2.5 py-1.5"+ style={[{ width }, column > 0 && styles.cellDivider]}+ >+ <InlineText+ segments={parseInline(cell)}+ selectable={selectable}+ style={[styles.cellText, isHeader && styles.headerCellText, { textAlign }]}+ />+ </View>+ );+ })}+ </View>+ );+ })}+ </View>+ </ScrollView>+ );}export function MarkdownRenderer({ content, selectable = false }: MarkdownRendererProps) {- const elements = useMemo(() => {- const lines = content.split('\n');- return lines.map((line) => parseLine(line));- }, [content]);+ const elements = useMemo(() => parseMarkdownBlocks(content), [content]);return (<View style={{ gap: 2 }}>@@ -118,6 +169,21 @@ export function MarkdownRenderer({ content, selectable = false }: MarkdownRenderreturn <View key={i} style={{ height: 12 }} />;}+ if (el.type === 'rule') {+ return (+ <View+ key={i}+ testID="markdown-rule"+ className="my-2.5 bg-separator"+ style={styles.rule}+ />+ );+ }++ if (el.type === 'table') {+ return <MarkdownTable key={i} table={el} selectable={selectable} />;+ }+if (el.type === 'h1') {return (<Text@@ -218,3 +284,19 @@ export function MarkdownRenderer({ content, selectable = false }: MarkdownRender</View>);}++const styles = StyleSheet.create({+ // A horizontal ScrollView defaults to flexGrow: 1 and would stretch to any+ // free height in its column, like the note chat sheet's.+ tableScroller: { flexGrow: 0, marginVertical: 6 },+ table: {+ borderWidth: StyleSheet.hairlineWidth,+ borderRadius: NOTES_GROUP_RADIUS,+ borderCurve: 'continuous',+ },+ rowDivider: { borderTopWidth: StyleSheet.hairlineWidth },+ cellDivider: { borderLeftWidth: StyleSheet.hairlineWidth },+ cellText: { fontSize: 15, lineHeight: 20 },+ headerCellText: { fontWeight: '600' },+ rule: { height: StyleSheet.hairlineWidth },+});diff --git a/openwhispr-mobile/src/components/notes/__tests__/MarkdownRenderer.test.tsx b/openwhispr-mobile/src/components/notes/__tests__/MarkdownRenderer.test.tsxnew file mode 100644index 000000000..896c78a50--- /dev/null+++ b/openwhispr-mobile/src/components/notes/__tests__/MarkdownRenderer.test.tsx@@ -0,0 +1,71 @@+import { render, type RenderResult } from '@testing-library/react-native';+import { MarkdownRenderer } from '../MarkdownRenderer';++jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));++type Node = ReturnType<RenderResult['getByText']>;++// getByText returns the innermost span; alignment and selection live on the+// cell's own Text around it.+function cellText(span: Node): Node {+ let node = span.parent;+ while (node && node.type !== 'Text') node = node.parent;+ if (!node) throw new Error('span has no enclosing cell Text');+ return node;+}++const TABLE = [+ 'Compared options:',+ '',+ '| Option | Cost | Notes |',+ '| --- | ---: | --- |',+ '| **Plan A** | $10 | fast \\| cheap |',+ '| Plan B | $25 |',+ '',+ '---',+ 'Done.',+].join('\n');++describe('MarkdownRenderer tables', () => {+ it('renders every cell, with inline formatting and escaped pipes', () => {+ const { getByTestId, getByText } = render(<MarkdownRenderer content={TABLE} />);++ expect(getByTestId('markdown-table')).toBeOnTheScreen();+ for (const cell of [+ 'Option',+ 'Cost',+ 'Notes',+ 'Plan A',+ '$10',+ 'fast | cheap',+ 'Plan B',+ '$25',+ ]) {+ expect(getByText(cell)).toBeOnTheScreen();+ }+ expect(getByText('Plan A')).toHaveStyle({ fontWeight: '600' });+ expect(cellText(getByText('$10'))).toHaveStyle({ textAlign: 'right' });+ expect(cellText(getByText('Plan B'))).toHaveStyle({ textAlign: 'auto' });+ });++ it('never prints the pipe syntax or the delimiter row', () => {+ const { queryByText, getByTestId, getByText } = render(<MarkdownRenderer content={TABLE} />);++ expect(queryByText(/\| ---|---/)).toBeNull();+ expect(queryByText(/^\|/)).toBeNull();+ expect(getByTestId('markdown-rule')).toBeOnTheScreen();+ expect(getByText('Done.')).toBeOnTheScreen();+ });++ // A horizontal ScrollView defaults to flexGrow: 1, which stretched the table to+ // the full height of the note chat sheet.+ it('sizes the table to its rows instead of filling the parent', () => {+ const { getByTestId } = render(<MarkdownRenderer content={TABLE} />);+ expect(getByTestId('markdown-table')).toHaveStyle({ flexGrow: 0 });+ });++ it('keeps cells selectable when the renderer is', () => {+ const { getByText } = render(<MarkdownRenderer content={TABLE} selectable />);+ expect(cellText(getByText('$25')).props.selectable).toBe(true);+ });+});diff --git a/openwhispr-mobile/src/components/notes/__tests__/markdownBlocks.test.ts b/openwhispr-mobile/src/components/notes/__tests__/markdownBlocks.test.tsnew file mode 100644index 000000000..03b109583--- /dev/null+++ b/openwhispr-mobile/src/components/notes/__tests__/markdownBlocks.test.ts@@ -0,0 +1,127 @@+import { parseMarkdownBlocks, splitTableRow } from '../markdownBlocks';++describe('splitTableRow', () => {+ it('drops the outer pipes and trims each cell', () => {+ expect(splitTableRow('| Item | Cost |')).toEqual(['Item', 'Cost']);+ });++ it('splits rows written without outer pipes', () => {+ expect(splitTableRow('Item | Cost')).toEqual(['Item', 'Cost']);+ });++ it('keeps empty cells in place', () => {+ expect(splitTableRow('| a | | c |')).toEqual(['a', '', 'c']);+ });++ it('reads an escaped pipe as part of the cell, as the desktop serializer writes it', () => {+ expect(splitTableRow('| a \\| b | c |')).toEqual(['a | b', 'c']);+ });++ it('does not split on a pipe inside a code span', () => {+ expect(splitTableRow('| `a | b` | c |')).toEqual(['`a | b`', 'c']);+ });++ it('treats an unclosed backtick as a literal so the row still splits', () => {+ expect(splitTableRow('| `a | b |')).toEqual(['`a', 'b']);+ });++ it('keeps a trailing escaped pipe as content', () => {+ expect(splitTableRow('| a | b \\|')).toEqual(['a', 'b |']);+ });+});++describe('parseMarkdownBlocks', () => {+ it('parses a table with its header, alignments, and rows', () => {+ const blocks = parseMarkdownBlocks(+ ['| Name | Qty | Price |', '| :--- | :-: | ---: |', '| Apple | 2 | $1 |'].join('\n'),+ );+ expect(blocks).toEqual([+ {+ type: 'table',+ header: ['Name', 'Qty', 'Price'],+ alignments: ['left', 'center', 'right'],+ rows: [['Apple', '2', '$1']],+ },+ ]);+ });++ it('leaves alignment unset when the delimiter has no colons', () => {+ const [block] = parseMarkdownBlocks('| a | b |\n|---|---|\n| 1 | 2 |');+ expect(block).toMatchObject({ type: 'table', alignments: [null, null] });+ });++ it('parses a table written without outer pipes', () => {+ const [block] = parseMarkdownBlocks('a | b\n--- | ---\n1 | 2');+ expect(block).toMatchObject({ type: 'table', header: ['a', 'b'], rows: [['1', '2']] });+ });++ it('parses a header-only table', () => {+ const blocks = parseMarkdownBlocks('| a | b |\n| - | - |');+ expect(blocks).toEqual([+ { type: 'table', header: ['a', 'b'], alignments: [null, null], rows: [] },+ ]);+ });++ it('pads short rows and drops cells beyond the header', () => {+ const [block] = parseMarkdownBlocks('| a | b |\n|---|---|\n| 1 |\n| 1 | 2 | 3 |');+ expect(block).toMatchObject({+ rows: [+ ['1', ''],+ ['1', '2'],+ ],+ });+ });++ it('ends the table at a blank line or a line without a pipe', () => {+ const blocks = parseMarkdownBlocks(+ ['| a |', '| - |', '| 1 |', 'After the table', '', '| x |'].join('\n'),+ );+ expect(blocks.map((block) => block.type)).toEqual(['table', 'paragraph', 'empty', 'paragraph']);+ expect(blocks[0]).toMatchObject({ rows: [['1']] });+ });++ it('keeps surrounding blocks around a table', () => {+ const blocks = parseMarkdownBlocks(+ ['## Budget', '| a | b |', '|---|---|', '| 1 | 2 |', '- next step'].join('\n'),+ );+ expect(blocks.map((block) => block.type)).toEqual(['h2', 'table', 'bullet']);+ });++ it('does not treat a pipe line without a delimiter row as a table', () => {+ expect(parseMarkdownBlocks('Pick A | B\nthen continue')).toEqual([+ { type: 'paragraph', content: 'Pick A | B' },+ { type: 'paragraph', content: 'then continue' },+ ]);+ });++ it('does not treat a delimiter whose column count differs from the header as a table', () => {+ const blocks = parseMarkdownBlocks('| a | b |\n| --- |');+ expect(blocks.map((block) => block.type)).toEqual(['paragraph', 'paragraph']);+ });++ it('reads a plain line followed by --- as text and a rule, not a table', () => {+ const blocks = parseMarkdownBlocks('Title\n---');+ expect(blocks).toEqual([{ type: 'paragraph', content: 'Title' }, { type: 'rule' }]);+ });++ it('parses thematic breaks instead of printing them', () => {+ const blocks = parseMarkdownBlocks(['---', '***', '___', '* * *', '- - -'].join('\n'));+ expect(blocks).toEqual(Array.from({ length: 5 }, () => ({ type: 'rule' })));+ });++ it('keeps the existing line blocks', () => {+ expect(+ parseMarkdownBlocks(+ ['# One', '## Two', '### Three', '- dash', '* star', '3. third', ''].join('\n'),+ ),+ ).toEqual([+ { type: 'h1', content: 'One' },+ { type: 'h2', content: 'Two' },+ { type: 'h3', content: 'Three' },+ { type: 'bullet', content: 'dash' },+ { type: 'bullet', content: 'star' },+ { type: 'numbered', content: 'third', number: 3 },+ { type: 'empty' },+ ]);+ });+});diff --git a/openwhispr-mobile/src/components/notes/markdownBlocks.ts b/openwhispr-mobile/src/components/notes/markdownBlocks.tsnew file mode 100644index 000000000..d0eb02cb4--- /dev/null+++ b/openwhispr-mobile/src/components/notes/markdownBlocks.ts@@ -0,0 +1,119 @@+export type TableAlignment = 'left' | 'center' | 'right' | null;++export type MarkdownBlock =+ | { type: 'h1' | 'h2' | 'h3' | 'bullet' | 'paragraph'; content: string }+ | { type: 'numbered'; content: string; number: number }+ | { type: 'empty' }+ | { type: 'rule' }+ | { type: 'table'; header: string[]; alignments: TableAlignment[]; rows: string[][] };++const THEMATIC_BREAK = /^ {0,3}([-*_])(?:\s*\1){2,}\s*$/;+const DELIMITER_CELL = /^:?-+:?$/;+const UNESCAPED_PIPE = /(?<!\\)\|/;++/**+ * Cells of one pipe-table row. `\|` is a literal pipe, matching how desktop+ * notes escape pipes in cells. Unlike GFM, a pipe inside a closed code span+ * does not split the cell: model answers put `a | b` in backticks unescaped.+ */+export function splitTableRow(line: string): string[] {+ let row = line.trim();+ if (row.startsWith('|')) row = row.slice(1);+ if (row.endsWith('|') && !row.endsWith('\\|')) row = row.slice(0, -1);++ const cells: string[] = [];+ let cell = '';+ for (let index = 0; index < row.length; index++) {+ const char = row[index];+ if (char === '\\' && row[index + 1] === '|') {+ cell += '|';+ index++;+ } else if (char === '`') {+ const close = row.indexOf('`', index + 1);+ if (close === -1) {+ cell += char;+ } else {+ cell += row.slice(index, close + 1).replace(/\\\|/g, '|');+ index = close;+ }+ } else if (char === '|') {+ cells.push(cell.trim());+ cell = '';+ } else {+ cell += char;+ }+ }+ cells.push(cell.trim());+ return cells;+}++function parseDelimiterRow(line: string, columnCount: number): TableAlignment[] | null {+ if (!line.includes('|')) return null;+ const cells = splitTableRow(line);+ if (cells.length !== columnCount || !cells.every((cell) => DELIMITER_CELL.test(cell))) {+ return null;+ }+ return cells.map((cell) => {+ const left = cell.startsWith(':');+ const right = cell.endsWith(':');+ if (left && right) return 'center';+ if (right) return 'right';+ if (left) return 'left';+ return null;+ });+}++function isTableRow(line: string): boolean {+ return line.trim() !== '' && UNESCAPED_PIPE.test(line);+}++function parseLine(line: string): MarkdownBlock {+ if (line.trim() === '') return { type: 'empty' };+ if (line.startsWith('### ')) return { type: 'h3', content: line.slice(4) };+ if (line.startsWith('## ')) return { type: 'h2', content: line.slice(3) };+ if (line.startsWith('# ')) return { type: 'h1', content: line.slice(2) };+ // Before bullets, which would otherwise swallow `* * *` and `- - -`.+ if (THEMATIC_BREAK.test(line)) return { type: 'rule' };++ const bulletMatch = line.match(/^[-*]\s+(.*)/);+ if (bulletMatch) return { type: 'bullet', content: bulletMatch[1] };++ const numberedMatch = line.match(/^(\d+)\.\s+(.*)/);+ if (numberedMatch) {+ return { type: 'numbered', content: numberedMatch[2], number: parseInt(numberedMatch[1], 10) };+ }++ return { type: 'paragraph', content: line };+}++export function parseMarkdownBlocks(content: string): MarkdownBlock[] {+ const lines = content.split('\n');+ const blocks: MarkdownBlock[] = [];+ let index = 0;++ while (index < lines.length) {+ const line = lines[index];+ const header = isTableRow(line) ? splitTableRow(line) : null;+ const alignments =+ header && index + 1 < lines.length+ ? parseDelimiterRow(lines[index + 1], header.length)+ : null;++ if (!header || !alignments) {+ blocks.push(parseLine(line));+ index++;+ continue;+ }++ const rows: string[][] = [];+ index += 2;+ while (index < lines.length && isTableRow(lines[index])) {+ const cells = splitTableRow(lines[index]);+ rows.push(header.map((_, column) => cells[column] ?? ''));+ index++;+ }+ blocks.push({ type: 'table', header, alignments, rows });+ }++ return blocks;+}