Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,10 @@ and a bar on the left, or `// [!code ++]` and `// [!code --]` for lines a
change adds and removes. Use the comment syntax of the block's language. The
Markdown copy of the page drops the comments and keeps the code. `rehypeTableLabels` gives each table cell after the
first a `data-label` so that tables stack on a phone, and marks short inline code
`data-short` so that it stays on one line.
`data-short` so that it stays on one line. Long inline code in a table cell
gets a break opportunity after each `_`, `-`, `.` and `/` and before a camelCase
capital, so it wraps at its own seams before it breaks inside a word. Copying
the code still gives its text unchanged.

### Configure Vite

Expand Down
71 changes: 71 additions & 0 deletions src/lib/table-labels.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,74 @@ describe('rehypeTableLabels', () => {
expect(marked(block)).toBe(false);
});
});

describe('breaks in long code in a table', () => {
const code = (...children: HastNode[]): HastNode => ({
type: 'element',
tagName: 'code',
properties: {},
children,
});
const plain = (value: string): HastNode => ({ type: 'text', value });
const inCell = (node: HastNode, column = 1): HastNode => {
const cells = [cell('td', 'name'), cell('td', '')];
cells[column] = { type: 'element', tagName: 'td', properties: {}, children: [node] };
return { ...table(['A', 'B'], ['x', 'y']), children: [{ type: 'element', tagName: 'tbody', children: [{ type: 'element', tagName: 'tr', children: cells }] }] };
};
const render = (node: HastNode): string =>
node.type === 'text' ? (node.value ?? '') : node.tagName === 'wbr' ? '|' : (node.children ?? []).map(render).join('');
const copy = (node: HastNode): string =>
node.type === 'text' ? (node.value ?? '') : (node.children ?? []).map(copy).join('');

it('adds a break after each separator and before a camelCase capital, and no character', () => {
const node = code(plain('mcp_fetch_timeout_seconds'));
const tree = inCell(node);
rehypeTableLabels()(tree);
expect(render(node)).toBe('mcp_|fetch_|timeout_|seconds');
expect(copy(node)).toBe('mcp_fetch_timeout_seconds');

const mixed = code(plain('api/v1/getDocumentByIdentifier.json'));
rehypeTableLabels()(inCell(mixed));
expect(render(mixed)).toBe('api/|v1/|get|Document|By|Identifier.|json');
expect(copy(mixed)).toBe('api/v1/getDocumentByIdentifier.json');
});

it('leaves short code whole', () => {
const node = code(plain('invalid-argument'));
rehypeTableLabels()(inCell(node));
expect(render(node)).toBe('invalid-argument');
});

it('does not break between consecutive separators or after a trailing one', () => {
const node = code(plain('a_very_long_prefix__with_double_and_trailing_'));
rehypeTableLabels()(inCell(node));
expect(render(node)).toBe('a_|very_|long_|prefix__|with_|double_|and_|trailing_');
});

it('breaks inside highlighted spans, and leaves code outside a table and in a block alone', () => {
const span: HastNode = { type: 'element', tagName: 'span', properties: {}, children: [plain('some_long_identifier_name_here_x')] };
const highlighted = code(span);
rehypeTableLabels()(inCell(highlighted));
expect(render(highlighted)).toBe('some_|long_|identifier_|name_|here_|x');

const prose = code(plain('some_long_identifier_name_here_x'));
const block = code(plain('some_long_identifier_name_here_x'));
const tree: HastNode = {
type: 'element',
tagName: 'root',
children: [
{ type: 'element', tagName: 'p', children: [prose] },
{ type: 'element', tagName: 'pre', children: [block] },
],
};
rehypeTableLabels()(tree);
expect([render(prose), render(block)]).toEqual(['some_long_identifier_name_here_x', 'some_long_identifier_name_here_x']);
});

it('breaks the same text once when tables nest', () => {
const node = code(plain('some_long_identifier_name_here_x'));
const outer = inCell({ type: 'element', tagName: 'div', children: [inCell(node)] });
rehypeTableLabels()(outer);
expect(render(node)).toBe('some_|long_|identifier_|name_|here_|x');
});
});
60 changes: 57 additions & 3 deletions src/lib/table-labels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@
*
* It also marks short inline code `data-short`, which the stylesheet keeps on
* one line so a name such as `invalid-argument` does not split at its hyphen.
* Longer code, such as a URL or a default value, is left to wrap.
* Longer code, such as a URL or a default value, is left to wrap. In a table,
* where a column is narrow, long code also gets a `<wbr>` after each separator
* (`_`, `-`, `.`, `/`) and before the capital of a camelCase word, so it breaks
* at its own seams before it breaks inside a word. A `<wbr>` adds no character,
* so copying the code gives its text unchanged.
*
* Stacking sets `display: block` on the table's parts, which drops their
* table semantics in some browsers, so every part also gets its ARIA role and
Expand Down Expand Up @@ -63,8 +67,6 @@ function giveRoles(table: HastNode): void {
visit(table, false);
}

