feat: table-styles

This commit is contained in:
Steffen Becker committed 2026-08-05 19:01:25 +02:00
1 parent 82699e653b
commit 1ed9f3d172
26 files changed
+1634 -110

No files matched your search

+18 -4
View File
@@ -25,7 +25,7 @@
import { loadOrientation, saveOrientation, type Orientation } from './lib/storage/pageOrientation';
import { loadPageFormat, savePageFormat, type PageFormat } from './lib/storage/pageFormat';
import { setStyleSheet, styleSheet } from './lib/styles/sheet.svelte';
import { builtinStyleSheet } from './lib/styles/styleSheet';
import { builtinStyleSheet, type StyleFamily } from './lib/styles/styleSheet';
import { loadHfDoc, saveHfDoc, loadHfDistances, saveHfDistances, loadDifferentFirstPage, saveDifferentFirstPage, loadDifferentOddEven, saveDifferentOddEven, hfIsEmpty, DEFAULT_HF_DISTANCES, type HfDoc, type HfZone, type HfDistances } from './lib/storage/headerFooter';
import { loadDocName, saveDocName, stripOdtExtension, sanitizeNameForFile } from './lib/storage/documentName';
import { loadDocumentLanguage, saveDocumentLanguage, odfFromLanguage, type DocumentLanguage } from './lib/storage/documentLanguage';
@@ -33,6 +33,7 @@
import LanguagePicker from './lib/components/LanguagePicker.svelte';
import UiLanguagePicker from './lib/components/UiLanguagePicker.svelte';
import AboutDialog from './lib/components/AboutDialog.svelte';
import StyleManagerDialog from './lib/components/StyleManagerDialog.svelte';
import { t } from './lib/i18n/i18n.svelte';
import { withShortcut } from './lib/i18n/shortcut';
import { DEFAULT_SHORTCUTS, matchesEvent, shortcutHint } from './lib/editor/shortcuts';
@@ -47,6 +48,13 @@
let currentPage: number = $state(1);
let numPages: number = $state(1);
let aboutOpen = $state(false);
let styleManagerOpen = $state(false);
let styleManagerFamily = $state<StyleFamily>('paragraph');
function openStyleManager(family: StyleFamily) {
styleManagerFamily = family;
styleManagerOpen = true;
}
// Header/footer content + live-edit state. While a zone is being edited, the
// top toolbars target hfEditor instead of the body editor (activeEditor below).
@@ -470,8 +478,10 @@
// Adopt the document's spell-check language (the $effect switches the
// controller + loads its dictionary). null = file declared none; keep ours.
if (result.language) documentLanguage = result.language;
// Adopt the document's named paragraph styles (built-ins + the file's own).
setStyleSheet(result.styles);
// Adopt the document's named paragraph styles (built-ins + the file's own). Table
// styles are not stored in the file (ODF has no banding), so the registry survives —
// an imported table finds its style again by name.
setStyleSheet({ ...result.styles, table: styleSheet().table });
// Adopt header/footer + first-page variants (null clears the zone); end any edit.
hfActive = null;
headerDoc = result.header;
@@ -772,7 +782,7 @@
<button class="logo-btn" onclick={() => (aboutOpen = true)} aria-label={t().about.label} title={t().about.label}>
<img src="/EdenText.png" alt="EdenText" class="app-logo" />
</button>
<Toolbar editor={activeEditor} tick={activeTick} />
<Toolbar editor={activeEditor} tick={activeTick} onManageStyles={openStyleManager} />
<div class="header-actions">
{#snippet saveIcon()}
<!-- Floppy disk -->
@@ -976,6 +986,7 @@
hfActive={hfActive}
onEditZone={(zone) => (hfActive = zone)}
onDebugDump={handleDebugDump}
onManageTableStyles={() => openStyleManager('table')}
/>
</div>
{@render toolbarScrollbar()}
@@ -1073,6 +1084,9 @@
</footer>
<AboutDialog bind:open={aboutOpen} />
<!-- One instance for every entry point (styles gallery, insert-table menu): the
callers only say which family to land on. -->
<StyleManagerDialog bind:open={styleManagerOpen} family={styleManagerFamily} editor={activeEditor} />
</main>
<style>
+3
View File
@@ -147,6 +147,9 @@
// Type sizes/margins changed under the layout, so page positions must be re-measured.
cancelAnimationFrame(styleRecalcRaf);
styleRecalcRaf = requestAnimationFrame(() => {
// A table style's fill/borders live in cell attrs, so an edited registry has to be
// painted into the document — this effect is the choke point every change passes.
ed.commands.refreshTableStyles();
ed.view.dispatch(ed.state.tr.setMeta('addToHistory', false).setMeta(FORCE_PAGE_RECALC, true));
});
});
+278 -39
View File
@@ -5,16 +5,26 @@
DEFAULT_STYLE, HEADING_PARENT, isAbstractStyle, propsFromBlock, resolveStyle, styleDelta,
styleOrder, uniqueStyleName, type Style, type StyleFamily,
} from '../styles/styleSheet';
import { deleteCharacterStyle, deleteStyle, putStyle, renameStyle, resetStyle, styleSheet } from '../styles/sheet.svelte';
import {
deleteCharacterStyle, deleteStyle, deleteTableStyle, putStyle, putTableStyle,
renameStyle, resetStyle, styleSheet,
} from '../styles/sheet.svelte';
import {
TABLE_REGIONS, previewCellCss,
type TableRegion, type TableRegionProps, type TableStyle,
} from '../styles/tableStyles';
import { borderAttrValue, parseBorderAttr } from '../editor/extensions/tableCellBorders';
import { blockStyleName } from '../editor/extensions/paragraphStyle';
import { activeCharacterStyle } from '../editor/extensions/characterStyle';
import { activeTableStyle } from '../editor/extensions/tableStyle';
import { CANDIDATE_FONTS, detectAvailableFonts } from '../utils/fontDetect';
import AlignIcon, { type AlignValue } from './AlignIcon.svelte';
import ColorPicker from './ColorPicker.svelte';
// LibreOffice's style manager: pick a style, edit its properties, or make a new one
// from the cursor's formatting. Edits apply live — every block using the style follows.
let { open = $bindable(false), editor }: { open?: boolean; editor: Editor | null } = $props();
let { open = $bindable(false), editor, family: openFamily = 'paragraph' }:
{ open?: boolean; editor: Editor | null; family?: StyleFamily } = $props();
const ALIGNMENTS: AlignValue[] = ['left', 'center', 'right', 'justify'];
// Beyond this the indent would push the name out of the 14rem pane, so deeper
@@ -23,19 +33,25 @@
const indentRem = (depth: number) => 0.6 + Math.min(depth, MAX_INDENT_DEPTH) * 0.8;
let dialogEl: HTMLDialogElement | null = $state(null);
// The tab to land on; the $effect below takes it from the caller on every open, so
// each entry point (styles gallery vs. table menu) lands where it should.
let family = $state<StyleFamily>('paragraph');
let selected = $state(DEFAULT_STYLE);
let selectedChar = $state('');
let selectedTable = $state('');
// Which conditional area of a table style is being edited.
let region = $state<TableRegion | 'wholeTable'>('wholeTable');
// The fonts installed on this machine, detected once the dialog is first opened
// (same list the font picker uses).
let fonts = $state<string[]>([]);
let sheet = $derived(styleSheet());
let isChar = $derived(family === 'character');
let isTable = $derived(family === 'table');
let styles = $derived(isChar ? sheet.character : sheet.paragraph);
// Indented by inheritance depth, so the chain is visible.
let rows = $derived(styleOrder(sheet, true, family).map((s) => ({ style: s, depth: depthOf(s) })));
let current = $derived(isChar ? selectedChar : selected);
let current = $derived(isTable ? selectedTable : isChar ? selectedChar : selected);
let style = $derived(styles[current] ?? Object.values(styles)[0]);
let resolved = $derived(resolveStyle(sheet, style?.name, family));
// A style can't inherit from itself or from one of its own descendants.
@@ -44,10 +60,59 @@
);
function select(name: string) {
if (isChar) selectedChar = name;
if (isTable) selectedTable = name;
else if (isChar) selectedChar = name;
else selected = name;
}
// ---- table styles: their own shape (no inheritance), so their own small set of state.
let tableList = $derived(Object.values(sheet.table ?? {}));
let tStyle = $derived(sheet.table?.[selectedTable] ?? tableList[0]);
let regionProps = $derived<TableRegionProps>(
(region === 'wholeTable' ? tStyle?.wholeTable : tStyle?.regions[region]) ?? {},
);
function editTable(patch: Partial<TableStyle>) {
if (tStyle) putTableStyle({ ...tStyle, ...patch });
}
function editRegion(patch: TableRegionProps) {
const next = { ...regionProps, ...patch };
for (const key of Object.keys(patch) as (keyof TableRegionProps)[]) {
if (patch[key] === undefined) delete next[key];
}
if (region === 'wholeTable') editTable({ wholeTable: next });
else editTable({ regions: { ...tStyle.regions, [region]: next } });
}
function newTableStyle() {
const name = uniqueStyleName(sheet, t().styles.newName, 'table');
putTableStyle({ name, border: null, innerBorder: null, regions: {} });
selectedTable = name;
}
const BORDER_WIDTHS = ['none', '0.5', '0.75', '1', '1.5', '2.25'];
// The three border controls; the inner ones fall back to the shared innerBorder.
type BorderKey = 'border' | 'innerBorderH' | 'innerBorderV';
const BORDER_FIELDS: { key: BorderKey; label: () => string }[] = [
{ key: 'border', label: () => t().styles.outerBorder },
{ key: 'innerBorderH', label: () => t().styles.rowLines },
{ key: 'innerBorderV', label: () => t().styles.columnLines },
];
const borderOf = (key: BorderKey): string | null | undefined =>
tStyle?.[key] !== undefined ? tStyle[key] : key === 'border' ? undefined : tStyle?.innerBorder;
const PREVIEW_ROWS = 5;
const PREVIEW_COLS = 4;
// The border select and its color picker split one canonical '<W>pt solid #RRGGBB'.
function borderParts(value: string | null | undefined) {
const b = parseBorderAttr(value ?? null);
if (b === 'none') return { width: 'none', color: '#000000' };
return b ? { width: String(b.widthPt), color: b.color } : { width: '0.5', color: '#000000' };
}
const borderValue = (width: string, color: string) =>
width === 'none' ? 'none' : borderAttrValue({ widthPt: parseFloat(width), color });
function depthOf(s: Style): number {
let depth = 0;
let cur = s.parent;
@@ -78,11 +143,16 @@
if (open && !fonts.length) fonts = detectAvailableFonts(CANDIDATE_FONTS);
});
$effect(() => {
if (open) family = openFamily;
});
// Follow the cursor's style when the dialog opens (LibreOffice preselects it too).
$effect(() => {
if (!open || !editor) return;
selected = blockStyleName(editor.state.selection.$from.parent as never);
selectedChar = activeCharacterStyle(editor.state as never) ?? Object.keys(sheet.character)[0] ?? '';
selectedTable = activeTableStyle(editor.state as never) ?? Object.keys(sheet.table ?? {})[0] ?? '';
});
// An undefined patch value clears the style's own property, so it inherits again.
@@ -98,11 +168,24 @@
putStyle({ ...style, para: merge(style.para, patch.para ?? {}), text: merge(style.text, patch.text ?? {}) }, family);
}
// The text fields are shared by all three families; a table style edits the selected
// region instead of the style itself (and has no parent chain, so own = resolved).
let ownText = $derived(isTable ? regionProps.text ?? {} : style.text);
let resolvedText = $derived(isTable ? regionProps.text ?? {} : resolved.text);
function editText(patch: Partial<Style['text']>) {
if (!isTable) return edit({ text: patch });
const text = { ...(regionProps.text ?? {}), ...patch };
for (const key of Object.keys(patch) as (keyof Style['text'])[]) {
if (patch[key] === undefined) delete text[key];
}
editRegion({ text });
}
// A style may name a font that isn't installed here; keep it in the list so editing
// another property doesn't silently drop it.
let fontOptions = $derived(
style.text.fontFamily && !fonts.includes(style.text.fontFamily)
? [style.text.fontFamily, ...fonts]
ownText.fontFamily && !fonts.includes(ownText.fontFamily)
? [ownText.fontFamily, ...fonts]
: fonts,
);
@@ -202,7 +285,7 @@
function commitRename(from: string, next: string) {
editingName = null;
next = next.trim();
if (!next || next === from || styles[next]) return;
if (!next || next === from || (isTable ? sheet.table[next] : styles[next])) return;
renameStyle(from, next, family);
// Retag every block that referenced the old name.
retag(from, next);
@@ -223,6 +306,8 @@
if (!mark) return;
tr.removeMark(pos, pos + node.nodeSize, mark);
if (to) tr.addMark(pos, pos + node.nodeSize, mark.type.create({ name: to }));
} else if (isTable) {
if (node.attrs?.tableStyle === from) tr.setNodeAttribute(pos, 'tableStyle', to);
} else if (node.attrs?.styleName === from && to) {
tr.setNodeAttribute(pos, 'styleName', to);
}
@@ -233,7 +318,14 @@
}
function remove() {
const gone = style.name;
const gone = isTable ? tStyle.name : style.name;
if (isTable) {
deleteTableStyle(gone);
// The link goes, the painted cells stay — as when a LibreOffice AutoFormat is gone.
retag(gone, null);
selectedTable = Object.keys(sheet.table)[0] ?? '';
return;
}
if (isChar) {
deleteCharacterStyle(gone);
retag(gone, null);
@@ -267,10 +359,42 @@
<div class="body">
<div class="pane">
<div class="family">
<button class:active={!isChar} onclick={() => (family = 'paragraph')}>{t().styles.paragraphStyles}</button>
<button class:active={isChar} onclick={() => (family = 'character')}>{t().styles.characterStyles}</button>
<button class:active={family === 'paragraph'} onclick={() => (family = 'paragraph')}>{t().styles.tabs.paragraph}</button>
<button class:active={isChar} onclick={() => (family = 'character')}>{t().styles.tabs.character}</button>
<button class:active={isTable} onclick={() => (family = 'table')}>{t().styles.tabs.table}</button>
</div>
<ul class="list">
{#if isTable}
{#each tableList as s (s.name)}
<li>
{#if editingName === s.name}
<input
class="entry rename"
style="padding-left: {indentRem(0)}rem"
value={s.name}
use:focusSelect
onblur={(e) => editingName === s.name && commitRename(s.name, e.currentTarget.value)}
onkeydown={(e) => {
if (e.key === 'Enter') e.currentTarget.blur();
else if (e.key === 'Escape') { e.preventDefault(); editingName = null; }
}}
/>
{:else}
<button
class="entry"
class:active={current === s.name}
style="padding-left: {indentRem(0)}rem"
title={s.name}
onclick={() => select(s.name)}
ondblclick={() => { if (!s.builtin) editingName = s.name; }}
>
<span class="name">{s.name}</span>
{#if !s.builtin}<span class="badge">{t().styles.custom}</span>{/if}
</button>
{/if}
</li>
{/each}
{/if}
{#each rows as { style: s, depth } (s.name)}
<li>
{#if editingName === s.name}
@@ -306,6 +430,53 @@
</div>
<div class="fields">
{#if isTable}
<!-- The same grid the toolbar gallery shows, from the same resolver. -->
<div class="preview table-preview">
<table aria-hidden="true">
<tbody>
{#each Array(PREVIEW_ROWS) as _, r}
<tr>
{#each Array(PREVIEW_COLS) as _, c}
<td style={previewCellCss(tStyle, r, c, PREVIEW_ROWS, PREVIEW_COLS)}></td>
{/each}
</tr>
{/each}
</tbody>
</table>
</div>
<label>{t().styles.region}
<select value={region} onchange={(e) => (region = e.currentTarget.value as TableRegion | 'wholeTable')}>
<option value="wholeTable">{t().styles.regions.wholeTable}</option>
{#each TABLE_REGIONS as name}<option value={name}>{t().styles.regions[name]}</option>{/each}
</select>
</label>
<div class="row">
<div class="field">
<span class="field-label">{t().styles.fill}</span>
{#key current + region}
<ColorPicker
editor={null}
currentColor={regionProps.fill ?? null}
defaultColor={regionProps.fill ?? '#F2F2F2'}
title={t().styles.fill}
chevronTitle={t().styles.fill}
clearLabel={t().table.noFill}
onApply={(c) => editRegion({ fill: c })}
onClear={() => editRegion({ fill: undefined })}
>
{#snippet icon()}
<svg width="16" height="16" viewBox="0 0 18 18" fill="none" aria-hidden="true">
<path d="M7.5 2.5l6 6-5 5a1.4 1.4 0 0 1-2 0l-4-4a1.4 1.4 0 0 1 0-2z" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round"/>
</svg>
{/snippet}
</ColorPicker>
{/key}
</div>
</div>
{:else}
<!-- Fallbacks are the page's own defaults, not `inherit`: an inline `inherit`
would beat the .preview rule and pull in the dialog's UI text color. -->
<div class="preview" style="
@@ -324,13 +495,14 @@
{#each parentOptions as name}<option value={name}>{name}</option>{/each}
</select>
</label>
{/if}
<label>{t().styles.font}
<select
value={style.text.fontFamily ?? ''}
onchange={(e) => edit({ text: { fontFamily: e.currentTarget.value || undefined } })}
value={ownText.fontFamily ?? ''}
onchange={(e) => editText({ fontFamily: e.currentTarget.value || undefined })}
>
<option value="">{inherited(resolved.text.fontFamily) || '—'}</option>
<option value="">{inherited(resolvedText.fontFamily) || '—'}</option>
{#each fontOptions as font}
<option value={font} style="font-family: '{font}'">{font}</option>
{/each}
@@ -340,23 +512,23 @@
<div class="row">
<label>{t().styles.size}
<input type="number" min="1" max="400" step="0.5"
value={style.text.fontSizePt ?? ''}
placeholder={inherited(resolved.text.fontSizePt)}
onchange={(e) => edit({ text: { fontSizePt: num(e.currentTarget.value) } })} />
value={ownText.fontSizePt ?? ''}
placeholder={inherited(resolvedText.fontSizePt)}
onchange={(e) => editText({ fontSizePt: num(e.currentTarget.value) })} />
</label>
<div class="field">
<span class="field-label">{t().styles.color}</span>
<!-- No editor: the picker sets a style property, not a document range. -->
{#key style.name}
{#key current + region}
<ColorPicker
editor={null}
currentColor={style.text.color ?? null}
defaultColor={style.text.color ?? resolved.text.color ?? '#000000'}
currentColor={ownText.color ?? null}
defaultColor={ownText.color ?? resolvedText.color ?? '#000000'}
title={t().styles.color}
chevronTitle={t().styles.color}
clearLabel={inherited(resolved.text.color) || '—'}
onApply={(c) => edit({ text: { color: c } })}
onClear={() => edit({ text: { color: undefined } })}
clearLabel={inherited(resolvedText.color) || '—'}
onApply={(c) => editText({ color: c })}
onClear={() => editText({ color: undefined })}
>
{#snippet icon()}
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
@@ -369,17 +541,55 @@
</div>
<div class="row toggles">
<label class="check"><input type="checkbox" checked={!!resolved.text.bold}
onchange={(e) => edit({ text: { bold: e.currentTarget.checked } })} />{t().styles.bold}</label>
<label class="check"><input type="checkbox" checked={!!resolved.text.italic}
onchange={(e) => edit({ text: { italic: e.currentTarget.checked } })} />{t().styles.italic}</label>
<label class="check"><input type="checkbox" checked={!!resolved.text.underline}
onchange={(e) => edit({ text: { underline: e.currentTarget.checked } })} />{t().styles.underline}</label>
<label class="check"><input type="checkbox" checked={!!resolved.text.strike}
onchange={(e) => edit({ text: { strike: e.currentTarget.checked } })} />{t().styles.strike}</label>
<label class="check"><input type="checkbox" checked={!!resolvedText.bold}
onchange={(e) => editText({ bold: e.currentTarget.checked })} />{t().styles.bold}</label>
<label class="check"><input type="checkbox" checked={!!resolvedText.italic}
onchange={(e) => editText({ italic: e.currentTarget.checked })} />{t().styles.italic}</label>
<label class="check"><input type="checkbox" checked={!!resolvedText.underline}
onchange={(e) => editText({ underline: e.currentTarget.checked })} />{t().styles.underline}</label>
<label class="check"><input type="checkbox" checked={!!resolvedText.strike}
onchange={(e) => editText({ strike: e.currentTarget.checked })} />{t().styles.strike}</label>
</div>
{#if !isChar}
{#if isTable}
<div class="row">
{#each BORDER_FIELDS as { key, label }}
<div class="field">
<span class="field-label">{label()}</span>
<div class="border-row">
<select
value={borderParts(borderOf(key)).width}
onchange={(e) => editTable({ [key]: borderValue(e.currentTarget.value, borderParts(borderOf(key)).color) })}
>
{#each BORDER_WIDTHS as w}
<option value={w}>{w === 'none' ? t().styles.noBorder : t().borders.pt(Number(w))}</option>
{/each}
</select>
{#key current + key}
<ColorPicker
editor={null}
currentColor={borderParts(borderOf(key)).color}
defaultColor={borderParts(borderOf(key)).color}
title={t().borders.lineColor}
chevronTitle={t().borders.lineColor}
clearLabel="—"
onApply={(c) => editTable({ [key]: borderValue(borderParts(borderOf(key)).width, c) })}
onClear={() => editTable({ [key]: null })}
>
{#snippet icon()}
<svg width="16" height="16" viewBox="0 0 18 18" fill="none" aria-hidden="true">
<rect x="2" y="2" width="14" height="14" stroke="currentColor" stroke-width="1.3"/>
</svg>
{/snippet}
</ColorPicker>
{/key}
</div>
</div>
{/each}
</div>
{/if}
{#if !isChar && !isTable}
<div class="field">
<span class="field-label">{t().styles.alignment}</span>
<div class="align-row">
@@ -420,21 +630,45 @@
</div>
<footer>
{#if isChar}<button onclick={newEmptyStyle}>{t().styles.newStyle}</button>{/if}
<button onclick={newFromSelection}>{t().styles.newFromSelection}</button>
<button onclick={updateFromSelection}>{t().styles.updateFromSelection}</button>
<span class="spacer"></span>
{#if style.builtin}
<button onclick={() => resetStyle(style.name, family)}>{t().styles.reset}</button>
{#if isTable}
<button onclick={newTableStyle}>{t().styles.newStyle}</button>
<span class="spacer"></span>
{#if tStyle?.builtin}
<button onclick={() => resetStyle(tStyle.name, 'table')}>{t().styles.reset}</button>
{:else}
<button onclick={() => (editingName = tStyle.name)}>{t().styles.rename}</button>
<button class="danger" onclick={remove}>{t().common.remove}</button>
{/if}
{:else}
<button onclick={() => (editingName = style.name)}>{t().styles.rename}</button>
<button class="danger" onclick={remove} disabled={style.name === HEADING_PARENT}>{t().common.remove}</button>
{#if isChar}<button onclick={newEmptyStyle}>{t().styles.newStyle}</button>{/if}
<button onclick={newFromSelection}>{t().styles.newFromSelection}</button>
<button onclick={updateFromSelection}>{t().styles.updateFromSelection}</button>
<span class="spacer"></span>
{#if style.builtin}
<button onclick={() => resetStyle(style.name, family)}>{t().styles.reset}</button>
{:else}
<button onclick={() => (editingName = style.name)}>{t().styles.rename}</button>
<button class="danger" onclick={remove} disabled={style.name === HEADING_PARENT}>{t().common.remove}</button>
{/if}
{/if}
</footer>
</div>
</dialog>
<style>
.table-preview { display: flex; align-items: center; justify-content: center; }
.table-preview table {
width: 12rem;
table-layout: fixed;
border-collapse: collapse;
background: var(--color-page-bg);
color: var(--color-page-text);
}
.table-preview td { height: 1rem; padding: 0; }
.border-row { display: flex; align-items: center; gap: 0.3rem; }
.border-row select { flex: 1; min-width: 0; }
.styles {
margin: auto;
padding: 0;
@@ -493,6 +727,11 @@
}
.family button {
flex: 1;
/* Without this a flex item can't shrink below its longest word — a German
compound has no break opportunity and pushed the strip out of the pane. */
min-width: 0;
overflow-wrap: break-word;
hyphens: auto;
padding: 0.3rem 0.2rem;
border: 1px solid var(--color-border);
border-radius: var(--radius);
+58
View File
@@ -7,6 +7,7 @@
open = $bindable(false),
onOpen,
onInsert,
onManageStyles,
}: {
editor: Editor | null;
open?: boolean;
@@ -14,6 +15,8 @@
// Mirrors ColorPicker's onApply: the parent runs the actual editor command
// against the saved selection range (focus is stolen by the popover).
onInsert: (rows: number, cols: number, range: { from: number; to: number }) => void;
// Opens the style manager on its table tab (mounted once, in App.svelte).
onManageStyles?: () => void;
} = $props();
// Quick-pick grid size (like Word/LibreOffice). Hovering selects the top-left
@@ -153,6 +156,20 @@
</label>
<button class="table-insert-btn" onclick={insertFromInputs}>{t().table.insert}</button>
</div>
<button
class="table-manage"
title={t().table.manageStyles}
onclick={() => { open = false; onManageStyles?.(); }}
>
<!-- Sliders, as on the style gallery's "Manage styles…" entry. -->
<svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
<path d="M2 4.5h8M13 4.5h1M2 11.5h1M6 11.5h8" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/>
<circle cx="11.5" cy="4.5" r="1.6" stroke="currentColor" stroke-width="1.4"/>
<circle cx="4.5" cy="11.5" r="1.6" stroke="currentColor" stroke-width="1.4"/>
</svg>
<span class="table-manage-label">{t().table.manageStyles}</span>
</button>
</div>
{/if}
</div>
@@ -191,6 +208,10 @@
position: absolute;
top: calc(100% + 3px);
left: 0;
/* A column so every child stretches to the panel width: a <button> with width:auto
sizes to its content in WebKit, which left the manage row short of the edge. */
display: flex;
flex-direction: column;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius);
@@ -215,6 +236,9 @@
display: flex;
flex-direction: column;
gap: 2px;
/* Centred, so whichever of grid and manage row is wider, the other isn't left
with a ragged gap on one side. */
align-self: center;
}
.table-grid-row {
@@ -291,4 +315,38 @@
.table-insert-btn:hover {
opacity: 0.9;
}
/* Bleeds to both panel edges below the grid, like the style gallery's manage row.
The panel is shrink-to-fit, so its width must come from the grid alone: width:0
keeps this row out of that calculation, and min-width then fills the resolved
width plus the two negative margins. The label truncates instead (title = full). */
.table-manage {
display: flex;
align-items: center;
gap: 0.4rem;
width: 0;
min-width: calc(100% + 16px);
margin: 8px -8px -8px;
padding: 0.45rem 0.5rem;
border: none;
border-top: 1px solid var(--color-border);
border-radius: 0;
background: color-mix(in srgb, var(--color-primary) 8%, var(--color-surface));
color: color-mix(in srgb, var(--color-primary) 55%, var(--color-text));
font-family: var(--font-sans);
font-size: 0.78rem;
font-weight: 600;
cursor: pointer;
}
.table-manage-label {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.table-manage:hover {
background: color-mix(in srgb, var(--color-primary) 16%, var(--color-surface));
}
</style>
+226
View File
@@ -0,0 +1,226 @@
<script lang="ts">
import type { Editor } from '@tiptap/core';
import { activeTableStyle } from '../editor/extensions/tableStyle';
import { styleSheet } from '../styles/sheet.svelte';
import { previewCellCss } from '../styles/tableStyles';
import { t } from '../i18n/i18n.svelte';
let { editor, tick }: { editor: Editor | null; tick: number } = $props();
let open = $state(false);
const sheet = $derived(styleSheet());
const styles = $derived(Object.values(sheet.table ?? {}));
const current = $derived(tick >= 0 && editor ? activeTableStyle(editor.state) : null);
// 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.
const ROWS = 4;
const COLS = 3;
function styleLabel(name: string): string {
return (t().table.styleNames as Record<string, string>)[name] ?? name;
}
function apply(name: string | null) {
open = false;
editor?.chain().focus().setTableStyle(name).run();
}
function clickOutside(node: HTMLElement) {
function handler(e: MouseEvent) {
if (!node.contains(e.target as Node)) open = false;
}
window.addEventListener('mousedown', handler);
return { destroy() { window.removeEventListener('mousedown', handler); } };
}
</script>
<div class="style-picker" use:clickOutside>
<button
class="tsp-trigger"
class:active={open}
title={t().table.tableStyle}
aria-label={t().table.tableStyle}
aria-expanded={open}
onclick={() => (open = !open)}
>
<svg width="18" height="18" viewBox="0 0 18 18" fill="none" aria-hidden="true">
<rect x="1.5" y="1.5" width="15" height="15" rx="1" stroke="currentColor" stroke-width="1.3"/>
<rect x="1.5" y="1.5" width="15" height="4.5" fill="currentColor" opacity="0.55"/>
<rect x="1.5" y="10.5" width="15" height="3" fill="currentColor" opacity="0.25"/>
</svg>
<svg class="tsp-chevron" width="8" height="8" viewBox="0 0 8 8" fill="none" aria-hidden="true">
<path d="M1 2.5l3 3 3-3" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</button>
{#if open}
<div class="tsp-dropdown">
<div class="tsp-title">{t().table.tableStyle}</div>
<div class="tsp-grid">
<button
class="tsp-tile"
class:active={current === null}
title={t().table.noTableStyle}
aria-pressed={current === null}
onclick={() => apply(null)}
>
<span class="tsp-none" aria-hidden="true">
<svg width="34" height="26" viewBox="0 0 34 26" fill="none">
<rect x="1" y="1" width="32" height="24" stroke="currentColor" stroke-width="1" opacity="0.35"/>
<path d="M6 20L28 6" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/>
</svg>
</span>
<span class="tsp-name">{t().table.noTableStyle}</span>
</button>
{#each styles as style (style.name)}
<button
class="tsp-tile"
class:active={current === style.name}
title={styleLabel(style.name)}
aria-pressed={current === style.name}
onclick={() => apply(style.name)}
>
<table class="tsp-preview" aria-hidden="true">
<tbody>
{#each Array(ROWS) as _, r}
<tr>
{#each Array(COLS) as _, c}
<td style={previewCellCss(style, r, c, ROWS, COLS)}></td>
{/each}
</tr>
{/each}
</tbody>
</table>
<span class="tsp-name">{styleLabel(style.name)}</span>
</button>
{/each}
</div>
</div>
{/if}
</div>
<style>
.style-picker {
position: relative;
}
.tsp-trigger {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 1px;
height: 1.7rem;
min-width: unset;
padding: 0 3px;
border: none;
border-radius: calc(var(--radius) - 2px);
background: transparent;
color: var(--color-text);
cursor: pointer;
transition: background 0.12s, color 0.12s;
}
.tsp-trigger:hover,
.tsp-trigger.active {
background: var(--color-btn-hover);
}
.tsp-chevron {
flex-shrink: 0;
}
.tsp-dropdown {
position: absolute;
top: calc(100% + 3px);
left: 0;
z-index: 200;
display: flex;
flex-direction: column;
gap: 4px;
padding: 6px;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}
.tsp-title {
padding: 0.1rem 0.2rem 0.2rem;
font-size: 0.65rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--color-text);
font-family: var(--font-sans);
user-select: none;
}
.tsp-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 3px;
/* The gallery grew past the toolbar's height; keep the panel scrollable. */
max-height: 21rem;
overflow-y: auto;
}
.tsp-tile {
display: flex;
flex-direction: column;
align-items: center;
gap: 3px;
width: 5.4rem;
min-width: unset;
padding: 4px 3px 3px;
border: 1px solid var(--color-border);
border-radius: calc(var(--radius) - 2px);
background: var(--color-bg);
color: var(--color-text);
cursor: pointer;
transition: background 0.1s;
}
.tsp-tile:hover {
background: var(--color-btn-hover);
}
.tsp-tile.active {
outline: 2px solid var(--color-primary);
outline-offset: -1px;
}
.tsp-preview {
width: 38px;
table-layout: fixed;
border-collapse: collapse;
background: var(--color-page-bg);
color: var(--color-page-text);
}
.tsp-preview td {
height: 7px;
padding: 0;
}
.tsp-none {
display: flex;
align-items: center;
justify-content: center;
height: 28px;
color: var(--color-text);
}
.tsp-name {
font-family: var(--font-sans);
font-size: 0.6rem;
line-height: 1.1;
text-align: center;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 100%;
user-select: none;
}
</style>
+3
View File
@@ -4,6 +4,7 @@
import { isHeaderStyled } from '../editor/extensions/tableHeaderRow';
import ColorPicker from './ColorPicker.svelte';
import TableBorderPicker from './TableBorderPicker.svelte';
import TableStylePicker from './TableStylePicker.svelte';
import { t } from '../i18n/i18n.svelte';
let {
@@ -218,6 +219,8 @@
<TableBorderPicker {editor} {tick} />
<TableStylePicker {editor} {tick} />
<span class="tt-sep"></span>
<button
+14 -7
View File
@@ -6,11 +6,11 @@
import { BULLET_TYPES } from '../utils/bulletListTypes';
import { effectiveOrderedTypeAt } from '../editor/extensions/orderedList';
import { isInHeaderCell } from '../editor/extensions/tableHeaderRow';
import { cellRegionText } from '../editor/extensions/tableStyle';
import { blockStyleName } from '../editor/extensions/paragraphStyle';
import { activeCharacterStyle } from '../editor/extensions/characterStyle';
import { DEFAULT_STYLE, headingStyleName, resolveStyle, styleOrder } from '../styles/styleSheet';
import { DEFAULT_STYLE, headingStyleName, resolveStyle, styleOrder, type StyleFamily } from '../styles/styleSheet';
import { styleSheet } from '../styles/sheet.svelte';
import StyleManagerDialog from './StyleManagerDialog.svelte';
import { t } from '../i18n/i18n.svelte';
import { withShortcut } from '../i18n/shortcut';
import { shortcutHint, type ShortcutId } from '../editor/shortcuts';
@@ -20,7 +20,12 @@
return (t().toolbar.bullets as Record<string, string>)[char] ?? char;
}
let { editor, tick }: { editor: Editor | null; tick: number } = $props();
// The style manager is mounted once in App.svelte; the gallery only asks for it.
let { editor, tick, onManageStyles }: {
editor: Editor | null;
tick: number;
onManageStyles?: (family: StyleFamily) => void;
} = $props();
// The document's named paragraph styles (LibreOffice model): the gallery lists the
// registry, assigning one only sets the style — hard formatting stays, as in Word/LO.
@@ -59,7 +64,6 @@
}
let stylesOpen = $state(false);
let managerOpen = $state(false);
// $derived re-evaluates whenever `tick` changes (i.e. on every TipTap transaction)
let isHeading = $derived(tick >= 0 && !!editor?.isActive('heading'));
@@ -90,7 +94,11 @@
// Header-row cells render bold by default (CSS), like headings — so the Bold button
// toggles the fontWeight:'normal' override there too (keeps header bold editable).
let inHeaderCell = $derived(tick >= 0 && !!editor && isInHeaderCell(editor.state));
// A table style's regions render the same way, so they count as well.
let inHeaderCell = $derived(
tick >= 0 && !!editor
&& (isInHeaderCell(editor.state) || cellRegionText(editor.state, sheet.table).bold === true),
);
let boldByDefault = $derived(isHeading || inHeaderCell);
// fontWeight:'normal' is set explicitly to override the default boldness
let hasNormalWeight = $derived(tick >= 0 && !!editor?.isActive('textStyle', { fontWeight: 'normal' }));
@@ -255,7 +263,7 @@
{/each}
{/if}
</div>
<button class="ol-option manage" onclick={() => { stylesOpen = false; managerOpen = true; }}>
<button class="ol-option manage" onclick={() => { stylesOpen = false; onManageStyles?.('paragraph'); }}>
<!-- Sliders, as on the Tools button: this opens a settings surface -->
<svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
<path d="M2 4.5h8M13 4.5h1M2 11.5h1M6 11.5h8" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/>
@@ -396,7 +404,6 @@
{/if}
</div>
<StyleManagerDialog bind:open={managerOpen} {editor} />
<style>
/* Sits inside the header island (which paints the frosted background). Not a
+3 -2
View File
@@ -24,8 +24,8 @@
import { t } from '../i18n/i18n.svelte';
import { shortcutHint, type ShortcutId } from '../editor/shortcuts';
let { editor, tick, showFormattingMarks = $bindable(), pageMargins = $bindable(DEFAULT_MARGINS), pageOrientation = $bindable<Orientation>('portrait'), pageFormat = $bindable<PageFormat>('A4'), hfDistances = $bindable(DEFAULT_HF_DISTANCES), differentFirstPage = $bindable(false), differentOddEven = $bindable(false), hfActive = null, onEditZone, onDebugDump }:
{ editor: Editor | null; tick: number; showFormattingMarks: boolean; pageMargins?: PageMargins; pageOrientation?: Orientation; pageFormat?: PageFormat; hfDistances?: HfDistances; differentFirstPage?: boolean; differentOddEven?: boolean; hfActive?: 'header' | 'footer' | null; onEditZone?: (zone: 'header' | 'footer') => void; onDebugDump?: () => void } = $props();
let { editor, tick, showFormattingMarks = $bindable(), pageMargins = $bindable(DEFAULT_MARGINS), pageOrientation = $bindable<Orientation>('portrait'), pageFormat = $bindable<PageFormat>('A4'), hfDistances = $bindable(DEFAULT_HF_DISTANCES), differentFirstPage = $bindable(false), differentOddEven = $bindable(false), hfActive = null, onEditZone, onDebugDump, onManageTableStyles }:
{ editor: Editor | null; tick: number; showFormattingMarks: boolean; pageMargins?: PageMargins; pageOrientation?: Orientation; pageFormat?: PageFormat; hfDistances?: HfDistances; differentFirstPage?: boolean; differentOddEven?: boolean; hfActive?: 'header' | 'footer' | null; onEditZone?: (zone: 'header' | 'footer') => void; onDebugDump?: () => void; onManageTableStyles?: () => void } = $props();
const PAGE_FORMATS = Object.keys(PAGE_FORMAT_CM) as PageFormat[];
@@ -1465,6 +1465,7 @@
bind:open={tableOpen}
onOpen={onTablePickerOpen}
onInsert={insertTable}
onManageStyles={onManageTableStyles}
/>
<SpecialCharPicker
{editor}
+4
View File
@@ -41,6 +41,7 @@ import { TableSplit } from './extensions/tableSplit';
import { TableCellBackground } from './extensions/tableCellBackground';
import { TableCellBorders } from './extensions/tableCellBorders';
import { TableHeaderRow } from './extensions/tableHeaderRow';
import { TableStyle } from './extensions/tableStyle';
import { TrailingNode } from './extensions/trailingNode';
import { Image } from './extensions/image';
import { DateTimeField } from './extensions/dateTimeField';
@@ -128,6 +129,9 @@ export const extensions = [
TableCellBorders,
// "Header row" styling preset: bold + light shading on the first row (toggle).
TableHeaderRow,
// Named table style (Word table style / LibreOffice AutoFormat): paints the table's
// conditional regions into cell attrs and re-bands on structural changes.
TableStyle.configure({ styles: () => styleSheet().table }),
// Guarantees a paragraph after a trailing table so the cursor isn't trapped
// and the user can keep writing below a table at the document's end.
TrailingNode,
+1 -1
View File
@@ -25,7 +25,7 @@ export const ParagraphStyle = Extension.create<{ types: string[]; sheet: () => S
name: 'paragraphStyle',
addOptions() {
return { types: ['paragraph', 'heading'], sheet: () => ({ paragraph: {}, character: {} }) };
return { types: ['paragraph', 'heading'], sheet: () => ({ paragraph: {}, character: {}, table: {} }) };
},
addGlobalAttributes() {
+197
View File
@@ -0,0 +1,197 @@
import { Extension } from '@tiptap/core';
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 type { TextProps } from '../../styles/styleSheet';
// Word/LibreOffice table styles: the link lives on the table (`tableStyle`), fill and
// borders are materialized into cell attrs (so export/PDF/clipboard need nothing), and
// each cell records its regions in `region` — the hook the generated CSS keys text on.
declare module '@tiptap/core' {
interface Commands<ReturnType> {
tableStyle: {
setTableStyle: (name: string | null) => ReturnType;
reapplyTableStyle: () => ReturnType;
refreshTableStyles: () => ReturnType;
};
}
}
export type TableStyleOptions = { styles: () => Record<string, TableStyleDef> };
// The style attrs a table style owns; clearing it resets exactly these.
const CLEARED = {
backgroundColor: null, region: null,
borderTop: null, borderRight: null, borderBottom: null, borderLeft: null,
};
// Write a table's cell attrs from `style` (null clears them). Only changed cells are
// touched, so re-running is a no-op — the condition the re-band plugin relies on.
function paintTable(tr: Transaction, tablePos: number, style: TableStyleDef | null): boolean {
const table = tr.doc.nodeAt(tablePos);
if (!table) return false;
const map = TableMap.get(table);
const start = tablePos + 1;
let changed = false;
for (const pos of new Set(map.map)) {
const cell = tr.doc.nodeAt(start + pos);
if (!cell) continue;
let next: Record<string, unknown> = CLEARED;
if (style) {
const box = map.findCell(pos);
const paint = resolveTableCell(style, {
row: box.top, col: box.left,
rowSpan: box.bottom - box.top, colSpan: box.right - box.left,
rows: map.height, cols: map.width,
});
next = {
backgroundColor: paint.fill,
region: paint.regions.length ? paint.regions.join(' ') : null,
...paint.borders,
};
}
if (Object.keys(next).every(key => cell.attrs[key] === next[key])) continue;
tr.setNodeMarkup(start + pos, undefined, { ...cell.attrs, ...next });
changed = true;
}
return changed;
}
// Every table carrying a style name, with its position. Tables sit at block level, so the
// walk stops at textblocks.
function styledTables(doc: PMNode): { pos: number; node: PMNode }[] {
const out: { pos: number; node: PMNode }[] = [];
doc.descendants((node, pos) => {
if (node.type.name === 'table') {
if (node.attrs.tableStyle) out.push({ pos, node });
return false;
}
return node.isBlock && !node.isTextblock;
});
return out;
}
const shapeOf = (node: PMNode) => `${node.attrs.tableStyle}:${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 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 {
const { $from } = state.selection;
let regions: unknown = null;
for (let d = $from.depth; d > 0; d--) {
const node = $from.node(d);
const role = node.type.spec.tableRole;
if (role === 'cell' || role === 'header_cell') regions = node.attrs.region;
else if (role === 'table') return regionText(styles[node.attrs.tableStyle as string], regions);
}
return {};
}
// `name` undefined re-applies the table's current style (after a structural change).
function applyStyle(styles: () => Record<string, TableStyleDef>, name?: string | null) {
return ({ state, tr, dispatch }: CommandProps): boolean => {
if (!isInTable(state)) return false;
const { table, tableStart } = selectedRect(state);
const wanted = name === undefined ? (table.attrs.tableStyle as string | null) : name;
const style = wanted ? styles()[wanted] ?? null : null;
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 });
}
paintTable(tr, tablePos, style);
dispatch(tr);
return true;
};
}
export const TableStyle = Extension.create<TableStyleOptions>({
name: 'tableStyle',
addOptions() {
return { styles: () => ({}) };
},
addGlobalAttributes() {
return [
{
types: ['table'],
attributes: {
tableStyle: {
default: null as string | null,
parseHTML: (el: HTMLElement) => el.getAttribute('data-table-style'),
renderHTML: (attrs: Record<string, unknown>) =>
attrs.tableStyle ? { 'data-table-style': String(attrs.tableStyle) } : {},
},
},
},
{
types: ['tableCell', 'tableHeader'],
attributes: {
region: {
default: null as string | null,
parseHTML: (el: HTMLElement) => el.getAttribute('data-region'),
renderHTML: (attrs: Record<string, unknown>) =>
attrs.region ? { 'data-region': String(attrs.region) } : {},
},
},
},
];
},
addCommands() {
const styles = () => this.options.styles();
return {
setTableStyle: (name: string | null) => applyStyle(styles, name),
reapplyTableStyle: () => applyStyle(styles),
// Repaint every styled table — the registry changed (edit, rename, reset, import).
refreshTableStyles: () => ({ tr, dispatch }: CommandProps) => {
let changed = false;
for (const { pos, node } of styledTables(tr.doc)) {
const style = styles()[node.attrs.tableStyle as string];
if (style) changed = paintTable(tr, pos, style) || changed;
}
if (changed && dispatch) dispatch(tr);
return changed;
},
};
},
addProseMirrorPlugins() {
const styles = () => this.options.styles();
return [
new Plugin({
key: new PluginKey('tableStyleReband'),
// Re-band a styled table when it gains or loses rows/columns. Deliberately not on
// every transaction: repainting each change would undo a manually shaded cell.
appendTransaction(transactions, oldState, newState) {
if (!transactions.some(tr => tr.docChanged)) return null;
const next = styledTables(newState.doc);
if (!next.length) return null;
const prev = styledTables(oldState.doc);
const aligned = prev.length === next.length;
const stale = next.filter((t, i) => !aligned || shapeOf(prev[i].node) !== shapeOf(t.node));
if (!stale.length) return null;
const tr = newState.tr;
let changed = false;
for (const { pos, node } of stale) {
const style = styles()[node.attrs.tableStyle as string];
// setNodeMarkup keeps node sizes, so the collected positions stay valid.
if (style) changed = paintTable(tr, pos, style) || changed;
}
return changed ? tr : null;
},
}),
];
},
});
+10
View File
@@ -45,6 +45,14 @@ function applyMargins(node: PMNode, wrapper: HTMLElement): void {
wrapper.style.marginRight = mr ? `${mr}cm` : '';
}
// The node view never calls the node's renderHTML, so the table-style hook the generated
// CSS keys on has to be set here too (the static path emits it in tableStyle.ts).
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;
}
function buildColgroup(node: PMNode, colgroup: HTMLElement): void {
while (colgroup.firstChild) colgroup.removeChild(colgroup.firstChild);
const percents = columnPercents(columnWeightsFromRow(node.firstChild));
@@ -74,6 +82,7 @@ export class TableView {
// table-layout/border-collapse come from editor.css. width:100% keeps the
// table the full text width regardless of the stored weights.
this.table.style.width = '100%';
applyTableStyleAttr(node, this.table);
this.colgroup = this.table.appendChild(document.createElement('colgroup'));
buildColgroup(node, this.colgroup);
this.contentDOM = this.table.appendChild(document.createElement('tbody'));
@@ -83,6 +92,7 @@ export class TableView {
if (node.type !== this.node.type) return false;
this.node = node;
applyMargins(node, this.dom);
applyTableStyleAttr(node, this.table);
buildColgroup(node, this.colgroup);
return true;
}
+63 -21
View File
@@ -5,7 +5,7 @@ import {
AlignmentType, LevelFormat, UnderlineType, BorderStyle, ShadingType,
WidthType, HeightRule, PageOrientation, LineRuleType, TableLayoutType, SectionType,
HorizontalPositionAlign, VerticalPositionRelativeFrom, HorizontalPositionRelativeFrom,
TextWrappingType, TextWrappingSide,
TextWrappingType, TextWrappingSide, ImportedXmlComponent,
} from 'docx';
import type { TiptapNode } from 'odf-kit';
import type {
@@ -23,12 +23,16 @@ import { parseBorderAttr, type BorderSide } from '../editor/extensions/tableCell
import { effectiveOrderedDefAt, formatOrdinal, childCycle, ROOT_ORDERED_CYCLE, type OrderedCycle } from '../utils/orderedListTypes';
import { defaultBulletChar } from '../utils/bulletListTypes';
import { normalizeColor, MAX_HEADING_LEVEL, mergeJoinedParagraphsJson, twinFontName, type HfExport } from './odt';
import { builtinStyleSheet, DEFAULT_STYLE, type Style, type StyleSheet } from '../styles/styleSheet';
import { builtinStyleSheet, DEFAULT_STYLE, type Style, type StyleSheet, type TextProps } from '../styles/styleSheet';
import { 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
// the document language (Word recomputes an auto field on open using its own locale).
let docLangTag = 'en-US';
// The sheet of the export in flight, so the table/cell emitters can resolve a named
// table style without threading it through every helper (mirrors odt.ts).
let exportSheet: StyleSheet = builtinStyleSheet();
// DOCX export. Mirrors export/odt.ts feature-for-feature, but builds OOXML via the
// `docx` library instead of odf-kit. Lazy-loaded from App.svelte so neither this
@@ -154,9 +158,10 @@ function markPresent(marks: TiptapNode['marks'], type: string): boolean {
return !!marks?.some((m) => m.type === type);
}
// TipTap marks + textStyle attrs → Word run properties. forceBold bakes bold onto
// every run (header-row cells), respecting an explicit fontWeight:normal un-bold.
function runPropsFromMarks(marks: TiptapNode['marks'] = [], forceBold = false): Writable<IRunStylePropertiesOptions> {
// TipTap marks + textStyle attrs → Word run properties. `force` bakes a cell's
// presentational formatting (header row, table-style region) onto every run,
// respecting an explicit fontWeight:normal un-bold.
function runPropsFromMarks(marks: TiptapNode['marks'] = [], force: TextProps = {}): Writable<IRunStylePropertiesOptions> {
const ts = marks.find((m) => m.type === 'textStyle');
const props: Writable<IRunStylePropertiesOptions> & { style?: string } = {};
@@ -171,23 +176,23 @@ function runPropsFromMarks(marks: TiptapNode['marks'] = [], forceBold = false):
if (s === 'normal' || s === '400') bold = false;
else if (s === 'bold' || /^[5-9]\d\d$/.test(s)) bold = true;
}
if (forceBold && bold !== false) bold = true;
if (force.bold && bold !== false) bold = true;
if (bold !== undefined) props.bold = bold;
if (markPresent(marks, 'italic')) props.italics = true;
if (markPresent(marks, 'italic') || force.italic) props.italics = true;
if (markPresent(marks, 'underline')) props.underline = { type: UnderlineType.SINGLE };
if (markPresent(marks, 'strike')) props.strike = true;
if (markPresent(marks, 'superscript')) props.superScript = true;
else if (markPresent(marks, 'subscript')) props.subScript = true;
const ff = ts?.attrs?.fontFamily;
const ff = ts?.attrs?.fontFamily ?? force.fontFamily;
if (ff) props.font = String(ff) === SCREEN_FONT ? DOC_FONT : String(ff);
const fs = ts?.attrs?.fontSize;
const fs = ts?.attrs?.fontSize ?? (force.fontSizePt != null ? `${force.fontSizePt}pt` : null);
if (fs) {
const hp = fontSizeToHalfPoints(String(fs));
if (hp) props.size = hp;
}
const col = ts?.attrs?.color;
const col = ts?.attrs?.color ?? force.color;
if (col) {
const h = hexColor(String(col));
if (h) props.color = h;
@@ -207,9 +212,9 @@ function runPropsFromMarks(marks: TiptapNode['marks'] = [], forceBold = false):
// A text node → one run; tab chars become <w:tab/> via mixed children (a literal \t
// would otherwise be dropped). Returned as an array so a link wrapper can adopt it.
function textNodeToRuns(node: TiptapNode, forceBold: boolean): TextRun[] {
function textNodeToRuns(node: TiptapNode, force: TextProps): TextRun[] {
const text = node.text ?? '';
const props = runPropsFromMarks(node.marks, forceBold);
const props = runPropsFromMarks(node.marks, force);
if (!text.includes('\t')) return [new TextRun({ text, ...props })];
const parts = text.split('\t');
const children: (string | Tab)[] = [];
@@ -238,11 +243,11 @@ function dateTimeRun(node: TiptapNode): Inline {
return new SimpleField(`${kind === 'time' ? 'TIME' : 'DATE'} \\@ "${docxPicture(fmt)}"`, text);
}
function inlineToRuns(content: TiptapNode[] = [], forceBold = false): Inline[] {
function inlineToRuns(content: TiptapNode[] = [], force: TextProps = {}): Inline[] {
const out: Inline[] = [];
for (const node of content) {
if (node.type === 'text' && node.text) {
const runs = textNodeToRuns(node, forceBold);
const runs = textNodeToRuns(node, force);
const href = node.marks?.find((m) => m.type === 'link')?.attrs?.href;
if (href) out.push(new ExternalHyperlink({ link: String(href), children: runs }));
else out.push(...runs);
@@ -579,7 +584,7 @@ function spacingOf(attrs: TiptapNode['attrs']): ISpacingProperties | undefined {
}
type ParaOpts = { numbering?: { reference: string; level: number }; indentLeftTwip?: number; forceBold?: boolean };
type ParaOpts = { numbering?: { reference: string; level: number }; indentLeftTwip?: number; force?: TextProps };
// Paragraph background ("colored field") → w:shd; per-side borders ("rule line") → w:pBdr.
function paraShadingOf(attrs: TiptapNode['attrs']) {
@@ -617,7 +622,7 @@ function paragraphToDocx(node: TiptapNode, opts: ParaOpts = {}): Paragraph {
shading: paraShadingOf(attrs),
border: paraBordersOf(attrs),
run: markSize ? { size: markSize } : undefined,
children: inlineToRuns(node.content, opts.forceBold),
children: inlineToRuns(node.content, opts.force),
});
}
@@ -676,6 +681,14 @@ function columnWidthsCm(node: TiptapNode, contentWidthCm: number): number[] | un
const cellBorder: IBorderOptions = { style: BorderStyle.SINGLE, size: 4, color: '000000' }; // 0.5pt
// A cell's per-side border attr → w:tcBorders options (size in eighth-points).
// Header cells and a table style's regions render bold/font via CSS in the editor, so
// bake that onto the cell's runs for Word.
function cellForce(style: TableStyle | undefined, cell: TiptapNode, bg: unknown): TextProps {
const force = regionText(style, cell.attrs?.region);
if (bg === HEADER_SHADE) force.bold = true;
return force;
}
function docxCellBorder(attrs: Record<string, unknown> | undefined, side: BorderSide): IBorderOptions {
const b = parseBorderAttr(attrs?.[side] as string | null);
if (b === 'none') return { style: BorderStyle.NONE, size: 0, color: 'auto' };
@@ -683,7 +696,7 @@ function docxCellBorder(attrs: Record<string, unknown> | undefined, side: Border
return cellBorder;
}
function cellBlocksToDocx(content: TiptapNode[] = [], headerBold: boolean, num: Numbering, contentWidthCm: number): (Paragraph | Table)[] {
function cellBlocksToDocx(content: TiptapNode[] = [], force: TextProps, num: Numbering, contentWidthCm: number): (Paragraph | Table)[] {
const out: (Paragraph | Table)[] = [];
for (const child of content) {
if (child.type === 'bulletList' || child.type === 'orderedList') {
@@ -691,7 +704,7 @@ function cellBlocksToDocx(content: TiptapNode[] = [], headerBold: boolean, num:
} else if (child.type === 'table') {
out.push(tableToDocx(child, contentWidthCm, num));
} else if (child.type === 'paragraph' || child.type === 'heading') {
out.push(paragraphToDocx(child, { forceBold: headerBold }));
out.push(paragraphToDocx(child, { force }));
}
}
if (out.length === 0) out.push(new Paragraph({}));
@@ -700,6 +713,10 @@ function cellBlocksToDocx(content: TiptapNode[] = [], headerBold: boolean, num:
function tableToDocx(node: TiptapNode, contentWidthCm: number, num: Numbering): Table {
const rows = (node.content ?? []).filter((r) => r.type === 'tableRow');
// The named table style, if the registry still knows it: Word gets the reference
// (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;
// 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);
@@ -731,7 +748,7 @@ function tableToDocx(node: TiptapNode, contentWidthCm: number, num: Numbering):
left: docxCellBorder(cell.attrs, 'borderLeft'),
right: docxCellBorder(cell.attrs, 'borderRight'),
},
children: cellBlocksToDocx(cell.content, bg === HEADER_SHADE, num, contentWidthCm),
children: cellBlocksToDocx(cell.content, cellForce(tableStyle, cell, bg), num, contentWidthCm),
}));
}
return new TableRow({
@@ -741,6 +758,7 @@ function tableToDocx(node: TiptapNode, contentWidthCm: number, num: Numbering):
});
return new Table({
...(tableStyle ? { style: docxStyleId(tableStyle.name) } : {}),
rows: tableRows,
columnWidths: colsTwip,
width: { size: totalTwip, type: WidthType.DXA },
@@ -912,7 +930,29 @@ function characterStyleOf(style: Style): ICharacterStyleOptions {
return { id: docxStyleId(style.name), name: style.name, quickFormat: true, run };
}
function buildStyles(sheet: StyleSheet, used: Set<string>, language?: { language: string; country: string } | null) {
// Word needs a referenced table style to exist. ODF/our model hold the banding, and the
// look is baked into the cells, so a name-only definition is enough (no w:tblStylePr).
function tableStyleXml(name: string): ImportedXmlComponent {
return ImportedXmlComponent.fromXmlString(
`<w:style w:type="table" w:styleId="${docxStyleId(name)}">`
+ `<w:name w:val="${escapeXml(name)}"/><w:basedOn w:val="TableNormal"/><w:uiPriority w:val="59"/>`
+ '</w:style>',
);
}
// The table styles the document actually references, and the registry still defines.
function usedTableStyles(doc: TiptapNode, sheet: StyleSheet): string[] {
const names = new Set<string>();
const walk = (node: TiptapNode) => {
const name = node.type === 'table' ? node.attrs?.tableStyle : null;
if (typeof name === 'string' && sheet.table?.[name]) names.add(name);
node.content?.forEach(walk);
};
walk(doc);
return [...names];
}
function buildStyles(sheet: StyleSheet, used: Set<string>, language?: { language: string; country: string } | null, usedTables: string[] = []) {
const run: Writable<IRunStylePropertiesOptions> = { font: DOC_FONT, size: 24 };
if (language) run.language = { value: `${language.language}-${language.country}` };
return {
@@ -922,6 +962,7 @@ function buildStyles(sheet: StyleSheet, used: Set<string>, language?: { language
// The document's named styles, chain intact — Word shows them in its style list.
paragraphStyles: Object.values(sheet.paragraph).filter(st => used.has(st.name)).map(paragraphStyleOf),
characterStyles: Object.values(sheet.character ?? {}).map(characterStyleOf),
...(usedTables.length ? { importedStyles: usedTables.map(tableStyleXml) } : {}),
};
}
@@ -936,6 +977,7 @@ export async function buildDocx(
styles: StyleSheet = builtinStyleSheet(),
): Promise<Uint8Array> {
docLangTag = localeTag(language ? language.language : 'en');
exportSheet = styles;
const num = new Numbering();
const landscape = orientation === 'landscape';
const { w: pageWidthCm, h: pageHeightCm } = pageDimsCm(pageFormat, orientation);
@@ -998,7 +1040,7 @@ export async function buildDocx(
defaultTabStop: cmToTwip(1.25),
...(differentOddEven ? { evenAndOddHeaderAndFooters: true } : {}),
...(hasToc ? { features: { updateFields: true } } : {}),
styles: buildStyles(styles, usedStyleNames(docJson, styles), language),
styles: buildStyles(styles, usedStyleNames(docJson, styles), language, usedTableStyles(docJson, styles)),
numbering: { config: num.config },
// A columns group is its own section; w:type=continuous describes the break
// BEFORE a section, so it goes on every section but the first.
+71 -18
View File
@@ -4,7 +4,8 @@ import { DEFAULT_MARGINS, type PageMargins } from '../storage/pageMargins';
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 } from '../styles/styleSheet';
import { builtinStyleSheet, DEFAULT_STYLE, resolveStyle, type StyleSheet, type TextProps } from '../styles/styleSheet';
import { regionText } from '../styles/tableStyles';
import { HEADER_SHADE } from '../editor/extensions/tableHeaderRow';
import { BORDER_SIDES, parseBorderAttr } from '../editor/extensions/tableCellBorders';
import { TEXTBOX_PADDING_CM } from '../editor/extensions/textBox';
@@ -756,6 +757,29 @@ function applyTableMargins(odtBytes: Uint8Array, margins: (TableMargins | null)[
return rezipOdt(files);
}
// 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;
const files = unzipSync(odtBytes);
const contentBytes = files['content.xml'];
if (!contentBytes) return odtBytes;
let content = strFromU8(contentBytes);
names.forEach((name, i) => {
if (!name) return;
content = content.replace(
new RegExp(`(<style:style[^>]*style:name="Table${i + 1}")`),
`$1 style:parent-style-name="${odfStyleName(name)}"`,
);
});
files['content.xml'] = strToU8(content);
return rezipOdt(files);
}
// 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.
@@ -1083,8 +1107,17 @@ function stripManagedProps(block: string): string {
// Write the document's named paragraph styles into styles.xml: merge into the blocks
// odf-kit already emits (Standard, Heading, Heading_20_N), append the rest. The parent
// chain is preserved, so LibreOffice/Word show them as real, inheriting styles.
function applyNamedStyles(styles: string, sheet: StyleSheet, used: Set<string>): string {
function applyNamedStyles(styles: string, sheet: StyleSheet, used: Set<string>, usedTables: Set<string> = new Set()): string {
const added: string[] = [];
// Table styles: ODF's table family carries no banding, so the name is all that travels
// (the look is baked into the cells). An empty style block is enough to make it real.
for (const name of usedTables) {
const odfName = odfStyleName(name);
if (findAutoStyle(styles, odfName)) continue;
added.push(setTagAttrs('<style:style/>', {
'style:name': odfName, 'style:family': 'table', 'style:display-name': name,
}));
}
// Character styles are the same shape, family "text" and text props only.
for (const style of Object.values(sheet.character ?? {})) {
const { text } = ownStyleAttrs(style);
@@ -1768,7 +1801,7 @@ function rezipOdt(files: Record<string, Uint8Array>): Uint8Array {
// Rewrite styles.xml to match the editor's preview: default font Liberation Serif →
// Times New Roman (metric-identical; see EXPORT_FONT), and Heading_20_1/2/3 sizes &
// margins → the editor's values (odf-kit's defaults are larger; HEADING_STYLE_OVERRIDES).
function rewriteStylesXml(odtBytes: Uint8Array, lang: { language: string; country: string } | null, pageFormat: PageFormat, orientation: Orientation, sheet: StyleSheet, used: Set<string>): Uint8Array {
function rewriteStylesXml(odtBytes: Uint8Array, lang: { language: string; country: string } | null, pageFormat: PageFormat, orientation: Orientation, sheet: StyleSheet, used: Set<string>, usedTables: Set<string> = new Set()): Uint8Array {
const files = unzipSync(odtBytes);
const stylesBytes = files['styles.xml'];
if (!stylesBytes) return odtBytes;
@@ -1818,7 +1851,7 @@ function rewriteStylesXml(odtBytes: Uint8Array, lang: { language: string; countr
// The document's named paragraph styles (Standard, Heading, Heading_20_N, Title, …)
// with their parent chain: merged into odf-kit's own blocks, appended when new.
styles = applyNamedStyles(styles, sheet, used);
styles = applyNamedStyles(styles, sheet, used, usedTables);
files['styles.xml'] = strToU8(styles);
return rezipOdt(files);
@@ -1908,12 +1941,18 @@ function linkHrefOf(marks: TiptapNode['marks'] = []): string | undefined {
// without threading it through every cell/list helper (mirrors docLangTag in docx.ts).
let exportSheet: StyleSheet = builtinStyleSheet();
function applyRuns(p: ParagraphBuilder | CellBuilder, content: TiptapNode[] = [], forceBold = false) {
function applyRuns(p: ParagraphBuilder | CellBuilder, content: TiptapNode[] = [], force: TextProps = {}) {
const forced = Object.keys(force).length ? textFormatting(force) : null;
for (const node of content) {
if (node.type !== 'text' || !node.text) continue;
const fmt = formattingFromMarks(node.marks);
// Bake header bold, but respect an explicit un-bold (fontWeight:normal) override.
if (forceBold && fmt.fontWeight !== 'normal') fmt.bold = true;
// A cell's header/region formatting is presentational (CSS) in the editor, so bake it
// under the run's own marks; an explicit un-bold (fontWeight:normal) still wins.
if (forced) {
const direct = { ...fmt };
Object.assign(fmt, forced, direct);
if (!direct.bold && fmt.fontWeight === 'normal') delete fmt.bold;
}
// A named character style: bake its resolved formatting (so odf-kit always mints a
// span) and mark the run, so applyCharacterStyles can re-point that span at the style.
const charStyle = charStyleOf(node.marks);
@@ -1939,7 +1978,11 @@ function charStyleOf(marks: TiptapNode['marks']): string | null {
// A character style's resolved props as odf-kit run formatting (baked so the file still
// looks right for readers that ignore the style reference).
function charFormatting(sheet: StyleSheet, name: string): Record<string, unknown> {
const t = resolveStyle(sheet, name, 'character').text;
return textFormatting(resolveStyle(sheet, name, 'character').text);
}
// TextProps as odf-kit run formatting.
function textFormatting(t: TextProps): Record<string, unknown> {
const fmt: Record<string, unknown> = {};
if (t.bold != null) fmt.bold = t.bold;
if (t.italic != null) fmt.italic = t.italic;
@@ -2027,14 +2070,14 @@ function applyHfRuns(b: HeaderFooterBuilder, para: TiptapNode, pageCount: number
// A segment is one paragraph, heading, or list item's paragraph; exactly one SEG
// between consecutive segments, so splitting yields one piece per segment in DFS order.
function buildCellContent(cell: TiptapNode, c: CellBuilder, forceBold = false): CellBlock[] {
function buildCellContent(cell: TiptapNode, c: CellBuilder, force: TextProps = {}): CellBlock[] {
const blocks: CellBlock[] = [];
const state = { emitted: false }; // whether any segment has been emitted yet
const emitSegment = (content: TiptapNode[] | undefined) => {
if (state.emitted) c.addText(SEG);
state.emitted = true;
applyRuns(c, content ?? [], forceBold);
applyRuns(c, content ?? [], force);
};
const walkList = (listNode: TiptapNode): CellListBlock => {
@@ -2118,11 +2161,16 @@ 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)[]): void {
function exportTable(node: TiptapNode, doc: OdtDocument, contentWidthCm: number, cellBlocks: CellBlock[][], tableMargins: (TableMargins | null)[], tableStyleNames: (string | null)[]): void {
const rows = (node.content ?? []).filter(r => r.type === 'tableRow');
if (rows.length === 0) return;
const margins = tableMarginsCm(node, contentWidthCm);
tableMargins.push(margins);
// The named table style, if the registry still knows it: its name goes on the table's
// 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 columnWidths = tableColumnWidthsCm(node, contentWidthCm - (margins ? margins.ml + margins.mr : 0));
doc.addTable((t: TableBuilder) => {
for (const row of rows) {
@@ -2152,11 +2200,12 @@ function exportTable(node: TiptapNode, doc: OdtDocument, contentWidthCm: number,
if (b === 'none') opts[side] = 'none';
else if (b) opts[side] = `${b.widthPt}pt solid ${normalizeColor(b.color) ?? b.color}`;
}
// Header-row cells render bold via CSS (presentational), so bake bold into the
// runs on export to keep Word/LibreOffice consistent (incl. freshly-typed text).
const headerBold = bg === HEADER_SHADE;
// Header cells and a table style's regions render bold/font via CSS
// (presentational), so bake that onto the runs for Word/LibreOffice.
const force = regionText(tableStyle, cell.attrs?.region);
if (bg === HEADER_SHADE) force.bold = true;
r.addCell((c: CellBuilder) => {
cellBlocks.push(buildCellContent(cell, c, headerBold));
cellBlocks.push(buildCellContent(cell, c, force));
}, opts);
}
});
@@ -2665,6 +2714,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)[] = [];
const odt = await tiptapToOdt(json, {
// Orientation sets style:print-orientation; rewriteStylesXml overrides the exact
@@ -2684,7 +2735,7 @@ export async function buildOdt(docJson: TiptapNode, margins: PageMargins = DEFAU
return;
}
if (node.type === CUST_TABLE) {
exportTable(node, doc, contentWidthCm, cellBlocks, tableMargins);
exportTable(node, doc, contentWidthCm, cellBlocks, tableMargins, tableStyleNames);
return;
}
const opts: {
@@ -2776,7 +2827,8 @@ export async function buildOdt(docJson: TiptapNode, margins: PageMargins = DEFAU
const rowHeights: (string | null)[] = [];
collectTableRowHeights(raw, rowHeights);
const styledRows = applyTableRowHeights(styledCells, rowHeights);
const withTableMargins = applyTableMargins(styledRows, tableMargins, contentWidthCm);
const withTableMargins = applyTableStyleNames(
applyTableMargins(styledRows, tableMargins, contentWidthCm), tableStyleNames);
const cleaned = collapseRunWhitespace(withTableMargins);
const withBreaks = applyInlineSentinels(cleaned);
@@ -2789,7 +2841,8 @@ export async function buildOdt(docJson: TiptapNode, margins: PageMargins = DEFAU
const withEmptyFontSizes = applyEmptyLineFontSizes(withPageBreaks);
const withParaBoxes = applyParagraphBoxes(withEmptyFontSizes);
const withNamedStyles = applyCharacterStyles(applyParagraphStyles(withParaBoxes));
const withStyles = rewriteStylesXml(withNamedStyles, language ?? null, pageFormat, orientation, styles, usedStyleNames(docJson, styles));
const usedTables = new Set(tableStyleNames.filter((n): n is string => !!n));
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);
}
+39
View File
@@ -95,6 +95,25 @@ const de: Messages = {
rename: 'Umbenennen…',
reset: 'Auf Standard zurücksetzen',
newName: 'Vorlage',
// Short forms for the manager's tab strip; the long names above still label
// the gallery sections.
tabs: { paragraph: 'Absatz', character: 'Zeichen', table: 'Tabelle' },
tableStyles: 'Tabellenvorlagen',
region: 'Bereich',
fill: 'Füllung',
outerBorder: 'Außenrahmen',
rowLines: 'Zeilenlinien',
columnLines: 'Spaltenlinien',
noBorder: 'Keiner',
regions: {
wholeTable: 'Ganze Tabelle',
headerRow: 'Kopfzeile',
lastRow: 'Letzte Zeile',
firstColumn: 'Erste Spalte',
lastColumn: 'Letzte Spalte',
bandedRow: 'Streifenzeilen',
bandedColumn: 'Streifenspalten',
} as Record<string, string>,
},
history: {
undo: 'Rückgängig',
@@ -255,6 +274,26 @@ const de: Messages = {
columns: 'Spalten',
rowsField: 'Zeilen',
split: 'Teilen',
// No trailing ellipsis here (unlike the other dialog-opening entries): the
// row truncates, so CSS adds the dots only when the label doesn't fit.
manageStyles: 'Tabellenvorlagen verwalten',
tableStyle: 'Tabellenvorlage',
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',
Academic: 'Akademisch',
Financial: 'Finanzen',
} as Record<string, string>,
},
borders: {
title: 'Rahmen',
+39
View File
@@ -99,6 +99,25 @@ const en = {
rename: 'Rename…',
reset: 'Reset to default',
newName: 'Style',
// Short forms for the manager's tab strip; the long names above still label
// the gallery sections.
tabs: { paragraph: 'Paragraph', character: 'Character', table: 'Table' },
tableStyles: 'Table styles',
region: 'Area',
fill: 'Fill',
outerBorder: 'Outer border',
rowLines: 'Row lines',
columnLines: 'Column lines',
noBorder: 'None',
regions: {
wholeTable: 'Whole table',
headerRow: 'Header row',
lastRow: 'Last row',
firstColumn: 'First column',
lastColumn: 'Last column',
bandedRow: 'Banded rows',
bandedColumn: 'Banded columns',
} as Record<string, string>,
},
history: {
undo: 'Undo',
@@ -259,6 +278,26 @@ const en = {
columns: 'Columns',
rowsField: 'Rows',
split: 'Split',
// No trailing ellipsis here (unlike the other dialog-opening entries): the
// row truncates, so CSS adds the dots only when the label doesn't fit.
manageStyles: 'Manage table styles',
tableStyle: 'Table style',
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',
Academic: 'Academic',
Financial: 'Financial',
} as Record<string, string>,
},
borders: {
title: 'Borders',
+7 -2
View File
@@ -1300,8 +1300,13 @@ function convertTable(tbl: Element, ctx: Ctx): Node | null {
rows.push(row);
}
if (rows.length === 0) return null;
const margins = tableMargins(tbl, useWeights, ctx);
return margins ? { type: 'table', attrs: margins, content: rows } : { type: 'table', content: rows };
// Word's w:tblStyle: only the name comes back — the look rides on the cell attrs, and
// the editor re-derives the regions from its own registry (refreshTableStyles).
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;
return Object.keys(attrs).length ? { type: 'table', attrs, content: rows } : { type: 'table', content: rows };
}
// A table narrower than the text width: w:tblInd is its left indent, the grid (or
+9 -1
View File
@@ -100,6 +100,7 @@ export class DocxStyles {
private ownIndentTwip = new Map<string, number>(); // style's own w:pPr/w:ind left
private paraStyleNames = new Map<string, string>(); // paragraph styleId → w:name
private charStyleNames = new Map<string, string>(); // character styleId → w:name
private tableStyleNames = new Map<string, string>(); // table styleId → w:name
private defaultParaStyle: string | null = null; // the w:default="1" paragraph style
private defaultsAlign: string | null = null; // docDefaults w:pPrDefault/w:jc
private defaultsSpacing: ParaSpacing = {}; // docDefaults w:pPrDefault/w:spacing
@@ -165,10 +166,11 @@ export class DocxStyles {
if (Number.isFinite(left)) this.ownIndentTwip.set(id, left);
}
const kind = style.getAttributeNS(W, 'type');
if (kind === 'paragraph' || kind === 'character') {
if (kind === 'paragraph' || kind === 'character' || kind === 'table') {
const nameEl = firstChild(style, 'name');
const name = (nameEl && wVal(nameEl)) || id;
if (kind === 'paragraph') this.paraStyleNames.set(id, name);
else if (kind === 'table') this.tableStyleNames.set(id, name);
else this.charStyleNames.set(id, name);
}
}
@@ -186,6 +188,12 @@ export class DocxStyles {
return new Map(this.charStyleNames);
}
// A w:tblStyle id → the style's display name (the id itself when it declares none).
tableStyleName(id: string | null | undefined): string | null {
if (!id) return null;
return this.tableStyleNames.get(id) ?? id;
}
// The style's effective left indent (twips) along the basedOn chain.
styleIndentTwip(styleId: string | null | undefined, seen = new Set<string>()): number | null {
if (!styleId || seen.has(styleId)) return null;
+7 -2
View File
@@ -1505,8 +1505,13 @@ function convertTable(el: Element, ctx: Ctx): Node | null {
}
if (rows.length === 0) return null;
const margins = tableMargins(el, ctx);
return margins ? { type: 'table', attrs: margins, content: rows } : { type: 'table', content: rows };
// The named table style behind the automatic one. ODF stores no banding, so only the
// name comes back — the look rides on the cell attrs above, and the editor re-derives
// 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);
return Object.keys(attrs).length ? { type: 'table', attrs, content: rows } : { type: 'table', content: rows };
}
// A table narrower than the text width → the editor's marginLeft/marginRight attrs.
+5 -3
View File
@@ -139,6 +139,7 @@ export class StyleResolver {
private stylesDoc: Document | null;
private namedParagraphNames = new Set<string>();
private namedTextNames = new Set<string>();
private namedTableNames = new Set<string>();
private displayNames = new Map<string, string>();
constructor(contentDoc: Document, stylesDoc: Document | null) {
@@ -172,8 +173,8 @@ export class StyleResolver {
// The nearest named style in a style's parent chain (an automatic style is direct
// formatting layered on top of it); null when the chain reaches none.
namedAncestor(styleName: string | null | undefined, family: 'paragraph' | 'text' = 'paragraph'): string | null {
const named = family === 'text' ? this.namedTextNames : this.namedParagraphNames;
namedAncestor(styleName: string | null | undefined, family: 'paragraph' | 'text' | 'table' = 'paragraph'): string | null {
const named = family === 'text' ? this.namedTextNames : family === 'table' ? this.namedTableNames : this.namedParagraphNames;
let cur = styleName ?? null;
const seen = new Set<string>();
while (cur && !seen.has(cur)) {
@@ -225,8 +226,9 @@ export class StyleResolver {
const name = el.getAttributeNS(NS.style, 'name');
const family = el.getAttributeNS(NS.style, 'family');
if (name && family) this.styles.set(`${family}\0${name}`, entryFromStyleElement(el));
if (name && named && (family === 'paragraph' || family === 'text')) {
if (name && named && (family === 'paragraph' || family === 'text' || family === 'table')) {
if (family === 'paragraph') this.namedParagraphNames.add(name);
else if (family === 'table') this.namedTableNames.add(name);
else this.namedTextNames.add(name);
const display = el.getAttributeNS(NS.style, 'display-name');
if (display) this.displayNames.set(name, display);
+29 -1
View File
@@ -3,6 +3,7 @@
// replaced. Persisted to localStorage like the other document side-cars.
import { builtinStyleSheet, DEFAULT_STYLE, mergeStoredSheet, STYLE_SHEET_VERSION, type Style, type StyleFamily, type StyleSheet } from './styleSheet';
import type { TableStyle } from './tableStyles';
const STORAGE_KEY = 'odf-editor-styles';
@@ -29,13 +30,35 @@ export function setStyleSheet(next: StyleSheet): void {
// Replace one style (add or edit) — everything using it re-renders via styleCss.
export function putStyle(style: Style, family: StyleFamily = 'paragraph'): void {
const key = family === 'character' ? 'character' : 'paragraph';
const key = family === 'table' ? 'paragraph' : family;
setStyleSheet({ ...current, [key]: { ...current[key], [style.name]: style } });
}
// Table styles have their own shape and no inheritance, so they get their own pair.
export function putTableStyle(style: TableStyle): void {
setStyleSheet({ ...current, table: { ...current.table, [style.name]: style } });
}
export function deleteTableStyle(name: string): void {
if (current.table[name]?.builtin) return;
const table = { ...current.table };
delete table[name];
setStyleSheet({ ...current, table });
}
export function renameTableStyle(from: string, to: string): void {
const style = current.table[from];
if (!style || from === to || current.table[to]) return;
const table = { ...current.table };
delete table[from];
table[to] = { ...style, name: to, builtin: undefined };
setStyleSheet({ ...current, table });
}
// Rename a style and re-point everything that referenced it (children, next-styles).
// Blocks keep their own `styleName`; the caller retags them.
export function renameStyle(from: string, to: string, family: StyleFamily = 'paragraph'): void {
if (family === 'table') return renameTableStyle(from, to);
if (family === 'character') return renameCharacterStyle(from, to);
const style = current.paragraph[from];
if (!style || from === to || current.paragraph[to]) return;
@@ -67,6 +90,11 @@ export function deleteStyle(name: string): void {
// Restore a built-in to its factory definition.
export function resetStyle(name: string, family: StyleFamily = 'paragraph'): void {
const base = builtinStyleSheet();
if (family === 'table') {
const factory = base.table[name];
if (factory) putTableStyle(factory);
return;
}
const factory = (family === 'character' ? base.character : base.paragraph)[name];
if (factory) putStyle(factory, family);
}
+31 -9
View File
@@ -2,6 +2,8 @@
// style and two property groups. Resolution walks the parent chain (nearer wins); direct
// formatting on the block or run still overrides the result.
import { builtinTableStyles, tableStyleCss, type TableStyle } from './tableStyles';
export type ParaProps = {
textAlign?: 'left' | 'center' | 'right' | 'justify';
lineHeight?: string;
@@ -38,12 +40,14 @@ export type Style = {
text: TextProps;
};
// Two families, as in LibreOffice: paragraph styles govern whole blocks, character
// styles a run of text inside one. Same Style shape; a character style only uses `text`.
export type StyleFamily = 'paragraph' | 'character';
// Three families, as in LibreOffice/Word: paragraph styles govern whole blocks, character
// styles a run of text inside one (same Style shape; a character style only uses `text`),
// table styles a whole table (their own shape, no inheritance — see tableStyles.ts).
export type StyleFamily = 'paragraph' | 'character' | 'table';
export type StyleSheet = {
paragraph: Record<string, Style>;
character: Record<string, Style>;
table: Record<string, TableStyle>;
};
export const DEFAULT_STYLE = 'Standard';
@@ -79,13 +83,15 @@ 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 = 2;
export const STYLE_SHEET_VERSION = 4;
// 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.
export function mergeStoredSheet(stored: unknown): StyleSheet {
const sheet = builtinStyleSheet();
const data = stored as { v?: number; paragraph?: Record<string, Style>; character?: Record<string, Style> } | null;
const data = stored as
| { v?: number; paragraph?: Record<string, Style>; character?: Record<string, Style>; table?: Record<string, TableStyle> }
| null;
if (!data?.paragraph || typeof data.paragraph !== 'object') return sheet;
const current = data.v === STYLE_SHEET_VERSION;
for (const family of ['paragraph', 'character'] as const) {
@@ -95,6 +101,12 @@ export function mergeStoredSheet(stored: unknown): StyleSheet {
sheet[family][name] = style;
}
}
// Table styles have their own shape, so they merge separately.
for (const [name, style] of Object.entries(data.table ?? {})) {
if (!style || typeof style !== 'object') continue;
if (!current && style.builtin) continue;
sheet.table[name] = style;
}
return sheet;
}
@@ -103,7 +115,7 @@ export function builtinStyleSheet(): StyleSheet {
for (const s of BUILTINS) paragraph[s.name] = structuredClone(s);
const character: Record<string, Style> = {};
for (const s of CHAR_BUILTINS) character[s.name] = structuredClone(s);
return { paragraph, character };
return { paragraph, character, table: builtinTableStyles() };
}
// Inheritance order: every style directly followed by its own children, so the manager's
@@ -111,6 +123,7 @@ export function builtinStyleSheet(): StyleSheet {
// `Heading` is an abstract parent (LibreOffice's, holding what all levels share) — never
// assignable, so the gallery hides it (its children stay); the manager passes withAbstract.
export function styleOrder(sheet: StyleSheet, withAbstract = false, family: StyleFamily = 'paragraph'): Style[] {
if (family === 'table') return []; // table styles have no inheritance — listed flat
const styles = family === 'character' ? sheet.character : sheet.paragraph;
const rank = new Map((family === 'character' ? CHAR_BUILTINS : BUILTINS).map((b, i) => [b.name, i]));
const order = (a: string, b: string) => (rank.get(a) ?? 1e9) - (rank.get(b) ?? 1e9) || a.localeCompare(b);
@@ -185,9 +198,9 @@ function cssFontFamily(name: string): string {
return `'${name.replace(/'/g, "\\'")}', var(--font-serif)`;
}
function declarations(r: ResolvedStyle): string[] {
// The text half of a rule, shared with the table-style family (tableStyles.ts).
export function textDeclarations(t: TextProps): string[] {
const out: string[] = [];
const { para: p, text: t } = r;
if (t.fontFamily) out.push(`font-family: ${cssFontFamily(t.fontFamily)}`);
if (t.fontSizePt != null) out.push(`font-size: ${t.fontSizePt}pt`);
if (t.bold != null) out.push(`font-weight: ${t.bold ? 700 : 400}`);
@@ -196,6 +209,12 @@ function declarations(r: ResolvedStyle): string[] {
out.push(`text-decoration: ${[t.underline && 'underline', t.strike && 'line-through'].filter(Boolean).join(' ')}`);
}
if (t.color) out.push(`color: ${t.color}`);
return out;
}
function declarations(r: ResolvedStyle): string[] {
const { para: p } = r;
const out = textDeclarations(r.text);
if (p.textAlign) out.push(`text-align: ${p.textAlign}`);
if (p.lineHeight) out.push(`line-height: ${p.lineHeight}`);
if (p.spaceBefore != null) out.push(`margin-top: ${p.spaceBefore}pt`);
@@ -229,6 +248,9 @@ export function styleCss(sheet: StyleSheet): string {
if (style.name === DEFAULT_STYLE) selectors.push('.paper .tiptap p:not([data-style])');
rules.push(`${selectors.join(',\n')} {\n ${decls.join(';\n ')};\n}`);
}
// Table styles last: their cell selectors must outrank the paragraph rules above.
const table = tableStyleCss(sheet.table ?? {});
if (table) rules.push(table);
return rules.join('\n\n');
}
@@ -292,7 +314,7 @@ export function styleDelta(shown: ResolvedStyle, base: ResolvedStyle): ResolvedS
// A name that isn't taken yet ("Style", "Style 2", …).
export function uniqueStyleName(sheet: StyleSheet, base: string, family: StyleFamily = 'paragraph'): string {
const styles = family === 'character' ? sheet.character : sheet.paragraph;
const styles: Record<string, unknown> = sheet[family] ?? sheet.paragraph;
if (!styles[base]) return base;
for (let i = 2; ; i++) if (!styles[`${base} ${i}`]) return `${base} ${i}`;
}
+240
View File
@@ -0,0 +1,240 @@
// Table styles, the third named-style family — Word's table styles / LibreOffice's table
// AutoFormats. A style paints conditional regions (header row, banded rows, first column,
// …); resolveTableCell is the single source of truth for applying, CSS, export and import.
import { textDeclarations, type TextProps } from './styleSheet';
// Ascending precedence, as in Word: a later region's properties win over an earlier one's.
// `wholeTable` is the base rather than a conditional region, so it is layered first and
// never listed in a cell's `region` attr.
export const TABLE_REGIONS = [
'bandedColumn', 'bandedRow', 'lastColumn', 'firstColumn', 'lastRow', 'headerRow',
] as const;
export type TableRegion = (typeof TABLE_REGIONS)[number];
export type BorderSideKey = 'top' | 'right' | 'bottom' | 'left';
export type TableRegionProps = {
// null = explicitly no fill; undefined = inherit from the lower-precedence region.
fill?: string | null;
text?: TextProps;
// Border overrides for the region's own sides, e.g. a rule under the header row.
borders?: Partial<Record<BorderSideKey, string | null>>;
};
// Border values follow the cell attrs (tableCellBorders.ts): null = the table default
// 0.5pt black, 'none' = no border, else the canonical '<W>pt solid #RRGGBB'.
export type TableStyle = {
name: string;
builtin?: boolean;
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)
innerBorderV?: string | null; // vertical inner lines only
wholeTable?: TableRegionProps;
regions: Partial<Record<TableRegion, TableRegionProps>>;
};
// The families Word and LibreOffice ship: plain grids, shaded lists, the coloured box
// lists, Word's accent tables, and the rule-only academic/financial pair. Colours follow
// the Office theme accents; a yellow header keeps black text to stay readable.
const HEADER_FILL = '#F2F2F2';
const BAND_FILL = '#F7F7F7';
const ACCENT = '#4472C4';
const ACCENT_LIGHT = '#D9E2F3';
const boxList = (name: string, header: string, band: string, text = '#FFFFFF'): TableStyle => ({
name, builtin: true, border: 'none', innerBorder: 'none',
regions: {
headerRow: { fill: header, text: { bold: true, color: text } },
bandedRow: { fill: band },
},
});
export const TABLE_BUILTINS: TableStyle[] = [
{ name: 'Simple Grid', builtin: true, border: null, innerBorder: null,
regions: { headerRow: { fill: HEADER_FILL, text: { bold: true } } } },
{ name: 'Simple Grid Rows', builtin: true, border: null, innerBorderH: null, innerBorderV: 'none',
regions: { headerRow: { fill: HEADER_FILL, text: { bold: true } } } },
{ name: 'Simple Grid Columns', builtin: true, border: null, innerBorderH: 'none', innerBorderV: null,
regions: { headerRow: { fill: HEADER_FILL, text: { bold: true } } } },
{ name: 'Simple List Shaded', builtin: true, border: null, innerBorder: 'none',
regions: {
headerRow: { fill: HEADER_FILL, text: { bold: true } },
bandedRow: { fill: BAND_FILL },
} },
{ name: 'Simple List Columns', builtin: true, border: null, innerBorder: 'none',
regions: {
headerRow: { fill: HEADER_FILL, text: { bold: true } },
bandedColumn: { fill: BAND_FILL },
} },
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'),
{ 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 },
} },
{ 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 },
} },
{ name: 'Academic', builtin: true, border: 'none', innerBorder: 'none',
regions: {
headerRow: { text: { bold: true }, borders: { top: '1pt solid #000000', bottom: '0.75pt solid #000000' } },
lastRow: { borders: { bottom: '1pt solid #000000' } },
} },
{ name: 'Financial', builtin: true, border: 'none', innerBorder: 'none',
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' } },
} },
];
export function builtinTableStyles(): Record<string, TableStyle> {
const out: Record<string, TableStyle> = {};
for (const s of TABLE_BUILTINS) out[s.name] = structuredClone(s);
return out;
}
export type CellCoords = {
row: number; col: number;
rowSpan?: number; colSpan?: number;
rows: number; cols: number;
};
export type ResolvedTableCell = {
regions: TableRegion[];
fill: string | null;
text: TextProps;
borders: Record<'borderTop' | 'borderRight' | 'borderBottom' | 'borderLeft', string | null>;
};
// 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);
const matches: Record<TableRegion, boolean> = {
bandedColumn: bodyCol >= 0 && bodyCol % 2 === 1,
bandedRow: bodyRow >= 0 && bodyRow % 2 === 1,
lastColumn: col === cols - 1,
firstColumn: col === 0,
lastRow: row === rows - 1,
headerRow: row === 0,
};
return TABLE_REGIONS.filter(name => r[name] && matches[name]);
}
// The border of one grid line, decided from both sides so the two facing cells always
// agree (collapsed borders must not disagree — see setTableBorders).
function boundary(
style: TableStyle,
before: TableRegion[] | null,
after: TableRegion[] | null,
beforeSide: BorderSideKey,
afterSide: BorderSideKey,
): string | null {
const horizontal = beforeSide === 'bottom';
let value = before === null || after === null
? style.border
: (horizontal ? style.innerBorderH : style.innerBorderV) ?? style.innerBorder;
if (value === undefined) value = null;
const layer = (regions: TableRegion[] | null, side: BorderSideKey) => {
if (!regions) return;
for (const name of regions) {
const v = style.regions[name]?.borders?.[side];
if (v !== undefined) value = v;
}
};
layer(before, beforeSide);
layer(after, afterSide);
return value;
}
// 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 {
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 regions = at(row, col);
let fill: string | null = style.wholeTable?.fill ?? null;
const text: TextProps = { ...style.wholeTable?.text };
for (const name of regions) {
const props = style.regions[name];
if (!props) continue;
if (props.fill !== undefined) fill = props.fill;
for (const [key, v] of Object.entries(props.text ?? {})) {
if (v !== undefined) (text as Record<string, unknown>)[key] = v;
}
}
return {
regions,
fill,
text,
borders: {
borderTop: boundary(style, row > 0 ? at(row - 1, col) : null, regions, 'bottom', 'top'),
borderBottom: boundary(style, at(rowEnd - 1, col), rowEnd < rows ? at(rowEnd, col) : null, 'bottom', 'top'),
borderLeft: boundary(style, col > 0 ? at(row, col - 1) : null, regions, 'right', 'left'),
borderRight: boundary(style, at(row, colEnd - 1), colEnd < cols ? at(row, colEnd) : null, 'right', 'left'),
},
};
}
// The text formatting a cell inherits from its table style, read off the `region` attr
// the paint left on it. Shared by the editor (Bold button) and both exporters.
export function regionText(style: TableStyle | null | undefined, regionAttr: unknown): TextProps {
if (!style) return {};
const text: TextProps = { ...style.wholeTable?.text };
for (const name of String(regionAttr ?? '').split(' ').filter(Boolean)) {
Object.assign(text, style.regions[name as TableRegion]?.text ?? {});
}
return text;
}
// 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 });
const side = (value: string | null): string => {
if (value === 'none') return 'none';
if (value === null) return '1px solid currentColor';
const m = /^([\d.]+)pt solid (#[0-9A-Fa-f]{6})$/.exec(value);
if (!m) return 'none';
return `${parseFloat(m[1]) > 0.75 ? 2 : 1}px solid ${m[2]}`;
};
const borders = (['Top', 'Right', 'Bottom', 'Left'] as const)
.map(s => `border-${s.toLowerCase()}: ${side(paint.borders[`border${s}`])}`)
.join(';');
return `background: ${paint.fill ?? 'transparent'};${borders};font-weight: ${paint.text.bold ? 700 : 400}`;
}
// 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.
export function tableStyleCss(styles: Record<string, TableStyle>): string {
const rules: string[] = [];
for (const style of Object.values(styles ?? {})) {
const table = `.paper .tiptap table[data-table-style="${style.name.replace(/"/g, '\\"')}"]`;
const emit = (cellSel: string, text: TextProps | undefined) => {
const decls = textDeclarations(text ?? {});
if (!decls.length) return;
const selectors = [`${table} ${cellSel}`, `${table} ${cellSel} :is(p,h1,h2,h3,h4,h5,li)`];
rules.push(`${selectors.join(',\n')} {\n ${decls.join(';\n ')};\n}`);
};
emit(':is(td,th)', style.wholeTable?.text);
for (const name of TABLE_REGIONS) emit(`:is(td,th)[data-region~="${name}"]`, style.regions[name]?.text);
}
return rules.join('\n\n');
}
+32
View File
@@ -119,6 +119,38 @@ describe('DOCX export → import round trip', () => {
expect(cols[1].attrs.count).toBe(3);
});
it('round-trips a named table style (w:tblStyle + a name-only definition)', async () => {
const cell = (t: string, bg?: string, region?: string): N => ({
type: 'tableCell',
attrs: { colspan: 1, rowspan: 1, colwidth: null, ...(bg ? { backgroundColor: bg } : {}), ...(region ? { region } : {}) },
content: [para(t)],
});
const doc = {
type: 'doc',
content: [{
type: 'table',
attrs: { tableStyle: 'Box List Blue' },
content: [
{ type: 'tableRow', content: [cell('Kopf', '#4A7EBB', 'headerRow')] },
{ type: 'tableRow', content: [cell('Zeile')] },
],
}],
} as any;
const bytes = await buildDocx(doc);
const files = unzipSync(bytes);
const xml = strFromU8(files['word/document.xml']);
const stylesXml = strFromU8(files['word/styles.xml']);
expect(xml).toContain('<w:tblStyle w:val="BoxListBlue"');
expect(stylesXml).toContain('w:type="table"');
// The header region's white bold is presentational in the editor, baked here.
expect(xml).toContain('<w:color w:val="FFFFFF"');
const res = importDocx(bytes).content as N;
const table = walk(res, 'table')[0];
expect(table.attrs.tableStyle).toBe('Box List Blue');
expect(table.content![0].content![0].attrs.backgroundColor).toBe('#4A7EBB');
});
it('re-merges a page-boundary line-split paragraph (joinPrev) on export', async () => {
const split = {
type: 'doc',
+46
View File
@@ -372,6 +372,52 @@ describe('Leg 1a3: continued ordered-list start value', () => {
});
});
describe('Leg 1a4: named table style', () => {
// The style itself lives in the app registry (ODF has no banding), so only its name
// travels — the look rides on the cell attrs the style painted.
const styled: N = {
type: 'doc',
content: [{
type: 'table',
attrs: { tableStyle: 'Simple List Shaded' },
content: [
ROW(CELLM(1, 1, null, 'Name', '#F2F2F2'), CELLM(1, 1, null, 'Menge', '#F2F2F2')),
ROW(CELL(null, P(null, T('Apfel'))), CELL(null, P(null, T('3')))),
ROW(CELLM(1, 1, null, 'Birne', '#F7F7F7'), CELLM(1, 1, null, '5', '#F7F7F7')),
],
}],
};
it('round-trips the style name and the painted cells', async () => {
const bytes = await buildOdt(styled, margins, 'portrait', undefined, null, 'A4', builtinStyleSheet());
const files = unzipSync(bytes);
const stylesXml = strFromU8(files['styles.xml']);
const contentXml = strFromU8(files['content.xml']);
check('styles.xml defines the table style', stylesXml.includes('style:family="table"')
&& stylesXml.includes('style:name="Simple_20_List_20_Shaded"'),
stylesXml.match(/<style:style[^>]*family="table"[^>]*>/g));
check('the table points at it', /style:name="Table1"[^>]*style:parent-style-name="Simple_20_List_20_Shaded"/.test(contentXml),
contentXml.match(/<style:style[^>]*style:name="Table1"[^>]*>/g));
const res = importOdt(bytes);
const table = res.content.content!.find((n: N) => n.type === 'table') as N;
check('the name comes back on the table', table?.attrs?.tableStyle === 'Simple List Shaded', table?.attrs);
const fills = table.content.map((r: N) => r.content[0].attrs.backgroundColor ?? null);
check('the painted fills survive', JSON.stringify(fills) === JSON.stringify(['#F2F2F2', null, '#F7F7F7']), fills);
});
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' },
content: [ROW(CELLM(1, 1, null, 'Kopf', '#4A7EBB'))] }] };
blue.content[0].content[0].content[0].attrs.region = 'headerRow';
const bytes = await buildOdt(blue, margins, 'portrait', undefined, null, 'A4', builtinStyleSheet());
const contentXml = strFromU8(unzipSync(bytes)['content.xml']);
check('a bold white run style is minted', /fo:font-weight="bold"/.test(contentXml) && /fo:color="#FFFFFF"/i.test(contentXml),
contentXml.match(/<style:text-properties[^>]*>/g));
});
});
describe('Leg 1b: merged table cells (colspan/rowspan)', () => {
// 3×3 grid: A spans 2 cols (row 0); C spans 2 rows (col 0, rows 1–2).
// row0: [A A][B] row1: [C][D][E] row2: [C][F][G]
+201
View File
@@ -0,0 +1,201 @@
// Table styles: region resolution (precedence, banding, shared grid lines) and the
// command that materializes them into cell attrs, incl. re-banding after a row insert.
import { describe, it, expect } from 'vitest';
import { Editor } from '@tiptap/core';
import Document from '@tiptap/extension-document';
import Paragraph from '@tiptap/extension-paragraph';
import Text from '@tiptap/extension-text';
import Bold from '@tiptap/extension-bold';
import { Table, TableHeader, TableCell } from '@tiptap/extension-table';
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';
type N = any;
const RULE = '1pt solid #000000';
const banded: TableStyleDef = {
name: 'Test Bands',
border: null,
innerBorder: 'none',
regions: {
headerRow: { fill: '#EEEEEE', text: { bold: true }, borders: { bottom: RULE } },
bandedRow: { fill: '#FAFAFA' },
firstColumn: { text: { italic: true } },
},
};
const styles = { [banded.name]: banded };
const at = (style: TableStyleDef, row: number, col: number, rows = 4, cols = 2) =>
resolveTableCell(style, { row, col, rows, cols });
describe('resolveTableCell', () => {
it('layers overlapping regions in Word precedence order', () => {
const corner = at(banded, 0, 0);
expect(corner.regions).toEqual(['firstColumn', 'headerRow']);
// Both contribute: the header's bold and the first column's italic.
expect(corner.text).toEqual({ italic: true, bold: true });
expect(corner.fill).toBe('#EEEEEE');
});
it('counts banding over body rows, so a header row does not shift the stripes', () => {
expect(at(banded, 1, 1).fill).toBe(null); // first body row
expect(at(banded, 2, 1).fill).toBe('#FAFAFA');
expect(at(banded, 3, 1).fill).toBe(null);
// Without a header region the stripes start one row higher.
const noHeader: TableStyleDef = { ...banded, regions: { bandedRow: { fill: '#FAFAFA' } } };
expect(at(noHeader, 0, 0).fill).toBe(null);
expect(at(noHeader, 1, 0).fill).toBe('#FAFAFA');
});
it('gives both cells of a grid line the same border', () => {
// The rule under the header row, seen from above and from below.
expect(at(banded, 0, 0).borders.borderBottom).toBe(RULE);
expect(at(banded, 1, 0).borders.borderTop).toBe(RULE);
// Outer edges take `border`, inner lines `innerBorder`.
expect(at(banded, 0, 0).borders.borderTop).toBe(null);
expect(at(banded, 0, 0).borders.borderRight).toBe('none');
expect(at(banded, 0, 1).borders.borderLeft).toBe('none');
expect(at(banded, 0, 1).borders.borderRight).toBe(null);
});
});
const cell = (text: string): N => ({
type: 'tableCell',
attrs: { colspan: 1, rowspan: 1, colwidth: null },
content: [{ type: 'paragraph', content: [{ type: 'text', text }] }],
});
const row = (...cells: N[]): N => ({ type: 'tableRow', content: cells });
function makeEditor(rows = 3) {
const el = document.createElement('div');
document.body.appendChild(el);
const content = Array.from({ length: rows }, (_, r) => row(cell(`a${r}`), cell(`b${r}`)));
return new Editor({
element: el,
extensions: [
Document, Paragraph, Text, Bold,
Table.configure({ resizable: false }), ResizableTableRow, TableHeader, TableCell,
TableCellBackground, TableCellBorders,
TableStyle.configure({ styles: () => styles }),
],
content: { type: 'doc', content: [{ type: 'table', content }] },
});
}
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('setTableStyle', () => {
it('materializes fill, borders and regions, and is idempotent', () => {
const editor = makeEditor();
editor.commands.focus('start');
editor.commands.setTableStyle('Test Bands');
const t = table(editor);
expect(t.attrs.tableStyle).toBe('Test Bands');
expect(t.content[0].content[0].attrs.backgroundColor).toBe('#EEEEEE');
expect(t.content[0].content[0].attrs.region).toBe('firstColumn headerRow');
expect(t.content[0].content[1].attrs.region).toBe('headerRow');
expect(t.content[0].content[0].attrs.borderBottom).toBe(RULE);
expect(t.content[1].content[0].attrs.borderTop).toBe(RULE);
expect(fills(editor)).toEqual(['#EEEEEE', null, '#FAFAFA']);
// Applying again changes nothing — the re-band plugin depends on this.
const before = JSON.stringify(editor.getJSON());
editor.commands.setTableStyle('Test Bands');
expect(JSON.stringify(editor.getJSON())).toBe(before);
editor.destroy();
});
it('re-bands when a row is inserted', () => {
const editor = makeEditor();
editor.commands.focus('start');
editor.commands.setTableStyle('Test Bands');
expect(fills(editor)).toEqual(['#EEEEEE', null, '#FAFAFA']);
// Cursor is in the header row; a row added after it shifts every stripe below.
editor.commands.addRowAfter();
expect(fills(editor)).toEqual(['#EEEEEE', null, '#FAFAFA', null]);
editor.destroy();
});
it('clears the style-owned attrs again', () => {
const editor = makeEditor();
editor.commands.focus('start');
editor.commands.setTableStyle('Test Bands');
editor.commands.setTableStyle(null);
const t = table(editor);
expect(t.attrs.tableStyle).toBe(null);
for (const r of t.content) {
for (const c of r.content) {
expect(c.attrs.backgroundColor).toBe(null);
expect(c.attrs.region).toBe(null);
expect(c.attrs.borderTop).toBe(null);
}
}
editor.destroy();
});
it('re-derives the regions of an imported table from the name alone', () => {
// An imported file carries the style name and the baked fill, but no region attrs
// (ODF/DOCX have no such concept) — refreshTableStyles restores them on load.
const el = document.createElement('div');
document.body.appendChild(el);
const editor = new Editor({
element: el,
extensions: [
Document, Paragraph, Text, Bold,
Table.configure({ resizable: false }), ResizableTableRow, TableHeader, TableCell,
TableCellBackground, TableCellBorders,
TableStyle.configure({ styles: () => styles }),
],
content: {
type: 'doc',
content: [{
type: 'table',
attrs: { tableStyle: 'Test Bands' },
content: [row(cell('H'), cell('H2')), row(cell('a'), cell('b'))],
}],
},
});
expect(table(editor).content[0].content[0].attrs.region).toBe(null);
editor.commands.refreshTableStyles();
expect(table(editor).content[0].content[0].attrs.region).toBe('firstColumn headerRow');
expect(table(editor).content[0].content[0].attrs.backgroundColor).toBe('#EEEEEE');
editor.destroy();
});
it('places a merged cell by its top-left grid position', () => {
const editor = makeEditor();
editor.commands.focus('start');
// Merge the two cells of the second row, then style: the merged cell is row 1.
const cells: number[] = [];
editor.state.doc.descendants((n, pos) => { if (n.type.name === 'tableCell') cells.push(pos); });
editor.commands.setCellSelection({ anchorCell: cells[2], headCell: cells[3] });
editor.commands.mergeCells();
editor.commands.setTableStyle('Test Bands');
const t = table(editor);
expect(t.content[1].content.length).toBe(1);
expect(t.content[1].content[0].attrs.colspan).toBe(2);
expect(t.content[1].content[0].attrs.region).toBe('firstColumn');
// Its bottom is the boundary to the banded row below, its right the table edge.
expect(t.content[1].content[0].attrs.borderRight).toBe(null);
editor.destroy();
});
it('ignores an unknown style name', () => {
const editor = makeEditor();
editor.commands.focus('start');
expect(editor.commands.setTableStyle('Nope')).toBe(false);
expect(table(editor).attrs.tableStyle).toBe(null);
editor.destroy();
});
});