import { readFileSync } from 'node:fs'; import path from 'node:path'; import { describe, expect, it } from 'vitest'; import { renderSvg } from '../src/cli/svg'; import { checkSource } from '../src/dsl/compile'; import { projectScene } from '../src/dsl/project'; import { formatSource, parseModel, printSource, readSource } from '../src/dsl/syntax'; import { translateEdit, UnsupportedEdit } from '../src/dsl/translate'; import { resolveAppearance } from '../src/model/appearance'; import { CODE_ADVANCE, CODE_PAD, CODE_TYPE, codeLayout, type CodeBlock } from '../src/model/code'; import { pastedTable, tableLines, writeTable } from '../src/model/code-table'; import { FACES } from '../src/model/fonts'; import { clone } from '../src/model/geometry'; import type { Diagram } from '../src/model/types'; const fixture = (name: string) => readFileSync(path.join(__dirname, 'fixtures/code', name + '.draft'), 'utf8'); const look = resolveAppearance(); const block = (lines: string[], extra: Partial = {}): CodeBlock => ({ lines, wrap: true, numbers: false, start: 1, maxWidth: 960, sourceLine: 2, ...extra, }); describe('code node source', () => { it('keeps a body byte for byte through format, and lines after it keep their numbers', () => { const body = [ '\t{ "a": "x # not a comment" } ', ' echo "$(date)" \\', '', ' // still text', ]; const source = [ 'diagram "t"', `node c "c.json" shape=code lang=json < l.kind === 'statement' && l.args[0]?.value === 'b'); expect(b && 'line' in b && b.line).toBe(8); }); it('dedents across every line, so a diff keeps its first column, and expands tabs', () => { const m = parseModel( 'node d shape=code lang=diff < { expect(() => readSource('diagram "t"\nnode c shape=code < parseModel('node c "C" shape=code')).toThrow(/A code node needs a body/); expect(() => parseModel('node c "C" < parseModel('node c "C" lang=sql')).toThrow(/lang= belongs on a code node/); // A body on any other statement would swallow the lines after it. expect(() => parseModel('node a "A"\nnode b "B"\nedge e a -> b "x" < { it('sizes to the longest line with no growth cap, and places columns exactly', () => { const line = 'x'.repeat(100), laid = codeLayout(block([' a', line]), '', look); expect(laid.w).toBe(Math.ceil(2 * CODE_PAD.x + 100 * CODE_ADVANCE + 0.01)); expect(laid.rows.map(r => r.col)).toEqual([0, 0]); expect(laid.long).toEqual([]); }); it('wraps a long line with a hanging indent, or clips it with wrap=off', () => { const line = ' ' + 'word '.repeat(60).trim(), wrapped = codeLayout(block([line], { maxWidth: 400 }), '', look); expect(wrapped.rows.length).toBeGreaterThan(1); expect(wrapped.rows[0].wraps).toBe(true); expect(wrapped.rows.slice(1).every(r => r.col === 6)).toBe(true); // Every character is drawn exactly once. const shown = wrapped.rows.map(r => line.slice(r.from, r.to)).join(''); expect(shown.replace(/ /g, '')).toBe(line.replace(/ /g, '')); const clipped = codeLayout(block([line], { maxWidth: 400, wrap: false }), '', look); expect(clipped.rows).toHaveLength(1); expect(clipped.rows[0]).toMatchObject({ clipped: true, to: clipped.cols - 1 }); }); it('draws no "more lines" row outside a box too short to hold it', () => { const laid = codeLayout(block(['a', 'b', 'c']), 'f.sql', look, { height: 20 }); expect(laid).toMatchObject({ h: 20, rows: [], more: 3, moreShown: false }); const roomy = codeLayout(block(['a', 'b', 'c']), 'f.sql', look, { height: 80 }); expect(roomy.moreShown).toBe(true); expect(roomy.moreY + 17).toBeLessThanOrEqual(80); }); it('never breaks a line inside its leading indent', () => { const line = ' '.repeat(20) + 'x'.repeat(40), laid = codeLayout(block([line]), '', look, { width: 200 }); expect(laid.rows.length).toBeGreaterThan(1); for (const r of laid.rows) expect(line.slice(r.from, r.to).trim()).not.toBe(''); }); it('clips a fixed height to whole lines and counts the rest', () => { const lines = Array.from({ length: 30 }, (_, i) => `line ${i}`), laid = codeLayout(block(lines, { numbers: true, start: 98 }), 'f.sql', look, { height: 150, }); expect(laid.h).toBe(150); expect(laid.more).toBe(30 - laid.rows.length); expect(laid.moreY + 17).toBeLessThanOrEqual(150); expect(laid.numberCols).toBe(3); }); }); describe('code tables', () => { it('finds columns from runs of spaces or blank positions, and right-aligns numbers', () => { // Ragged gaps of two or more spaces. expect(tableLines(['name cat count', 'apple fruit 10', 'bread bakery 4'])).toEqual([ 'name cat count', 'apple fruit 10', 'bread bakery 4', ]); // Single spaces in a cell, aligned by hand: blank positions split the columns. expect(tableLines(['city pop', 'New York 8.3', 'Rome 2.8'])).toEqual([ 'city pop', 'New York 8.3', 'Rome 2.8', ]); // One column is no table: the text stays as it is. expect(tableLines(['apples', 'kiwi'])).toEqual(['apples', 'kiwi']); }); it('reads Markdown and psql pastes, drops a typed rule and keeps its alignment marks', () => { // `:---` holds a number column left; units and NULL still count as numbers. expect( tableLines([ '| id | ms | note |', '|:---|---:|------|', '| 7 | 12ms | ok |', '| 10 | NULL | x |', ]), ).toEqual(['id ms note', '7 12ms ok', '10 NULL x']); expect(tableLines([' id | plan', '----+------', ' 1 | pro', ' 2 | free'])).toEqual([ 'id plan', ' 1 pro', ' 2 free', ]); // `:---:` centres; a psql row count stays as its own line, out of the columns. expect(tableLines(['| a | b |', '|:-:|---|', '| x | 1 |', '| long | 2 |'])).toEqual([ ' a b', ' x 1', 'long 2', ]); expect(tableLines([' id | n', '----+---', ' 1 | 5', '(1 row)'])).toEqual([ 'id n', ' 1 5', '(1 row)', ]); // The old workaround: dashes typed under the header. expect(tableLines(['name n', '----- --', 'apple 10'])).toEqual(['name n', 'apple 10']); }); it('draws the rule in a gap under the header, clear of both rows', () => { const lh = CODE_TYPE.lineHeight, plain = codeLayout(block(['a b', '1 2', '3 4']), 'q', look), laid = codeLayout(block(['a b', '1 2', '3 4'], { table: true }), 'q', look), gap = laid.rows[1].y - laid.rows[0].y - lh; expect(plain.rule).toBeUndefined(); expect(gap).toBeGreaterThan(0); expect(laid.rule).toBe(laid.rows[0].y + lh + gap / 2); expect(laid.rows[2].y - laid.rows[1].y).toBe(lh); expect(laid.h).toBe(plain.h + gap); // A box wider than its table: the rule stops at the table's last column. const wide = codeLayout(block(['k v', '1 2'], { table: true }), 'a long caption here', look); expect(wide.ruleEnd).toBe(CODE_PAD.x + 4 * CODE_ADVANCE); expect(wide.ruleEnd).toBeLessThan(wide.w - CODE_PAD.x); // A box too short to show the header draws no rule. expect(codeLayout(block(['a', 'b'], { table: true }), 'q', look, { height: 20 }).rule).toBe( undefined, ); }); it('keeps line numbers for ranges, and draws the rule in the SVG', () => { const doc = projectScene( checkSource( [ 'node df "Query result" shape=code table=on < n.id === 'df')!; expect(node.code!.lines).toEqual([ 'name cat count', 'apple fruit 10', 'bread bakery 4', ]); expect(node.code!.ranges![0]).toMatchObject({ from: 2, to: 2 }); expect(renderSvg(doc)).toContain('class="code-rule"'); }); }); describe('code nodes in a diagram', () => { it('reports long lines, a clipped body and an unknown language', () => { const scene = checkSource( [ 'node a shape=code lang=cobol < `row ${i}`), 'C', 'size d width=200 height=100', ].join('\n'), ); const codes = scene.diagnostics.map(d => `${d.code}@${d.line}`); expect(codes).toEqual( expect.arrayContaining(['code-lang@1', 'code-wrap@6', 'code-clip@9', 'code-clipped@33']), ); }); it('draws every sample with left-aligned runs at column x, in JetBrains Mono', () => { for (const name of ['sql', 'python', 'config', 'shell', 'diff']) { const doc = projectScene(checkSource(fixture(name))), svg = renderSvg(doc); expect(svg).not.toContain('xml:space'); expect(svg).toContain(`font-family:'${FACES['mono-500'].family}'`); expect(svg).toMatch(//); } const doc = projectScene(checkSource(fixture('diff'))), r = doc.layout.nodes.fix, svg = renderSvg(doc); // ` same`-style lines keep their first column: `+` sits in column 0 at the left padding. expect(svg).toContain(` { const source = fixture('config'), scene = checkSource(source), before = projectScene(scene), run = (fn: (d: Diagram) => void) => { const after = clone(before); fn(after); return printSource( translateEdit({ source: readSource(source), scene, before, after, label: 'Edit', selection: ['yaml'], }).source, ); }; const renamed = run(d => (d.graph.nodes.find(n => n.id === 'yaml')!.title = 'values.yaml')); expect(renamed).toContain('node yaml "values.yaml" shape=code lang=yaml < run(d => (d.styles.yaml.shape = 'box'))).toThrow(UnsupportedEdit); }); }); describe('editing code tables', () => { it('saves an edited body and the table setting to the source, and only those', () => { const save = ( source: string, edit: (code: CodeBlock, node: Diagram['graph']['nodes'][0]) => void, ) => { const scene = checkSource(source), before = projectScene(scene), after = clone(before), node = after.graph.nodes[0]; edit(node.code!, node); return printSource( translateEdit({ source: readSource(source), scene, before, after, label: 'Edit', selection: [], }).source, ); }; // A pasted table, turned on. const pasted = writeTable(pastedTable('id\tms\n1\t12\n2\t7')!); expect( save('node q "Result" shape=code < { c.table = true; c.body = pasted; }), ).toBe('node q "Result" shape=code table=on < { delete c.table; c.body = ['id name', ' 1 ana']; }), ).toBe('node t shape=code < (n.title = 'b'))).toBe(tabbed.replace('"a"', '"b"')); // A caption edit made while the file changed underneath never writes the old body back. const older = 'node c "a" shape=code < translateEdit({ source: readSource(newer), scene, before, after: bodyEdit, label: 'Edit', selection: [], }), ).toThrow(UnsupportedEdit); // A file's lines are never written over. const file = 'node f shape=code src="a.sql"\n', fileScene = checkSource(file, { 'a.sql': { text: 'x\n' } }), was = projectScene(fileScene), edited = clone(was); edited.graph.nodes[0].code = { ...edited.graph.nodes[0].code!, body: ['y'] }; expect(() => translateEdit({ source: readSource(file), scene: fileScene, before: was, after: edited, label: 'Edit', selection: [], }), ).toThrow(UnsupportedEdit); }); });