import type { FlatNode } from './normalize.js' import type { TableColumn } from './schema.js' export const TABLE_INSET = 16 export const TABLE_ICON = 20 const TITLE_SIZE = 17 const TITLE_LINE = 24 const ROW_SIZE = 15 const ROW_HEIGHT = 32 const GAP = 20 interface TableText { value: string x: number y: number size: number width: number kind: 'title' | 'name' | 'key' | 'type' } // Allow room for wide SQL identifiers and CJK across the SVG font fallbacks. function widthOf(value: string, size: number): number { let width = 0 let adjustedWidth = 0 for (const char of value) { const advance = char.charCodeAt(0) > 127 || /[MW@%&]/.test(char) ? 1.08 : 0.66 width += advance * size if (/[mw]/.test(char)) adjustedWidth += size else if (/[DGHOQUVXY]/.test(char)) adjustedWidth += 0.82 * size else if (/[ .,:;!iltI]/.test(char)) adjustedWidth += 0.4 * size else adjustedWidth += advance * size } return Math.ceil(Math.max(width, adjustedWidth)) } function keyOf(column: TableColumn): string { if (column.primaryKey) return column.foreignKey ? 'PK, FK' : 'PK' return column.foreignKey ? 'FK' : '' } export function tableLayout(node: FlatNode, columns: readonly TableColumn[], width?: number) { const title = node.label.split('\n') const titleX = TABLE_INSET + (node.type ? TABLE_ICON + 10 : 0) const headerHeight = 42 + (title.length - 1) * TITLE_LINE const titleWidth = title.reduce((max, line) => Math.max(max, widthOf(line, TITLE_SIZE)), 0) const max = { key: 0, name: 0, type: 0 } const rows = columns.map((column) => { const key = keyOf(column) const type = column.type ?? '' const widths = { key: widthOf(key, ROW_SIZE), name: widthOf(column.name, ROW_SIZE), type: widthOf(type, ROW_SIZE), } max.key = Math.max(max.key, widths.key) max.name = Math.max(max.name, widths.name) max.type = Math.max(max.type, widths.type) return { key, name: column.name, type, widths } }) const nameX = TABLE_INSET + (max.key ? max.key + GAP : 0) const statusSpace = node.status ? 24 : 0 const preferredWidth = Math.max( 160, titleX + titleWidth + statusSpace + TABLE_INSET, nameX + max.name + (max.type ? GAP + max.type : 0) + TABLE_INSET, ) const typeX = (width ?? preferredWidth) - TABLE_INSET return { width: preferredWidth, height: headerHeight + rows.length * ROW_HEIGHT + 6, headerHeight, text: (): TableText[] => { const lines: TableText[] = title.map((value, index) => ({ value, x: titleX, y: 27 + index * TITLE_LINE, size: TITLE_SIZE, width: widthOf(value, TITLE_SIZE), kind: 'title', })) for (const [index, row] of rows.entries()) { const y = headerHeight + index * ROW_HEIGHT + 22 lines.push({ value: row.name, x: nameX, y, size: ROW_SIZE, width: row.widths.name, kind: 'name', }) if (row.key) lines.push({ value: row.key, x: TABLE_INSET, y, size: ROW_SIZE, width: row.widths.key, kind: 'key', }) if (row.type) lines.push({ value: row.type, x: typeX, y, size: ROW_SIZE, width: row.widths.type, kind: 'type', }) } return lines }, } }