const shortCodeLength = 24;

/** Marks each inline code element of at most `shortCodeLength` characters. */
function markShortCode(tree: HastNode): void {
const visit = (node: HastNode) => {
Expand All @@ -80,9 +82,61 @@ function markShortCode(tree: HastNode): void {
visit(tree);
}

const shortCodeLength = 24;
const separators = '_-./';

/** The offsets in `value` where a line may break: after a separator, before a camelCase capital. */
function breakOffsets(value: string): number[] {
const offsets: number[] = [];
for (let i = 1; i < value.length; i++) {
const previous = value[i - 1]!;
const next = value[i]!;
const afterSeparator = separators.includes(previous) && !separators.includes(next);
const beforeCapital = /[a-z0-9]/.test(previous) && /[A-Z]/.test(next);
if (afterSeparator || beforeCapital) offsets.push(i);
}
return offsets;
}

function addBreaks(node: HastNode): void {
const children: HastNode[] = [];
for (const child of node.children ?? []) {
if (child.type === 'text') {
const value = child.value ?? '';
let start = 0;
for (const offset of breakOffsets(value)) {
children.push({ type: 'text', value: value.slice(start, offset) });
children.push({ type: 'element', tagName: 'wbr', properties: {}, children: [] });
start = offset;
}
children.push({ type: 'text', value: value.slice(start) });
} else {
if (child.type === 'element') addBreaks(child);
children.push(child);
}
}
node.children = children;
}

/** Adds break opportunities to each long inline code element in a table cell. */
function breakCodeInCells(table: HastNode): void {
const visit = (node: HastNode, inCell: boolean) => {
for (const child of node.children ?? []) {
if (child.type !== 'element' || child.tagName === 'pre' || child.tagName === 'table') continue;
if (inCell && child.tagName === 'code') {
if (text(child).trim().length > shortCodeLength) addBreaks(child);
continue;
}
visit(child, inCell || child.tagName === 'td' || child.tagName === 'th');
}
};
visit(table, false);
}

/** Gives one table's parts their roles and labels its cells from its header row. */
export function labelTable(table: HastNode): void {
giveRoles(table);
breakCodeInCells(table);
const [head] = elements(table, 'thead');
const [headRow] = head ? elements(head, 'tr') : [];
if (!headRow) return;
Expand Down
4 changes: 3 additions & 1 deletion styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,9 @@
paragraph read as part of the text rather than a row of buttons. A long
value, such as a URL, breaks anywhere rather than running off a phone; a
short one, which `rehypeTableLabels` marks `data-short`, stays whole, where
a break would split a name such as `invalid-argument` at its hyphen. */
a break would split a name such as `invalid-argument` at its hyphen. Long
code in a table cell also carries `<wbr>` at its separators, so it breaks
there first and anywhere only as a last resort. */
.prose :where(code):not(:where([class~='not-prose'], [class~='not-prose'] *)) {
overflow-wrap: anywhere;
padding: 0.125em 0.375em;
Expand Down