feat: add table options

This commit is contained in:
Steffen Becker committed 2026-08-06 20:01:44 +02:00
1 parent 1ed9f3d172
commit d608771105
18 files changed
+677 -96

No files matched your search

+5 -1
View File
@@ -35,6 +35,10 @@
- Style gallery in the toolbar lists both families; assigning a style keeps hard formatting (Word/LibreOffice behavior), Ctrl+M clears direct formatting but keeps the style
- Style manager ("Manage styles…"): inheritance tree, live property editing (empty field = inherit again), new / update from selection, rename, delete, reset a built-in — for paragraph and character styles alike
- Round-trips as real styles, not baked formatting: ODF `style:style` (`style:family="paragraph"`/`"text"`, `style:parent-style-name`, `style:next-style-name`) and DOCX `w:pStyle`/`w:rStyle` with `w:basedOn`/`w:next`; import adopts the file's used styles plus their parent chains, so only formatting beyond the style stays direct
- Named table styles as the third family (Word's table styles / LibreOffice's AutoFormats): 14 built-ins — Grid (+ rows / columns only), List shaded / columns, Plain, four colored box lists, Grid & List Accent, Academic, Financial. Picking one from the gallery in the table toolbar paints header row, banded rows/columns, first/last column and total row, and a styled table re-bands itself when rows or columns are added
- Word's Table Style Options as six checkboxes beside the gallery (header row, total row, first/last column, banded rows/columns): an area is painted only when the style defines it *and* the table opts in, and turning the header row off shifts the banding by one row. The toolbar's header row / first column buttons drive the same flags, so both surfaces always agree
- Table styles are edited in the same style manager (third tab: area picker for fill and font, outer / row line / column line controls, new / rename / remove), also reachable from the insert-table dropdown
- Round-trip: the style name travels as an ODF `style:family="table"` (`style:parent-style-name`) and DOCX `w:tblStyle`, the options as ODF's `table:use-*-styles` and Word's `w:tblLook`. Fills and borders are materialized into the cells and the region's font is baked onto the runs, so the table looks right in Word/LibreOffice even though ODF has no banding concept — the style definitions themselves live in the app, as LibreOffice's AutoFormats do
- A new document starts from the built-in styles, like Word's/LibreOffice's default template
**Paragraphs & lists**
@@ -48,7 +52,7 @@
- Tab stops (real tab character) and manual line breaks (Shift+Enter)
**Insert**
- Tables: insert via size picker, Word-style row/column drag-resize, add / delete rows & columns, delete table, cell borders, merge cells and split cells (N×M, Word/LibreOffice-style), cell background shading, header-row toggle (bold + shading); a table splits cleanly across page boundaries
- Tables: insert via size picker, Word-style row/column drag-resize, add / delete rows & columns, delete table, cell borders, merge cells and split cells (N×M, Word/LibreOffice-style), cell background shading, header row / first column toggles, named table styles (see Styles); a table splits cleanly across page boundaries
- Table border control (Word/LibreOffice-style): per-side cell borders with presets (all / outside / inside / single edges / none), line width and color; buttons show active states matching the current pen and toggle borders off; round-trips to ODF `fo:border-*` and DOCX `w:tcBorders`
- Images: inline or floating with text wrap (left / right / top-bottom), resize handles, rotation, live size badge; insert via toolbar, drag-and-drop, or paste
- Special characters picker
+9 -4
View File
@@ -10,8 +10,8 @@
renameStyle, resetStyle, styleSheet,
} from '../styles/sheet.svelte';
import {
TABLE_REGIONS, previewCellCss,
type TableRegion, type TableRegionProps, type TableStyle,
TABLE_REGIONS, previewCellCss, previewTextCss,
type TableLook, type TableRegion, type TableRegionProps, type TableStyle,
} from '../styles/tableStyles';
import { borderAttrValue, parseBorderAttr } from '../editor/extensions/tableCellBorders';
import { blockStyleName } from '../editor/extensions/paragraphStyle';
@@ -103,6 +103,8 @@
tStyle?.[key] !== undefined ? tStyle[key] : key === 'border' ? undefined : tStyle?.innerBorder;
const PREVIEW_ROWS = 5;
const PREVIEW_COLS = 4;
// The manager edits the definition, not one table's options, so it shows every area.
const ALL_AREAS = Object.fromEntries(TABLE_REGIONS.map(r => [r, true])) as TableLook;
// The border select and its color picker split one canonical '<W>pt solid #RRGGBB'.
function borderParts(value: string | null | undefined) {
@@ -438,7 +440,9 @@
{#each Array(PREVIEW_ROWS) as _, r}
<tr>
{#each Array(PREVIEW_COLS) as _, c}
<td style={previewCellCss(tStyle, r, c, PREVIEW_ROWS, PREVIEW_COLS)}></td>
<td style={previewCellCss(tStyle, r, c, PREVIEW_ROWS, PREVIEW_COLS, ALL_AREAS)}>
<i class="tp-text" style={previewTextCss(tStyle, r, c, PREVIEW_ROWS, PREVIEW_COLS, ALL_AREAS)}></i>
</td>
{/each}
</tr>
{/each}
@@ -664,7 +668,8 @@
background: var(--color-page-bg);
color: var(--color-page-text);
}
.table-preview td { height: 1rem; padding: 0; }
.table-preview td { height: 1rem; padding: 0 3px; }
.tp-text { display: block; width: 100%; }
.border-row { display: flex; align-items: center; gap: 0.3rem; }
.border-row select { flex: 1; min-width: 0; }
+86 -5
View File
@@ -1,8 +1,9 @@
<script lang="ts">
import type { Editor } from '@tiptap/core';
import { activeTableStyle } from '../editor/extensions/tableStyle';
import { activeTableLook, activeTableStyle, styleRegions } from '../editor/extensions/tableStyle';
import { DEFAULT_TABLE_LOOK } from '../styles/tableStyles';
import { styleSheet } from '../styles/sheet.svelte';
import { previewCellCss } from '../styles/tableStyles';
import { previewCellCss, previewTextCss, styleLook, type TableRegion } from '../styles/tableStyles';
import { t } from '../i18n/i18n.svelte';
let { editor, tick }: { editor: Editor | null; tick: number } = $props();
@@ -11,6 +12,16 @@
const sheet = $derived(styleSheet());
const styles = $derived(Object.values(sheet.table ?? {}));
const current = $derived(tick >= 0 && editor ? activeTableStyle(editor.state) : null);
// Word's Table Style Options: the tiles preview the table's own options, and an option
// the current style doesn't paint is shown disabled.
const look = $derived(tick >= 0 && editor ? activeTableLook(editor.state) : null);
const painted = $derived(new Set(styleRegions(current ? sheet.table?.[current] : undefined)));
// Word's order in the ribbon, reading down each column.
const OPTIONS: TableRegion[] = ['headerRow', 'lastRow', 'firstColumn', 'lastColumn', 'bandedRow', 'bandedColumn'];
function toggle(region: TableRegion, on: boolean) {
editor?.chain().focus().setTableLook(region, on).run();
}
// A tile shows the style on a small grid, painted by the same resolver that paints the
// real table — so a preview can never disagree with what applying it does.
@@ -57,6 +68,7 @@
{#if open}
<div class="tsp-dropdown">
<div class="tsp-title">{t().table.tableStyle}</div>
<div class="tsp-body">
<div class="tsp-grid">
<button
class="tsp-tile"
@@ -75,6 +87,7 @@
</button>
{#each styles as style (style.name)}
{@const tileLook = styleLook(style, look ?? DEFAULT_TABLE_LOOK)}
<button
class="tsp-tile"
class:active={current === style.name}
@@ -87,7 +100,9 @@
{#each Array(ROWS) as _, r}
<tr>
{#each Array(COLS) as _, c}
<td style={previewCellCss(style, r, c, ROWS, COLS)}></td>
<td style={previewCellCss(style, r, c, ROWS, COLS, tileLook)}>
<i class="tsp-text" style={previewTextCss(style, r, c, ROWS, COLS, tileLook)}></i>
</td>
{/each}
</tr>
{/each}
@@ -97,6 +112,23 @@
</button>
{/each}
</div>
<div class="tsp-options">
<div class="tsp-title">{t().table.styleOptions}</div>
<!-- Without a style nothing is in effect yet, so the boxes read clear. -->
{#each OPTIONS as region}
<label class="tsp-option" class:muted={!painted.has(region)}>
<input
type="checkbox"
checked={!!current && !!look?.[region]}
disabled={!current}
onchange={(e) => toggle(region, e.currentTarget.checked)}
/>
{t().styles.regions[region]}
</label>
{/each}
</div>
</div>
</div>
{/if}
</div>
@@ -157,6 +189,13 @@
user-select: none;
}
/* Tiles and options side by side, as in Word's Table Design tab. */
.tsp-body {
display: flex;
align-items: flex-start;
gap: 8px;
}
.tsp-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
@@ -166,6 +205,42 @@
overflow-y: auto;
}
.tsp-options {
display: flex;
flex-direction: column;
gap: 1px;
padding-left: 8px;
border-left: 1px solid var(--color-border);
}
.tsp-option {
display: flex;
align-items: center;
gap: 0.35rem;
padding: 0.15rem 0.1rem;
font-family: var(--font-sans);
font-size: 0.7rem;
color: var(--color-text);
white-space: nowrap;
cursor: pointer;
user-select: none;
}
.tsp-option input {
margin: 0;
cursor: pointer;
}
/* The current style doesn't paint this area, so the toggle has no visible effect. */
.tsp-option.muted {
color: var(--color-text-muted);
}
.tsp-option:has(input:disabled) {
opacity: 0.5;
cursor: default;
}
.tsp-tile {
display: flex;
flex-direction: column;
@@ -200,8 +275,14 @@
}
.tsp-preview td {
height: 7px;
padding: 0;
height: 8px;
padding: 0 1px;
}
/* The schematic text line; its weight is what makes a bold-only region visible. */
.tsp-text {
display: block;
width: 100%;
}
.tsp-none {
+7 -5
View File
@@ -32,7 +32,9 @@
// Merge needs a multi-cell selection; re-evaluated per transaction via `tick`.
const canMerge = $derived(tick >= 0 && !!editor && editor.can().mergeCells());
// Whether the first row / first column is styled as a header (bold + light shading).
// Whether the header row / first column area is on. With a table style that is its
// Table Style Option (the same flag the gallery's checkbox shows), else the manual
// header shading — so the two surfaces share one state, and one label.
const isHeaderRow = $derived(tick >= 0 && !!editor && isHeaderStyled(editor.state, 'row'));
const isHeaderCol = $derived(tick >= 0 && !!editor && isHeaderStyled(editor.state, 'column'));
@@ -226,8 +228,8 @@
<button
class="tt-btn"
class:active={isHeaderRow}
title={t().table.headerRow}
aria-label={t().table.headerRowAria}
title={t().styles.regions.headerRow}
aria-label={t().styles.regions.headerRow}
aria-pressed={isHeaderRow}
onclick={() => run((c) => c.toggleHeaderRowStyle())}
>
@@ -243,8 +245,8 @@
<button
class="tt-btn"
class:active={isHeaderCol}
title={t().table.headerColumn}
aria-label={t().table.headerColumnAria}
title={t().styles.regions.firstColumn}
aria-label={t().styles.regions.firstColumn}
aria-pressed={isHeaderCol}
onclick={() => run((c) => c.toggleHeaderColumnStyle())}
>
+24 -2
View File
@@ -1,16 +1,31 @@
import { Extension } from '@tiptap/core';
import type { CommandProps } from '@tiptap/core';
import type { Node as PMNode } from '@tiptap/pm/model';
import type { EditorState } from '@tiptap/pm/state';
import { selectedRect, isInTable } from '@tiptap/pm/tables';
import { parseTableLook, type TableRegion } from '../../styles/tableStyles';
// Word/LibreOffice "header row"/"header column" as a styling preset: the first row (or
// column) gets bold text + a light grey fill, both of which round-trip to ODF/DOCX. The
// fill doubles as the marker, so no <table:table-header-rows> and no page repetition.
// A table carrying a *table style* owns these two areas through its Table Style Options
// instead, so there the toggle reads and writes that flag — one state, two surfaces
// (this button and the gallery's checkbox), never disagreeing.
export const HEADER_SHADE = '#F2F2F2';
export type HeaderAxis = 'row' | 'column';
// The axis' matching Table Style Option.
const LOOK_REGION: Record<HeaderAxis, TableRegion> = { row: 'headerRow', column: 'firstColumn' };
// The cursor's table, if it has a named table style (else the manual shading applies).
function styledTable(state: EditorState): PMNode | null {
if (!isInTable(state)) return null;
const { table } = selectedRect(state);
return table.attrs.tableStyle ? table : null;
}
declare module '@tiptap/core' {
interface Commands<ReturnType> {
tableHeaderRow: {
@@ -50,8 +65,11 @@ export function isInHeaderCell(state: EditorState): boolean {
return false;
}
// True when every cell of the first row / first column carries the header fill.
// True when the area is on: the style's option for a styled table, else the header fill
// on every cell of the first row / first column.
export function isHeaderStyled(state: EditorState, axis: HeaderAxis): boolean {
const styled = styledTable(state);
if (styled) return parseTableLook(styled.attrs.tableLook)[LOOK_REGION[axis]];
const info = headerCellPositions(state, axis);
if (!info || info.positions.length === 0) return false;
return info.positions.every(
@@ -60,7 +78,11 @@ export function isHeaderStyled(state: EditorState, axis: HeaderAxis): boolean {
}
export function toggleHeaderStyle(axis: HeaderAxis) {
return ({ state, tr, dispatch }: CommandProps): boolean => {
return ({ state, tr, dispatch, commands }: CommandProps): boolean => {
// A styled table: flip the Table Style Option the gallery's checkbox shows.
if (styledTable(state)) {
return commands.setTableLook(LOOK_REGION[axis], !isHeaderStyled(state, axis));
}
const info = headerCellPositions(state, axis);
if (!info) return false;
if (!dispatch) return true;
+49 -5
View File
@@ -3,7 +3,11 @@ import type { CommandProps } from '@tiptap/core';
import type { Node as PMNode } from '@tiptap/pm/model';
import { Plugin, PluginKey, type EditorState, type Transaction } from '@tiptap/pm/state';
import { TableMap, isInTable, selectedRect } from '@tiptap/pm/tables';
import { regionText, resolveTableCell, type TableStyle as TableStyleDef } from '../../styles/tableStyles';
import {
DEFAULT_TABLE_LOOK, TABLE_REGIONS, parseTableLook, regionText, resolveTableCell, styleLook,
tableLookAttr,
type TableLook, type TableRegion, type TableStyle as TableStyleDef,
} from '../../styles/tableStyles';
import type { TextProps } from '../../styles/styleSheet';
// Word/LibreOffice table styles: the link lives on the table (`tableStyle`), fill and
@@ -14,6 +18,7 @@ declare module '@tiptap/core' {
interface Commands<ReturnType> {
tableStyle: {
setTableStyle: (name: string | null) => ReturnType;
setTableLook: (region: TableRegion, on: boolean) => ReturnType;
reapplyTableStyle: () => ReturnType;
refreshTableStyles: () => ReturnType;
};
@@ -33,6 +38,7 @@ const CLEARED = {
function paintTable(tr: Transaction, tablePos: number, style: TableStyleDef | null): boolean {
const table = tr.doc.nodeAt(tablePos);
if (!table) return false;
const look = parseTableLook(table.attrs.tableLook);
const map = TableMap.get(table);
const start = tablePos + 1;
let changed = false;
@@ -46,7 +52,7 @@ function paintTable(tr: Transaction, tablePos: number, style: TableStyleDef | nu
row: box.top, col: box.left,
rowSpan: box.bottom - box.top, colSpan: box.right - box.left,
rows: map.height, cols: map.width,
});
}, look);
next = {
backgroundColor: paint.fill,
region: paint.regions.length ? paint.regions.join(' ') : null,
@@ -74,13 +80,25 @@ function styledTables(doc: PMNode): { pos: number; node: PMNode }[] {
return out;
}
const shapeOf = (node: PMNode) => `${node.attrs.tableStyle}:${node.childCount}x${TableMap.get(node).width}`;
const shapeOf = (node: PMNode) =>
`${node.attrs.tableStyle}|${node.attrs.tableLook}:${node.childCount}x${TableMap.get(node).width}`;
export function activeTableStyle(state: EditorState): string | null {
if (!isInTable(state)) return null;
return (selectedRect(state).table.attrs.tableStyle as string | null) ?? null;
}
// The cursor's table's options, for the checkbox states (and the gallery previews).
export function activeTableLook(state: EditorState): TableLook {
if (!isInTable(state)) return { ...DEFAULT_TABLE_LOOK };
return parseTableLook(selectedRect(state).table.attrs.tableLook);
}
// Which options the style actually paints — the rest are shown disabled, as in Word.
export function styleRegions(style: TableStyleDef | undefined): TableRegion[] {
return style ? TABLE_REGIONS.filter(r => !!style.regions[r]) : [];
}
// The text formatting the cursor's cell inherits from its table style — what the CSS
// paints. Drives the Bold button's heading-like behaviour in a styled header row.
export function cellRegionText(state: EditorState, styles: Record<string, TableStyleDef>): TextProps {
@@ -105,8 +123,15 @@ function applyStyle(styles: () => Record<string, TableStyleDef>, name?: string |
if (wanted && !style) return false; // unknown style: leave the table alone
if (!dispatch) return true;
const tablePos = tableStart - 1;
if (table.attrs.tableStyle !== wanted) {
tr.setNodeMarkup(tablePos, undefined, { ...table.attrs, tableStyle: wanted });
// Assigning a style adopts the options it is about (a column-banded style switches
// the bands to columns); a re-apply after a structural change leaves them alone.
const attrs: Record<string, unknown> = { ...table.attrs };
if (table.attrs.tableStyle !== wanted) attrs.tableStyle = wanted;
if (name !== undefined && style?.look) {
attrs.tableLook = tableLookAttr(styleLook(style, parseTableLook(table.attrs.tableLook)));
}
if (attrs.tableStyle !== table.attrs.tableStyle || attrs.tableLook !== table.attrs.tableLook) {
tr.setNodeMarkup(tablePos, undefined, attrs);
}
paintTable(tr, tablePos, style);
dispatch(tr);
@@ -132,6 +157,13 @@ export const TableStyle = Extension.create<TableStyleOptions>({
renderHTML: (attrs: Record<string, unknown>) =>
attrs.tableStyle ? { 'data-table-style': String(attrs.tableStyle) } : {},
},
// Word's Table Style Options; null = the default look (parseTableLook).
tableLook: {
default: null as string | null,
parseHTML: (el: HTMLElement) => el.getAttribute('data-table-look'),
renderHTML: (attrs: Record<string, unknown>) =>
attrs.tableLook == null ? {} : { 'data-table-look': String(attrs.tableLook) },
},
},
},
{
@@ -152,6 +184,18 @@ export const TableStyle = Extension.create<TableStyleOptions>({
const styles = () => this.options.styles();
return {
setTableStyle: (name: string | null) => applyStyle(styles, name),
// Toggle one Table Style Option and repaint the table under the new look.
setTableLook: (region: TableRegion, on: boolean) => ({ state, tr, dispatch }: CommandProps) => {
if (!isInTable(state)) return false;
if (!dispatch) return true;
const { table, tableStart } = selectedRect(state);
const tablePos = tableStart - 1;
const look = { ...parseTableLook(table.attrs.tableLook), [region]: on };
tr.setNodeMarkup(tablePos, undefined, { ...table.attrs, tableLook: tableLookAttr(look) });
paintTable(tr, tablePos, styles()[table.attrs.tableStyle as string] ?? null);
dispatch(tr);
return true;
},
reapplyTableStyle: () => applyStyle(styles),
// Repaint every styled table — the registry changed (edit, rename, reset, import).
refreshTableStyles: () => ({ tr, dispatch }: CommandProps) => {
+3
View File
@@ -51,6 +51,9 @@ function applyTableStyleAttr(node: PMNode, table: HTMLElement): void {
const name = node.attrs.tableStyle as string | null;
if (name) table.dataset.tableStyle = name;
else delete table.dataset.tableStyle;
const look = node.attrs.tableLook as string | null;
if (look != null) table.dataset.tableLook = look;
else delete table.dataset.tableLook;
}
function buildColgroup(node: PMNode, colgroup: HTMLElement): void {
+11 -2
View File
@@ -24,7 +24,7 @@ import { effectiveOrderedDefAt, formatOrdinal, childCycle, ROOT_ORDERED_CYCLE, t
import { defaultBulletChar } from '../utils/bulletListTypes';
import { normalizeColor, MAX_HEADING_LEVEL, mergeJoinedParagraphsJson, twinFontName, type HfExport } from './odt';
import { builtinStyleSheet, DEFAULT_STYLE, type Style, type StyleSheet, type TextProps } from '../styles/styleSheet';
import { regionText, type TableStyle } from '../styles/tableStyles';
import { parseTableLook, regionText, type TableStyle } from '../styles/tableStyles';
import { findFormat, renderFormat, docxPicture, localeTag, DEFAULT_DATE_FORMAT, DEFAULT_TIME_FORMAT } from '../utils/dateTime';
// BCP-47 tag for rendering a fixed field's cached text; set at buildDocx start from
@@ -717,6 +717,7 @@ function tableToDocx(node: TiptapNode, contentWidthCm: number, num: Numbering):
// (w:tblStyle) plus the baked cell formatting, since w:tblStylePr isn't emitted.
const styleName = typeof node.attrs?.tableStyle === 'string' ? node.attrs.tableStyle : null;
const tableStyle = styleName ? exportSheet.table?.[styleName] : undefined;
const look = parseTableLook(node.attrs?.tableLook);
// A dragged table edge (tableColumnResize.ts) → w:tblInd + the narrower grid.
let ml = Math.max(0, Number(node.attrs?.marginLeft) || 0);
let mr = Math.max(0, Number(node.attrs?.marginRight) || 0);
@@ -758,7 +759,15 @@ function tableToDocx(node: TiptapNode, contentWidthCm: number, num: Numbering):
});
return new Table({
...(tableStyle ? { style: docxStyleId(tableStyle.name) } : {}),
...(tableStyle ? {
style: docxStyleId(tableStyle.name),
// Word's Table Style Options are w:tblLook (its band flags are inverted).
tableLook: {
firstRow: look.headerRow, lastRow: look.lastRow,
firstColumn: look.firstColumn, lastColumn: look.lastColumn,
noHBand: !look.bandedRow, noVBand: !look.bandedColumn,
},
} : {}),
rows: tableRows,
columnWidths: colsTwip,
width: { size: totalTwip, type: WidthType.DXA },
+41 -11
View File
@@ -5,7 +5,13 @@ import type { Orientation } from '../storage/pageOrientation';
import { pageDimsCm, type PageFormat } from '../storage/pageFormat';
import { HF_DISTANCE_CM, hfIsEmpty, type HfDoc } from '../storage/headerFooter';
import { builtinStyleSheet, DEFAULT_STYLE, resolveStyle, type StyleSheet, type TextProps } from '../styles/styleSheet';
import { regionText } from '../styles/tableStyles';
import {
TABLE_REGIONS, parseTableLook, regionText, type TableLook, type TableRegion,
} from '../styles/tableStyles';
// A table's named style plus the conditional areas it opts into (Word's Table Style
// Options), collected by exportTable in document order.
type TableStyleRef = { name: string; look: TableLook };
import { HEADER_SHADE } from '../editor/extensions/tableHeaderRow';
import { BORDER_SIDES, parseBorderAttr } from '../editor/extensions/tableCellBorders';
import { TEXTBOX_PADDING_CM } from '../editor/extensions/textBox';
@@ -760,26 +766,49 @@ function applyTableMargins(odtBytes: Uint8Array, margins: (TableMargins | null)[
// A table's named style: odf-kit's automatic Table{n} style gets it as its parent, and
// applyNamedStyles defines it in styles.xml. ODF has no banding, so only the name
// travels — the look rides on the cell attrs the style painted.
function applyTableStyleNames(odtBytes: Uint8Array, names: (string | null)[]): Uint8Array {
if (names.every(n => n === null)) return odtBytes;
function applyTableStyleNames(odtBytes: Uint8Array, tables: (TableStyleRef | null)[]): Uint8Array {
if (tables.every(t => t === null)) return odtBytes;
const files = unzipSync(odtBytes);
const contentBytes = files['content.xml'];
if (!contentBytes) return odtBytes;
let content = strFromU8(contentBytes);
names.forEach((name, i) => {
if (!name) return;
let nth = 0;
tables.forEach((ref, i) => {
if (!ref) return;
content = content.replace(
new RegExp(`(<style:style[^>]*style:name="Table${i + 1}")`),
`$1 style:parent-style-name="${odfStyleName(name)}"`,
`$1 style:parent-style-name="${odfStyleName(ref.name)}"`,
);
});
// Which conditional areas the table opts into: ODF's own table:use-*-styles pair with
// a table template, so the toggles survive a round trip through our own importer.
// Lookahead, not \b: a hyphen is a word boundary, so \b would also match
// <table:table-cell/-row/-column and consume the counter.
content = content.replace(/<table:table(?=[\s>])[^>]*/g, (tag) => {
const ref = tables[nth++];
return ref ? `${tag} ${odfLookAttrs(ref.look)}` : tag;
});
files['content.xml'] = strToU8(content);
return rezipOdt(files);
}
// ODF names these per conditional area on <table:table> (§ table template attributes).
export const ODF_LOOK_ATTRS: Record<TableRegion, string> = {
headerRow: 'table:use-first-row-styles',
lastRow: 'table:use-last-row-styles',
firstColumn: 'table:use-first-column-styles',
lastColumn: 'table:use-last-column-styles',
bandedRow: 'table:use-banding-rows-styles',
bandedColumn: 'table:use-banding-columns-styles',
};
function odfLookAttrs(look: TableLook): string {
return TABLE_REGIONS.map(r => `${ODF_LOOK_ATTRS[r]}="${look[r]}"`).join(' ');
}
// odf-kit's ListBuilder has no per-item paragraph options, so list-item paragraphs all
// emit as List_20_Bullet/Number. Rewrite content.xml to point those at automatic styles
// that inherit the list style and add fo:text-align / fo:margin-top / fo:margin-bottom.
@@ -2161,7 +2190,7 @@ function tableMarginsCm(node: TiptapNode, contentWidthCm: number): TableMargins
// Build an ODF table from a CUST_TABLE node, bypassing odf-kit's native walkTable to
// pass an explicit cell border (the native path emits none → invisible). Column widths
// come from tableColumnWidthsCm; when absent odf-kit distributes columns evenly.
function exportTable(node: TiptapNode, doc: OdtDocument, contentWidthCm: number, cellBlocks: CellBlock[][], tableMargins: (TableMargins | null)[], tableStyleNames: (string | null)[]): void {
function exportTable(node: TiptapNode, doc: OdtDocument, contentWidthCm: number, cellBlocks: CellBlock[][], tableMargins: (TableMargins | null)[], tableStyleNames: (TableStyleRef | null)[]): void {
const rows = (node.content ?? []).filter(r => r.type === 'tableRow');
if (rows.length === 0) return;
const margins = tableMarginsCm(node, contentWidthCm);
@@ -2170,7 +2199,8 @@ function exportTable(node: TiptapNode, doc: OdtDocument, contentWidthCm: number,
// automatic style (applyTableStyleNames), its text formatting is baked per cell.
const styleName = typeof node.attrs?.tableStyle === 'string' ? node.attrs.tableStyle : null;
const tableStyle = styleName ? exportSheet.table?.[styleName] : undefined;
tableStyleNames.push(tableStyle ? styleName : null);
const look = parseTableLook(node.attrs?.tableLook);
tableStyleNames.push(tableStyle && styleName ? { name: styleName, look } : null);
const columnWidths = tableColumnWidthsCm(node, contentWidthCm - (margins ? margins.ml + margins.mr : 0));
doc.addTable((t: TableBuilder) => {
for (const row of rows) {
@@ -2714,8 +2744,8 @@ export async function buildOdt(docJson: TiptapNode, margins: PageMargins = DEFAU
const cellBlocks: CellBlock[][] = [];
// One entry per table, same order — consumed by applyTableMargins.
const tableMargins: (TableMargins | null)[] = [];
// The named table style per table, same order — consumed by applyTableStyleNames.
const tableStyleNames: (string | null)[] = [];
// The named table style + its options per table, same order — applyTableStyleNames.
const tableStyleNames: (TableStyleRef | null)[] = [];
const odt = await tiptapToOdt(json, {
// Orientation sets style:print-orientation; rewriteStylesXml overrides the exact
@@ -2841,7 +2871,7 @@ export async function buildOdt(docJson: TiptapNode, margins: PageMargins = DEFAU
const withEmptyFontSizes = applyEmptyLineFontSizes(withPageBreaks);
const withParaBoxes = applyParagraphBoxes(withEmptyFontSizes);
const withNamedStyles = applyCharacterStyles(applyParagraphStyles(withParaBoxes));
const usedTables = new Set(tableStyleNames.filter((n): n is string => !!n));
const usedTables = new Set(tableStyleNames.filter((t): t is TableStyleRef => !!t).map(t => t.name));
const withStyles = rewriteStylesXml(withNamedStyles, language ?? null, pageFormat, orientation, styles, usedStyleNames(docJson, styles), usedTables);
return applyHfPostProcess(withStyles, margins, headerPara, footerPara, headerDist, footerDist, firstHeaderPara, firstFooterPara, hf?.pageCount ?? 1, hfImages, evenHeaderPara, evenFooterPara);
}
+13 -15
View File
@@ -257,10 +257,6 @@ const de: Messages = {
cellShading: 'Zellenschattierung',
chooseCellColor: 'Zellenfarbe wählen',
noFill: 'Keine Füllung',
headerRow: 'Kopfzeile (fett + Schattierung)',
headerRowAria: 'Kopfzeile',
headerColumn: 'Kopfspalte (fett + Schattierung)',
headerColumnAria: 'Kopfspalte',
insertTable: 'Tabelle einfügen',
selectSize: 'Tabellengröße wählen',
dimensions: (cols, rows) => `${cols} × ${rows}`,
@@ -278,19 +274,21 @@ const de: Messages = {
// row truncates, so CSS adds the dots only when the label doesn't fit.
manageStyles: 'Tabellenvorlagen verwalten',
tableStyle: 'Tabellenvorlage',
styleOptions: 'Optionen',
noTableStyle: 'Keine',
styleNames: {
'Simple Grid': 'Einfaches Gitter',
'Simple Grid Rows': 'Gitter nur Zeilen',
'Simple Grid Columns': 'Gitter nur Spalten',
'Simple List Shaded': 'Einfache Liste schattiert',
'Simple List Columns': 'Einfache Liste Spalten',
'Box List Blue': 'Kastenliste blau',
'Box List Green': 'Kastenliste grün',
'Box List Red': 'Kastenliste rot',
'Box List Yellow': 'Kastenliste gelb',
'Grid Table Accent': 'Gittertabelle Akzent',
'List Table Accent': 'Listentabelle Akzent',
'Simple Grid': 'Gitter',
'Simple Grid Rows': 'Gitter Zeilen',
'Simple Grid Columns': 'Gitter Spalten',
'Simple List Shaded': 'Liste schattiert',
'Simple List Columns': 'Liste Spalten',
'Plain Table': 'Schlicht',
'Box List Blue': 'Kasten blau',
'Box List Green': 'Kasten grün',
'Box List Red': 'Kasten rot',
'Box List Yellow': 'Kasten gelb',
'Grid Table Accent': 'Gitter Akzent',
'List Table Accent': 'Liste Akzent',
Academic: 'Akademisch',
Financial: 'Finanzen',
} as Record<string, string>,
+13 -15
View File
@@ -261,10 +261,6 @@ const en = {
cellShading: 'Cell shading',
chooseCellColor: 'Choose cell color',
noFill: 'No fill',
headerRow: 'Header row (bold + shading)',
headerRowAria: 'Header row',
headerColumn: 'Header column (bold + shading)',
headerColumnAria: 'Header column',
insertTable: 'Insert table',
selectSize: 'Select table size',
dimensions: (cols: number, rows: number) => `${cols} × ${rows}`,
@@ -282,19 +278,21 @@ const en = {
// row truncates, so CSS adds the dots only when the label doesn't fit.
manageStyles: 'Manage table styles',
tableStyle: 'Table style',
styleOptions: 'Options',
noTableStyle: 'None',
styleNames: {
'Simple Grid': 'Simple Grid',
'Simple Grid Rows': 'Simple Grid Rows',
'Simple Grid Columns': 'Simple Grid Columns',
'Simple List Shaded': 'Simple List Shaded',
'Simple List Columns': 'Simple List Columns',
'Box List Blue': 'Box List Blue',
'Box List Green': 'Box List Green',
'Box List Red': 'Box List Red',
'Box List Yellow': 'Box List Yellow',
'Grid Table Accent': 'Grid Table Accent',
'List Table Accent': 'List Table Accent',
'Simple Grid': 'Grid',
'Simple Grid Rows': 'Grid Rows',
'Simple Grid Columns': 'Grid Columns',
'Simple List Shaded': 'List Shaded',
'Simple List Columns': 'List Columns',
'Plain Table': 'Plain',
'Box List Blue': 'Box Blue',
'Box List Green': 'Box Green',
'Box List Red': 'Box Red',
'Box List Yellow': 'Box Yellow',
'Grid Table Accent': 'Grid Accent',
'List Table Accent': 'List Accent',
Academic: 'Academic',
Financial: 'Financial',
} as Record<string, string>,
+22 -1
View File
@@ -4,6 +4,7 @@ import { lengthToPt } from './styleResolver';
import { HEADING_STYLE_OVERRIDES, MAX_HEADING_LEVEL, normalizeColor } from '../export/odt';
import { builtinStyleSheet, DEFAULT_STYLE, type ParaProps, type Style, type StyleSheet, type TextProps } from '../styles/styleSheet';
import { HEADER_SHADE } from '../editor/extensions/tableHeaderRow';
import { tableLookAttr } from '../styles/tableStyles';
import { orderedTypeFromFormat, orderedTypeAttrAt, childCycle, ROOT_ORDERED_CYCLE, type OrderedCycle } from '../utils/orderedListTypes';
import { bulletCharAttr, bulletCharFromDocx } from '../utils/bulletListTypes';
import { DATE_FORMATS, TIME_FORMATS, docxPicture, toDateValue } from '../utils/dateTime';
@@ -1305,10 +1306,30 @@ function convertTable(tbl: Element, ctx: Ctx): Node | null {
const styleEl = fc(fc(tbl, 'tblPr'), 'tblStyle');
const named = ctx.styles.tableStyleName(styleEl ? wVal(styleEl) : null);
const attrs: Record<string, unknown> = { ...(tableMargins(tbl, useWeights, ctx) ?? {}) };
if (named) attrs.tableStyle = named;
if (named) {
attrs.tableStyle = named;
const look = docxTableLook(fc(tbl, 'tblPr'));
if (look) attrs.tableLook = look;
}
return Object.keys(attrs).length ? { type: 'table', attrs, content: rows } : { type: 'table', content: rows };
}
// Word's w:tblLook → the editor's tableLook attr (its band flags are inverted).
// null when the file declares none, so the default look applies.
function docxTableLook(tblPr: Element | null): string | null {
const el = fc(tblPr, 'tblLook');
if (!el) return null;
const on = (name: string) => {
const v = el.getAttributeNS(W, name);
return v === '1' || v === 'true';
};
return tableLookAttr({
headerRow: on('firstRow'), lastRow: on('lastRow'),
firstColumn: on('firstColumn'), lastColumn: on('lastColumn'),
bandedRow: !on('noHBand'), bandedColumn: !on('noVBand'),
});
}
// A table narrower than the text width: w:tblInd is its left indent, the grid (or
// w:tblW) its width — the rest becomes the editor's right margin.
function tableMargins(tbl: Element, weights: number[] | null, ctx: Ctx): { marginLeft: number; marginRight: number } | null {
+27 -2
View File
@@ -1,8 +1,9 @@
import { unzipSync, strFromU8 } from 'fflate';
import { StyleResolver, NS, lengthToPt, lengthToCm, layerTextProps, type PropMap } from './styleResolver';
import { HEADING_STYLE_OVERRIDES, MAX_HEADING_LEVEL, normalizeColor } from '../export/odt';
import { HEADING_STYLE_OVERRIDES, MAX_HEADING_LEVEL, ODF_LOOK_ATTRS, normalizeColor } from '../export/odt';
import { builtinStyleSheet, DEFAULT_STYLE, type ParaProps, type Style, type StyleSheet, type TextProps } from '../styles/styleSheet';
import { HEADER_SHADE } from '../editor/extensions/tableHeaderRow';
import { TABLE_REGIONS, tableLookAttr, type TableLook, type TableRegion } from '../styles/tableStyles';
import { orderedTypeFromFormat, orderedTypeAttrAt, childCycle, ROOT_ORDERED_CYCLE, type OrderedCycle } from '../utils/orderedListTypes';
import { bulletCharAttr, bulletCharFromOdf } from '../utils/bulletListTypes';
import { matchFormat, toDateValue, type Token } from '../utils/dateTime';
@@ -1510,10 +1511,34 @@ function convertTable(el: Element, ctx: Ctx): Node | null {
// the regions from the registry (refreshTableStyles).
const named = ctx.resolver.namedAncestor(el.getAttributeNS(NS.table, 'style-name'), 'table');
const attrs: Record<string, unknown> = { ...(tableMargins(el, ctx) ?? {}) };
if (named) attrs.tableStyle = displayStyleName(named);
if (named) {
attrs.tableStyle = displayStyleName(named);
// Which conditional areas the table opts into (ODF's table template attributes).
// Absent ⇒ leave the attr null, so parseTableLook falls back to the default.
const look = odfTableLook(el);
if (look) attrs.tableLook = look;
}
return Object.keys(attrs).length ? { type: 'table', attrs, content: rows } : { type: 'table', content: rows };
}
// The six table:use-*-styles attributes → the editor's space-separated tableLook attr.
// null when the file declares none (a foreign producer), so the default look applies.
function odfTableLook(el: Element): string | null {
const on: TableRegion[] = [];
let declared = false;
for (const [region, attr] of Object.entries(ODF_LOOK_ATTRS) as [TableRegion, string][]) {
// ODF_LOOK_ATTRS holds the qualified names the exporter writes; getAttributeNS
// wants the local one.
const v = el.getAttributeNS(NS.table, attr.replace('table:', ''));
if (v == null) continue;
declared = true;
if (v === 'true') on.push(region);
}
return declared ? tableLookAttr(Object.fromEntries(
TABLE_REGIONS.map(r => [r, on.includes(r)]),
) as TableLook) : null;
}
// A table narrower than the text width → the editor's marginLeft/marginRight attrs.
// LibreOffice states the width plus one margin (per table:align), the other follows.
function tableMargins(el: Element, ctx: Ctx): { marginLeft: number; marginRight: number } | null {
+1 -1
View File
@@ -83,7 +83,7 @@ const CHAR_BUILTINS: Style[] = [
// Bumped whenever the built-in definitions change: a stored sheet from an older version
// keeps its user styles but takes the new factory built-ins (see mergeStoredSheet).
export const STYLE_SHEET_VERSION = 4;
export const STYLE_SHEET_VERSION = 7;
// A persisted sheet merged onto the current built-ins. Same version: stored entries win
// (a document's own styles, and edits to built-ins). Older: only user styles survive.
+133 -23
View File
@@ -12,6 +12,31 @@ export const TABLE_REGIONS = [
] as const;
export type TableRegion = (typeof TABLE_REGIONS)[number];
// Word's "Table Style Options": which conditional regions a given table opts into. A
// region paints only when the style defines it AND the table's look enables it, so the
// same style reads differently per table (and the gallery previews follow the toggles).
export type TableLook = Record<TableRegion, boolean>;
// Word's default for a new table (its w:tblLook 04A0): header row, first column, bands.
export const DEFAULT_TABLE_LOOK: TableLook = {
headerRow: true, firstColumn: true, bandedRow: true,
lastRow: false, lastColumn: false, bandedColumn: false,
};
const isRegion = (v: string): v is TableRegion => (TABLE_REGIONS as readonly string[]).includes(v);
// Stored space-separated on the table node, like a cell's `region` list. An absent attr
// means the Word default, so a table predating the toggles keeps looking the same.
export function parseTableLook(attr: unknown): TableLook {
if (typeof attr !== 'string') return { ...DEFAULT_TABLE_LOOK };
const on = new Set(attr.split(' ').filter(isRegion));
return Object.fromEntries(TABLE_REGIONS.map(r => [r, on.has(r)])) as TableLook;
}
export function tableLookAttr(look: TableLook): string {
return TABLE_REGIONS.filter(r => look[r]).join(' ');
}
export type BorderSideKey = 'top' | 'right' | 'bottom' | 'left';
export type TableRegionProps = {
@@ -27,6 +52,10 @@ export type TableRegionProps = {
export type TableStyle = {
name: string;
builtin?: boolean;
// The Table Style Options this style is about, applied on assignment over whatever the
// table already had. Defining all six areas keeps every toggle meaningful, so without
// this a row-banded and a column-banded style would be indistinguishable.
look?: Partial<TableLook>;
border?: string | null; // the table's outer edges
innerBorder?: string | null; // the grid lines inside it
innerBorderH?: string | null; // horizontal inner lines only (falls back to innerBorder)
@@ -42,56 +71,107 @@ const HEADER_FILL = '#F2F2F2';
const BAND_FILL = '#F7F7F7';
const ACCENT = '#4472C4';
const ACCENT_LIGHT = '#D9E2F3';
const ACCENT_MID = '#B4C6E7';
const boxList = (name: string, header: string, band: string, text = '#FFFFFF'): TableStyle => ({
// Every built-in defines all six conditional areas, so each Table-Style-Option toggle
// visibly does something (as in Word).
const boxList = (name: string, header: string, band: string, mid: string, text = '#FFFFFF'): TableStyle => ({
name, builtin: true, border: 'none', innerBorder: 'none',
regions: {
headerRow: { fill: header, text: { bold: true, color: text } },
bandedRow: { fill: band },
bandedColumn: { fill: band },
// The colourful families shade their emphasis areas as well, so switching one on
// is as visible as the header row (Word's Grid Table families do the same).
firstColumn: { fill: mid, text: { bold: true } },
lastColumn: { fill: mid, text: { bold: true } },
lastRow: { fill: mid, text: { bold: true }, borders: { top: `1pt solid ${header}` } },
},
});
// The grey and rule-based families keep emphasis text-only, as in Word.
const emphasis = { text: { bold: true } };
const greyEdges = {
firstColumn: emphasis,
lastColumn: emphasis,
lastRow: { ...emphasis, borders: { top: '1pt solid #000000' } },
};
export const TABLE_BUILTINS: TableStyle[] = [
{ name: 'Simple Grid', builtin: true, border: null, innerBorder: null,
regions: { headerRow: { fill: HEADER_FILL, text: { bold: true } } } },
regions: {
headerRow: { fill: HEADER_FILL, text: { bold: true } },
bandedRow: { fill: BAND_FILL }, bandedColumn: { fill: BAND_FILL },
...greyEdges,
} },
{ name: 'Simple Grid Rows', builtin: true, border: null, innerBorderH: null, innerBorderV: 'none',
regions: { headerRow: { fill: HEADER_FILL, text: { bold: true } } } },
regions: {
headerRow: { fill: HEADER_FILL, text: { bold: true } },
bandedRow: { fill: BAND_FILL }, bandedColumn: { fill: BAND_FILL },
...greyEdges,
} },
{ name: 'Simple Grid Columns', builtin: true, border: null, innerBorderH: 'none', innerBorderV: null,
regions: { headerRow: { fill: HEADER_FILL, text: { bold: true } } } },
look: { bandedRow: false, bandedColumn: true },
regions: {
headerRow: { fill: HEADER_FILL, text: { bold: true } },
bandedRow: { fill: BAND_FILL }, bandedColumn: { fill: BAND_FILL },
...greyEdges,
} },
{ name: 'Simple List Shaded', builtin: true, border: null, innerBorder: 'none',
regions: {
headerRow: { fill: HEADER_FILL, text: { bold: true } },
bandedRow: { fill: BAND_FILL },
bandedRow: { fill: BAND_FILL }, bandedColumn: { fill: BAND_FILL },
...greyEdges,
} },
{ name: 'Simple List Columns', builtin: true, border: null, innerBorder: 'none',
look: { bandedRow: false, bandedColumn: true },
regions: {
headerRow: { fill: HEADER_FILL, text: { bold: true } },
bandedColumn: { fill: BAND_FILL },
bandedColumn: { fill: BAND_FILL }, bandedRow: { fill: BAND_FILL },
...greyEdges,
} },
boxList('Box List Blue', '#4A7EBB', '#DCE6F1'),
boxList('Box List Green', '#77933C', '#EBF1DE'),
boxList('Box List Red', '#C0504D', '#F2DCDB'),
boxList('Box List Yellow', '#E6B800', '#FFF2CC', '#000000'),
// Word's "Plain Table": no lines at all, emphasis by weight only.
{ name: 'Plain Table', builtin: true, border: 'none', innerBorder: 'none',
regions: {
headerRow: { text: { bold: true }, borders: { bottom: '0.75pt solid #000000' } },
bandedRow: { fill: BAND_FILL }, bandedColumn: { fill: BAND_FILL },
...greyEdges,
} },
boxList('Box List Blue', '#4A7EBB', '#DCE6F1', '#B8CCE4'),
boxList('Box List Green', '#77933C', '#EBF1DE', '#D6E3BC'),
boxList('Box List Red', '#C0504D', '#F2DCDB', '#E5B8B7'),
boxList('Box List Yellow', '#E6B800', '#FFF2CC', '#FFE699', '#000000'),
{ name: 'Grid Table Accent', builtin: true, border: `0.5pt solid #8EAADB`, innerBorder: '0.5pt solid #8EAADB',
regions: {
headerRow: { fill: ACCENT, text: { bold: true, color: '#FFFFFF' } },
bandedRow: { fill: ACCENT_LIGHT },
bandedRow: { fill: ACCENT_LIGHT }, bandedColumn: { fill: ACCENT_LIGHT },
firstColumn: { fill: ACCENT_MID, text: { bold: true } },
lastColumn: { fill: ACCENT_MID, text: { bold: true } },
lastRow: { fill: ACCENT_MID, text: { bold: true }, borders: { top: `1pt solid ${ACCENT}` } },
} },
{ name: 'List Table Accent', builtin: true, border: 'none', innerBorderH: null, innerBorderV: 'none',
regions: {
headerRow: { text: { bold: true, color: ACCENT }, borders: { bottom: `1pt solid ${ACCENT}` } },
bandedRow: { fill: ACCENT_LIGHT },
bandedRow: { fill: ACCENT_LIGHT }, bandedColumn: { fill: ACCENT_LIGHT },
firstColumn: { fill: ACCENT_MID, text: { bold: true } },
lastColumn: { fill: ACCENT_MID, text: { bold: true } },
lastRow: { fill: ACCENT_MID, text: { bold: true }, borders: { top: `1pt solid ${ACCENT}` } },
} },
{ name: 'Academic', builtin: true, border: 'none', innerBorder: 'none',
look: { bandedRow: false, bandedColumn: false, firstColumn: false },
regions: {
headerRow: { text: { bold: true }, borders: { top: '1pt solid #000000', bottom: '0.75pt solid #000000' } },
lastRow: { borders: { bottom: '1pt solid #000000' } },
bandedRow: { fill: BAND_FILL }, bandedColumn: { fill: BAND_FILL },
firstColumn: emphasis, lastColumn: emphasis,
} },
{ name: 'Financial', builtin: true, border: 'none', innerBorder: 'none',
look: { lastRow: true, bandedRow: false, bandedColumn: false },
regions: {
headerRow: { text: { bold: true }, borders: { top: '1pt solid #000000', bottom: '0.75pt solid #000000' } },
firstColumn: { text: { bold: true } },
lastRow: { text: { bold: true }, borders: { top: '0.75pt solid #000000', bottom: '1pt solid #000000' } },
firstColumn: emphasis, lastColumn: emphasis,
lastRow: { ...emphasis, borders: { top: '0.75pt solid #000000', bottom: '1pt solid #000000' } },
bandedRow: { fill: BAND_FILL }, bandedColumn: { fill: BAND_FILL },
} },
];
@@ -116,10 +196,15 @@ export type ResolvedTableCell = {
// The conditional regions a grid position belongs to, in ascending precedence. Banding
// counts body rows only, so a header row doesn't shift the stripes (as in Word).
function regionsAt(style: TableStyle, row: number, col: number, rows: number, cols: number): TableRegion[] {
const r = style.regions;
const bodyRow = row - (r.headerRow ? 1 : 0);
const bodyCol = col - (r.firstColumn ? 1 : 0);
function regionsAt(
style: TableStyle, look: TableLook,
row: number, col: number, rows: number, cols: number,
): TableRegion[] {
// A region counts as present only when the style paints it and the table opts in —
// that also decides whether banding skips the header row / first column.
const on = (name: TableRegion) => !!style.regions[name] && look[name];
const bodyRow = row - (on('headerRow') ? 1 : 0);
const bodyCol = col - (on('firstColumn') ? 1 : 0);
const matches: Record<TableRegion, boolean> = {
bandedColumn: bodyCol >= 0 && bodyCol % 2 === 1,
bandedRow: bodyRow >= 0 && bodyRow % 2 === 1,
@@ -128,7 +213,7 @@ function regionsAt(style: TableStyle, row: number, col: number, rows: number, co
lastRow: row === rows - 1,
headerRow: row === 0,
};
return TABLE_REGIONS.filter(name => r[name] && matches[name]);
return TABLE_REGIONS.filter(name => on(name) && matches[name]);
}
// The border of one grid line, decided from both sides so the two facing cells always
@@ -160,11 +245,13 @@ function boundary(
// Everything a table style paints on one cell. Fill and borders are materialized as cell
// attrs (so export/PDF/clipboard need no extra work); `text` is rendered via CSS keyed on
// the `region` attr and baked onto the runs on export.
export function resolveTableCell(style: TableStyle, cell: CellCoords): ResolvedTableCell {
export function resolveTableCell(
style: TableStyle, cell: CellCoords, look: TableLook = DEFAULT_TABLE_LOOK,
): ResolvedTableCell {
const { row, col, rows, cols } = cell;
const rowEnd = row + (cell.rowSpan ?? 1);
const colEnd = col + (cell.colSpan ?? 1);
const at = (r: number, c: number) => regionsAt(style, r, c, rows, cols);
const at = (r: number, c: number) => regionsAt(style, look, r, c, rows, cols);
const regions = at(row, col);
let fill: string | null = style.wholeTable?.fill ?? null;
@@ -205,8 +292,11 @@ export function regionText(style: TableStyle | null | undefined, regionAttr: unk
// Inline CSS for one cell of a style's preview grid (the toolbar gallery and the style
// manager show the same tile). Widths collapse to 1–2px so a thick rule stays legible;
// the table default border rides on currentColor, so the tile has to carry a page color.
export function previewCellCss(style: TableStyle, row: number, col: number, rows: number, cols: number): string {
const paint = resolveTableCell(style, { row, col, rows, cols });
export function previewCellCss(
style: TableStyle, row: number, col: number, rows: number, cols: number,
look: TableLook = DEFAULT_TABLE_LOOK,
): string {
const paint = resolveTableCell(style, { row, col, rows, cols }, look);
const side = (value: string | null): string => {
if (value === 'none') return 'none';
if (value === null) return '1px solid currentColor';
@@ -220,6 +310,26 @@ export function previewCellCss(style: TableStyle, row: number, col: number, rows
return `background: ${paint.fill ?? 'transparent'};${borders};font-weight: ${paint.text.bold ? 700 : 400}`;
}
// The options a style is applied with: its own declared ones over the table's current.
export function styleLook(style: TableStyle | undefined, table: TableLook): TableLook {
return { ...table, ...style?.look };
}
// The text bar inside a preview cell: a schematic line whose weight and colour follow
// the region, so bold-only areas (first/last column, total row) are visible in a tile —
// they would otherwise look identical, the tiles carrying no real text.
export function previewTextCss(
style: TableStyle, row: number, col: number, rows: number, cols: number,
look: TableLook = DEFAULT_TABLE_LOOK,
): string {
const { text } = resolveTableCell(style, { row, col, rows, cols }, look);
const bold = text.bold === true;
return `height: ${bold ? 2 : 1}px; background: ${text.color ?? 'currentColor'};`
+ `opacity: ${bold ? 0.85 : 0.45};`
// A slant for italic, so an italic-only region is visible too.
+ `transform: ${text.italic ? 'skewX(-14deg)' : 'none'}`;
}
// One rule per style and region, emitted in ascending precedence so an overlap (header
// row ∩ first column) resolves by source order. The descendant selector is required: the
// Standard paragraph rule would otherwise beat a plain cell rule on font/size/color.
+26
View File
@@ -151,6 +151,32 @@ describe('DOCX export → import round trip', () => {
expect(table.content![0].content![0].attrs.backgroundColor).toBe('#4A7EBB');
});
it('round-trips the table style options as w:tblLook', async () => {
const cell = (t: string): N => ({
type: 'tableCell', attrs: { colspan: 1, rowspan: 1, colwidth: null }, content: [para(t)],
});
const doc = {
type: 'doc',
content: [{
type: 'table',
attrs: { tableStyle: 'Box List Blue', tableLook: 'lastRow headerRow' },
content: [
{ type: 'tableRow', content: [cell('Kopf')] },
{ type: 'tableRow', content: [cell('Summe')] },
],
}],
} as any;
const bytes = await buildDocx(doc);
const xml = strFromU8(unzipSync(bytes)['word/document.xml']);
// Word inverts the band flags, so both are switched off here.
expect(xml).toMatch(/<w:tblLook[^>]*w:firstRow="true"/);
expect(xml).toMatch(/<w:tblLook[^>]*w:lastRow="true"/);
expect(xml).toMatch(/<w:tblLook[^>]*w:noHBand="true"/);
const table = walk(importDocx(bytes).content as N, 'table')[0];
expect(table.attrs.tableLook).toBe('lastRow headerRow');
});
it('re-merges a page-boundary line-split paragraph (joinPrev) on export', async () => {
const split = {
type: 'doc',
+30
View File
@@ -406,6 +406,36 @@ describe('Leg 1a4: named table style', () => {
check('the painted fills survive', JSON.stringify(fills) === JSON.stringify(['#F2F2F2', null, '#F7F7F7']), fills);
});
it('round-trips the table style options (Word\'s tblLook)', async () => {
// Header row + banded rows on, everything else off.
const opts: N = { ...styled, content: [{ ...styled.content![0],
attrs: { tableStyle: 'Simple List Shaded', tableLook: 'bandedRow headerRow' } }] };
const bytes = await buildOdt(opts, margins, 'portrait', undefined, null, 'A4', builtinStyleSheet());
const contentXml = strFromU8(unzipSync(bytes)['content.xml']);
check('the options ride on table:use-*-styles',
contentXml.includes('table:use-first-row-styles="true"')
&& contentXml.includes('table:use-banding-rows-styles="true"')
&& contentXml.includes('table:use-first-column-styles="false"'),
contentXml.match(/table:use-[a-z-]*="[a-z]*"/g));
const table = importOdt(bytes).content.content!.find((n: N) => n.type === 'table') as N;
check('they come back on the table', table?.attrs?.tableLook === 'bandedRow headerRow', table?.attrs);
});
it('keeps two styled tables apart (the pass walks table elements, not cells)', async () => {
const one = { ...styled.content![0], attrs: { tableStyle: 'Simple Grid', tableLook: 'headerRow' } };
const two = { ...styled.content![0], attrs: { tableStyle: 'Academic', tableLook: 'headerRow lastRow' } };
const bytes = await buildOdt({ type: 'doc', content: [one, P(null, T('between')), two] } as N,
margins, 'portrait', undefined, null, 'A4', builtinStyleSheet());
const tables = importOdt(bytes).content.content!.filter((n: N) => n.type === 'table');
check('both names survive',
tables.map((t: N) => t.attrs?.tableStyle).join('|') === 'Simple Grid|Academic',
tables.map((t: N) => t.attrs));
check('each keeps its own options',
tables.map((t: N) => t.attrs?.tableLook).join('|') === 'headerRow|lastRow headerRow',
tables.map((t: N) => t.attrs?.tableLook));
});
it('bakes a region font onto the runs so Word/LibreOffice match', async () => {
// Box List Blue writes white bold on the header row; the editor renders that from CSS.
const blue: N = { ...styled, content: [{ ...styled.content![0], attrs: { tableStyle: 'Box List Blue' },
+177 -4
View File
@@ -11,7 +11,12 @@ import { ResizableTableRow } from '../../src/lib/editor/extensions/tableRow';
import { TableCellBackground } from '../../src/lib/editor/extensions/tableCellBackground';
import { TableCellBorders } from '../../src/lib/editor/extensions/tableCellBorders';
import { TableStyle } from '../../src/lib/editor/extensions/tableStyle';
import { resolveTableCell, type TableStyle as TableStyleDef } from '../../src/lib/styles/tableStyles';
import { HEADER_SHADE, TableHeaderRow, isHeaderStyled } from '../../src/lib/editor/extensions/tableHeaderRow';
import {
DEFAULT_TABLE_LOOK, TABLE_REGIONS, builtinTableStyles, parseTableLook, previewCellCss,
previewTextCss, resolveTableCell, styleLook, tableLookAttr,
type TableLook, type TableRegion, type TableStyle as TableStyleDef,
} from '../../src/lib/styles/tableStyles';
type N = any;
@@ -29,8 +34,13 @@ const banded: TableStyleDef = {
};
const styles = { [banded.name]: banded };
const at = (style: TableStyleDef, row: number, col: number, rows = 4, cols = 2) =>
resolveTableCell(style, { row, col, rows, cols });
const ALL_ON: TableLook = {
headerRow: true, lastRow: true, firstColumn: true,
lastColumn: true, bandedRow: true, bandedColumn: true,
};
const at = (style: TableStyleDef, row: number, col: number, rows = 4, cols = 2, look = ALL_ON) =>
resolveTableCell(style, { row, col, rows, cols }, look);
describe('resolveTableCell', () => {
it('layers overlapping regions in Word precedence order', () => {
@@ -80,7 +90,7 @@ function makeEditor(rows = 3) {
extensions: [
Document, Paragraph, Text, Bold,
Table.configure({ resizable: false }), ResizableTableRow, TableHeader, TableCell,
TableCellBackground, TableCellBorders,
TableCellBackground, TableCellBorders, TableHeaderRow,
TableStyle.configure({ styles: () => styles }),
],
content: { type: 'doc', content: [{ type: 'table', content }] },
@@ -91,6 +101,152 @@ const table = (editor: Editor): N => editor.getJSON().content![0];
const fills = (editor: Editor): (string | null)[] =>
table(editor).content.map((r: N) => r.content[0].attrs.backgroundColor ?? null);
describe('table style options (Word\'s tblLook)', () => {
it('only paints a region the table opts into', () => {
const off: TableLook = { ...ALL_ON, headerRow: false };
expect(at(banded, 0, 1).fill).toBe('#EEEEEE');
expect(at(banded, 0, 1, 4, 2, off).fill).toBe(null);
// The header's rule goes with it, from both sides of that grid line.
expect(at(banded, 0, 0, 4, 2, off).borders.borderBottom).toBe('none');
expect(at(banded, 1, 0, 4, 2, off).borders.borderTop).toBe('none');
});
it('shifts the banding when the header row is switched off', () => {
const off: TableLook = { ...ALL_ON, headerRow: false };
// Header on: row 0 is the header, so the first stripe is row 2.
expect([0, 1, 2, 3].map(r => at(banded, r, 1).fill)).toEqual([
'#EEEEEE', null, '#FAFAFA', null,
]);
// Header off: the body starts at row 0, so the stripes move up one row.
expect([0, 1, 2, 3].map(r => at(banded, r, 1, 4, 2, off).fill)).toEqual([
null, '#FAFAFA', null, '#FAFAFA',
]);
});
it('drops the banding entirely when switched off', () => {
const off: TableLook = { ...ALL_ON, bandedRow: false };
expect([1, 2, 3].map(r => at(banded, r, 1, 4, 2, off).fill)).toEqual([null, null, null]);
// The header still counts for the (now unused) body offset, and still paints.
expect(at(banded, 0, 1, 4, 2, off).fill).toBe('#EEEEEE');
});
it('round-trips the look attr, defaulting to Word\'s', () => {
expect(parseTableLook(null)).toEqual(DEFAULT_TABLE_LOOK);
expect(parseTableLook('')).toEqual({
headerRow: false, lastRow: false, firstColumn: false,
lastColumn: false, bandedRow: false, bandedColumn: false,
});
const look = parseTableLook('headerRow bandedRow');
expect(look.headerRow && look.bandedRow).toBe(true);
expect(look.firstColumn || look.lastRow).toBe(false);
expect(parseTableLook(tableLookAttr(ALL_ON))).toEqual(ALL_ON);
});
});
describe('built-in styles', () => {
it('has families that shade the emphasis areas, not only embolden them', () => {
const sheet = builtinTableStyles();
const shaded = Object.values(sheet).filter(
st => ['firstColumn', 'lastColumn', 'lastRow'].every(r => st.regions[r as TableRegion]?.fill),
);
// The colourful families (box lists + the two accent tables) fill those areas, so
// switching one on is as visible as the header row.
expect(shaded.map(st => st.name)).toContain('Box List Blue');
expect(shaded.length).toBeGreaterThanOrEqual(6);
// …and the plain/rule-based ones deliberately stay text-only.
expect(sheet['Academic'].regions.firstColumn?.fill).toBeUndefined();
expect(sheet['Academic'].regions.firstColumn?.text?.bold).toBe(true);
});
it('renders no two built-ins identically', () => {
// Each style is previewed the way it is applied: its own options over the default.
// Giving every style all six areas once made the two list styles indistinguishable.
const signature = (style: TableStyleDef) => {
const look = styleLook(style, DEFAULT_TABLE_LOOK);
const cells: string[] = [];
for (let r = 0; r < 5; r++) {
for (let c = 0; c < 4; c++) {
cells.push(previewCellCss(style, r, c, 5, 4, look) + previewTextCss(style, r, c, 5, 4, look));
}
}
return cells.join('|');
};
const seen = new Map<string, string>();
for (const style of Object.values(builtinTableStyles())) {
const sig = signature(style);
expect(seen.get(sig), `${style.name} looks exactly like ${seen.get(sig)}`).toBeUndefined();
seen.set(sig, style.name);
}
});
it('gives every built-in all six areas, so no toggle is a no-op', () => {
for (const style of Object.values(builtinTableStyles())) {
for (const region of TABLE_REGIONS) {
expect(style.regions[region], `${style.name} / ${region}`).toBeDefined();
}
}
});
});
describe('preview tiles', () => {
it('shows a bold-only region, which the fills alone cannot', () => {
const bar = (r: number, c: number, look = ALL_ON) =>
previewTextCss(banded, r, c, 4, 2, look);
// The first column is emphasis-only: no fill, so the tile can only show it via
// the text line's weight.
const fill = (r: number, c: number) => /^background: [^;]*/.exec(previewCellCss(banded, r, c, 4, 2, ALL_ON))![0];
expect(fill(1, 0)).toBe(fill(1, 1)); // identical cell background
// The fixture's first column is italic-only, the header bold — both must show.
expect(bar(1, 0)).toContain('skewX'); // first column: italic
expect(bar(1, 1)).toContain('none'); // body: upright
expect(bar(0, 1)).toContain('height: 2px'); // header row: bold
expect(bar(1, 1)).toContain('height: 1px');
// Switching the area off levels them out again.
const off: TableLook = { ...ALL_ON, firstColumn: false };
expect(bar(1, 0, off)).toBe(bar(1, 1, off));
});
});
describe('header toggles and style options are one state', () => {
it('drives the look on a styled table, the shading otherwise', () => {
const editor = makeEditor(3);
editor.commands.focus('start');
// No style: the toolbar toggle paints the header fill, as before.
editor.commands.toggleHeaderRowStyle();
expect(isHeaderStyled(editor.state, 'row')).toBe(true);
expect(table(editor).content[0].content[0].attrs.backgroundColor).toBe(HEADER_SHADE);
editor.commands.toggleHeaderRowStyle();
expect(isHeaderStyled(editor.state, 'row')).toBe(false);
// With a style the same button flips the Table Style Option instead — so the
// toolbar button and the gallery checkbox can never disagree.
editor.commands.setTableStyle('Test Bands');
expect(isHeaderStyled(editor.state, 'row')).toBe(true);
editor.commands.toggleHeaderRowStyle();
expect(parseTableLook(table(editor).attrs.tableLook).headerRow).toBe(false);
expect(isHeaderStyled(editor.state, 'row')).toBe(false);
expect(table(editor).content[0].content[0].attrs.backgroundColor).toBe(null);
// And the other way round: setting the option updates the button's state.
editor.commands.setTableLook('headerRow', true);
expect(isHeaderStyled(editor.state, 'row')).toBe(true);
editor.destroy();
});
it('maps the header-column button onto the first-column option', () => {
const editor = makeEditor(3);
editor.commands.focus('start');
editor.commands.setTableStyle('Test Bands');
expect(isHeaderStyled(editor.state, 'column')).toBe(true);
editor.commands.toggleHeaderColumnStyle();
expect(parseTableLook(table(editor).attrs.tableLook).firstColumn).toBe(false);
expect(isHeaderStyled(editor.state, 'column')).toBe(false);
editor.destroy();
});
});
describe('setTableStyle', () => {
it('materializes fill, borders and regions, and is idempotent', () => {
const editor = makeEditor();
@@ -191,6 +347,23 @@ describe('setTableStyle', () => {
editor.destroy();
});
it('repaints when an option is toggled', () => {
const editor = makeEditor(4);
editor.commands.focus('start');
editor.commands.setTableStyle('Test Bands');
expect(fills(editor)).toEqual(['#EEEEEE', null, '#FAFAFA', null]);
// Header row off: it loses its fill and the stripes move up a row.
editor.commands.setTableLook('headerRow', false);
expect(fills(editor)).toEqual([null, '#FAFAFA', null, '#FAFAFA']);
expect(table(editor).content[0].content[0].attrs.region).toBe('firstColumn');
// And back again.
editor.commands.setTableLook('headerRow', true);
expect(fills(editor)).toEqual(['#EEEEEE', null, '#FAFAFA', null]);
editor.destroy();
});
it('ignores an unknown style name', () => {
const editor = makeEditor();
editor.commands.focus('start');