Loading generateBaseline/htmlToGridTable.py +119 −66 Changes for generateBaseline/htmlToGridTable.py: 119 added lines, 66 removed lines. Original line number Diff line number Diff line Loading @@ -13,6 +13,7 @@ Cell content (including existing markdown) is preserved as-is. from __future__ import annotations import re from typing import Optional, Any from bs4 import BeautifulSoup, NavigableString, Comment Loading Loading @@ -197,6 +198,99 @@ def _formatCellContent(content: str, totalWidth: int) -> str: return ' ' + content + (' ' * padding) + ' ' class _GridLine: """One visual line of a grid cell. hardBreak is an explicit <br>/newline between segments (Pandoc '\\' continuation). Word-wrap lines inside a segment are not hard breaks. """ __slots__ = ('text', 'hardBreak') def __init__(self, text: str, hardBreak: bool) -> None: self.text = text self.hardBreak = hardBreak def _wordWrapGrid(text: str, maxWidth: int) -> list[str]: """Word-wrap to at most maxWidth characters. Long words are hard-broken. Port of TableEditor.wordWrapGrid in static/script.js, with long words broken even when they do not start the line so a column cannot exceed maxWidth. """ if maxWidth <= 0 or len(text) <= maxWidth: return [text] words = text.split(' ') lines: list[str] = [] current = '' for word in words: if len(word) > maxWidth: if current: lines.append(current) current = '' for i in range(0, len(word), maxWidth): lines.append(word[i:i + maxWidth]) continue if not current: current = word elif len(current) + 1 + len(word) <= maxWidth: current += ' ' + word else: lines.append(current) current = word if current: lines.append(current) return lines or [''] def _splitCellForGrid(raw: str, maxColWidth: Optional[int]) -> list[_GridLine]: """Split cell text into grid lines. When maxColWidth is set, this matches TableEditor.splitCellForGrid: segments separated by <br> or newlines are word-wrapped, and only the last line of a segment that is followed by another segment is a hard break. Without a limit, each existing newline is a hard break (HTML conversion). """ text = raw or '' jsStyle = maxColWidth is not None and maxColWidth > 0 if not jsStyle: parts = text.split('\n') if text else [''] if not parts: parts = [''] return [_GridLine(part, i < len(parts) - 1) for i, part in enumerate(parts)] normalized = re.sub(r'<br\s*/?>', '\n', text, flags=re.IGNORECASE) brSegments = [segment.strip() for segment in normalized.split('\n')] result: list[_GridLine] = [] lastSegment = len(brSegments) - 1 for si, seg in enumerate(brSegments): wrapped = _wordWrapGrid(seg, maxColWidth) # The '\\' continuation must still fit inside the column. if si != lastSegment and wrapped and len(wrapped[-1]) >= maxColWidth: wrapped = _wordWrapGrid(seg, max(1, maxColWidth - 1)) if not wrapped: wrapped = [''] lastLine = len(wrapped) - 1 for li, line in enumerate(wrapped): result.append(_GridLine(line, li == lastLine and si != lastSegment)) if not result: result.append(_GridLine('', False)) return result def _gridLineDisplay(entry: _GridLine, jsStyle: bool) -> str: if not entry.hardBreak: return entry.text # script.js appends '\\' only. The HTML path keeps the historical ' \\'. return entry.text + '\\' if jsStyle else entry.text + ' \\' def _gridLineWidth(entry: _GridLine, jsStyle: bool) -> int: if not entry.hardBreak: return len(entry.text) return len(entry.text) + (1 if jsStyle else 2) def _formatAlignSegment(innerWidth: int, char: str, alignment: str) -> str: """Format one separator segment between + signs with per-column alignment colons.""" if innerWidth <= 0: Loading Loading @@ -285,7 +379,9 @@ def _buildPlacementGrid(table: list[list[_HtmlCell]], maxCols: int) -> list[list return grid def _updateColWidths(table: list[list[_HtmlCell]], maxCols: int, colWidths: list[int]) -> None: def _updateColWidths(table: list[list[_HtmlCell]], maxCols: int, colWidths: list[int], maxColWidth: Optional[int] = None) -> None: jsStyle = maxColWidth is not None and maxColWidth > 0 grid = _buildPlacementGrid(table, maxCols) for row in grid: for colIdx, cell in enumerate(row): Loading @@ -293,12 +389,8 @@ def _updateColWidths(table: list[list[_HtmlCell]], maxCols: int, colWidths: list continue if cell.content == '' and cell.colspan == 1: continue cellLines = cell.content.split('\n') maxLineLength = 0 for i, line in enumerate(cellLines): # Pandoc multi-line continuation adds ' \' (+2) on non-last lines extra = 2 if len(cellLines) > 1 and i < len(cellLines) - 1 else 0 maxLineLength = max(maxLineLength, len(line) + extra) entries = _splitCellForGrid(cell.content, maxColWidth if jsStyle else None) maxLineLength = max((_gridLineWidth(entry, jsStyle) for entry in entries), default=0) if maxLineLength == 0: continue minWidth = maxLineLength if cell.colspan == 1 else -(-maxLineLength // cell.colspan) Loading @@ -308,7 +400,8 @@ def _updateColWidths(table: list[list[_HtmlCell]], maxCols: int, colWidths: list def _generateGridSubTable(table: list[list[_HtmlCell]], maxCols: int, colWidths: list[int], colAlignments: Optional[list[str]] = None, alignmentOn: Optional[str] = None) -> str: alignmentOn: Optional[str] = None, maxColWidth: Optional[int] = None) -> str: """Generate a grid sub-table. alignmentOn: 'first' or 'last' — which separator line receives per-column : alignment markers. Loading @@ -316,6 +409,7 @@ def _generateGridSubTable(table: list[list[_HtmlCell]], maxCols: int, colWidths: if not table: return '' jsStyle = maxColWidth is not None and maxColWidth > 0 grid = _buildPlacementGrid(table, maxCols) def formatRow(rowIdx: int, lineIndex: int = 0) -> str: Loading @@ -332,20 +426,10 @@ def _generateGridSubTable(table: list[list[_HtmlCell]], maxCols: int, colWidths: cell = row[col] if cell is not None and not cell.merged: cellContent = cell.content if cell.content is not None else '' # Do not trim lines — preserve markdown indentation / spacing cellLines = cellContent.split('\n') entries = _splitCellForGrid(cellContent, maxColWidth if jsStyle else None) width = _calculateCellWidth(col, cell.colspan, colWidths) if len(cellLines) > 1: if lineIndex < len(cellLines): lineContent = cellLines[lineIndex] if lineIndex < len(cellLines) - 1: lineContent += ' \\' line += _formatCellContent(lineContent, width) else: line += ' ' * width else: if lineIndex == 0: line += _formatCellContent(cellContent, width) if lineIndex < len(entries): line += _formatCellContent(_gridLineDisplay(entries[lineIndex], jsStyle), width) else: line += ' ' * width col += cell.colspan Loading @@ -362,7 +446,7 @@ def _generateGridSubTable(table: list[list[_HtmlCell]], maxCols: int, colWidths: for col in range(maxCols): cell = row[col] if cell is not None and not cell.merged and cell.content: maxLines = max(maxLines, len(cell.content.split('\n'))) maxLines = max(maxLines, len(_splitCellForGrid(cell.content, maxColWidth if jsStyle else None))) return maxLines firstAlign = colAlignments if alignmentOn == 'first' else None Loading @@ -378,9 +462,14 @@ def _generateGridSubTable(table: list[list[_HtmlCell]], maxCols: int, colWidths: lines.append(_createSeparator(colWidths, maxCols, '-', colAlignments=lastAlign)) return '\n'.join(lines) def generateGridTableFromRows(headerRows: list[list[_HtmlCell]], bodyRows: list[list[_HtmlCell]]) -> str: """Assemble a Pandoc grid table from parsed header/body cell rows.""" def generateGridTableFromRows(headerRows: list[list[_HtmlCell]], bodyRows: list[list[_HtmlCell]], maxColWidth: Optional[int] = None) -> str: """Generate a Pandoc-style grid table from already-parsed header and body rows. maxColWidth, when set, word-wraps each cell to that many characters before measuring columns (same role as TableEditor.gridTableMaxCol in script.js). """ if not headerRows and not bodyRows: return '' Loading @@ -391,19 +480,19 @@ def generateGridTableFromRows(headerRows: list[list[_HtmlCell]], colWidths = [1] * maxCols if headerRows: _updateColWidths(headerRows, maxCols, colWidths) _updateColWidths(headerRows, maxCols, colWidths, maxColWidth) if bodyRows: _updateColWidths(bodyRows, maxCols, colWidths) _updateColWidths(bodyRows, maxCols, colWidths, maxColWidth) colAlignments = _deriveColumnAlignments(headerRows, bodyRows, maxCols) headerGridTable = ( _generateGridSubTable(headerRows, maxCols, colWidths, colAlignments, 'last') _generateGridSubTable(headerRows, maxCols, colWidths, colAlignments, 'last', maxColWidth) if headerRows else '' ) bodyAlignmentOn = 'first' if not headerRows else None bodyGridTable = ( _generateGridSubTable(bodyRows, maxCols, colWidths, colAlignments, bodyAlignmentOn) _generateGridSubTable(bodyRows, maxCols, colWidths, colAlignments, bodyAlignmentOn, maxColWidth) if bodyRows else '' ) Loading Loading @@ -436,40 +525,4 @@ def generateGridTableFromHtml(htmlContent: str) -> str: ValueError: If no table is found or the table is empty. """ headerRows, bodyRows = _parseHtmlTableStructure(htmlContent) if not headerRows and not bodyRows: return '' allRows = headerRows + bodyRows maxCols = max((cell.col + cell.colspan for row in allRows for cell in row), default=0) if maxCols == 0: return '' colWidths = [1] * maxCols if headerRows: _updateColWidths(headerRows, maxCols, colWidths) if bodyRows: _updateColWidths(bodyRows, maxCols, colWidths) colAlignments = _deriveColumnAlignments(headerRows, bodyRows, maxCols) headerGridTable = ( _generateGridSubTable(headerRows, maxCols, colWidths, colAlignments, 'last') if headerRows else '' ) bodyAlignmentOn = 'first' if not headerRows else None bodyGridTable = ( _generateGridSubTable(bodyRows, maxCols, colWidths, colAlignments, bodyAlignmentOn) if bodyRows else '' ) if headerGridTable: headerLines = headerGridTable.split('\n') headerLines[-1] = headerLines[-1].replace('-', '=') bodyLines = bodyGridTable.split('\n') if bodyGridTable else [] if bodyLines: bodyLines = bodyLines[1:] # drop body's top border if bodyLines: return '\n'.join(headerLines) + '\n' + '\n'.join(bodyLines) return '\n'.join(headerLines) return bodyGridTable return generateGridTableFromRows(headerRows, bodyRows) Loading
generateBaseline/htmlToGridTable.py +119 −66 Changes for generateBaseline/htmlToGridTable.py: 119 added lines, 66 removed lines. Original line number Diff line number Diff line Loading @@ -13,6 +13,7 @@ Cell content (including existing markdown) is preserved as-is. from __future__ import annotations import re from typing import Optional, Any from bs4 import BeautifulSoup, NavigableString, Comment Loading Loading @@ -197,6 +198,99 @@ def _formatCellContent(content: str, totalWidth: int) -> str: return ' ' + content + (' ' * padding) + ' ' class _GridLine: """One visual line of a grid cell. hardBreak is an explicit <br>/newline between segments (Pandoc '\\' continuation). Word-wrap lines inside a segment are not hard breaks. """ __slots__ = ('text', 'hardBreak') def __init__(self, text: str, hardBreak: bool) -> None: self.text = text self.hardBreak = hardBreak def _wordWrapGrid(text: str, maxWidth: int) -> list[str]: """Word-wrap to at most maxWidth characters. Long words are hard-broken. Port of TableEditor.wordWrapGrid in static/script.js, with long words broken even when they do not start the line so a column cannot exceed maxWidth. """ if maxWidth <= 0 or len(text) <= maxWidth: return [text] words = text.split(' ') lines: list[str] = [] current = '' for word in words: if len(word) > maxWidth: if current: lines.append(current) current = '' for i in range(0, len(word), maxWidth): lines.append(word[i:i + maxWidth]) continue if not current: current = word elif len(current) + 1 + len(word) <= maxWidth: current += ' ' + word else: lines.append(current) current = word if current: lines.append(current) return lines or [''] def _splitCellForGrid(raw: str, maxColWidth: Optional[int]) -> list[_GridLine]: """Split cell text into grid lines. When maxColWidth is set, this matches TableEditor.splitCellForGrid: segments separated by <br> or newlines are word-wrapped, and only the last line of a segment that is followed by another segment is a hard break. Without a limit, each existing newline is a hard break (HTML conversion). """ text = raw or '' jsStyle = maxColWidth is not None and maxColWidth > 0 if not jsStyle: parts = text.split('\n') if text else [''] if not parts: parts = [''] return [_GridLine(part, i < len(parts) - 1) for i, part in enumerate(parts)] normalized = re.sub(r'<br\s*/?>', '\n', text, flags=re.IGNORECASE) brSegments = [segment.strip() for segment in normalized.split('\n')] result: list[_GridLine] = [] lastSegment = len(brSegments) - 1 for si, seg in enumerate(brSegments): wrapped = _wordWrapGrid(seg, maxColWidth) # The '\\' continuation must still fit inside the column. if si != lastSegment and wrapped and len(wrapped[-1]) >= maxColWidth: wrapped = _wordWrapGrid(seg, max(1, maxColWidth - 1)) if not wrapped: wrapped = [''] lastLine = len(wrapped) - 1 for li, line in enumerate(wrapped): result.append(_GridLine(line, li == lastLine and si != lastSegment)) if not result: result.append(_GridLine('', False)) return result def _gridLineDisplay(entry: _GridLine, jsStyle: bool) -> str: if not entry.hardBreak: return entry.text # script.js appends '\\' only. The HTML path keeps the historical ' \\'. return entry.text + '\\' if jsStyle else entry.text + ' \\' def _gridLineWidth(entry: _GridLine, jsStyle: bool) -> int: if not entry.hardBreak: return len(entry.text) return len(entry.text) + (1 if jsStyle else 2) def _formatAlignSegment(innerWidth: int, char: str, alignment: str) -> str: """Format one separator segment between + signs with per-column alignment colons.""" if innerWidth <= 0: Loading Loading @@ -285,7 +379,9 @@ def _buildPlacementGrid(table: list[list[_HtmlCell]], maxCols: int) -> list[list return grid def _updateColWidths(table: list[list[_HtmlCell]], maxCols: int, colWidths: list[int]) -> None: def _updateColWidths(table: list[list[_HtmlCell]], maxCols: int, colWidths: list[int], maxColWidth: Optional[int] = None) -> None: jsStyle = maxColWidth is not None and maxColWidth > 0 grid = _buildPlacementGrid(table, maxCols) for row in grid: for colIdx, cell in enumerate(row): Loading @@ -293,12 +389,8 @@ def _updateColWidths(table: list[list[_HtmlCell]], maxCols: int, colWidths: list continue if cell.content == '' and cell.colspan == 1: continue cellLines = cell.content.split('\n') maxLineLength = 0 for i, line in enumerate(cellLines): # Pandoc multi-line continuation adds ' \' (+2) on non-last lines extra = 2 if len(cellLines) > 1 and i < len(cellLines) - 1 else 0 maxLineLength = max(maxLineLength, len(line) + extra) entries = _splitCellForGrid(cell.content, maxColWidth if jsStyle else None) maxLineLength = max((_gridLineWidth(entry, jsStyle) for entry in entries), default=0) if maxLineLength == 0: continue minWidth = maxLineLength if cell.colspan == 1 else -(-maxLineLength // cell.colspan) Loading @@ -308,7 +400,8 @@ def _updateColWidths(table: list[list[_HtmlCell]], maxCols: int, colWidths: list def _generateGridSubTable(table: list[list[_HtmlCell]], maxCols: int, colWidths: list[int], colAlignments: Optional[list[str]] = None, alignmentOn: Optional[str] = None) -> str: alignmentOn: Optional[str] = None, maxColWidth: Optional[int] = None) -> str: """Generate a grid sub-table. alignmentOn: 'first' or 'last' — which separator line receives per-column : alignment markers. Loading @@ -316,6 +409,7 @@ def _generateGridSubTable(table: list[list[_HtmlCell]], maxCols: int, colWidths: if not table: return '' jsStyle = maxColWidth is not None and maxColWidth > 0 grid = _buildPlacementGrid(table, maxCols) def formatRow(rowIdx: int, lineIndex: int = 0) -> str: Loading @@ -332,20 +426,10 @@ def _generateGridSubTable(table: list[list[_HtmlCell]], maxCols: int, colWidths: cell = row[col] if cell is not None and not cell.merged: cellContent = cell.content if cell.content is not None else '' # Do not trim lines — preserve markdown indentation / spacing cellLines = cellContent.split('\n') entries = _splitCellForGrid(cellContent, maxColWidth if jsStyle else None) width = _calculateCellWidth(col, cell.colspan, colWidths) if len(cellLines) > 1: if lineIndex < len(cellLines): lineContent = cellLines[lineIndex] if lineIndex < len(cellLines) - 1: lineContent += ' \\' line += _formatCellContent(lineContent, width) else: line += ' ' * width else: if lineIndex == 0: line += _formatCellContent(cellContent, width) if lineIndex < len(entries): line += _formatCellContent(_gridLineDisplay(entries[lineIndex], jsStyle), width) else: line += ' ' * width col += cell.colspan Loading @@ -362,7 +446,7 @@ def _generateGridSubTable(table: list[list[_HtmlCell]], maxCols: int, colWidths: for col in range(maxCols): cell = row[col] if cell is not None and not cell.merged and cell.content: maxLines = max(maxLines, len(cell.content.split('\n'))) maxLines = max(maxLines, len(_splitCellForGrid(cell.content, maxColWidth if jsStyle else None))) return maxLines firstAlign = colAlignments if alignmentOn == 'first' else None Loading @@ -378,9 +462,14 @@ def _generateGridSubTable(table: list[list[_HtmlCell]], maxCols: int, colWidths: lines.append(_createSeparator(colWidths, maxCols, '-', colAlignments=lastAlign)) return '\n'.join(lines) def generateGridTableFromRows(headerRows: list[list[_HtmlCell]], bodyRows: list[list[_HtmlCell]]) -> str: """Assemble a Pandoc grid table from parsed header/body cell rows.""" def generateGridTableFromRows(headerRows: list[list[_HtmlCell]], bodyRows: list[list[_HtmlCell]], maxColWidth: Optional[int] = None) -> str: """Generate a Pandoc-style grid table from already-parsed header and body rows. maxColWidth, when set, word-wraps each cell to that many characters before measuring columns (same role as TableEditor.gridTableMaxCol in script.js). """ if not headerRows and not bodyRows: return '' Loading @@ -391,19 +480,19 @@ def generateGridTableFromRows(headerRows: list[list[_HtmlCell]], colWidths = [1] * maxCols if headerRows: _updateColWidths(headerRows, maxCols, colWidths) _updateColWidths(headerRows, maxCols, colWidths, maxColWidth) if bodyRows: _updateColWidths(bodyRows, maxCols, colWidths) _updateColWidths(bodyRows, maxCols, colWidths, maxColWidth) colAlignments = _deriveColumnAlignments(headerRows, bodyRows, maxCols) headerGridTable = ( _generateGridSubTable(headerRows, maxCols, colWidths, colAlignments, 'last') _generateGridSubTable(headerRows, maxCols, colWidths, colAlignments, 'last', maxColWidth) if headerRows else '' ) bodyAlignmentOn = 'first' if not headerRows else None bodyGridTable = ( _generateGridSubTable(bodyRows, maxCols, colWidths, colAlignments, bodyAlignmentOn) _generateGridSubTable(bodyRows, maxCols, colWidths, colAlignments, bodyAlignmentOn, maxColWidth) if bodyRows else '' ) Loading Loading @@ -436,40 +525,4 @@ def generateGridTableFromHtml(htmlContent: str) -> str: ValueError: If no table is found or the table is empty. """ headerRows, bodyRows = _parseHtmlTableStructure(htmlContent) if not headerRows and not bodyRows: return '' allRows = headerRows + bodyRows maxCols = max((cell.col + cell.colspan for row in allRows for cell in row), default=0) if maxCols == 0: return '' colWidths = [1] * maxCols if headerRows: _updateColWidths(headerRows, maxCols, colWidths) if bodyRows: _updateColWidths(bodyRows, maxCols, colWidths) colAlignments = _deriveColumnAlignments(headerRows, bodyRows, maxCols) headerGridTable = ( _generateGridSubTable(headerRows, maxCols, colWidths, colAlignments, 'last') if headerRows else '' ) bodyAlignmentOn = 'first' if not headerRows else None bodyGridTable = ( _generateGridSubTable(bodyRows, maxCols, colWidths, colAlignments, bodyAlignmentOn) if bodyRows else '' ) if headerGridTable: headerLines = headerGridTable.split('\n') headerLines[-1] = headerLines[-1].replace('-', '=') bodyLines = bodyGridTable.split('\n') if bodyGridTable else [] if bodyLines: bodyLines = bodyLines[1:] # drop body's top border if bodyLines: return '\n'.join(headerLines) + '\n' + '\n'.join(bodyLines) return '\n'.join(headerLines) return bodyGridTable return generateGridTableFromRows(headerRows, bodyRows)