Sync snapshot (2026-08-26) (#159)

- Sheets: CSV export and save support, Excel-matching data validation
- Docs: image, shape, WordArt, and chart rendering fixes
- Slides: downloadable font catalog with a missing-font banner
- Slides: better AI text layout and a speaker-notes tool

Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
merrick-2002
2026-08-26 17:34:55 +08:00
committed by GitHub
co-authored by GenOffice
parent 9711a4507c
commit 0a2c25d483
201 changed files with 16950 additions and 1271 deletions
+3 -1
View File
@@ -1,6 +1,6 @@
# GenOffice Privacy # GenOffice Privacy
Last updated: August 24, 2026 Last updated: August 26, 2026
GenOffice opens, edits, and saves documents locally. Document editing does not GenOffice opens, edits, and saves documents locally. Document editing does not
upload files to GenOffice. AI features require a network connection and send upload files to GenOffice. AI features require a network connection and send
@@ -20,6 +20,8 @@ subsequent analytics events.
When enabled, the app sends these events: When enabled, the app sends these events:
- `install_first_launch` — marks the first analytics-enabled use of a newly
assigned anonymous `client_id`; used for retention cohorts
- `app_launch` — no event-specific parameter - `app_launch` — no event-specific parameter
- `file_open` — `ext`, the file extension such as `docx` or `xlsx` - `file_open` — `ext`, the file extension such as `docx` or `xlsx`
- `file_new` — `kind`, one of `docx`, `xlsx`, `pptx`, `md`, or `pdf` - `file_new` — `kind`, one of `docx`, `xlsx`, `pptx`, `md`, or `pdf`
+3 -1
View File
@@ -55,7 +55,9 @@ the same command pipeline as manual edits.
JSON-like, prototype-free data. Errors discard all buffered operations; JSON-like, prototype-free data. Errors discard all buffered operations;
logs are capped. logs are capped.
5. Execution has statement/expression and call-depth limits to bound runaway 5. Execution has statement/expression and call-depth limits to bound runaway
loops or recursion. loops or recursion. Regular expressions run on an interpreter-owned matcher
with its own step budget (a supported subset; no native backtracking), so a
catastrophic pattern cannot stall the renderer past those limits.
The Electron renderer sandbox remains defense in depth, but it is not the The Electron renderer sandbox remains defense in depth, but it is not the
layout-script security boundary. The interpreter is designed so a layout layout-script security boundary. The interpreter is designed so a layout
+1
View File
@@ -2662,6 +2662,7 @@ export function registerAiIpc(): void {
await streamForProvider(provider, config, system, messages, tools, maxTokens, { await streamForProvider(provider, config, system, messages, tools, maxTokens, {
signal: controller.signal, signal: controller.signal,
onDelta: (text) => send({ requestId, type: 'delta', text }), onDelta: (text) => send({ requestId, type: 'delta', text }),
onReasoningDelta: (text) => send({ requestId, type: 'reasoning', text }),
onToolCall: (toolCall) => send({ requestId, type: 'tool-call', toolCall }), onToolCall: (toolCall) => send({ requestId, type: 'tool-call', toolCall }),
onActivity: ping, onActivity: ping,
onStopReason: (reason) => { onStopReason: (reason) => {
+44 -4
View File
@@ -275,10 +275,48 @@ function posFromAnchor(view: Editor['view'], anchor: LineAnchor): number | undef
/** Clean pasted Word/web HTML: mso conditional comments, <o:p>, and unwrapping <li><p>x</p></li> */ /** Clean pasted Word/web HTML: mso conditional comments, <o:p>, and unwrapping <li><p>x</p></li> */
function cleanPastedHtml(html: string): string { function cleanPastedHtml(html: string): string {
return html return unwrapSingleCellTable(
.replace(/<!--\[if[\s\S]*?<!\[endif\]-->/g, '') html
.replace(/<o:p>[\s\S]*?<\/o:p>/g, '') .replace(/<!--\[if[\s\S]*?<!\[endif\]-->/g, '')
.replace(/<li([^>]*)>\s*<p[^>]*>([\s\S]*?)<\/p>\s*<\/li>/g, '<li$1>$2</li>') .replace(/<o:p>[\s\S]*?<\/o:p>/g, '')
.replace(/<li([^>]*)>\s*<p[^>]*>([\s\S]*?)<\/p>\s*<\/li>/g, '<li$1>$2</li>'),
)
}
/**
* Word parity: pasting a copy of a SINGLE spreadsheet cell inserts its
* content as text, not a 1x1 table (alpha ledger r146 — a lone cell copied
* from Sheets/Excel pasted into Docs as a table and flipped the ribbon into
* table tools). Only a payload whose entire content is one table with one
* cell unwraps; anything else — multi-cell tables, tables mixed with prose —
* stays intact.
*/
function unwrapSingleCellTable(html: string): string {
if (!/<table/i.test(html)) return html
try {
const doc = new window.DOMParser().parseFromString(html, 'text/html')
const body = doc.body
const tables = body.querySelectorAll('table')
if (tables.length !== 1) return html
const table = tables[0]!
// The table must be the only real content of the paste. Text equality
// covers prose ANYWHERE outside the table — including inside wrappers
// that also contain it — and Element.textContent excludes HTML comments,
// so Excel's StartFragment markers don't block the unwrap (bugbot).
if ((body.textContent ?? '').trim() !== (table.textContent ?? '').trim()) return html
// text-less content outside the table (images, separators) also keeps it
if (
[...body.querySelectorAll('img,svg,video,hr')].some((element) => !table.contains(element))
) {
return html
}
const cells = table.querySelectorAll('td,th')
if (cells.length !== 1) return html
if (cells[0]!.querySelector('table')) return html
return cells[0]!.innerHTML
} catch {
return html
}
} }
/** All runs a footnote/endnote reference may live in: paragraph runs, plus table /** All runs a footnote/endnote reference may live in: paragraph runs, plus table
@@ -1537,6 +1575,8 @@ export function App() {
// for real-device verification: trigger export directly via CDP (same as __pageDebug) // for real-device verification: trigger export directly via CDP (same as __pageDebug)
useEffect(() => { useEffect(() => {
;(window as unknown as Record<string, unknown>).__exportPdf = exportPdf ;(window as unknown as Record<string, unknown>).__exportPdf = exportPdf
;(window as unknown as Record<string, unknown>).__openPagePreview = () =>
setShowPagePreview(true)
}, [exportPdf]) }, [exportPdf])
useEffect(() => { useEffect(() => {
@@ -277,6 +277,22 @@ export function AiAskPopover({
} }
}} }}
> >
<button
type="button"
className="ai-ask-pop-close"
data-tip={t('appClose')}
aria-label={t('appClose')}
onClick={close}
>
<svg viewBox="0 0 24 24" width="12" height="12" fill="none" aria-hidden>
<path
d="M6 6l12 12M18 6L6 18"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
/>
</svg>
</button>
<div className="ai-ask-pop-title"> <div className="ai-ask-pop-title">
{t(open.mode === 'edit' ? 'aiAskEditTitle' : 'aiAskTitle')} {t(open.mode === 'edit' ? 'aiAskEditTitle' : 'aiAskTitle')}
</div> </div>
@@ -185,8 +185,17 @@ export function EditorContextMenu({
isImage || isImage ||
(Array.isArray(protAttrs?.textboxes) && (protAttrs.textboxes as unknown[]).length > 0) (Array.isArray(protAttrs?.textboxes) && (protAttrs.textboxes as unknown[]).length > 0)
const currentWrap = (protAttrs?.imageWrap as string | null) ?? null const currentWrap = (protAttrs?.imageWrap as string | null) ?? null
const setWrap = (wrap: string | null) => const setWrap = (wrap: string | null) => {
editor.chain().focus().updateAttributes('docProtected', { imageWrap: wrap }).run() const clearedPosition =
wrap === null
? { imagePosH: null, imagePosV: null, imageOffsetXEmu: null, imageOffsetYEmu: null }
: {}
editor
.chain()
.focus()
.updateAttributes('docProtected', { imageWrap: wrap, ...clearedPosition })
.run()
}
// Stacking order among overlapping floating pictures. z-order only has a // Stacking order among overlapping floating pictures. z-order only has a
// visible effect on floating (front/behind) images, so the menu enables it // visible effect on floating (front/behind) images, so the menu enables it
// there; a bring-forward on an inline image also floats it (Word parity). // there; a bring-forward on an inline image also floats it (Word parity).
@@ -26,7 +26,9 @@ export interface HfValue {
function runStyle(run: Run): React.CSSProperties { function runStyle(run: Run): React.CSSProperties {
const style: React.CSSProperties = {} const style: React.CSSProperties = {}
if (run.bold) style.fontWeight = 600 if (run.bold) style.fontWeight = 600
else if (run.bold === false) style.fontWeight = 'normal'
if (run.italic) style.fontStyle = 'italic' if (run.italic) style.fontStyle = 'italic'
else if (run.italic === false) style.fontStyle = 'normal'
if (run.underline) style.textDecoration = 'underline' if (run.underline) style.textDecoration = 'underline'
if (run.strike) style.textDecoration = `${style.textDecoration ?? ''} line-through`.trim() if (run.strike) style.textDecoration = `${style.textDecoration ?? ''} line-through`.trim()
if (run.color) style.color = `#${run.color}` if (run.color) style.color = `#${run.color}`
@@ -36,6 +38,10 @@ function runStyle(run: Run): React.CSSProperties {
if (run.font || run.fontAscii) style.fontFamily = cssRunFontFamily(run.fontAscii, run.font) if (run.font || run.fontAscii) style.fontFamily = cssRunFontFamily(run.fontAscii, run.font)
if (run.caps === 'all') style.textTransform = 'uppercase' if (run.caps === 'all') style.textTransform = 'uppercase'
else if (run.caps === 'small') style.fontVariantCaps = 'small-caps' else if (run.caps === 'small') style.fontVariantCaps = 'small-caps'
else if (run.caps === 'none') {
style.textTransform = 'none'
style.fontVariantCaps = 'normal'
}
return style return style
} }
@@ -17,6 +17,7 @@ import {
liveSections, liveSections,
measureBlocks, measureBlocks,
pageNumbers, pageNumbers,
pinnedFloatPage,
sectionBidi, sectionBidi,
sectionColGeom, sectionColGeom,
sectionFirstPages, sectionFirstPages,
@@ -111,6 +112,25 @@ export function prunedCloneHtml(kids: CloneChild[], from: number, to: number): s
return parts.join('') return parts.join('')
} }
/**
* Page-pinned boxes (cover art) ride the full-document clone onto every page at
* the same page coordinates; only the copy on the owning page (data-pin-page,
* stamped on the canvas wrapper before cloning) may stay visible. Expressed as
* CSS rules because React re-assigns each clone's innerHTML on every re-render
* (the {__html} wrapper is a fresh object), wiping any imperative DOM fixup.
* visibility (not display): a stray-run wrapper carries flow height the slices
* were measured with, and hidden ink must not emit glyphs into the PDF layer.
*/
export function pinnedCloneCss(pageCount: number): string {
const rules: string[] = []
for (let i = 0; i < pageCount; i++) {
rules.push(
`.pv-page[data-pv-page="${i}"] .doc-protected-pagepinned[data-pin-page]:not([data-pin-page="${i}"]){visibility:hidden;}`,
)
}
return rules.join('\n')
}
export interface HfSet { export interface HfSet {
header: HeaderFooter | null header: HeaderFooter | null
footer: HeaderFooter | null footer: HeaderFooter | null
@@ -312,6 +332,13 @@ export function PaginationPreview({
blockMetaOf, blockMetaOf,
) )
} }
// stamp each page-pinned box's owning page on its canvas wrapper before
// cloning so the per-page CSS rules can hide the copies on other pages
for (const f of floats) {
if (!f.pinned) continue
const wrap = f.el.closest<HTMLElement>('.doc-protected-pagepinned')
if (wrap) wrap.dataset.pinPage = String(pinnedFloatPage(computed, f.anchorTop))
}
setSlices(computed) setSlices(computed)
setPageNotes(pageFootnotesOf ? pageFootnotesOf(blocks, computed) : []) setPageNotes(pageFootnotesOf ? pageFootnotesOf(blocks, computed) : [])
// Per-page full clones explode on large documents (pages × doc DOM → // Per-page full clones explode on large documents (pages × doc DOM →
@@ -467,6 +494,7 @@ export function PaginationPreview({
{t('appClose')} {t('appClose')}
</button> </button>
</div> </div>
<style>{pinnedCloneCss(slices.length)}</style>
<div className="pv-scroll"> <div className="pv-scroll">
{slices.map((slice, i) => { {slices.map((slice, i) => {
const parts = hfFor(i) const parts = hfFor(i)
@@ -498,6 +526,7 @@ export function PaginationPreview({
<div <div
key={i} key={i}
className="pv-page" className="pv-page"
data-pv-page={i}
style={ style={
{ {
width: pageW, width: pageW,
+491 -2
View File
@@ -26,6 +26,8 @@ import type {
SectionSettings, SectionSettings,
SourceInfo, SourceInfo,
StyleInfo, StyleInfo,
TableAutoFitMode,
TableLook,
TextboxDisplay, TextboxDisplay,
TextboxParaDisplay, TextboxParaDisplay,
ThemeColors, ThemeColors,
@@ -41,6 +43,14 @@ import { formatNumber } from '../editor/numbering'
import type { InkTool } from '../editor/ink' import type { InkTool } from '../editor/ink'
import type { RibbonFormatState } from './ribbon-format-state' import type { RibbonFormatState } from './ribbon-format-state'
import { setSelectedColumnWidth } from '../editor/table-sizing' import { setSelectedColumnWidth } from '../editor/table-sizing'
import {
applyTablePreset,
repeatHeaderState,
setTableAutoFit,
setTableLookOption,
toggleRepeatHeaderRows,
updateSelectedTableAttrs,
} from '../editor/table-properties'
import { useI18n, type StringKey } from '../i18n/locale' import { useI18n, type StringKey } from '../i18n/locale'
import { fontFamiliesFor, isEastAsianFontName } from '../font-list' import { fontFamiliesFor, isEastAsianFontName } from '../font-list'
import { useSystemFontFamilies } from '../system-fonts' import { useSystemFontFamilies } from '../system-fonts'
@@ -68,6 +78,7 @@ import {
IconAlignJustify, IconAlignJustify,
IconAlignLeft, IconAlignLeft,
IconAlignRight, IconAlignRight,
IconAutoFit,
IconBorderAll, IconBorderAll,
IconBorderInner, IconBorderInner,
IconBorderNone, IconBorderNone,
@@ -115,6 +126,8 @@ import {
IconSubscript, IconSubscript,
IconSuperscript, IconSuperscript,
IconTableDelete, IconTableDelete,
IconRepeatHeader,
IconTableProperties,
} from './icons' } from './icons'
interface RibbonProps { interface RibbonProps {
/** App keyboard shortcuts reuse ribbon closures through here (font-size stepping keeps its coalescing) */ /** App keyboard shortcuts reuse ribbon closures through here (font-size stepping keeps its coalescing) */
@@ -300,6 +313,56 @@ type RibbonTab =
| (typeof IMAGE_TABS)[number] | (typeof IMAGE_TABS)[number]
| (typeof SHAPE_TABS)[number] | (typeof SHAPE_TABS)[number]
const TABLE_PRESETS = [
{
label: 'ribbonTablePresetGrid',
headerFill: null,
band1Fill: null,
band2Fill: null,
borderColor: '808080',
},
{
label: 'ribbonTablePresetBlueHeader',
headerFill: 'D9EAF7',
band1Fill: null,
band2Fill: null,
borderColor: '5B9BD5',
},
{
label: 'ribbonTablePresetBlueBanded',
headerFill: 'BDD7EE',
band1Fill: 'DDEBF7',
band2Fill: 'FFFFFF',
borderColor: '9DC3E6',
},
{
label: 'ribbonTablePresetGrayBanded',
headerFill: 'D9E1F2',
band1Fill: 'E7E6E6',
band2Fill: 'FFFFFF',
borderColor: 'A5A5A5',
},
{
label: 'ribbonTablePresetGreenHeader',
headerFill: 'E2F0D9',
band1Fill: null,
band2Fill: null,
borderColor: '70AD47',
},
] as const satisfies ReadonlyArray<{
label: StringKey
headerFill: string | null
band1Fill: string | null
band2Fill: string | null
borderColor: string
}>
const TABLE_AUTO_FIT_OPTIONS: Array<[TableAutoFitMode, StringKey]> = [
['contents', 'ribbonAutoFitContents'],
['window', 'ribbonAutoFitWindow'],
['fixed', 'ribbonFixedColumnWidth'],
]
// tab values double as internal-state / external tabRequest keys; translated for display via these string keys // tab values double as internal-state / external tabRequest keys; translated for display via these string keys
const TAB_LABEL_KEYS: Record<string, StringKey> = { const TAB_LABEL_KEYS: Record<string, StringKey> = {
file: 'ribbonTabFile', file: 'ribbonTabFile',
@@ -655,6 +718,7 @@ function RibbonInner({
/** Picture Format → remove background / crop dialogs */ /** Picture Format → remove background / crop dialogs */
const [pictureDialog, setPictureDialog] = useState<'cutout' | 'crop' | null>(null) const [pictureDialog, setPictureDialog] = useState<'cutout' | 'crop' | null>(null)
const [listDialog, setListDialog] = useState(false) const [listDialog, setListDialog] = useState(false)
const [tablePropertiesOpen, setTablePropertiesOpen] = useState(false)
useEffect(() => { useEffect(() => {
if (tabRequest && (TABS as readonly string[]).includes(tabRequest.tab)) { if (tabRequest && (TABS as readonly string[]).includes(tabRequest.tab)) {
@@ -1053,6 +1117,87 @@ function RibbonInner({
vAlign: fs.cellVAlign, vAlign: fs.cellVAlign,
} }
const tableAttrs = inTable ? editor.getAttributes('docTable') : {}
const tableHeader = inTable ? repeatHeaderState(editor.state) : { enabled: false, active: false }
const tableLook = (tableAttrs.tblLook as TableLook | null) ?? {
firstRow: true,
lastRow: false,
firstColumn: true,
lastColumn: false,
bandedRows: true,
bandedColumns: false,
}
const tableAutoFitMode: TableAutoFitMode =
tableAttrs.tblAutoFit === 'contents' || tableAttrs.tblAutoFit === 'window'
? tableAttrs.tblAutoFit
: 'fixed'
const tableAutoFitLabel =
TABLE_AUTO_FIT_OPTIONS.find(([mode]) => mode === tableAutoFitMode)?.[1] ??
'ribbonFixedColumnWidth'
const applyTableProperties = (value: TablePropertiesValue) => {
if (!canEdit || !inTable) return
let measuredWidthPx = Number(tableAttrs.widthPx) || 0
if (!(measuredWidthPx > 0)) {
try {
const rect = selectedRect(editor.state)
const tableDom = editor.view.nodeDOM(rect.tableStart - 1)
if (tableDom instanceof HTMLElement) {
const zoomEl = document.querySelector('.doc-zoom') as HTMLElement | null
const zoom = zoomEl ? parseFloat(getComputedStyle(zoomEl).zoom || '1') || 1 : 1
measuredWidthPx = tableDom.getBoundingClientRect().width / zoom
}
} catch {
// A malformed table falls back to the section width below.
}
}
measuredWidthPx = Math.max(1, Math.round(measuredWidthPx || sectionContentWidthPx))
const positionedWidthPx =
value.autoFit === 'window' ? Math.round(sectionContentWidthPx) : measuredWidthPx
runTableCommand(setTableAutoFit(value.autoFit, sectionContentWidthPx))
const twips = (cm: number) => Math.max(0, Math.round(cm * TWIPS_PER_CM))
const signedTwips = (cm: number) => Math.round(cm * TWIPS_PER_CM)
const floatX =
value.wrap === 'right' && Math.abs(value.positionXCm) < 0.001
? value.autoFit === 'window'
? 0
: Math.max(0, Math.round((sectionContentWidthPx - positionedWidthPx) * 15))
: signedTwips(value.positionXCm)
const keepFloatSuppressed = value.floatSuppressed && value.wrap !== 'none'
runTableCommand(
updateSelectedTableAttrs({
tblFloatWidthPx: value.wrap === 'right' ? positionedWidthPx : null,
cellMar: {
top: twips(value.marginTopCm),
right: twips(value.marginRightCm),
bottom: twips(value.marginBottomCm),
left: twips(value.marginLeftCm),
},
cellMarEdited: true,
tblFloat: keepFloatSuppressed ? null : value.wrap,
tblFloatSource: value.wrap,
tblFloatSuppressed: keepFloatSuppressed,
tblFloatXTwips: value.wrap === 'none' ? null : floatX,
tblFloatYTwips: value.wrap === 'none' ? null : signedTwips(value.positionYCm),
tblFloatHorzAnchor:
value.wrap === 'none' ? null : (tableAttrs.tblFloatHorzAnchor ?? 'margin'),
tblFloatVertAnchor:
value.wrap === 'none' ? null : (tableAttrs.tblFloatVertAnchor ?? 'margin'),
tblFloatDistance:
value.wrap === 'none'
? null
: {
top: twips(value.distanceCm),
right: twips(value.distanceCm),
bottom: twips(value.distanceCm),
left: twips(value.distanceCm),
},
tblFloatEdited: true,
}),
)
setTablePropertiesOpen(false)
}
const activeCharStyleId = fs.charStyleId const activeCharStyleId = fs.charStyleId
const presetAccent = themeColors?.accent1?.trim().toUpperCase() || DEFAULT_PRESET_ACCENT const presetAccent = themeColors?.accent1?.trim().toUpperCase() || DEFAULT_PRESET_ACCENT
@@ -2184,13 +2329,34 @@ function RibbonInner({
<span className="table-style-card-grid plain" /> <span className="table-style-card-grid plain" />
<span>{t('ribbonNoStyle')}</span> <span>{t('ribbonNoStyle')}</span>
</button> </button>
{TABLE_PRESETS.map((preset) => (
<button
key={preset.label}
className="table-style-card"
data-tip={t(preset.label)}
onClick={() => runTableCommand(applyTablePreset(preset))}
>
<span
className="table-style-card-grid"
style={{
borderColor: `#${preset.borderColor}`,
borderTopColor: `#${preset.headerFill ?? 'FFFFFF'}`,
background: `repeating-linear-gradient(to bottom,#${preset.band1Fill ?? 'FFFFFF'} 0 50%,#${preset.band2Fill ?? preset.band1Fill ?? 'FFFFFF'} 50% 100%)`,
}}
/>
<span>{t(preset.label)}</span>
</button>
))}
{[...(styles?.values() ?? [])] {[...(styles?.values() ?? [])]
.filter((info) => info.type === 'table' && info.styleId !== 'TableNormal') .filter((info) => info.type === 'table' && info.styleId !== 'TableNormal')
.slice(0, 8)
.map((info) => ( .map((info) => (
<button <button
key={info.styleId} key={info.styleId}
className="table-style-card" className={
tableAttrs.tblStyleId === info.styleId
? 'table-style-card active'
: 'table-style-card'
}
data-tip={t('ribbonApplyTableStyleTip', { name: info.name })} data-tip={t('ribbonApplyTableStyleTip', { name: info.name })}
onClick={() => onClick={() =>
chain().updateAttributes('docTable', { tblStyleId: info.styleId }).run() chain().updateAttributes('docTable', { tblStyleId: info.styleId }).run()
@@ -2214,6 +2380,36 @@ function RibbonInner({
<div className="ribbon-group-label">{t('ribbonGroupTableStyles')}</div> <div className="ribbon-group-label">{t('ribbonGroupTableStyles')}</div>
</div> </div>
<div className="ribbon-sep" /> <div className="ribbon-sep" />
<div className="table-tool-group">
<div className="table-style-options">
{(
[
['firstRow', 'ribbonTableFirstRow'],
['lastRow', 'ribbonTableLastRow'],
['bandedRows', 'ribbonTableBandedRows'],
['firstColumn', 'ribbonTableFirstColumn'],
['lastColumn', 'ribbonTableLastColumn'],
['bandedColumns', 'ribbonTableBandedColumns'],
] as Array<[keyof TableLook, StringKey]>
).map(([key, label]) => (
<button
key={key}
className={
tableLook[key]
? 'table-option-toggle table-tool-button active'
: 'table-option-toggle table-tool-button'
}
aria-pressed={tableLook[key]}
onClick={() => runTableCommand(setTableLookOption(key, !tableLook[key]))}
>
<span className="table-option-check" aria-hidden="true" />
<span>{t(label)}</span>
</button>
))}
</div>
<div className="ribbon-group-label">{t('ribbonTableStyleOptions')}</div>
</div>
<div className="ribbon-sep" />
<div className="table-tool-group"> <div className="table-tool-group">
<div className="table-style-swatches"> <div className="table-style-swatches">
{['FFFFFF', 'D9EAF7', 'FFF2CC', 'E2F0D9', 'FCE4D6', 'E4DFEC'].map((hex) => ( {['FFFFFF', 'D9EAF7', 'FFF2CC', 'E2F0D9', 'FCE4D6', 'E4DFEC'].map((hex) => (
@@ -2468,6 +2664,76 @@ function RibbonInner({
</div> </div>
<div className="ribbon-group-label">{t('ribbonGroupCellSize')}</div> <div className="ribbon-group-label">{t('ribbonGroupCellSize')}</div>
</div> </div>
<div className="ribbon-sep" />
<div className="table-tool-group table-tool-autofit">
<div className="table-tool-row">
<div className="rb-split-wrap table-autofit-wrap">
<button
className={`table-command-button${dropdown === 'tableAutoFit' ? ' active' : ''}`}
data-tip={t('ribbonAutoFit')}
aria-expanded={dropdown === 'tableAutoFit'}
onClick={() =>
setDropdown((current) => (current === 'tableAutoFit' ? null : 'tableAutoFit'))
}
>
<IconAutoFit size={18} />
<span className="table-command-copy">
<span>{t('ribbonAutoFit')}</span>
<small>{t(tableAutoFitLabel)}</small>
</span>
<IconCaret size={12} />
</button>
{dropdown === 'tableAutoFit' && (
<div data-rb-panel="" className="layout-menu table-autofit-menu">
{TABLE_AUTO_FIT_OPTIONS.map(([mode, label]) => (
<button
key={mode}
className={tableAutoFitMode === mode ? 'active' : ''}
onClick={() => {
runTableCommand(setTableAutoFit(mode, sectionContentWidthPx))
setDropdown(null)
}}
>
<IconAutoFit size={17} />
<span>{t(label)}</span>
<span className="table-menu-state" aria-hidden="true" />
</button>
))}
</div>
)}
</div>
</div>
<div className="ribbon-group-label">{t('ribbonAutoFit')}</div>
</div>
<div className="ribbon-sep" />
<div className="table-tool-group table-tool-advanced">
<div className="table-tool-stack">
<button
className={
tableHeader.active
? 'table-command-row table-tool-button active'
: 'table-command-row table-tool-button'
}
disabled={!tableHeader.enabled}
aria-pressed={tableHeader.active}
onClick={() => runTableCommand(toggleRepeatHeaderRows())}
>
<IconRepeatHeader size={17} />
<span>{t('ribbonRepeatHeaderRows')}</span>
</button>
<button
className="table-command-row"
onClick={() => {
setDropdown(null)
setTablePropertiesOpen(true)
}}
>
<IconTableProperties size={17} />
<span>{t('ribbonTableProperties')}</span>
</button>
</div>
<div className="ribbon-group-label">{t('ribbonTableData')}</div>
</div>
</div> </div>
) : tab === 'home' ? ( ) : tab === 'home' ? (
<> <>
@@ -3538,6 +3804,13 @@ function RibbonInner({
onClose={() => setListDialog(false)} onClose={() => setListDialog(false)}
/> />
)} )}
{tablePropertiesOpen && (
<TablePropertiesDialog
initial={tablePropertiesFromAttrs(tableAttrs)}
onApply={applyTableProperties}
onClose={() => setTablePropertiesOpen(false)}
/>
)}
</div> </div>
) )
} }
@@ -3570,6 +3843,222 @@ const LIST_FMT_SAMPLES: Record<string, string> = {
const TWIPS_PER_CM = 567 const TWIPS_PER_CM = 567
type TableWrapMode = 'none' | 'left' | 'right'
interface TablePropertiesValue {
autoFit: TableAutoFitMode
wrap: TableWrapMode
floatSuppressed: boolean
positionXCm: number
positionYCm: number
distanceCm: number
marginTopCm: number
marginRightCm: number
marginBottomCm: number
marginLeftCm: number
}
function tablePropertiesFromAttrs(attrs: Record<string, unknown>): TablePropertiesValue {
const cm = (value: unknown, fallback = 0) =>
+((Number.isFinite(Number(value)) ? Number(value) : fallback) / TWIPS_PER_CM).toFixed(2)
const margins = (attrs.cellMar as Record<string, number> | null) ?? {}
const distance = (attrs.tblFloatDistance as Record<string, number> | null) ?? {}
const wrap: TableWrapMode =
attrs.tblFloat === 'left' || attrs.tblFloat === 'right'
? attrs.tblFloat
: attrs.tblFloatSource === 'left' || attrs.tblFloatSource === 'right'
? attrs.tblFloatSource
: 'none'
return {
autoFit:
attrs.tblAutoFit === 'contents' || attrs.tblAutoFit === 'window' ? attrs.tblAutoFit : 'fixed',
wrap,
floatSuppressed: attrs.tblFloatSuppressed === true,
positionXCm: cm(attrs.tblFloatXTwips),
positionYCm: cm(attrs.tblFloatYTwips),
distanceCm: cm(distance.right ?? distance.left ?? distance.top ?? distance.bottom, 180),
marginTopCm: cm(margins.top),
marginRightCm: cm(margins.right, 108),
marginBottomCm: cm(margins.bottom),
marginLeftCm: cm(margins.left, 108),
}
}
function TablePropertiesDialog({
initial,
onApply,
onClose,
}: {
initial: TablePropertiesValue
onApply: (value: TablePropertiesValue) => void
onClose: () => void
}) {
const { t } = useI18n()
const [value, setValue] = useState(initial)
const update = (patch: Partial<TablePropertiesValue>) =>
setValue((current) => ({ ...current, ...patch }))
const numberInput = (
key:
| 'positionXCm'
| 'positionYCm'
| 'distanceCm'
| 'marginTopCm'
| 'marginRightCm'
| 'marginBottomCm'
| 'marginLeftCm',
) => (
<input
type="number"
min={key === 'positionXCm' || key === 'positionYCm' ? -50 : 0}
max={50}
step={0.1}
value={value[key]}
onChange={(event) => update({ [key]: Number(event.target.value) || 0 })}
/>
)
const wrapLabel: StringKey =
value.wrap === 'left'
? 'appWrapSquareLeft'
: value.wrap === 'right'
? 'appWrapSquareRight'
: 'appWrapInline'
const autoFitLabel =
TABLE_AUTO_FIT_OPTIONS.find(([mode]) => mode === value.autoFit)?.[1] ?? 'ribbonFixedColumnWidth'
return (
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal gs-form table-properties-dialog">
<div className="table-properties-header">
<span className="table-properties-header-icon" aria-hidden="true">
<IconTableProperties size={22} />
</span>
<div>
<h2>{t('ribbonTableProperties')}</h2>
<p className="modal-desc">
{t(autoFitLabel)} · {t(wrapLabel)}
</p>
</div>
</div>
<section className="table-properties-card">
<h3>{t('ribbonAutoFit')}</h3>
<div className="table-properties-segments">
{TABLE_AUTO_FIT_OPTIONS.map(([mode, label]) => (
<label key={mode} className="table-properties-segment">
<input
type="radio"
name="table-autofit"
checked={value.autoFit === mode}
onChange={() => update({ autoFit: mode })}
/>
<span>{t(label)}</span>
</label>
))}
</div>
</section>
<section className="table-properties-card">
<h3>{t('ribbonWrapText')}</h3>
<div className="table-properties-segments">
{(
[
['none', 'appWrapInline'],
['left', 'appWrapSquareLeft'],
['right', 'appWrapSquareRight'],
] as Array<[TableWrapMode, StringKey]>
).map(([mode, label]) => (
<label key={mode} className="table-properties-segment">
<input
type="radio"
name="table-wrap"
checked={value.wrap === mode}
onChange={() => update({ wrap: mode })}
/>
<span>{t(label)}</span>
</label>
))}
</div>
{value.wrap !== 'none' && (
<div className="table-properties-grid">
<label>
{t('ribbonHorizontalPosition')}
<span>
{numberInput('positionXCm')}
{t('ribbonCm')}
</span>
</label>
<label>
{t('ribbonVerticalPosition')}
<span>
{numberInput('positionYCm')}
{t('ribbonCm')}
</span>
</label>
<label>
{t('ribbonDistanceFromText')}
<span>
{numberInput('distanceCm')}
{t('ribbonCm')}
</span>
</label>
</div>
)}
</section>
<section className="table-properties-card table-properties-margins">
<h3>{t('ribbonCellMargins')}</h3>
<div className="table-properties-margin-layout">
<div className="table-properties-grid">
<label>
{t('ribbonMarginTop')}
<span>
{numberInput('marginTopCm')}
{t('ribbonCm')}
</span>
</label>
<label>
{t('ribbonMarginBottom')}
<span>
{numberInput('marginBottomCm')}
{t('ribbonCm')}
</span>
</label>
<label>
{t('ribbonMarginLeft')}
<span>
{numberInput('marginLeftCm')}
{t('ribbonCm')}
</span>
</label>
<label>
{t('ribbonMarginRight')}
<span>
{numberInput('marginRightCm')}
{t('ribbonCm')}
</span>
</label>
</div>
<div className="table-margin-preview" aria-hidden="true">
<span className="table-margin-value top">{value.marginTopCm}</span>
<span className="table-margin-value right">{value.marginRightCm}</span>
<span className="table-margin-value bottom">{value.marginBottomCm}</span>
<span className="table-margin-value left">{value.marginLeftCm}</span>
<span className="table-margin-preview-cell" />
</div>
</div>
</section>
<div className="modal-actions">
<button onClick={onClose}>{t('ribbonCancel')}</button>
<button className="primary" onClick={() => onApply(value)}>
{t('ribbonOk')}
</button>
</div>
</div>
</div>
)
}
function ListDefineDialog({ function ListDefineDialog({
onApply, onApply,
onClose, onClose,
@@ -564,6 +564,42 @@ export function IconTableDelete(props: IconProps) {
) )
} }
export function IconAutoFit(props: IconProps) {
return (
<Svg {...props}>
<rect x="3.1" y="4" width="9.8" height="8" rx="0.65" />
<path d="M 6.35 4 v 8 M 9.65 4 v 8 M 3.1 8 h 9.8" strokeWidth="1" />
<path d="M 1.35 8 h 2.6 M 1.35 8 l 1 -1 M 1.35 8 l 1 1" />
<path d="M 14.65 8 h -2.6 M 14.65 8 l -1 -1 M 14.65 8 l -1 1" />
</Svg>
)
}
export function IconRepeatHeader(props: IconProps) {
return (
<Svg {...props}>
<rect x="3" y="3.45" width="8.8" height="9.1" rx="0.65" />
<path d="M 3 6.2 h 8.8 M 3 9.35 h 8.8 M 7.4 3.45 v 9.1" strokeWidth="1" />
<path d="M 3.6 4.8 h 7.6" strokeWidth="1.5" />
<path d="M 11.35 10.15 a 2.15 2.15 0 1 1 -0.5 2.25" />
<path d="m 10.2 10.15 1.3 -0.05 -0.35 1.22" />
</Svg>
)
}
export function IconTableProperties(props: IconProps) {
return (
<Svg {...props}>
<rect x="2.85" y="3.2" width="7.7" height="9.6" rx="0.65" />
<path d="M 2.85 6.4 h 7.7 M 2.85 9.6 h 7.7 M 6.7 3.2 v 9.6" strokeWidth="1" />
<path d="M 11.7 5.15 h 2.15 M 11.7 8 h 2.15 M 11.7 10.85 h 2.15" />
<circle cx="12.35" cy="5.15" r="0.55" fill="currentColor" stroke="none" />
<circle cx="13.15" cy="8" r="0.55" fill="currentColor" stroke="none" />
<circle cx="12.65" cy="10.85" r="0.55" fill="currentColor" stroke="none" />
</Svg>
)
}
export function IconRowInsertAbove(props: IconProps) { export function IconRowInsertAbove(props: IconProps) {
return ( return (
<Svg {...props}> <Svg {...props}>
+20 -6
View File
@@ -151,17 +151,19 @@ export function docStyleCss(parsed: ParsedDocFull): string {
// re-resolve the snap with their 1em (exact/atLeast lines never snap) // re-resolve the snap with their 1em (exact/atLeast lines never snap)
rules.push(`${gridBlocks} span { ${gridSpanSnap} }`) rules.push(`${gridBlocks} span { ${gridSpanSnap} }`)
} }
// settings.xml w:autoHyphenation: Word breaks words at line ends document-wide.
// Chromium hyphenates only under an explicit lang; file-actions sets it on the
// editor root from docDefaults w:lang.
if (parsed.autoHyphenation) {
rules.push('.doc-page { hyphens:auto; -webkit-hyphens:auto }')
}
const dd = parsed.docDefaults const dd = parsed.docDefaults
// Word applies the w:default="1" paragraph style (Normal) to every paragraph // Word applies the w:default="1" paragraph style (Normal) to every paragraph
// without a w:pStyle, so its display merges into the document baseline here // without a w:pStyle, so its display merges into the document baseline here
// ([data-style] rules only reach explicitly styled paragraphs). // ([data-style] rules only reach explicitly styled paragraphs).
const normal = defaultParaDisplay(parsed) const normal = defaultParaDisplay(parsed)
// settings.xml w:autoHyphenation: Word breaks words at line ends document-wide,
// except paragraphs opted out via w:suppressAutoHyphens (pPrDefault/Normal decide
// the baseline here; explicit style values override per style below). Chromium
// hyphenates only under an explicit lang; file-actions sets it on the editor root
// from docDefaults w:lang.
if (parsed.autoHyphenation && !(normal?.suppressAutoHyphens ?? dd?.suppressAutoHyphens)) {
rules.push('.doc-page { hyphens:auto; -webkit-hyphens:auto }')
}
{ {
const decls: string[] = [] const decls: string[] = []
// Paragraph level also overrides this variable per paragraph's text (blockAttrs // Paragraph level also overrides this variable per paragraph's text (blockAttrs
@@ -332,8 +334,11 @@ export function docStyleCss(parsed: ParsedDocFull): string {
const decls: string[] = [] const decls: string[] = []
if (d.sizeHalfPoints) decls.push(`font-size:${d.sizeHalfPoints / 2}pt`) if (d.sizeHalfPoints) decls.push(`font-size:${d.sizeHalfPoints / 2}pt`)
if (d.color) decls.push(`color:#${d.color}`) if (d.color) decls.push(`color:#${d.color}`)
// explicit off (w:val="0") must out-rule an inherited on from .doc-page defaults
if (d.bold) decls.push('font-weight:600') if (d.bold) decls.push('font-weight:600')
else if (d.bold === false) decls.push('font-weight:400')
if (d.italic) decls.push('font-style:italic') if (d.italic) decls.push('font-style:italic')
else if (d.italic === false) decls.push('font-style:normal')
if (d.underline || d.strike) { if (d.underline || d.strike) {
decls.push( decls.push(
`text-decoration:${[d.underline && 'underline', d.strike && 'line-through'].filter(Boolean).join(' ')}`, `text-decoration:${[d.underline && 'underline', d.strike && 'line-through'].filter(Boolean).join(' ')}`,
@@ -365,6 +370,7 @@ export function docStyleCss(parsed: ParsedDocFull): string {
if (d.charSpacingTwips) decls.push(`letter-spacing:${d.charSpacingTwips / 20}pt`) if (d.charSpacingTwips) decls.push(`letter-spacing:${d.charSpacingTwips / 20}pt`)
if (d.caps === 'all') decls.push('text-transform:uppercase') if (d.caps === 'all') decls.push('text-transform:uppercase')
else if (d.caps === 'small') decls.push('font-variant-caps:small-caps') else if (d.caps === 'small') decls.push('font-variant-caps:small-caps')
else if (d.caps === 'none') decls.push('text-transform:none', 'font-variant-caps:normal')
const styleLh = cssLineHeight(d.lineRule, d.lineRawTwips, d.lineSpacing) const styleLh = cssLineHeight(d.lineRule, d.lineRawTwips, d.lineSpacing)
if (styleLh) decls.push(`line-height:${styleLh}`) if (styleLh) decls.push(`line-height:${styleLh}`)
// grid span snapping scales by the style's multiple (an explicit single // grid span snapping scales by the style's multiple (an explicit single
@@ -406,6 +412,14 @@ export function docStyleCss(parsed: ParsedDocFull): string {
if (d.indentFirstLineTwips) if (d.indentFirstLineTwips)
decls.push(`text-indent:${(d.indentFirstLineTwips / 20).toFixed(1)}pt`) decls.push(`text-indent:${(d.indentFirstLineTwips / 20).toFixed(1)}pt`)
if (d.align) decls.push(`text-align:${d.align}`) if (d.align) decls.push(`text-align:${d.align}`)
if (
parsed.autoHyphenation &&
info.type === 'paragraph' &&
d.suppressAutoHyphens !== undefined
) {
const h = d.suppressAutoHyphens ? 'manual' : 'auto'
decls.push(`hyphens:${h}`, `-webkit-hyphens:${h}`)
}
// style-level paragraph shading (explicit pPr w:shd is inline style and wins) // style-level paragraph shading (explicit pPr w:shd is inline style and wins)
if (d.shadingFill) decls.push(`background-color:#${d.shadingFill}`) if (d.shadingFill) decls.push(`background-color:#${d.shadingFill}`)
// the static sheet guesses italic for h4-h6 (Word's built-in defaults); // the static sheet guesses italic for h4-h6 (Word's built-in defaults);
+148 -16
View File
@@ -540,11 +540,23 @@ function blockToPmNode(
imageHeightPx: block.imageHeightPx ?? null, imageHeightPx: block.imageHeightPx ?? null,
imageCrop: block.imageCrop ?? null, imageCrop: block.imageCrop ?? null,
imageFillRect: block.imageFillRect ?? null, imageFillRect: block.imageFillRect ?? null,
imageLeadingText: block.imageLeadingText ?? null,
imageLeadingFont: block.imageLeadingFont ?? null,
imageLeadingExplicitSpaceWidthPx: block.imageLeadingExplicitSpaceWidthPx ?? null,
imageLeadingImplicitSpaceCount: block.imageLeadingImplicitSpaceCount ?? null,
imageParagraphIndentLeft: block.imageParagraphIndentLeft ?? null,
imageParagraphIndentRight: block.imageParagraphIndentRight ?? null,
imageParagraphIndentFirstLine: block.imageParagraphIndentFirstLine ?? null,
imageAlign: block.imageAlign ?? null, imageAlign: block.imageAlign ?? null,
imageWrap: block.imageWrap ?? null, imageWrap: block.imageWrap ?? null,
imageWrapDistTopEmu: block.imageWrapDistTopEmu ?? null,
imageWrapDistBottomEmu: block.imageWrapDistBottomEmu ?? null,
imageWrapDistLeftEmu: block.imageWrapDistLeftEmu ?? null,
imageWrapDistRightEmu: block.imageWrapDistRightEmu ?? null,
imageZOrder: block.imageZOrder ?? null, imageZOrder: block.imageZOrder ?? null,
imageOffsetXEmu: block.imageOffsetXEmu ?? null, imageOffsetXEmu: block.imageOffsetXEmu ?? null,
imageOffsetYEmu: block.imageOffsetYEmu ?? null, imageOffsetYEmu: block.imageOffsetYEmu ?? null,
imageAnchorLocked: block.imageAnchorLocked ?? false,
imagePosH: block.imagePosH ?? null, imagePosH: block.imagePosH ?? null,
imagePosV: block.imagePosV ?? null, imagePosV: block.imagePosV ?? null,
imageRotDeg: block.imageRotDeg ?? null, imageRotDeg: block.imageRotDeg ?? null,
@@ -648,7 +660,9 @@ export function tableModelToPmNode(
(sum, _row, i) => sum + Math.max(model.rowHeightsTwips?.[i] ?? 0, 240), (sum, _row, i) => sum + Math.max(model.rowHeightsTwips?.[i] ?? 0, 240),
0, 0,
) )
const tblFloat = minHeightTwips > 12960 ? null : (model.floatSide ?? null) const tblFloatSource = model.floatSide ?? null
const tblFloatSuppressed = minHeightTwips > 12960 && tblFloatSource !== null
const tblFloat = tblFloatSuppressed ? null : tblFloatSource
const table: PmNode = { const table: PmNode = {
type: 'docTable', type: 'docTable',
attrs: { attrs: {
@@ -661,11 +675,28 @@ export function tableModelToPmNode(
: null, : null,
widthPct: model.widthPct ?? null, widthPct: model.widthPct ?? null,
cellMar: model.cellMarTwips ?? null, cellMar: model.cellMarTwips ?? null,
cellSpacingTwips: model.cellSpacingTwips ?? null,
tblFill: model.fill ?? null,
cellMarEdited: false,
borders: model.borders ?? null, borders: model.borders ?? null,
tblAlign: model.align ?? null, tblAlign: model.align ?? null,
tblFloat, tblFloat,
tblFloatSource,
tblFloatSuppressed,
tblFloatXTwips: model.floatPos?.xTwips ?? null,
tblFloatYTwips: model.floatPos?.yTwips ?? null,
tblFloatHorzAnchor: model.floatPos?.horzAnchor ?? null,
tblFloatVertAnchor: model.floatPos?.vertAnchor ?? null,
tblFloatDistance: model.floatPos?.distanceTwips ?? null,
tblFloatWidthPx:
tblFloatSource && widthPx ? widthPx.reduce((sum, width) => sum + width, 0) : null,
tblFloatEdited: false,
tblAutoFit: model.autoFit ?? (model.autoLayout ? 'contents' : 'fixed'),
tblAutoFitEdited: false,
indentTwips: model.indentTwips ?? null, indentTwips: model.indentTwips ?? null,
tblStyleId: model.tblStyleId ?? null, tblStyleId: model.tblStyleId ?? null,
tblLook: model.tableLook ?? null,
tblLookEdited: false,
bidiVisual: model.bidiVisual ?? false, bidiVisual: model.bidiVisual ?? false,
originalStructure: null, originalStructure: null,
originalFormatting: null, originalFormatting: null,
@@ -675,6 +706,8 @@ export function tableModelToPmNode(
attrs: { attrs: {
heightTwips: model.rowHeightsTwips?.[rowIndex] ?? null, heightTwips: model.rowHeightsTwips?.[rowIndex] ?? null,
heightRule: model.rowHeightRules?.[rowIndex] ?? null, heightRule: model.rowHeightRules?.[rowIndex] ?? null,
repeatHeader: model.repeatHeaderRows?.[rowIndex] ?? false,
repeatHeaderEdited: false,
rawTrPr: model.rawTrPrs?.[rowIndex] ?? null, rawTrPr: model.rawTrPrs?.[rowIndex] ?? null,
rowRevision: model.rowRevisions?.[rowIndex] ?? null, rowRevision: model.rowRevisions?.[rowIndex] ?? null,
}, },
@@ -691,6 +724,7 @@ export function tableModelToPmNode(
rowspan, rowspan,
clipHeightTwips: cellClipTwips(model, rowIndex, cell, rowspan), clipHeightTwips: cellClipTwips(model, rowIndex, cell, rowspan),
colwidth: widthPx ? widthPx.slice(start, start + colspan) : null, colwidth: widthPx ? widthPx.slice(start, start + colspan) : null,
gridGap: cell.gridGap ?? false,
cellMar: cell.cellMarTwips ?? null, cellMar: cell.cellMarTwips ?? null,
textDirection: cell.textDirection ?? null, textDirection: cell.textDirection ?? null,
fill: cell.fill ?? null, fill: cell.fill ?? null,
@@ -777,10 +811,27 @@ function cellContentNodes(cell: TableCell): PmNode[] {
export function tableStructureSignature(table: PmNode): string { export function tableStructureSignature(table: PmNode): string {
return JSON.stringify({ return JSON.stringify({
widths: table.attrs?.colWidthsPct ?? null, widths: table.attrs?.colWidthsPct ?? null,
widthPx: table.attrs?.widthPx ?? null,
widthPct: table.attrs?.widthPct ?? null,
autoFit: table.attrs?.tblAutoFit ?? null,
autoFitEdited: table.attrs?.tblAutoFitEdited ?? false,
cellMar: table.attrs?.cellMar ?? null,
cellMarEdited: table.attrs?.cellMarEdited ?? false,
tblStyle: table.attrs?.tblStyleId ?? null, tblStyle: table.attrs?.tblStyleId ?? null,
tblAlign: table.attrs?.tblAlign ?? null, tblAlign: table.attrs?.tblAlign ?? null,
tblFloat: table.attrs?.tblFloat ?? null,
tblFloatXTwips: table.attrs?.tblFloatXTwips ?? null,
tblFloatYTwips: table.attrs?.tblFloatYTwips ?? null,
tblFloatHorzAnchor: table.attrs?.tblFloatHorzAnchor ?? null,
tblFloatVertAnchor: table.attrs?.tblFloatVertAnchor ?? null,
tblFloatDistance: table.attrs?.tblFloatDistance ?? null,
tblFloatEdited: table.attrs?.tblFloatEdited ?? false,
tblLook: table.attrs?.tblLook ?? null,
tblLookEdited: table.attrs?.tblLookEdited ?? false,
rows: (table.content ?? []).map((row) => [ rows: (table.content ?? []).map((row) => [
row.attrs?.heightTwips ?? null, row.attrs?.heightTwips ?? null,
row.attrs?.repeatHeader ?? false,
row.attrs?.repeatHeaderEdited ?? false,
// accepting/rejecting revisions strips records from trPr/tcPr: include them in the signature to trigger regeneration (works for empty rows too) // accepting/rejecting revisions strips records from trPr/tcPr: include them in the signature to trigger regeneration (works for empty rows too)
row.attrs?.rawTrPr ?? null, row.attrs?.rawTrPr ?? null,
row.attrs?.rowRevision ?? null, row.attrs?.rowRevision ?? null,
@@ -855,6 +906,7 @@ export function pmTableToModel(table: PmNode): TableModel {
const rowHeightsTwips: Array<number | null> = [] const rowHeightsTwips: Array<number | null> = []
const rowHeightRules: NonNullable<TableModel['rowHeightRules']> = [] const rowHeightRules: NonNullable<TableModel['rowHeightRules']> = []
const repeatHeaderRows: Array<boolean | null> = []
const rawTrPrs: Array<string | null> = [] const rawTrPrs: Array<string | null> = []
const rowRevisions: TableModel['rowRevisions'] = [] const rowRevisions: TableModel['rowRevisions'] = []
for (const rowNode of table.content ?? []) { for (const rowNode of table.content ?? []) {
@@ -862,6 +914,11 @@ export function pmTableToModel(table: PmNode): TableModel {
rowHeightRules.push( rowHeightRules.push(
(rowNode.attrs?.heightRule as NonNullable<TableModel['rowHeightRules']>[number]) ?? null, (rowNode.attrs?.heightRule as NonNullable<TableModel['rowHeightRules']>[number]) ?? null,
) )
repeatHeaderRows.push(
rowNode.attrs?.repeatHeaderEdited || table.attrs?.docxIndex == null
? !!rowNode.attrs?.repeatHeader
: null,
)
rawTrPrs.push((rowNode.attrs?.rawTrPr as string | null) ?? null) rawTrPrs.push((rowNode.attrs?.rawTrPr as string | null) ?? null)
rowRevisions.push( rowRevisions.push(
(rowNode.attrs?.rowRevision as NonNullable<TableModel['rowRevisions']>[number]) ?? null, (rowNode.attrs?.rowRevision as NonNullable<TableModel['rowRevisions']>[number]) ?? null,
@@ -895,6 +952,7 @@ export function pmTableToModel(table: PmNode): TableModel {
vAlign: (cellNode.attrs?.vAlign as TableCell['vAlign'] | null) ?? undefined, vAlign: (cellNode.attrs?.vAlign as TableCell['vAlign'] | null) ?? undefined,
borders: (cellNode.attrs?.borders as TableCell['borders'] | null) ?? undefined, borders: (cellNode.attrs?.borders as TableCell['borders'] | null) ?? undefined,
rawTcPr: (cellNode.attrs?.rawTcPr as string | null) ?? undefined, rawTcPr: (cellNode.attrs?.rawTcPr as string | null) ?? undefined,
gridGap: cellNode.attrs?.gridGap ? true : undefined,
} }
const cellParas = (cellNode.content ?? []).filter( const cellParas = (cellNode.content ?? []).filter(
(n) => n.type === 'docParagraph' || n.type === 'docListItem', (n) => n.type === 'docParagraph' || n.type === 'docListItem',
@@ -972,11 +1030,56 @@ export function pmTableToModel(table: PmNode): TableModel {
colWidthsPct = Array.from({ length: maximumColumns }, () => 100 / maximumColumns) colWidthsPct = Array.from({ length: maximumColumns }, () => 100 / maximumColumns)
} }
const tblStyleAttr = table.attrs?.tblStyleId as string | null | undefined const tblStyleAttr = table.attrs?.tblStyleId as string | null | undefined
const isNew = table.attrs?.docxIndex == null
const tablePropsEdited = (name: string): boolean => isNew || table.attrs?.[name] === true
const visibleFloat =
table.attrs?.tblFloat === 'left' || table.attrs?.tblFloat === 'right'
? (table.attrs.tblFloat as 'left' | 'right')
: null
const suppressedFloat =
table.attrs?.tblFloatSuppressed &&
(table.attrs?.tblFloatSource === 'left' || table.attrs?.tblFloatSource === 'right')
? (table.attrs.tblFloatSource as 'left' | 'right')
: null
const floatSide = visibleFloat ?? suppressedFloat
const floatPosition =
floatSide && (table.attrs?.tblFloatXTwips != null || table.attrs?.tblFloatYTwips != null)
? {
xTwips: Number(table.attrs?.tblFloatXTwips) || 0,
yTwips: Number(table.attrs?.tblFloatYTwips) || 0,
...(table.attrs?.tblFloatHorzAnchor
? {
horzAnchor: table.attrs.tblFloatHorzAnchor as NonNullable<
TableModel['floatPos']
>['horzAnchor'],
}
: {}),
...(table.attrs?.tblFloatVertAnchor
? {
vertAnchor: table.attrs.tblFloatVertAnchor as NonNullable<
TableModel['floatPos']
>['vertAnchor'],
}
: {}),
...(table.attrs?.tblFloatDistance
? {
distanceTwips: table.attrs.tblFloatDistance as NonNullable<
TableModel['floatPos']
>['distanceTwips'],
}
: {}),
}
: undefined
return { return {
rows, rows,
...(colWidthsPct ? { colWidthsPct } : {}), ...(colWidthsPct ? { colWidthsPct } : {}),
...(colWidthsTwips ? { colWidthsTwips } : {}), ...(colWidthsTwips ? { colWidthsTwips } : {}),
...(table.attrs?.cellSpacingTwips
? { cellSpacingTwips: Number(table.attrs.cellSpacingTwips) }
: {}),
...(table.attrs?.tblFill ? { fill: String(table.attrs.tblFill) } : {}),
...(rowHeightsTwips.some((h) => h !== null) ? { rowHeightsTwips, rowHeightRules } : {}), ...(rowHeightsTwips.some((h) => h !== null) ? { rowHeightsTwips, rowHeightRules } : {}),
...(repeatHeaderRows.some((value) => value !== null) ? { repeatHeaderRows } : {}),
...(rawTrPrs.some((r) => r !== null) ? { rawTrPrs } : {}), ...(rawTrPrs.some((r) => r !== null) ? { rawTrPrs } : {}),
...(rowRevisions.some((revision) => revision !== null) ? { rowRevisions } : {}), ...(rowRevisions.some((revision) => revision !== null) ? { rowRevisions } : {}),
// null (cleared) → '' removes explicitly; undefined leaves it alone // null (cleared) → '' removes explicitly; undefined leaves it alone
@@ -984,6 +1087,18 @@ export function pmTableToModel(table: PmNode): TableModel {
// explicit only when set ('left' = remove w:jc); null leaves the original // explicit only when set ('left' = remove w:jc); null leaves the original
// tblPr untouched so unmapped w:jc values (e.g. 'start') survive rebuilds // tblPr untouched so unmapped w:jc values (e.g. 'start') survive rebuilds
...(table.attrs?.tblAlign ? { align: table.attrs.tblAlign as TableModel['align'] } : {}), ...(table.attrs?.tblAlign ? { align: table.attrs.tblAlign as TableModel['align'] } : {}),
...(tablePropsEdited('tblAutoFitEdited')
? { autoFit: table.attrs?.tblAutoFit as NonNullable<TableModel['autoFit']> }
: {}),
...(tablePropsEdited('cellMarEdited') && table.attrs?.cellMar
? { cellMarTwips: table.attrs.cellMar as NonNullable<TableModel['cellMarTwips']> }
: {}),
...(tablePropsEdited('tblFloatEdited')
? { floatSide, ...(floatPosition ? { floatPos: floatPosition } : {}) }
: {}),
...(tablePropsEdited('tblLookEdited') && table.attrs?.tblLook
? { tableLook: table.attrs.tblLook as NonNullable<TableModel['tableLook']> }
: {}),
} }
} }
@@ -1044,6 +1159,10 @@ export function runsToInline(runs: Run[]): PmNode[] {
wrap: run.image.wrap ?? null, wrap: run.image.wrap ?? null,
offsetXEmu: run.image.offsetXEmu ?? null, offsetXEmu: run.image.offsetXEmu ?? null,
offsetYEmu: run.image.offsetYEmu ?? null, offsetYEmu: run.image.offsetYEmu ?? null,
wrapDistTopEmu: run.image.wrapDistTopEmu ?? null,
wrapDistBottomEmu: run.image.wrapDistBottomEmu ?? null,
wrapDistLeftEmu: run.image.wrapDistLeftEmu ?? null,
wrapDistRightEmu: run.image.wrapDistRightEmu ?? null,
border: run.image.border ?? null, border: run.image.border ?? null,
lineCenterV: run.image.lineCenterV ?? false, lineCenterV: run.image.lineCenterV ?? false,
}, },
@@ -1109,6 +1228,8 @@ function runMarks(run: Run): PmMark[] {
run.shading || run.shading ||
run.vertAlign || run.vertAlign ||
run.em || run.em ||
run.bold === false ||
run.italic === false ||
run.caps || run.caps ||
run.cs || run.cs ||
run.styleId || run.styleId ||
@@ -1130,6 +1251,8 @@ function runMarks(run: Run): PmMark[] {
shading: run.shading ?? null, shading: run.shading ?? null,
vertAlign: run.vertAlign ?? null, vertAlign: run.vertAlign ?? null,
em: run.em ?? null, em: run.em ?? null,
boldOff: run.bold === false || null,
italicOff: run.italic === false || null,
caps: run.caps ?? null, caps: run.caps ?? null,
cs: run.cs ?? null, cs: run.cs ?? null,
styleId: run.styleId ?? null, styleId: run.styleId ?? null,
@@ -1876,6 +1999,12 @@ function imagePatchOf(node: PmNode, original: Block): ImageBlockPatch | null {
return Object.keys(patch).length > 0 ? patch : null return Object.keys(patch).length > 0 ? patch : null
} }
/** gridGap placeholders have no w:tc in the original XML: drop them so the
* patch grid's indexes line up with document-order w:tc segments */
function patchableCells(row: TableCell[] | undefined): TableCell[] {
return (row ?? []).filter((cell) => !cell.gridGap)
}
/** per-cell text changes on an original table block; null when untouched */ /** per-cell text changes on an original table block; null when untouched */
function tableTextsPatch(node: PmNode, original: Block): (string[] | null)[][] | null { function tableTextsPatch(node: PmNode, original: Block): (string[] | null)[][] | null {
if (original.type !== 'table' || node.attrs?.blockType !== 'table') return null if (original.type !== 'table' || node.attrs?.blockType !== 'table') return null
@@ -1883,15 +2012,16 @@ function tableTextsPatch(node: PmNode, original: Block): (string[] | null)[][] |
const orig = original.table const orig = original.table
if (!current || !orig) return null if (!current || !orig) return null
let changed = false let changed = false
const texts = current.rows.map((row, r) => const texts = current.rows.map((row, r) => {
row.map((cell, c) => { const origRow = patchableCells(orig.rows[r])
const originalCell = orig.rows[r]?.[c] return patchableCells(row).map((cell, c) => {
const originalCell = origRow[c]
if (!originalCell) return null if (!originalCell) return null
if (cell.paras.join('\n') === originalCell.paras.join('\n')) return null if (cell.paras.join('\n') === originalCell.paras.join('\n')) return null
changed = true changed = true
return cell.paras return cell.paras
}), })
) })
return changed ? texts : null return changed ? texts : null
} }
@@ -1901,9 +2031,10 @@ function tableTextsPatchFromModel(
): (CellTextsPatch | null)[][] | null { ): (CellTextsPatch | null)[][] | null {
if (original.type !== 'table' || !original.table) return null if (original.type !== 'table' || !original.table) return null
let changed = false let changed = false
const texts = current.rows.map((row, r) => const texts = current.rows.map((row, r) => {
row.map((cell, c): CellTextsPatch | null => { const origRow = patchableCells(original.table!.rows[r])
const originalCell = original.table!.rows[r]?.[c] return patchableCells(row).map((cell, c): CellTextsPatch | null => {
const originalCell = origRow[c]
if (!originalCell) return null if (!originalCell) return null
// nested tables: diff cell texts per table; changes go through the recursive surgical patch // nested tables: diff cell texts per table; changes go through the recursive surgical patch
if (cell.nestedTables?.length && originalCell.nestedTables?.length) { if (cell.nestedTables?.length && originalCell.nestedTables?.length) {
@@ -1922,8 +2053,8 @@ function tableTextsPatchFromModel(
if (cell.paras.join('\n') === originalCell.paras.join('\n')) return null if (cell.paras.join('\n') === originalCell.paras.join('\n')) return null
changed = true changed = true
return cell.paras return cell.paras
}), })
) })
return changed ? texts : null return changed ? texts : null
} }
@@ -1931,14 +2062,15 @@ function tableTextsPatchFromModel(
function nestedTextsDiff(current: TableModel, original: TableModel): (string[] | null)[][] | null { function nestedTextsDiff(current: TableModel, original: TableModel): (string[] | null)[][] | null {
if (current.rows.length !== original.rows.length) return null if (current.rows.length !== original.rows.length) return null
let changed = false let changed = false
const grid = current.rows.map((row, r) => const grid = current.rows.map((row, r) => {
row.map((cell, c) => { const origRow = patchableCells(original.rows[r])
const originalCell = original.rows[r]?.[c] return patchableCells(row).map((cell, c) => {
const originalCell = origRow[c]
if (!originalCell || cell.paras.join('\n') === originalCell.paras.join('\n')) return null if (!originalCell || cell.paras.join('\n') === originalCell.paras.join('\n')) return null
changed = true changed = true
return cell.paras return cell.paras
}), })
) })
return changed ? grid : null return changed ? grid : null
} }
+484 -47
View File
@@ -459,11 +459,12 @@ function blockAttrs(
} else if (node.attrs.emptyRunSize || node.attrs.emptyRunFont) { } else if (node.attrs.emptyRunSize || node.attrs.emptyRunFont) {
// Word sizes an empty line by the paragraph mark / empty run, both directions // Word sizes an empty line by the paragraph mark / empty run, both directions
if (node.attrs.emptyRunSize) styles.push(`font-size:${Number(node.attrs.emptyRunSize) / 2}pt`) if (node.attrs.emptyRunSize) styles.push(`font-size:${Number(node.attrs.emptyRunSize) / 2}pt`)
// CJK mark faces stay on the document factor: table cells deliberately keep // the mark face sizes the empty line, CJK included (empty-line probe
// the Latin factor for empty lines, and KR/JP line height is calibrated // 2026-08-25: SimSun 1.30 / DengXian 1.36 / Malgun 1.74 / Calibri 1.24 —
// doc-wide — scoping to Western faces fixes their hairline surplus only // each face's own text factor; the earlier Western-only scoping starved
// CJK marks down to the document factor and doubled their grid rows)
const fam = node.attrs.emptyRunFont ? String(node.attrs.emptyRunFont) : null const fam = node.attrs.emptyRunFont ? String(node.attrs.emptyRunFont) : null
if (fam && !isCjkFontName(fam)) { if (fam) {
styles.push(`--doc-line-factor:${lineHeightFactor(fam)}`, `font-family:${cssFontFamily(fam)}`) styles.push(`--doc-line-factor:${lineHeightFactor(fam)}`, `font-family:${cssFontFamily(fam)}`)
} }
} }
@@ -687,6 +688,10 @@ export const DocInlineImage = Node.create({
wrap: { default: null as string | null }, wrap: { default: null as string | null },
offsetXEmu: { default: null as number | null }, offsetXEmu: { default: null as number | null },
offsetYEmu: { default: null as number | null }, offsetYEmu: { default: null as number | null },
wrapDistTopEmu: { default: null as number | null },
wrapDistBottomEmu: { default: null as number | null },
wrapDistLeftEmu: { default: null as number | null },
wrapDistRightEmu: { default: null as number | null },
/** picture outline (pic:spPr a:ln solid fill, display-only) */ /** picture outline (pic:spPr a:ln solid fill, display-only) */
border: { default: null as { color: string; widthPt: number } | null }, border: { default: null as { color: string; widthPt: number } | null },
/** positionV line/center: the picture centers on its anchor line (display only) */ /** positionV line/center: the picture centers on its anchor line (display only) */
@@ -732,6 +737,34 @@ export const DocInlineImage = Node.create({
// square/tight/through wrap → real CSS float so the surrounding text wraps; // square/tight/through wrap → real CSS float so the surrounding text wraps;
// topBottom → block line of its own // topBottom → block line of its own
if (wrap) attrs.class += ` doc-inline-img--wrap-${wrap}` if (wrap) attrs.class += ` doc-inline-img--wrap-${wrap}`
// free-position floats honor the numeric posOffset X like the block-image
// path: X measures from the column start; right floats convert it to a
// right-edge inset so the picture is not stuck flush against the margin
const tx = node.attrs.offsetXEmu != null ? Number(node.attrs.offsetXEmu) / EMU_PER_PX : null
if (tx != null && wrap) {
if (wrap.endsWith('-right') && w > 0) {
attrs.style = `${attrs.style ?? ''};margin-right:calc(100% - ${(tx + w).toFixed(1)}px);max-width:none`
} else if (wrap.endsWith('-left')) {
attrs.style = `${attrs.style ?? ''};margin-left:${tx.toFixed(1)}px;max-width:none`
}
}
if (wrap) {
const distancePx = (attr: string): number | null =>
node.attrs[attr] != null ? Number(node.attrs[attr]) / EMU_PER_PX : null
const top = distancePx('wrapDistTopEmu')
const bottom = distancePx('wrapDistBottomEmu')
const left = distancePx('wrapDistLeftEmu')
const right = distancePx('wrapDistRightEmu')
const distances = [
top != null ? `margin-top:${top.toFixed(1)}px` : '',
bottom != null ? `margin-bottom:${bottom.toFixed(1)}px` : '',
wrap.endsWith('-right') && left != null ? `margin-left:${left.toFixed(1)}px` : '',
wrap.endsWith('-left') && right != null ? `margin-right:${right.toFixed(1)}px` : '',
].filter(Boolean)
if (distances.length) {
attrs.style = `${attrs.style ?? ''};${distances.join(';')}`
}
}
// positionV line/center: lift so the picture centers on the anchor line // positionV line/center: lift so the picture centers on the anchor line
// (0.75em ≈ half a single-spaced line) instead of hanging below it // (0.75em ≈ half a single-spaced line) instead of hanging below it
if (node.attrs.lineCenterV && h > 0) { if (node.attrs.lineCenterV && h > 0) {
@@ -1499,6 +1532,8 @@ const tableCellAttrs = {
textDirection: { default: null as string | null }, textDirection: { default: null as string | null },
/** inner clip-box height (twips) when the row is hRule="exact" (computed in convert.ts) */ /** inner clip-box height (twips) when the row is hRule="exact" (computed in convert.ts) */
clipHeightTwips: { default: null as number | null }, clipHeightTwips: { default: null as number | null },
/** display placeholder for the row's w:gridBefore/w:gridAfter columns (borderless, not saved as w:tc) */
gridGap: { default: false },
colspan: { default: 1 }, colspan: { default: 1 },
rowspan: { default: 1 }, rowspan: { default: 1 },
colwidth: { default: null as number[] | null }, colwidth: { default: null as number[] | null },
@@ -1529,6 +1564,8 @@ export function borderLineCss(
function tableCellHtml(node: PmNode): Record<string, string> { function tableCellHtml(node: PmNode): Record<string, string> {
const attrs: Record<string, string> = {} const attrs: Record<string, string> = {}
// gap placeholders never save back as w:tc, so typed text would vanish — keep them inert
if (node.attrs.gridGap) attrs.contenteditable = 'false'
if (node.attrs.colspan > 1) attrs.colspan = String(node.attrs.colspan) if (node.attrs.colspan > 1) attrs.colspan = String(node.attrs.colspan)
if (node.attrs.rowspan > 1) attrs.rowspan = String(node.attrs.rowspan) if (node.attrs.rowspan > 1) attrs.rowspan = String(node.attrs.rowspan)
if (node.attrs.colwidth) attrs['data-colwidth'] = (node.attrs.colwidth as number[]).join(',') if (node.attrs.colwidth) attrs['data-colwidth'] = (node.attrs.colwidth as number[]).join(',')
@@ -1545,6 +1582,8 @@ function tableCellHtml(node: PmNode): Record<string, string> {
} }
const mar = node.attrs.cellMar as Record<string, number> | null const mar = node.attrs.cellMar as Record<string, number> | null
const styles = [ const styles = [
// gridBefore/gridAfter placeholder: bare grid space (inline border beats the --doc-b-* cell rules)
node.attrs.gridGap ? 'border:none;background:none' : '',
// vertical-text cells: tbRl = vertical right-to-left (vertical-rl), btLr = rotated 90° counterclockwise (sideways-lr) // vertical-text cells: tbRl = vertical right-to-left (vertical-rl), btLr = rotated 90° counterclockwise (sideways-lr)
node.attrs.textDirection === 'tbRl' node.attrs.textDirection === 'tbRl'
? 'writing-mode:vertical-rl' ? 'writing-mode:vertical-rl'
@@ -1656,11 +1695,30 @@ export const DocTable = Node.create({
widthPx: { default: null as number | null }, widthPx: { default: null as number | null },
widthPct: { default: null as number | null }, widthPct: { default: null as number | null },
cellMar: { default: null as Record<string, number> | null }, cellMar: { default: null as Record<string, number> | null },
/** w:tblCellSpacing (twips, half the inter-cell gap) → CSS border-spacing */
cellSpacingTwips: { default: null as number | null },
/** table shading (tblPr w:shd), hex without '#' */
tblFill: { default: null as string | null },
cellMarEdited: { default: false },
borders: { default: null as Record<string, unknown> | null }, borders: { default: null as Record<string, unknown> | null },
tblAlign: { default: null as string | null }, tblAlign: { default: null as string | null },
tblFloat: { default: null as string | null }, tblFloat: { default: null as string | null },
tblFloatSource: { default: null as string | null },
tblFloatSuppressed: { default: false },
tblFloatXTwips: { default: null as number | null },
tblFloatYTwips: { default: null as number | null },
tblFloatHorzAnchor: { default: null as string | null },
tblFloatVertAnchor: { default: null as string | null },
tblFloatDistance: { default: null as Record<string, number> | null },
/** display-only measured width used to place right AutoFit floats */
tblFloatWidthPx: { default: null as number | null },
tblFloatEdited: { default: false },
tblAutoFit: { default: 'fixed' as 'contents' | 'window' | 'fixed' },
tblAutoFitEdited: { default: false },
indentTwips: { default: null as number | null }, indentTwips: { default: null as number | null },
tblStyleId: { default: null as string | null }, tblStyleId: { default: null as string | null },
tblLook: { default: null as Record<string, boolean> | null },
tblLookEdited: { default: false },
/** SDT shell JSON when the table is a content-control member (chrome hit-testing) */ /** SDT shell JSON when the table is a content-control member (chrome hit-testing) */
sdtShell: { default: null as string | null }, sdtShell: { default: null as string | null },
/** RTL table (tblPr w:bidiVisual): columns right to left */ /** RTL table (tblPr w:bidiVisual): columns right to left */
@@ -1677,12 +1735,22 @@ export const DocTable = Node.create({
const attrs: Record<string, string> = { class: 'doc-table' } const attrs: Record<string, string> = { class: 'doc-table' }
if (node.attrs.docxIndex !== null) attrs['data-idx'] = String(node.attrs.docxIndex) if (node.attrs.docxIndex !== null) attrs['data-idx'] = String(node.attrs.docxIndex)
if (node.attrs.tblStyleId) attrs['data-tbl-style'] = String(node.attrs.tblStyleId) if (node.attrs.tblStyleId) attrs['data-tbl-style'] = String(node.attrs.tblStyleId)
const tblFloated = node.attrs.tblFloat === 'left' || node.attrs.tblFloat === 'right' const autoFit = node.attrs.tblAutoFit as 'contents' | 'window' | 'fixed'
// Imported auto-layout tables may carry a display-only expanded width from
// the fidelity pass. Keep that measured grid until the user explicitly
// chooses AutoFit Contents (the command clears widthPx).
const displayAutoFit = autoFit === 'contents' && node.attrs.widthPx ? 'fixed' : autoFit
attrs.class += ` doc-table-autofit-${displayAutoFit}`
const tblFloated =
!node.attrs.tblFloatSuppressed &&
(node.attrs.tblFloat === 'left' || node.attrs.tblFloat === 'right')
if (tblFloated) attrs.class += ` doc-table-float-${node.attrs.tblFloat}` if (tblFloated) attrs.class += ` doc-table-float-${node.attrs.tblFloat}`
if (node.attrs.bidiVisual) attrs.dir = 'rtl' if (node.attrs.bidiVisual) attrs.dir = 'rtl'
const styles: string[] = [] const styles: string[] = []
let centerMargin: string | null = null let centerMargin: string | null = null
if (node.attrs.widthPct) styles.push(`width:${Number(node.attrs.widthPct)}%`) if (displayAutoFit === 'contents') styles.push('width:auto')
else if (displayAutoFit === 'window') styles.push('width:100%')
else if (node.attrs.widthPct) styles.push(`width:${Number(node.attrs.widthPct)}%`)
// Over-wide grids may spill into the page margins like Word/LO (clamping // Over-wide grids may spill into the page margins like Word/LO (clamping
// them to the content box narrowed every column, wrapped cell text onto extra // them to the content box narrowed every column, wrapped cell text onto extra
// lines and inflated PDF-converted documents by pages), but never past the paper: // lines and inflated PDF-converted documents by pages), but never past the paper:
@@ -1709,11 +1777,39 @@ export const DocTable = Node.create({
} }
const pad = cellPadCss(node.attrs.cellMar as Record<string, number> | null) const pad = cellPadCss(node.attrs.cellMar as Record<string, number> | null)
if (pad) styles.push(`--doc-cell-pad:${pad}`) if (pad) styles.push(`--doc-cell-pad:${pad}`)
// w:tblCellSpacing: each cell contributes the value on its side, so the CSS
// gap between cells is twice it; cells render individually boxed like Word
if (node.attrs.cellSpacingTwips) {
const gapPx = ((Number(node.attrs.cellSpacingTwips) * 2) / 15).toFixed(1)
styles.push('border-collapse:separate', `border-spacing:${gapPx}px`)
}
if (node.attrs.tblFill) styles.push(`background-color:#${node.attrs.tblFill}`)
styles.push(...tableBordersCss(node.attrs.borders as TableBordersAttr | null)) styles.push(...tableBordersCss(node.attrs.borders as TableBordersAttr | null))
// w:tblpPr positioning supersedes w:jc / w:tblInd: alignment or indent // w:tblpPr positioning supersedes w:jc / w:tblInd: alignment or indent
// margins would override the float stylesheet's wrap gaps // margins would override the float stylesheet's wrap gaps
if (tblFloated) { if (tblFloated) {
// no alignment/indent margins const distance = (node.attrs.tblFloatDistance as Record<string, number> | null) ?? {}
const px = (twips: unknown): number => (Number(twips) || 0) / 15
const x = px(node.attrs.tblFloatXTwips)
const y = px(node.attrs.tblFloatYTwips)
const top = y + Math.max(0, px(distance.top))
const bottom = Math.max(0, px(distance.bottom))
const left = Math.max(0, px(distance.left))
const right = Math.max(0, px(distance.right))
if (top) styles.push(`margin-top:${top.toFixed(1)}px`)
if (bottom) styles.push(`margin-bottom:${bottom.toFixed(1)}px`)
if (node.attrs.tblFloat === 'left') {
if (x) styles.push(`margin-left:${x.toFixed(1)}px`)
if (right) styles.push(`margin-right:${right.toFixed(1)}px`)
} else {
if (left) styles.push(`margin-left:${left.toFixed(1)}px`)
const width = Number(node.attrs.widthPx) || Number(node.attrs.tblFloatWidthPx)
if (node.attrs.tblFloatXTwips != null && width > 0) {
styles.push(
`margin-right:max(0px,calc(var(--doc-content-w,100%) - ${x.toFixed(1)}px - ${width.toFixed(1)}px))`,
)
}
}
} else if (node.attrs.tblAlign === 'center') { } else if (node.attrs.tblAlign === 'center') {
if (centerMargin) styles.push(centerMargin) if (centerMargin) styles.push(centerMargin)
else styles.push('margin-left:auto', 'margin-right:auto') else styles.push('margin-left:auto', 'margin-right:auto')
@@ -1730,7 +1826,7 @@ export const DocTable = Node.create({
firstRowCols += Number(cell.attrs.colspan) || 1 firstRowCols += Number(cell.attrs.colspan) || 1
}) })
const rawPct = node.attrs.colWidthsPct as number[] | null const rawPct = node.attrs.colWidthsPct as number[] | null
if (rawPct?.length) { if (displayAutoFit !== 'contents' && rawPct?.length) {
// zero-width grid slots get a small floor, short grids pad with the average — // zero-width grid slots get a small floor, short grids pad with the average —
// dropping the whole colgroup falls back to fixed-layout even splitting, which // dropping the whole colgroup falls back to fixed-layout even splitting, which
// is always worse than an approximate grid // is always worse than an approximate grid
@@ -1762,6 +1858,8 @@ export const DocTableRow = Node.create({
return { return {
heightTwips: { default: null as number | null }, heightTwips: { default: null as number | null },
heightRule: { default: null as 'atLeast' | 'exact' | null }, heightRule: { default: null as 'atLeast' | 'exact' | null },
repeatHeader: { default: false },
repeatHeaderEdited: { default: false },
rawTrPr: { default: null as string | null }, rawTrPr: { default: null as string | null },
/** trPr w:ins/w:del row-level revision ({kind, author, ...} | null) */ /** trPr w:ins/w:del row-level revision ({kind, author, ...} | null) */
rowRevision: { default: null as Record<string, string> | null }, rowRevision: { default: null as Record<string, string> | null },
@@ -1779,6 +1877,7 @@ export const DocTableRow = Node.create({
attrs.style = `height:${((h / 1440) * 96).toFixed(1)}px` attrs.style = `height:${((h / 1440) * 96).toFixed(1)}px`
if (node.attrs.heightRule === 'exact') classes.push('row-h-exact') if (node.attrs.heightRule === 'exact') classes.push('row-h-exact')
} }
attrs['data-repeat-header'] = node.attrs.repeatHeader ? '1' : '0'
if (rev?.kind) { if (rev?.kind) {
classes.push(`row-rev-${rev.kind}`) classes.push(`row-rev-${rev.kind}`)
if (rev.author) attrs.title = rev.author if (rev.author) attrs.title = rev.author
@@ -2181,9 +2280,20 @@ export const DocProtected = Node.create({
imageCrop: { default: null as { l: number; t: number; r: number; b: number } | null }, imageCrop: { default: null as { l: number; t: number; r: number; b: number } | null },
/** fill placement (a:fillRect) fractions (negative = bleed), display-only */ /** fill placement (a:fillRect) fractions (negative = bleed), display-only */
imageFillRect: { default: null as { l: number; t: number; r: number; b: number } | null }, imageFillRect: { default: null as { l: number; t: number; r: number; b: number } | null },
imageLeadingText: { default: null as string | null },
imageLeadingFont: { default: null as string | null },
imageLeadingExplicitSpaceWidthPx: { default: null as number | null },
imageLeadingImplicitSpaceCount: { default: null as number | null },
imageParagraphIndentLeft: { default: null as number | null },
imageParagraphIndentRight: { default: null as number | null },
imageParagraphIndentFirstLine: { default: null as number | null },
/** paragraph alignment of the image (w:jc) */ /** paragraph alignment of the image (w:jc) */
imageAlign: { default: null as string | null }, imageAlign: { default: null as string | null },
imageWrap: { default: null as string | null }, imageWrap: { default: null as string | null },
imageWrapDistTopEmu: { default: null as number | null },
imageWrapDistBottomEmu: { default: null as number | null },
imageWrapDistLeftEmu: { default: null as number | null },
imageWrapDistRightEmu: { default: null as number | null },
/** /**
* Stacking rank of a floating image among overlapping anchors * Stacking rank of a floating image among overlapping anchors
* (bring-to-front / send-to-back). Written to the anchor's * (bring-to-front / send-to-back). Written to the anchor's
@@ -2196,6 +2306,8 @@ export const DocProtected = Node.create({
* or is inline. * or is inline.
*/ */
imageOffsetXEmu: { default: null as number | null }, imageOffsetXEmu: { default: null as number | null },
/** wp:anchor locked="1": keep the anchor paragraph fixed while dragging */
imageAnchorLocked: { default: false },
/** margin-relative wp:align preset (Word position gallery) */ /** margin-relative wp:align preset (Word position gallery) */
imagePosH: { default: null as string | null }, imagePosH: { default: null as string | null },
imagePosV: { default: null as string | null }, imagePosV: { default: null as string | null },
@@ -2651,11 +2763,65 @@ function protectedDomSpec(node: PmNode): DomSpec {
attrs['style'] = `text-align:${imageAlign}` attrs['style'] = `text-align:${imageAlign}`
} }
if (imageWrap) attrs.class += ` img-wrap-${String(imageWrap)}` if (imageWrap) attrs.class += ` img-wrap-${String(imageWrap)}`
const imageLeadingText = String(node.attrs.imageLeadingText ?? '')
const cjkFixedLeadingSpaces =
!imageWrap &&
/^[ ]+$/.test(imageLeadingText) &&
!!node.attrs.imageLeadingFont &&
isCjkFontName(String(node.attrs.imageLeadingFont))
// paragraph indents place the picture like its (possibly empty) first line;
// anchored pictures position from the column instead and ignore them
if (!imageWrap) {
const paragraphLayout = [
node.attrs.imageParagraphIndentLeft
? `margin-inline-start:${Number(node.attrs.imageParagraphIndentLeft) / 20}pt`
: '',
node.attrs.imageParagraphIndentRight
? `margin-inline-end:${Number(node.attrs.imageParagraphIndentRight) / 20}pt`
: '',
!cjkFixedLeadingSpaces && node.attrs.imageParagraphIndentFirstLine
? `text-indent:${Number(node.attrs.imageParagraphIndentFirstLine) / 20}pt`
: '',
].filter(Boolean)
if (paragraphLayout.length) {
attrs.style = `${attrs.style ? `${attrs.style};` : ''}${paragraphLayout.join(';')}`
}
}
const imageLeadingStyle = [
node.attrs.imageLeadingFont
? `font-family:${cssFontFamily(String(node.attrs.imageLeadingFont))}`
: '',
]
.filter(Boolean)
.join(';')
const imageLeadingSpecs: DomSpec[] =
imageLeadingText && !cjkFixedLeadingSpaces
? [
[
'span',
{
class: 'doc-image-leading-space',
...(imageLeadingStyle ? { style: imageLeadingStyle } : {}),
},
imageLeadingText,
],
]
: []
// no-wrap / behind-text anchors leave the flow like floating textboxes: // no-wrap / behind-text anchors leave the flow like floating textboxes:
// zero-height wrapper (doc-img-float), absolutely positioned inner wrap // zero-height wrapper (doc-img-float), absolutely positioned inner wrap
// (Word overlays them on the text instead of reserving a line) // (Word overlays them on the text instead of reserving a line)
let imgWrapTransform = '' const explicitSpaceWidthPx = Number(node.attrs.imageLeadingExplicitSpaceWidthPx ?? 0)
const implicitSpaceCount = Number(
node.attrs.imageLeadingImplicitSpaceCount ??
(explicitSpaceWidthPx > 0 ? 0 : imageLeadingText.length),
)
let imgWrapTransform = cjkFixedLeadingSpaces
? `margin-left:calc(${Number(node.attrs.imageParagraphIndentFirstLine ?? 0) / 15 + explicitSpaceWidthPx}px + ${implicitSpaceCount * 0.5}em)`
: ''
let imgFloatPos = '' let imgFloatPos = ''
// the vertical posOffset margin must not be clobbered by a wrap-distance
// margin-top below (distT is clearance, the offset is position — position wins)
let hasOffsetTopMargin = false
if (imageWrap === 'front' || imageWrap === 'behind') { if (imageWrap === 'front' || imageWrap === 'behind') {
attrs.class += ' doc-img-float' attrs.class += ' doc-img-float'
// z-index bands keep behind-text pictures under the body text and // z-index bands keep behind-text pictures under the body text and
@@ -2694,7 +2860,10 @@ function protectedDomSpec(node: PmNode): DomSpec {
// a negative offset lifts via the inner wrap so the flow band keeps // a negative offset lifts via the inner wrap so the flow band keeps
// its height (Word: logo above its anchor line must not push) // its height (Word: logo above its anchor line must not push)
if (ty < 0) imgWrapTransform = `margin-top:${ty.toFixed(1)}px` if (ty < 0) imgWrapTransform = `margin-top:${ty.toFixed(1)}px`
else if (ty > 0) wrapperCss.push(`margin-top:${ty.toFixed(1)}px`) else if (ty > 0) {
wrapperCss.push(`margin-top:${ty.toFixed(1)}px`)
hasOffsetTopMargin = true
}
} }
if (node.attrs.imageOffsetXEmu != null) { if (node.attrs.imageOffsetXEmu != null) {
const tx = Number(node.attrs.imageOffsetXEmu) / EMU_PER_PX const tx = Number(node.attrs.imageOffsetXEmu) / EMU_PER_PX
@@ -2717,6 +2886,30 @@ function protectedDomSpec(node: PmNode): DomSpec {
attrs['style'] = `${attrs['style'] ? `${attrs['style']};` : ''}${wrapperCss.join(';')}` attrs['style'] = `${attrs['style'] ? `${attrs['style']};` : ''}${wrapperCss.join(';')}`
} }
} }
// wrap distances apply to in-flow wraps only: wrapNone (front/behind)
// anchors ignore them in Word, and margins on the zero-height wrapper
// would displace the following flow content
if (imageWrap && imageWrap !== 'front' && imageWrap !== 'behind') {
const distancePx = (attr: string): number | null =>
node.attrs[attr] != null ? Number(node.attrs[attr]) / EMU_PER_PX : null
const top = distancePx('imageWrapDistTopEmu')
const bottom = distancePx('imageWrapDistBottomEmu')
const left = distancePx('imageWrapDistLeftEmu')
const right = distancePx('imageWrapDistRightEmu')
const distances = [
!hasOffsetTopMargin && top != null ? `margin-top:${top.toFixed(1)}px` : '',
bottom != null ? `margin-bottom:${bottom.toFixed(1)}px` : '',
String(imageWrap).endsWith('-right') && left != null
? `margin-left:${left.toFixed(1)}px`
: '',
String(imageWrap).endsWith('-left') && right != null
? `margin-right:${right.toFixed(1)}px`
: '',
].filter(Boolean)
if (distances.length) {
attrs.style = `${attrs.style ? `${attrs.style};` : ''}${distances.join(';')}`
}
}
const imgAttrs: Record<string, string> = { const imgAttrs: Record<string, string> = {
src: String(imageDataUrl), src: String(imageDataUrl),
class: 'doc-protected-img', class: 'doc-protected-img',
@@ -2778,14 +2971,23 @@ function protectedDomSpec(node: PmNode): DomSpec {
'div', 'div',
attrs, attrs,
moveHandleSpec(t('editorMoveImage')), moveHandleSpec(t('editorMoveImage')),
...(imageWrap ? [imageAnchorMarkerSpec()] : []),
...imageLeadingSpecs,
[ [
'span', 'span',
{ {
class: 'doc-img-wrap doc-img-crop', class: 'doc-img-wrap doc-img-crop',
style: `position:${imgFloatPos ? `absolute;${imgFloatPos}` : 'relative'};display:inline-block;overflow:hidden;width:${W}px;height:${H}px${wrapXf.length ? `;transform:${wrapXf.join(' ')}` : ''}${imgWrapTransform && !imgWrapTransform.startsWith('transform:') ? `;${imgWrapTransform}` : ''}${borderCss ? `;${borderCss}` : ''}`, style: `position:${imgFloatPos ? `absolute;${imgFloatPos}` : 'relative'};display:inline-block;width:${W}px;height:${H}px${wrapXf.length ? `;transform:${wrapXf.join(' ')}` : ''}${imgWrapTransform && !imgWrapTransform.startsWith('transform:') ? `;${imgWrapTransform}` : ''}${borderCss ? `;${borderCss}` : ''}`,
}, },
['img', imgAttrs], [
['span', { class: 'img-resize-handle' }], 'span',
{
class: 'doc-img-crop-viewport',
style: 'position:absolute;inset:0;overflow:hidden',
},
['img', imgAttrs],
],
...imageSelectionControlsSpec(),
], ],
] ]
} }
@@ -2800,6 +3002,8 @@ function protectedDomSpec(node: PmNode): DomSpec {
'div', 'div',
attrs, attrs,
moveHandleSpec(t('editorMoveImage')), moveHandleSpec(t('editorMoveImage')),
...(imageWrap ? [imageAnchorMarkerSpec()] : []),
...imageLeadingSpecs,
[ [
'span', 'span',
{ {
@@ -2811,7 +3015,7 @@ function protectedDomSpec(node: PmNode): DomSpec {
: {}), : {}),
}, },
['img', imgAttrs], ['img', imgAttrs],
['span', { class: 'img-resize-handle' }], ...imageSelectionControlsSpec(),
], ],
] ]
} }
@@ -2941,6 +3145,44 @@ function moveHandleSpec(label: string): DomSpec {
] ]
} }
type ImageResizeHandle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w'
const IMAGE_RESIZE_HANDLES: readonly ImageResizeHandle[] = [
'nw',
'n',
'ne',
'e',
'se',
's',
'sw',
'w',
]
function imageSelectionControlsSpec(): DomSpec[] {
return IMAGE_RESIZE_HANDLES.map((direction): DomSpec => [
'span',
{
class: `img-resize-handle img-resize-handle-${direction}`,
'data-resize-handle': direction,
contenteditable: 'false',
draggable: 'false',
'aria-hidden': 'true',
},
])
}
function imageAnchorMarkerSpec(): DomSpec {
return [
'span',
{
class: 'doc-image-anchor-marker',
contenteditable: 'false',
'aria-hidden': 'true',
},
'⚓',
]
}
export function buildProtectedDom(node: PmNode): HTMLElement { export function buildProtectedDom(node: PmNode): HTMLElement {
const { dom } = DOMSerializer.renderSpec(document, protectedDomSpec(node) as never) const { dom } = DOMSerializer.renderSpec(document, protectedDomSpec(node) as never)
const el = dom as HTMLElement const el = dom as HTMLElement
@@ -3599,11 +3841,15 @@ function imageResizePlugin(): Plugin {
window.addEventListener('mouseup', onUp) window.addEventListener('mouseup', onUp)
return true return true
} }
if (!target.classList?.contains('img-resize-handle')) return false const handle = target.closest('.img-resize-handle') as HTMLElement | null
const wrapper = target.closest('.doc-protected') as HTMLElement | null const direction = handle?.dataset.resizeHandle as ImageResizeHandle | undefined
if (!handle || !direction || !IMAGE_RESIZE_HANDLES.includes(direction)) return false
const wrapper = handle.closest('.doc-protected') as HTMLElement | null
const imageBox = handle.closest('.doc-img-wrap') as HTMLElement | null
const img = wrapper?.querySelector('img.doc-protected-img') as HTMLImageElement | null const img = wrapper?.querySelector('img.doc-protected-img') as HTMLImageElement | null
if (!wrapper || !img) return false if (!wrapper || !imageBox || !img) return false
event.preventDefault() event.preventDefault()
event.stopPropagation()
let pos = -1 let pos = -1
view.state.doc.descendants((node, p) => { view.state.doc.descendants((node, p) => {
@@ -3614,42 +3860,126 @@ function imageResizePlugin(): Plugin {
if (pos === -1) return false if (pos === -1) return false
view.dispatch(view.state.tr.setSelection(NodeSelection.create(view.state.doc, pos))) view.dispatch(view.state.tr.setSelection(NodeSelection.create(view.state.doc, pos)))
view.focus()
// CSS `zoom` scales client coordinates; divide it back out // CSS `zoom` scales client coordinates; divide it back out
const zoomEl = document.querySelector('.doc-zoom') as HTMLElement | null const zoomEl = document.querySelector('.doc-zoom') as HTMLElement | null
const zoom = zoomEl ? parseFloat(getComputedStyle(zoomEl).zoom || '1') || 1 : 1 const zoom = zoomEl ? parseFloat(getComputedStyle(zoomEl).zoom || '1') || 1 : 1
// Layout-box measurements: getBoundingClientRect would include the // Layout-box measurements: getBoundingClientRect would include the
// rotation/flip transform, swapping width/height for 90°-rotated images // rotation/flip transform, swapping width/height for 90°-rotated images
const startW = img.offsetWidth const selectedNode = view.state.doc.nodeAt(pos)
const ratio = img.offsetHeight / Math.max(1, img.offsetWidth) const modelW = Number(selectedNode?.attrs.imageWidthPx)
const priorStyle = img.getAttribute('style') const modelH = Number(selectedNode?.attrs.imageHeightPx)
const startW = modelW > 0 ? modelW : imageBox.offsetWidth || img.offsetWidth
const startH = modelH > 0 ? modelH : imageBox.offsetHeight || img.offsetHeight
if (!(startW > 0) || !(startH > 0)) return false
const priorBoxStyle = imageBox.getAttribute('style')
const priorImgStyle = img.getAttribute('style')
const cropped = imageBox.classList.contains('doc-img-crop')
const startImgW = parseFloat(img.style.width) || img.offsetWidth || startW
const startImgH = parseFloat(img.style.height) || img.offsetHeight || startH
const startImgLeft = parseFloat(img.style.left) || 0
const startImgTop = parseFloat(img.style.top) || 0
const pxLeft = /^-?\d+(?:\.\d+)?px$/.test(imageBox.style.left)
? parseFloat(imageBox.style.left)
: null
const pxTop = /^-?\d+(?:\.\d+)?px$/.test(imageBox.style.top)
? parseFloat(imageBox.style.top)
: null
const shiftsInFlow = imageBox.style.position !== 'absolute'
const startX = event.clientX const startX = event.clientX
const startY = event.clientY
const west = direction.includes('w')
const east = direction.includes('e')
const north = direction.includes('n')
const south = direction.includes('s')
const widthAt = (e: MouseEvent) => Math.max(24, startW + (e.clientX - startX) / zoom) const geometryAt = (e: MouseEvent) => {
const dx = (e.clientX - startX) / zoom
const dy = (e.clientY - startY) / zoom
let w = startW
let h = startH
if ((west || east) && (north || south)) {
// Project the pointer onto the aspect-ratio diagonal. Corner
// handles keep picture proportions, matching Word's default.
const sx = west ? -1 : 1
const sy = north ? -1 : 1
const delta =
(dx * sx * startW + dy * sy * startH) /
Math.max(1, startW * startW + startH * startH)
const minScale = Math.max(24 / startW, 24 / startH)
const scale = Math.max(minScale, 1 + delta)
w = startW * scale
h = startH * scale
} else if (west || east) {
w = Math.max(24, startW + (west ? -dx : dx))
} else if (north || south) {
h = Math.max(24, startH + (north ? -dy : dy))
}
return {
w,
h,
shiftX: west ? startW - w : 0,
shiftY: north ? startH - h : 0,
}
}
const restorePreview = () => {
if (priorBoxStyle === null) imageBox.removeAttribute('style')
else imageBox.setAttribute('style', priorBoxStyle)
if (priorImgStyle === null) img.removeAttribute('style')
else img.setAttribute('style', priorImgStyle)
}
const onMove = (e: MouseEvent) => { const onMove = (e: MouseEvent) => {
const w = widthAt(e) const { w, h, shiftX, shiftY } = geometryAt(e)
img.style.width = `${w}px` imageBox.style.width = `${w}px`
img.style.height = `${w * ratio}px` imageBox.style.height = `${h}px`
if (pxLeft !== null) imageBox.style.left = `${pxLeft + shiftX}px`
else if (west && shiftsInFlow) imageBox.style.left = `${shiftX}px`
if (pxTop !== null) imageBox.style.top = `${pxTop + shiftY}px`
else if (north && shiftsInFlow) imageBox.style.top = `${shiftY}px`
if (cropped) {
const sx = w / startW
const sy = h / startH
img.style.left = `${startImgLeft * sx}px`
img.style.top = `${startImgTop * sy}px`
img.style.width = `${startImgW * sx}px`
img.style.height = `${startImgH * sy}px`
} else {
img.style.width = `${w}px`
img.style.height = `${h}px`
}
} }
const onUp = (e: MouseEvent) => { const onUp = (e: MouseEvent) => {
window.removeEventListener('mousemove', onMove) window.removeEventListener('mousemove', onMove)
window.removeEventListener('mouseup', onUp) window.removeEventListener('mouseup', onUp)
// A plain click on the handle must not rewrite the stored size // A plain click on the handle must not rewrite the stored size
if (Math.abs(e.clientX - startX) < 2) { if (Math.abs(e.clientX - startX) < 2 && Math.abs(e.clientY - startY) < 2) {
if (priorStyle === null) img.removeAttribute('style') restorePreview()
else img.setAttribute('style', priorStyle)
return return
} }
const w = Math.round(widthAt(e))
const node = view.state.doc.nodeAt(pos) const node = view.state.doc.nodeAt(pos)
if (!node) return if (!node) {
view.dispatch( restorePreview()
view.state.tr.setNodeMarkup(pos, undefined, { return
...node.attrs, }
imageWidthPx: w, const geometry = geometryAt(e)
imageHeightPx: Math.round(w * ratio), const w = Math.round(geometry.w)
}), const h = Math.round(geometry.h)
) const attrs: Record<string, unknown> = {
...node.attrs,
imageWidthPx: w,
imageHeightPx: h,
}
if (west && node.attrs.imageOffsetXEmu != null) {
attrs.imageOffsetXEmu =
Number(node.attrs.imageOffsetXEmu) + Math.round((startW - w) * EMU_PER_PX)
}
if (north && node.attrs.imageOffsetYEmu != null) {
attrs.imageOffsetYEmu =
Number(node.attrs.imageOffsetYEmu) + Math.round((startH - h) * EMU_PER_PX)
}
view.dispatch(view.state.tr.setNodeMarkup(pos, undefined, attrs))
} }
window.addEventListener('mousemove', onMove) window.addEventListener('mousemove', onMove)
window.addEventListener('mouseup', onUp) window.addEventListener('mouseup', onUp)
@@ -3701,6 +4031,51 @@ export function findFloatImageAt(x: number, y: number): HTMLElement | null {
return null return null
} }
interface ImageParagraphAnchor {
pos: number
node: PmNode
dom: HTMLElement
rect: DOMRect
}
const IMAGE_ANCHOR_NODE_TYPES = new Set(['docParagraph', 'docHeading', 'docListItem'])
function imageParagraphAnchors(view: EditorView, imagePos: number): ImageParagraphAnchor[] {
const anchors: ImageParagraphAnchor[] = []
view.state.doc.forEach((node, pos) => {
if (pos === imagePos || !IMAGE_ANCHOR_NODE_TYPES.has(node.type.name)) return
const dom = view.nodeDOM(pos)
if (!(dom instanceof HTMLElement)) return
anchors.push({ pos, node, dom, rect: dom.getBoundingClientRect() })
})
return anchors
}
function pickImageParagraphAnchor(
anchors: ImageParagraphAnchor[],
x: number,
y: number,
): ImageParagraphAnchor | null {
let best: ImageParagraphAnchor | null = null
let bestScore = Infinity
for (const anchor of anchors) {
const rect = anchor.dom.getBoundingClientRect()
anchor.rect = rect
const dy = y < rect.top ? rect.top - y : y > rect.bottom ? y - rect.bottom : 0
const dx = x < rect.left ? rect.left - x : x > rect.right ? x - rect.right : 0
// Vertical proximity determines the paragraph; horizontal proximity only
// breaks ties for multi-column lines at a similar Y.
const score = dy * 10000 + dx
// Stacked paragraphs share a bottom/top edge. At that exact boundary,
// prefer the paragraph beginning there instead of the one that just ended.
if (score < bestScore || (score === bestScore && rect.top > (best?.rect.top ?? -Infinity))) {
best = anchor
bestScore = score
}
}
return best
}
function floatingObjectDragPlugin(): Plugin { function floatingObjectDragPlugin(): Plugin {
return new Plugin({ return new Plugin({
props: { props: {
@@ -3767,6 +4142,11 @@ function floatingObjectDragPlugin(): Plugin {
// inline pictures) derive it from the rendered slot, so the drop // inline pictures) derive it from the rendered slot, so the drop
// lands exactly where the user let go instead of jumping. // lands exactly where the user let go instead of jumping.
const innerWrap = wrapper.querySelector('.doc-img-wrap') as HTMLElement | null const innerWrap = wrapper.querySelector('.doc-img-wrap') as HTMLElement | null
const startVisualRect = (innerWrap ?? wrapper).getBoundingClientRect()
const wrapperStartRect = wrapper.getBoundingClientRect()
const anchorLocked = !!node.attrs.imageAnchorLocked
const paragraphAnchors = isImage && !anchorLocked ? imageParagraphAnchors(view, pos) : []
let paragraphAnchor: ImageParagraphAnchor | null = null
const wrapMode = (node.attrs.imageWrap as string | null) ?? null const wrapMode = (node.attrs.imageWrap as string | null) ?? null
const isSideFloat = !!wrapMode && /^(?:square|tight|through)-/.test(wrapMode) const isSideFloat = !!wrapMode && /^(?:square|tight|through)-/.test(wrapMode)
const imgW = innerWrap?.offsetWidth || Number(node.attrs.imageWidthPx ?? 0) || 0 const imgW = innerWrap?.offsetWidth || Number(node.attrs.imageWidthPx ?? 0) || 0
@@ -3817,6 +4197,11 @@ function floatingObjectDragPlugin(): Plugin {
// must compose with it (prepended = applied in screen space) and the // must compose with it (prepended = applied in screen space) and the
// original must come back on mouseup, or the orientation vanishes // original must come back on mouseup, or the orientation vanishes
const baseTransform = visual?.style.transform ?? '' const baseTransform = visual?.style.transform ?? ''
const anchorMarker = isImage
? (wrapper.querySelector('.doc-image-anchor-marker') as HTMLElement | null)
: null
const anchorMarkerTransform = anchorMarker?.style.transform ?? ''
const anchorMarkerLeft = anchorMarker?.style.left ?? ''
// 3px threshold keeps plain clicks (select, first click of a // 3px threshold keeps plain clicks (select, first click of a
// double-click-to-edit) from nudging the object // double-click-to-edit) from nudging the object
@@ -3830,12 +4215,33 @@ function floatingObjectDragPlugin(): Plugin {
visual.style.transform = visual.style.transform =
`translate(${dx}px, ${dy}px)` + (baseTransform ? ` ${baseTransform}` : '') `translate(${dx}px, ${dy}px)` + (baseTransform ? ` ${baseTransform}` : '')
} }
if (isImage) {
const clientDx = e.clientX - startX
const clientDy = e.clientY - startY
paragraphAnchor = pickImageParagraphAnchor(
paragraphAnchors,
startVisualRect.left + clientDx,
startVisualRect.top + clientDy,
)
if (anchorMarker && paragraphAnchor) {
const markerY = (paragraphAnchor.rect.top - wrapperStartRect.top) / zoom
const markerX = (paragraphAnchor.rect.left - wrapperStartRect.left) / zoom - 32
anchorMarker.style.transform = `translateY(${markerY.toFixed(1)}px)`
anchorMarker.style.left = `${markerX.toFixed(1)}px`
anchorMarker.dataset.anchorTargetPos = String(paragraphAnchor.pos)
}
}
} }
const onUp = (e: MouseEvent) => { const onUp = (e: MouseEvent) => {
window.removeEventListener('mousemove', onMove) window.removeEventListener('mousemove', onMove)
window.removeEventListener('mouseup', onUp) window.removeEventListener('mouseup', onUp)
if (visual) visual.style.transform = baseTransform if (visual) visual.style.transform = baseTransform
if (anchorMarker) {
anchorMarker.style.transform = anchorMarkerTransform
anchorMarker.style.left = anchorMarkerLeft
delete anchorMarker.dataset.anchorTargetPos
}
const dx = (e.clientX - startX) / zoom const dx = (e.clientX - startX) / zoom
const dy = (e.clientY - startY) / zoom const dy = (e.clientY - startY) / zoom
@@ -3845,7 +4251,18 @@ function floatingObjectDragPlugin(): Plugin {
// Word allows negative offsets (into the page margin / above the // Word allows negative offsets (into the page margin / above the
// anchor paragraph): no clamping // anchor paragraph): no clamping
const newX = Math.round((startPxX + dx) * EMU_PER_PX) const newX = Math.round((startPxX + dx) * EMU_PER_PX)
const newY = Math.round((startPxY + dy) * EMU_PER_PX) if (isImage) {
paragraphAnchor = pickImageParagraphAnchor(
paragraphAnchors,
startVisualRect.left + (e.clientX - startX),
startVisualRect.top + (e.clientY - startY),
)
}
const newY = Math.round(
(paragraphAnchor
? (startVisualRect.top + (e.clientY - startY) - paragraphAnchor.rect.top) / zoom
: startPxY + dy) * EMU_PER_PX,
)
const currentNode = view.state.doc.nodeAt(pos) const currentNode = view.state.doc.nodeAt(pos)
if (!currentNode) return if (!currentNode) return
@@ -3872,16 +4289,36 @@ function floatingObjectDragPlugin(): Plugin {
const centerX = startPxX + dx + imgW / 2 const centerX = startPxX + dx + imgW / 2
nextWrap = `${kind}-${colW > 0 && centerX > colW / 2 ? 'right' : 'left'}` nextWrap = `${kind}-${colW > 0 && centerX > colW / 2 ? 'right' : 'left'}`
} }
view.dispatch( const attrs = {
view.state.tr.setNodeMarkup(pos, undefined, { ...currentNode.attrs,
...currentNode.attrs, imageWrap: nextWrap,
imageWrap: nextWrap, imageOffsetXEmu: newX,
imageOffsetXEmu: newX, imageOffsetYEmu: newY,
imageOffsetYEmu: newY, imagePosH: null,
imagePosH: null, imagePosV: null,
imagePosV: null, }
}), if (
) paragraphAnchor &&
!currentNode.attrs.imageAnchorLocked &&
!currentNode.attrs.blockRevision
) {
// A floating picture's top-level atom is its OOXML anchor
// paragraph. Move that atom immediately before the paragraph
// selected by the drag, preserving docxIndex as the patch
// identity and rebasing Y to the new paragraph above.
const movedNode = currentNode.type.create(
attrs,
currentNode.content,
currentNode.marks,
)
const tr = view.state.tr.delete(pos, pos + currentNode.nodeSize)
const insertPos = tr.mapping.map(paragraphAnchor.pos)
tr.insert(insertPos, movedNode)
tr.setSelection(NodeSelection.create(tr.doc, insertPos))
view.dispatch(tr)
} else {
view.dispatch(view.state.tr.setNodeMarkup(pos, undefined, attrs))
}
} }
} }
+6
View File
@@ -23,7 +23,9 @@ export function paraBorderCss(line?: { color?: string; szPt?: number }): string
function applyRunStyle(span: HTMLElement, run: Run): void { function applyRunStyle(span: HTMLElement, run: Run): void {
if (run.bold) span.style.fontWeight = '600' if (run.bold) span.style.fontWeight = '600'
else if (run.bold === false) span.style.fontWeight = 'normal'
if (run.italic) span.style.fontStyle = 'italic' if (run.italic) span.style.fontStyle = 'italic'
else if (run.italic === false) span.style.fontStyle = 'normal'
const deco = [run.underline && 'underline', run.strike && 'line-through'].filter(Boolean) const deco = [run.underline && 'underline', run.strike && 'line-through'].filter(Boolean)
if (deco.length > 0) span.style.textDecoration = deco.join(' ') if (deco.length > 0) span.style.textDecoration = deco.join(' ')
if (run.color) span.style.color = `#${run.color}` if (run.color) span.style.color = `#${run.color}`
@@ -33,6 +35,10 @@ function applyRunStyle(span: HTMLElement, run: Run): void {
if (run.font || run.fontAscii) span.style.fontFamily = cssRunFontFamily(run.fontAscii, run.font) if (run.font || run.fontAscii) span.style.fontFamily = cssRunFontFamily(run.fontAscii, run.font)
if (run.caps === 'all') span.style.textTransform = 'uppercase' if (run.caps === 'all') span.style.textTransform = 'uppercase'
else if (run.caps === 'small') span.style.fontVariantCaps = 'small-caps' else if (run.caps === 'small') span.style.fontVariantCaps = 'small-caps'
else if (run.caps === 'none') {
span.style.textTransform = 'none'
span.style.fontVariantCaps = 'normal'
}
} }
/** one tab-delimited chunk of a paragraph: the runs after the k-th tab, laid out at its stop */ /** one tab-delimited chunk of a paragraph: the runs after the k-th tab, laid out at its stop */
+11 -2
View File
@@ -400,6 +400,8 @@ const CLIPBOARD_TEXT_STYLE_TYPES: Record<string, 'string' | 'number' | 'boolean'
shading: 'string', shading: 'string',
vertAlign: 'string', vertAlign: 'string',
em: 'string', em: 'string',
boldOff: 'boolean',
italicOff: 'boolean',
caps: 'string', caps: 'string',
styleId: 'string', styleId: 'string',
} }
@@ -488,8 +490,11 @@ export const TextStyleMark = Mark.create({
vertAlign: { default: null as 'superscript' | 'subscript' | null }, vertAlign: { default: null as 'superscript' | 'subscript' | null },
// East Asian emphasis mark (w:em val); saving is kept faithful by rawRPr // East Asian emphasis mark (w:em val); saving is kept faithful by rawRPr
em: { default: null as string | null }, em: { default: null as string | null },
// w:caps ('all') / w:smallCaps ('small'); saving is kept faithful by rawRPr // run-level explicit off (w:b/w:i w:val="0"): counters style-inherited bold/italic CSS
caps: { default: null as 'all' | 'small' | null }, boldOff: { default: null as boolean | null },
italicOff: { default: null as boolean | null },
// w:caps ('all') / w:smallCaps ('small'), 'none' = explicit off; saving is kept faithful by rawRPr
caps: { default: null as 'all' | 'small' | 'none' | null },
// rtl run (w:rtl, explicit or style-inherited): save-side decode selects the Cs twins. // rtl run (w:rtl, explicit or style-inherited): save-side decode selects the Cs twins.
// Position must match runMarks' attr order (mark attrs are JSON-compared in signatures) // Position must match runMarks' attr order (mark attrs are JSON-compared in signatures)
cs: { default: null as boolean | null, rendered: false }, cs: { default: null as boolean | null, rendered: false },
@@ -553,8 +558,12 @@ export const TextStyleMark = Mark.create({
const pos = em === 'comma' || em === 'circle' ? 'over' : 'under' const pos = em === 'comma' || em === 'circle' ? 'over' : 'under'
styles.push(`text-emphasis:${shape}`, `text-emphasis-position:${pos} right`) styles.push(`text-emphasis:${shape}`, `text-emphasis-position:${pos} right`)
} }
if (mark.attrs.boldOff) styles.push('font-weight:normal')
if (mark.attrs.italicOff) styles.push('font-style:normal')
if (mark.attrs.caps === 'all') styles.push('text-transform:uppercase') if (mark.attrs.caps === 'all') styles.push('text-transform:uppercase')
else if (mark.attrs.caps === 'small') styles.push('font-variant-caps:small-caps') else if (mark.attrs.caps === 'small') styles.push('font-variant-caps:small-caps')
else if (mark.attrs.caps === 'none')
styles.push('text-transform:none', 'font-variant-caps:normal')
// the attr value carries the exact attrs for clipboard round-trip; '1' // the attr value carries the exact attrs for clipboard round-trip; '1'
// (nothing set) keeps the attribute present for CSS/selector consumers // (nothing set) keeps the attribute present for CSS/selector consumers
const clip: Record<string, unknown> = {} const clip: Record<string, unknown> = {}
+69 -13
View File
@@ -28,19 +28,32 @@ type Rect = { left: number; right: number; top: number; bottom: number }
* PM's estimate is the fallback when the DOM selection is absent or elsewhere. * PM's estimate is the fallback when the DOM selection is absent or elsewhere.
*/ */
function caretRect(view: EditorView, head: number, dir: -1 | 1): Rect { function caretRect(view: EditorView, head: number, dir: -1 | 1): Rect {
const estimate = view.coordsAtPos(head, dir === 1 ? -1 : 1)
const domSel = (view.root as Document).getSelection?.() const domSel = (view.root as Document).getSelection?.()
if (domSel?.focusNode && view.dom.contains(domSel.focusNode)) { if (domSel?.focusNode && view.dom.contains(domSel.focusNode)) {
try { // A focus parked ON the gap widget (a click near the page seam leaves it
const range = document.createRange() // there) yields the gap's own multi-hundred-px box as the "caret" rect;
range.setStart(domSel.focusNode, domSel.focusOffset) // every downstream computation then runs on garbage and the dispatched
range.collapse(true) // jump can land paragraphs — or the whole document — past the boundary
const r = range.getClientRects()[0] ?? range.getBoundingClientRect() // (alpha ledger r143). Only a text-line-sized rect off the gap counts.
if (r && r.height > 0) return r const focusEl =
} catch { domSel.focusNode.nodeType === Node.TEXT_NODE
/* element-boundary offsets: fall through to the estimate */ ? domSel.focusNode.parentElement
: (domSel.focusNode as HTMLElement)
if (!focusEl?.closest?.('.page-gap')) {
try {
const range = document.createRange()
range.setStart(domSel.focusNode, domSel.focusOffset)
range.collapse(true)
const r = range.getClientRects()[0] ?? range.getBoundingClientRect()
const estimateH = Math.max(estimate.bottom - estimate.top, 8)
if (r && r.height > 0 && r.height <= estimateH * 3) return r
} catch {
/* element-boundary offsets: fall through to the estimate */
}
} }
} }
return view.coordsAtPos(head, dir === 1 ? -1 : 1) return estimate
} }
/** /**
@@ -54,12 +67,32 @@ function caretRect(view: EditorView, head: number, dir: -1 | 1): Rect {
* just past it ourselves; everywhere else the browser's native motion (with * just past it ourselves; everywhere else the browser's native motion (with
* its goal-column memory) stays in charge. * its goal-column memory) stays in charge.
*/ */
/** consume escape valve (r147): absorbing a press twice for the SAME
* selection head means the geometry error is persistent, not a transient
* reflow race — hand the press back to native rather than freezing the key.
* One absorbed tick covers the r143 race; the next press either recomputes
* cleanly (race) or goes native (persistent). */
let lastConsumedHead = -1
const consumePress = (head: number): boolean => {
const firstTime = head !== lastConsumedHead
lastConsumedHead = head
return firstTime
}
function crossPageGap(view: EditorView, dir: -1 | 1, extend: boolean): boolean { function crossPageGap(view: EditorView, dir: -1 | 1, extend: boolean): boolean {
const { selection, doc } = view.state const { selection, doc } = view.state
if (!(selection instanceof TextSelection)) return false if (!(selection instanceof TextSelection)) return false
const caret = caretRect(view, selection.head, dir) const caret = caretRect(view, selection.head, dir)
const lineH = Math.max(caret.bottom - caret.top, 8) const lineH = Math.max(caret.bottom - caret.top, 8)
const x = (caret.left + caret.right) / 2 // Horizontal comes from the POSITION estimate, not the DOM rect: under key
// repeat the DOM selection rect can be read mid-reflow and report a stale x
// at the page margin — every hit-test below then probes the wrong column,
// the band test passes vacuously and the landing resolves garbage (alpha
// ledger r143 reopen: page 2 selections jumped to page 4). The DOM rect
// stays authoritative for the VERTICAL line only (the r122 wrap-boundary
// ambiguity it was introduced for).
const estimate = view.coordsAtPos(selection.head, dir === 1 ? -1 : 1)
const x = (estimate.left + estimate.right) / 2
// nearest gap in the pressed direction at this x (rect scan, not // nearest gap in the pressed direction at this x (rect scan, not
// elementFromPoint: the gap may sit outside the viewport) // elementFromPoint: the gap may sit outside the viewport)
let gap: HTMLElement | null = null let gap: HTMLElement | null = null
@@ -128,12 +161,31 @@ function crossPageGap(view: EditorView, dir: -1 | 1, extend: boolean): boolean {
} }
} }
const landingY = (r: DOMRect) => (dir === 1 ? r.bottom + lineH * 0.5 : r.top - lineH * 0.5) const landingY = (r: DOMRect) => (dir === 1 ? r.bottom + lineH * 0.5 : r.top - lineH * 0.5)
let targetY = landingY(gapRect) let landingGapRect: DOMRect = gapRect
if (ensureVisible(targetY) !== 0) targetY = landingY(gap.getBoundingClientRect()) let targetY = landingY(landingGapRect)
if (ensureVisible(targetY) !== 0) {
landingGapRect = gap.getBoundingClientRect()
targetY = landingY(landingGapRect)
}
const target = view.posAtCoords({ left: x, top: targetY }) const target = view.posAtCoords({ left: x, top: targetY })
if (!target) { if (!target) {
// the gap IS the adjacent line (the band check passed) — native cannot
// cross an inline gap and would jump a whole page, so CONSUME the press:
// one skipped key-repeat tick, and the next press recomputes fresh
restore() restore()
return false return consumePress(selection.head)
}
// the landing must be the line adjacent to the gap: a hit-test that
// resolves further away (stale geometry, margins) would dispatch a
// multi-paragraph jump (r143)
const landed = view.coordsAtPos(target.pos)
if (
dir === 1
? landed.top > landingGapRect.bottom + lineH * 2
: landed.bottom < landingGapRect.top - lineH * 2
) {
restore()
return consumePress(selection.head)
} }
const next = extend const next = extend
? TextSelection.create(doc, selection.anchor, target.pos) ? TextSelection.create(doc, selection.anchor, target.pos)
@@ -142,6 +194,10 @@ function crossPageGap(view: EditorView, dir: -1 | 1, extend: boolean): boolean {
restore() restore()
return false return false
} }
// a successful crossing clears the absorb marker: a LATER transient
// failure at this same head must get its skipped tick again instead of
// falling straight to native (bugbot)
lastConsumedHead = -1
view.dispatch(view.state.tr.setSelection(next).scrollIntoView()) view.dispatch(view.state.tr.setSelection(next).scrollIntoView())
return true return true
} }
+331 -24
View File
@@ -27,6 +27,7 @@ import {
import { custGeomBackgroundCss, shapeBackgroundCss, shapeTextInsetsPx } from './shape-svg' import { custGeomBackgroundCss, shapeBackgroundCss, shapeTextInsetsPx } from './shape-svg'
import { t } from '../i18n/locale' import { t } from '../i18n/locale'
import { import {
lumHex,
type ChartDisplay, type ChartDisplay,
type FieldDisplay, type FieldDisplay,
type FormulaDisplay, type FormulaDisplay,
@@ -95,7 +96,35 @@ export function renderFieldSpec(field: FieldDisplay): DomSpec | null {
return ['div', { class: 'doc-field-pagebreak' }, ['span', {}, t('editorPageBreak')]] return ['div', { class: 'doc-field-pagebreak' }, ['span', {}, t('editorPageBreak')]]
} }
if (field.kind === 'text' && field.left) { if (field.kind === 'text' && field.left) {
return ['div', { class: 'doc-field-text', contenteditable: 'false' }, field.left] // carry the result runs' face/size: the passthrough div otherwise inherits
// the document default and mis-snaps on a typed line grid. Spaces must
// survive inline: prosemirror-view injects a higher-specificity
// `.ProseMirror [contenteditable=false] { white-space: normal }`
const styles: string[] = ['white-space:pre-wrap']
if (field.szHalfPoints) styles.push(`font-size:${field.szHalfPoints / 2}pt`)
if (field.align) styles.push(`text-align:${field.align}`)
if (field.fontFamily) {
styles.push(
`--doc-line-factor:${lineHeightFactor(field.fontFamily)}`,
`font-family:${cssFontFamily(field.fontFamily)}`,
)
}
if (field.szHalfPoints || field.fontFamily || field.lineRule) {
// explicit w:spacing beats the single-spacing snap; either way the line
// strut must recompute from the field's own size/face, not the
// wrapper's document-default computed box
styles.push(
`line-height:${cssLineHeight(field.lineRule, field.lineRawTwips, field.lineSpacing) ?? cssGridLineBase()}`,
)
const mult = cssAutoLineMult(field.lineRule, field.lineRawTwips, field.lineSpacing)
if (mult && mult !== 1) styles.push(`--doc-line-mult:${mult}`)
}
const attrs: Record<string, string> = {
class: 'doc-field-text',
contenteditable: 'false',
style: styles.join(';'),
}
return ['div', attrs, field.left]
} }
return null return null
} }
@@ -127,10 +156,28 @@ export function renderFormulaSpec(formula: FormulaDisplay): DomSpec {
// ---- embedded charts: SVG preview + editable data grid ---- // ---- embedded charts: SVG preview + editable data grid ----
/** Office theme default accent colors, used for new charts */ /** Office theme default accent colors, used for new charts / theme-less docs */
const CHART_PALETTE = ['4472C4', 'ED7D31', 'A5A5A5', 'FFC000', '5B9BD5', '70AD47'] const CHART_PALETTE = ['4472C4', 'ED7D31', 'A5A5A5', 'FFC000', '5B9BD5', '70AD47']
const chartColor = (i: number) => `#${CHART_PALETTE[i % CHART_PALETTE.length]}` /** series/point cycle color; repeat rounds darken like Word (accentN lumMod 60%) */
function chartColor(chart: ChartDisplay, i: number): string {
const palette = chart.palette?.length ? chart.palette : CHART_PALETTE
const base = palette[i % palette.length]
const round = Math.floor(i / palette.length)
return `#${round > 0 ? lumHex(base, 0.6 ** round, 0) : base}`
}
/** explicit c:ser fill beats the style cycle */
function seriesColor(chart: ChartDisplay, s: number): string {
const explicit = chart.series[s]?.color
return explicit ? `#${explicit}` : chartColor(chart, s)
}
/** per-point fill (pie slices): c:dPt beats the cycle */
function pointColor(chart: ChartDisplay, s: number, i: number): string {
const explicit = chart.series[s]?.pointColors?.[i]
return explicit ? `#${explicit}` : chartColor(chart, i)
}
/** /**
* Chart preview + data grid. The grid is a chart data sheet * Chart preview + data grid. The grid is a chart data sheet
@@ -167,7 +214,7 @@ export function renderChartSpec(chart: ChartDisplay): DomSpec {
class: `doc-chart-name${ser.name !== undefined ? ' doc-chart-cell' : ''}`, class: `doc-chart-name${ser.name !== undefined ? ' doc-chart-cell' : ''}`,
'data-ser': String(s), 'data-ser': String(s),
contenteditable: 'false', contenteditable: 'false',
style: `border-left-color:${chartColor(s)}`, style: `border-left-color:${seriesColor(chart, s)}`,
}, },
ser.name ?? t('editorChartSeries', { num: s + 1 }), ser.name ?? t('editorChartSeries', { num: s + 1 }),
], ],
@@ -224,9 +271,16 @@ export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void
if (!canvas || !chart?.series.length) return if (!canvas || !chart?.series.length) return
// series-name legend inside the SVG: the data grid is an editing affordance // series-name legend inside the SVG: the data grid is an editing affordance
// (hidden unless the block is selected), so the printed chart must carry the // (hidden unless the block is selected), so the printed chart must carry the
// legend itself, like Word/LibreOffice output // legend itself, like Word/LibreOffice output. Pie legends list the
const legendNames = chart.series.map((s, i) => s.name ?? t('editorChartSeries', { num: i + 1 })) // categories (one colored slice each), not the series.
const showLegend = chart.series.length > 1 || chart.series.some((s) => s.name) const isPie = chart.kind === 'pie'
const legendNames = isPie
? chart.categories
: chart.series.map((s, i) => s.name ?? t('editorChartSeries', { num: i + 1 }))
const legendColor = (i: number) => (isPie ? pointColor(chart, 0, i) : seriesColor(chart, i))
const showLegend = isPie
? legendNames.length > 0
: chart.series.length > 1 || chart.series.some((s) => s.name)
// the title row renders above the SVG but Word draws the title inside the // the title row renders above the SVG but Word draws the title inside the
// drawing extent; shrink the plot so title + plot together fill heightPx, // drawing extent; shrink the plot so title + plot together fill heightPx,
// or pagination gains ~22px per titled chart and drifts // or pagination gains ~22px per titled chart and drifts
@@ -254,6 +308,7 @@ export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void
svg.style.height = `${geom.height}px` svg.style.height = `${geom.height}px`
if (chart.kind === 'pie') drawPie(svg, chart, geom) if (chart.kind === 'pie') drawPie(svg, chart, geom)
else if (chart.kind === 'scatter' || chart.kind === 'bubble') drawScatter(svg, chart, geom)
else if (chart.kind === 'bar' && chart.horizontal) drawAxesHorizontal(svg, chart, geom) else if (chart.kind === 'bar' && chart.horizontal) drawAxesHorizontal(svg, chart, geom)
else drawAxes(svg, chart, geom) else drawAxes(svg, chart, geom)
@@ -266,7 +321,7 @@ export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void
y: String(geom.height - 15), y: String(geom.height - 15),
width: '8', width: '8',
height: '8', height: '8',
fill: chartColor(i), fill: legendColor(i),
}) })
svgEl( svgEl(
svg, svg,
@@ -298,21 +353,49 @@ function svgEl(
return el return el
} }
/** per-category positive/negative stack sums plus the absolute total (percentStacked base) */
function stackSums(
chart: ChartDisplay,
cols: number,
): { pos: number[]; neg: number[]; abs: number[] } {
const pos = new Array<number>(cols).fill(0)
const neg = new Array<number>(cols).fill(0)
const abs = new Array<number>(cols).fill(0)
for (const ser of chart.series) {
ser.values.forEach((v, c) => {
if (v === null || c >= cols) return
if (v >= 0) pos[c] += v
else neg[c] += v
abs[c] += Math.abs(v)
})
}
return { pos, neg, abs }
}
/** bar / line / area charts share the same axes and scale */ /** bar / line / area charts share the same axes and scale */
function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void { function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
const values = chart.series.flatMap((s) => s.values).filter((v): v is number => v !== null) const cols = Math.max(chart.categories.length, ...chart.series.map((s) => s.values.length), 1)
const stacked = (chart.kind === 'bar' || chart.kind === 'area') && chart.grouping !== undefined
const pct = stacked && chart.grouping === 'percentStacked'
const sums = stacked ? stackSums(chart, cols) : null
// percentStacked: each value becomes its share of the category's absolute total
const norm = (value: number, c: number) =>
pct ? (sums!.abs[c] > 0 ? (value / sums!.abs[c]) * 100 : 0) : value
const values = stacked
? [...sums!.pos.map(norm), ...sums!.neg.map(norm)]
: chart.series.flatMap((s) => s.values).filter((v): v is number => v !== null)
// "nice" axis bounds (1/2/5×10ⁿ step, integer-friendly labels like Word/LO) // "nice" axis bounds (1/2/5×10ⁿ step, integer-friendly labels like Word/LO)
const rawMax = Math.max(0, ...values) const rawMax = Math.max(0, ...values)
const rawMin = Math.min(0, ...values) const rawMin = Math.min(0, ...values)
const step = niceStep((rawMax - rawMin) / 5 || 1) const step = niceStep((rawMax - rawMin) / 5 || 1)
const min = Math.floor(rawMin / step) * step const min = Math.floor(rawMin / step) * step
// Word/LO leave headroom: the top tick sits strictly above the data maximum // Word/LO leave headroom: the top tick sits strictly above the data maximum
// (percent axes stop at 100%)
let max = Math.ceil(rawMax / step) * step || step let max = Math.ceil(rawMax / step) * step || step
if (rawMax > 0 && max <= rawMax + 1e-9) max += step if (!pct && rawMax > 0 && max <= rawMax + 1e-9) max += step
const span = max - min || 1 const span = max - min || 1
const plotW = geom.width - geom.left - geom.right const plotW = geom.width - geom.left - geom.right
const plotH = geom.height - geom.top - geom.bottom const plotH = geom.height - geom.top - geom.bottom
const cols = Math.max(chart.categories.length, ...chart.series.map((s) => s.values.length), 1)
const yOf = (v: number) => geom.top + plotH - ((v - min) / span) * plotH const yOf = (v: number) => geom.top + plotH - ((v - min) / span) * plotH
const slotW = plotW / cols const slotW = plotW / cols
@@ -337,7 +420,7 @@ function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
class: 'doc-chart-axis-label', class: 'doc-chart-axis-label',
'text-anchor': 'end', 'text-anchor': 'end',
}, },
formatAxisValue(v), formatAxisValue(v) + (pct ? '%' : ''),
) )
} }
@@ -357,7 +440,31 @@ function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
) )
}) })
if (chart.kind === 'bar') { if (chart.kind === 'bar' && stacked) {
// one bar per category, series segments cumulated up (down for negatives)
const posBase = new Array<number>(cols).fill(0)
const negBase = new Array<number>(cols).fill(0)
const barPad = slotW * 0.2
chart.series.forEach((ser, s) => {
ser.values.forEach((value, c) => {
if (value === null || c >= cols) return
const v = norm(value, c)
const from = v >= 0 ? posBase[c] : negBase[c]
const to = from + v
const y0 = yOf(from)
const y1 = yOf(to)
svgEl(svg, 'rect', {
x: String(geom.left + slotW * c + barPad),
y: String(Math.min(y0, y1)),
width: String(slotW - barPad * 2),
height: String(Math.max(1, Math.abs(y0 - y1))),
fill: seriesColor(chart, s),
})
if (v >= 0) posBase[c] = to
else negBase[c] = to
})
})
} else if (chart.kind === 'bar') {
const groupPad = slotW * 0.15 const groupPad = slotW * 0.15
const barW = (slotW - groupPad * 2) / chart.series.length const barW = (slotW - groupPad * 2) / chart.series.length
chart.series.forEach((ser, s) => { chart.series.forEach((ser, s) => {
@@ -371,10 +478,33 @@ function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
y: String(Math.min(y0, y1)), y: String(Math.min(y0, y1)),
width: String(barW * 0.84), width: String(barW * 0.84),
height: String(Math.max(1, Math.abs(y0 - y1))), height: String(Math.max(1, Math.abs(y0 - y1))),
fill: chartColor(s), fill: seriesColor(chart, s),
}) })
}) })
}) })
} else if (chart.kind === 'area' && stacked) {
// stacked / 100% stacked area: each band fills between the running total
// below it and its own cumulated top (empty cells count as 0, like Excel)
const bases = new Array<number>(cols).fill(0)
const xAt = (c: number) => geom.left + slotW * c + slotW / 2
chart.series.forEach((ser, s) => {
const tops = bases.map((b, c) => b + norm(ser.values[c] ?? 0, c))
const upper = tops.map((v, c) => `${xAt(c)},${yOf(v)}`)
const lower = bases.map((v, c) => `${xAt(c)},${yOf(v)}`).reverse()
svgEl(svg, 'polygon', {
points: [...upper, ...lower].join(' '),
fill: seriesColor(chart, s),
'fill-opacity': '0.35',
stroke: 'none',
})
svgEl(svg, 'polyline', {
points: upper.join(' '),
fill: 'none',
stroke: seriesColor(chart, s),
'stroke-width': '2',
})
tops.forEach((v, c) => (bases[c] = v))
})
} else { } else {
// line / area / other: one polyline per series through slot centers // line / area / other: one polyline per series through slot centers
chart.series.forEach((ser, s) => { chart.series.forEach((ser, s) => {
@@ -389,7 +519,7 @@ function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
const last = points[points.length - 1].split(',')[0] const last = points[points.length - 1].split(',')[0]
svgEl(svg, 'polygon', { svgEl(svg, 'polygon', {
points: `${first},${yOf(0)} ${points.join(' ')} ${last},${yOf(0)}`, points: `${first},${yOf(0)} ${points.join(' ')} ${last},${yOf(0)}`,
fill: chartColor(s), fill: seriesColor(chart, s),
'fill-opacity': '0.35', 'fill-opacity': '0.35',
stroke: 'none', stroke: 'none',
}) })
@@ -397,27 +527,169 @@ function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
svgEl(svg, 'polyline', { svgEl(svg, 'polyline', {
points: points.join(' '), points: points.join(' '),
fill: 'none', fill: 'none',
stroke: chartColor(s), stroke: seriesColor(chart, s),
'stroke-width': '2', 'stroke-width': '2',
}) })
if (chart.markers) {
for (const p of points) {
const [x, y] = p.split(',')
svgEl(svg, 'circle', { cx: x, cy: y, r: '2.5', fill: seriesColor(chart, s) })
}
}
}) })
} }
} }
/** scatter / bubble: numeric x-y plot; bubble radius scales by point size (area-true) */
function drawScatter(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
interface Pt {
x: number
y: number
size: number | null
c: number
}
const pts: Pt[][] = chart.series.map((ser) =>
ser.values
.map((y, c) => {
// no xVal cache at all → 1-based index axis; a null inside the cache is a gap
const x = ser.xValues ? (ser.xValues[c] ?? null) : c + 1
return y === null || x === null ? null : { x, y, size: ser.sizes?.[c] ?? null, c }
})
.filter((p): p is Pt => p !== null),
)
const all = pts.flat()
if (all.length === 0) return
const axis = (vals: number[]) => {
let rawMax = Math.max(...vals)
let rawMin = Math.min(...vals)
// Excel-style auto minimum: anchor at 0 unless the data sits far above it
// (date-serial x values must not squash the points against the right edge)
if (rawMin > 0 && rawMin <= rawMax - rawMin) rawMin = 0
if (rawMax < 0) rawMax = 0
const step = niceStep((rawMax - rawMin) / 5 || 1)
const min = Math.floor(rawMin / step) * step
let max = Math.ceil(rawMax / step) * step || step
if (rawMax > 0 && max <= rawMax + 1e-9) max += step
return { min, max, step, span: max - min || 1 }
}
const ax = axis(all.map((p) => p.x))
const ay = axis(all.map((p) => p.y))
const plotW = geom.width - geom.left - geom.right
const plotH = geom.height - geom.top - geom.bottom
const xOf = (v: number) => geom.left + ((v - ax.min) / ax.span) * plotW
const yOf = (v: number) => geom.top + plotH - ((v - ay.min) / ay.span) * plotH
// horizontal gridlines with value labels, like the category charts
const ySteps = Math.max(1, Math.round(ay.span / ay.step))
for (let i = 0; i <= ySteps; i++) {
const v = ay.min + ay.step * i
const y = yOf(v)
svgEl(svg, 'line', {
x1: String(geom.left),
y1: String(y),
x2: String(geom.width - geom.right),
y2: String(y),
class: 'doc-chart-grid',
})
svgEl(
svg,
'text',
{
x: String(geom.left - 6),
y: String(y + 3),
class: 'doc-chart-axis-label',
'text-anchor': 'end',
},
formatAxisValue(v),
)
}
// x labels: date/text categories sit under their own data points (Word puts
// the cached texts along the axis); numeric x gets plain scale ticks
const catNumeric =
chart.categories.length === 0 ||
chart.categories.every((c) => c === '' || Number.isFinite(Number(c)))
const labelY = String(geom.height - geom.bottom + 14)
if (catNumeric) {
const xSteps = Math.max(1, Math.round(ax.span / ax.step))
for (let i = 0; i <= xSteps; i++) {
const v = ax.min + ax.step * i
svgEl(
svg,
'text',
{ x: String(xOf(v)), y: labelY, class: 'doc-chart-axis-label', 'text-anchor': 'middle' },
formatAxisValue(v),
)
}
} else {
const anchor = pts[0] ?? []
let lastEnd = -Infinity
chart.categories.forEach((cat, c) => {
const p = anchor.find((pt) => pt.c === c)
if (!p) return
// greedy label thinning: drop labels that would overlap the previous one
const x = xOf(p.x)
const half = cat.length * 2.6
if (x - half < lastEnd + 4) return
lastEnd = x + half
svgEl(
svg,
'text',
{ x: String(x), y: labelY, class: 'doc-chart-axis-label', 'text-anchor': 'middle' },
cat,
)
})
}
const maxSize = Math.max(0, ...all.map((p) => p.size ?? 0))
const rMax = Math.min(plotW, plotH) * 0.125
pts.forEach((points, s) => {
const color = seriesColor(chart, s)
if (chart.series[s]?.line && points.length > 1) {
svgEl(svg, 'polyline', {
points: points.map((p) => `${xOf(p.x)},${yOf(p.y)}`).join(' '),
fill: 'none',
stroke: color,
'stroke-width': '2',
})
}
// scatterStyle "line"/"smooth" draws no point markers on lined series
if (chart.kind === 'scatter' && !chart.markers && chart.series[s]?.line) return
for (const p of points) {
const bubble = chart.kind === 'bubble' && p.size !== null && maxSize > 0
const r = bubble ? Math.max(3, rMax * Math.sqrt(Math.abs(p.size!) / maxSize)) : 3
svgEl(svg, 'circle', {
cx: String(xOf(p.x)),
cy: String(yOf(p.y)),
r: String(r),
fill: color,
...(bubble ? { 'fill-opacity': '0.85', stroke: '#fff', 'stroke-width': '1' } : {}),
})
}
})
}
/** horizontal bar charts (c:barDir="bar"): value axis on x, categories on y, /** horizontal bar charts (c:barDir="bar"): value axis on x, categories on y,
* first category in the bottom row and series 1 at the bottom of each group, like Word */ * first category in the bottom row and series 1 at the bottom of each group, like Word */
function drawAxesHorizontal(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void { function drawAxesHorizontal(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
const values = chart.series.flatMap((s) => s.values).filter((v): v is number => v !== null) const rows = Math.max(chart.categories.length, ...chart.series.map((s) => s.values.length), 1)
const stacked = chart.grouping !== undefined
const pct = chart.grouping === 'percentStacked'
const sums = stacked ? stackSums(chart, rows) : null
const norm = (value: number, c: number) =>
pct ? (sums!.abs[c] > 0 ? (value / sums!.abs[c]) * 100 : 0) : value
const values = stacked
? [...sums!.pos.map(norm), ...sums!.neg.map(norm)]
: chart.series.flatMap((s) => s.values).filter((v): v is number => v !== null)
const rawMax = Math.max(0, ...values) const rawMax = Math.max(0, ...values)
const rawMin = Math.min(0, ...values) const rawMin = Math.min(0, ...values)
const step = niceStep((rawMax - rawMin) / 5 || 1) const step = niceStep((rawMax - rawMin) / 5 || 1)
const min = Math.floor(rawMin / step) * step const min = Math.floor(rawMin / step) * step
let max = Math.ceil(rawMax / step) * step || step let max = Math.ceil(rawMax / step) * step || step
if (rawMax > 0 && max <= rawMax + 1e-9) max += step if (!pct && rawMax > 0 && max <= rawMax + 1e-9) max += step
const span = max - min || 1 const span = max - min || 1
const plotW = geom.width - geom.left - geom.right const plotW = geom.width - geom.left - geom.right
const plotH = geom.height - geom.top - geom.bottom const plotH = geom.height - geom.top - geom.bottom
const rows = Math.max(chart.categories.length, ...chart.series.map((s) => s.values.length), 1)
const xOf = (v: number) => geom.left + ((v - min) / span) * plotW const xOf = (v: number) => geom.left + ((v - min) / span) * plotW
const slotH = plotH / rows const slotH = plotH / rows
@@ -442,7 +714,7 @@ function drawAxesHorizontal(svg: SVGElement, chart: ChartDisplay, geom: ChartGeo
class: 'doc-chart-axis-label', class: 'doc-chart-axis-label',
'text-anchor': 'middle', 'text-anchor': 'middle',
}, },
formatAxisValue(v), formatAxisValue(v) + (pct ? '%' : ''),
) )
} }
@@ -461,6 +733,32 @@ function drawAxesHorizontal(svg: SVGElement, chart: ChartDisplay, geom: ChartGeo
) )
}) })
if (stacked) {
const posBase = new Array<number>(rows).fill(0)
const negBase = new Array<number>(rows).fill(0)
const barPad = slotH * 0.2
chart.series.forEach((ser, s) => {
ser.values.forEach((value, c) => {
if (value === null || c >= rows) return
const v = norm(value, c)
const from = v >= 0 ? posBase[c] : negBase[c]
const to = from + v
const x0 = xOf(from)
const x1 = xOf(to)
svgEl(svg, 'rect', {
x: String(Math.min(x0, x1)),
y: String(geom.top + plotH - slotH * (c + 1) + barPad),
width: String(Math.max(1, Math.abs(x0 - x1))),
height: String(slotH - barPad * 2),
fill: seriesColor(chart, s),
})
if (v >= 0) posBase[c] = to
else negBase[c] = to
})
})
return
}
const groupPad = slotH * 0.15 const groupPad = slotH * 0.15
const barH = (slotH - groupPad * 2) / chart.series.length const barH = (slotH - groupPad * 2) / chart.series.length
chart.series.forEach((ser, s) => { chart.series.forEach((ser, s) => {
@@ -474,7 +772,7 @@ function drawAxesHorizontal(svg: SVGElement, chart: ChartDisplay, geom: ChartGeo
y: String(y + barH * 0.08), y: String(y + barH * 0.08),
width: String(Math.max(1, Math.abs(x0 - x1))), width: String(Math.max(1, Math.abs(x0 - x1))),
height: String(barH * 0.84), height: String(barH * 0.84),
fill: chartColor(s), fill: seriesColor(chart, s),
}) })
}) })
}) })
@@ -502,7 +800,7 @@ function drawPie(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
values.filter((v) => v > 0).length === 1 values.filter((v) => v > 0).length === 1
? `M ${cx - r} ${cy} A ${r} ${r} 0 1 1 ${cx - r} ${cy - 0.01} Z` ? `M ${cx - r} ${cy} A ${r} ${r} 0 1 1 ${cx - r} ${cy - 0.01} Z`
: `M ${cx} ${cy} L ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2} Z` : `M ${cx} ${cy} L ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2} Z`
svgEl(svg, 'path', { d, fill: chartColor(i), stroke: '#fff', 'stroke-width': '1' }) svgEl(svg, 'path', { d, fill: pointColor(chart, 0, i), stroke: '#fff', 'stroke-width': '1' })
}) })
} }
@@ -713,8 +1011,8 @@ function textSpanSpec(run: Run, autoSpace?: boolean): DomSpec {
const letterSpacing = runLetterSpacingCss(run) const letterSpacing = runLetterSpacingCss(run)
const runStyle = [ const runStyle = [
run.color ? `color:#${run.color}` : '', run.color ? `color:#${run.color}` : '',
run.bold ? 'font-weight:700' : '', run.bold ? 'font-weight:700' : run.bold === false ? 'font-weight:normal' : '',
run.italic ? 'font-style:italic' : '', run.italic ? 'font-style:italic' : run.italic === false ? 'font-style:normal' : '',
run.underline ? 'text-decoration:underline' : '', run.underline ? 'text-decoration:underline' : '',
run.font || run.fontAscii || cs run.font || run.fontAscii || cs
? `font-family:${ ? `font-family:${
@@ -727,6 +1025,7 @@ function textSpanSpec(run: Run, autoSpace?: boolean): DomSpec {
letterSpacing ? `letter-spacing:${letterSpacing}` : '', letterSpacing ? `letter-spacing:${letterSpacing}` : '',
run.caps === 'all' ? 'text-transform:uppercase' : '', run.caps === 'all' ? 'text-transform:uppercase' : '',
run.caps === 'small' ? 'font-variant-caps:small-caps' : '', run.caps === 'small' ? 'font-variant-caps:small-caps' : '',
run.caps === 'none' ? 'text-transform:none;font-variant-caps:normal' : '',
// explicit autoSpaceDE/DN off also disables the browser's native gap (same as the editor path) // explicit autoSpaceDE/DN off also disables the browser's native gap (same as the editor path)
autoSpace === false ? 'text-autospace:no-autospace' : '', autoSpace === false ? 'text-autospace:no-autospace' : '',
] ]
@@ -963,6 +1262,8 @@ export function renderTableSpec(model: TableModel, nested = false): DomSpec {
} }
} }
const style = [ const style = [
// gridBefore/gridAfter placeholder: bare grid space, never bordered/filled
cell.gridGap ? 'border:none;background:none' : '',
cell.textDirection === 'tbRl' cell.textDirection === 'tbRl'
? 'writing-mode:vertical-rl' ? 'writing-mode:vertical-rl'
: cell.textDirection === 'btLr' : cell.textDirection === 'btLr'
@@ -1084,6 +1385,12 @@ export function renderTableSpec(model: TableModel, nested = false): DomSpec {
} }
const pad = cellPadCss(model.cellMarTwips ?? null) const pad = cellPadCss(model.cellMarTwips ?? null)
if (pad) tableStyles.push(`--doc-cell-pad:${pad}`) if (pad) tableStyles.push(`--doc-cell-pad:${pad}`)
// w:tblCellSpacing: the CSS gap is twice the per-cell-side value (see DocTable.renderHTML)
if (model.cellSpacingTwips) {
const gapPx = ((model.cellSpacingTwips * 2) / 15).toFixed(1)
tableStyles.push('border-collapse:separate', `border-spacing:${gapPx}px`)
}
if (model.fill) tableStyles.push(`background-color:#${model.fill}`)
tableStyles.push(...tableBordersCss((model.borders as TableBordersAttr | undefined) ?? null)) tableStyles.push(...tableBordersCss((model.borders as TableBordersAttr | undefined) ?? null))
if (model.align === 'center') { if (model.align === 'center') {
if (centerMargin) tableStyles.push(centerMargin) if (centerMargin) tableStyles.push(centerMargin)
+93 -1
View File
@@ -31,6 +31,23 @@ function tablePosAt(view: EditorView, coords: { left: number; top: number }): nu
return null return null
} }
/** DOM hit-testing remains reliable for CSS-floated tables where posAtCoords may resolve to wrapped text. */
function tablePosFromTarget(view: EditorView, target: EventTarget | null): number | null {
const element = target instanceof Element ? target : null
const table = element?.closest('table.doc-table')
if (!(table instanceof HTMLElement) || !view.dom.contains(table)) return null
let found: number | null = null
view.state.doc.descendants((node, pos) => {
if (found !== null) return false
if (node.type.name === 'docTable' && view.nodeDOM(pos) === table) {
found = pos
return false
}
return true
})
return found
}
const MOVE_SVG = const MOVE_SVG =
'<svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" ' + '<svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" ' +
'stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' + 'stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
@@ -59,6 +76,8 @@ function tableHandlePlugin(): Plugin {
} }
let tablePos: number | null = null let tablePos: number | null = null
let suppressClick = false
let stopFloatDrag: (() => void) | null = null
const hideHandle = () => { const hideHandle = () => {
handle.style.display = 'none' handle.style.display = 'none'
@@ -83,7 +102,9 @@ function tableHandlePlugin(): Plugin {
const onMouseMove = (event: MouseEvent) => { const onMouseMove = (event: MouseEvent) => {
if (!view.editable) return if (!view.editable) return
const pos = tablePosAt(view, { left: event.clientX, top: event.clientY }) const pos =
tablePosFromTarget(view, event.target) ??
tablePosAt(view, { left: event.clientX, top: event.clientY })
if (pos === null) { if (pos === null) {
// moving toward the handle itself must not hide it (it sits outside the table box) // moving toward the handle itself must not hide it (it sits outside the table box)
if (tablePos !== null) scheduleHide() if (tablePos !== null) scheduleHide()
@@ -105,6 +126,10 @@ function tableHandlePlugin(): Plugin {
} }
const onClick = () => { const onClick = () => {
if (suppressClick) {
suppressClick = false
return
}
const selection = selectTable() const selection = selectTable()
if (!selection) return if (!selection) return
view.dispatch(view.state.tr.setSelection(selection)) view.dispatch(view.state.tr.setSelection(selection))
@@ -115,6 +140,10 @@ function tableHandlePlugin(): Plugin {
if (!event.dataTransfer) return if (!event.dataTransfer) return
const selection = selectTable() const selection = selectTable()
if (!selection) return event.preventDefault() if (!selection) return event.preventDefault()
if (selection.node.attrs.tblFloat === 'left' || selection.node.attrs.tblFloat === 'right') {
event.preventDefault()
return
}
view.dispatch(view.state.tr.setSelection(selection)) view.dispatch(view.state.tr.setSelection(selection))
view.dragging = { slice: selection.content(), move: true } view.dragging = { slice: selection.content(), move: true }
event.dataTransfer.effectAllowed = 'move' event.dataTransfer.effectAllowed = 'move'
@@ -123,6 +152,67 @@ function tableHandlePlugin(): Plugin {
if (dom instanceof HTMLElement) event.dataTransfer.setDragImage(dom, 0, 0) if (dom instanceof HTMLElement) event.dataTransfer.setDragImage(dom, 0, 0)
} }
// A floating table uses the same drag-to-position interaction as Word's
// anchored pictures. In-flow tables keep ProseMirror's native block move.
const onMouseDown = (event: MouseEvent) => {
if (event.button !== 0 || tablePos === null) return
const dragPos = tablePos
const node = view.state.doc.nodeAt(dragPos)
if (!node || (node.attrs.tblFloat !== 'left' && node.attrs.tblFloat !== 'right')) return
event.preventDefault()
event.stopPropagation()
const visual = view.nodeDOM(dragPos)
if (!(visual instanceof HTMLElement)) return
const zoomEl = document.querySelector('.doc-zoom') as HTMLElement | null
const zoom = zoomEl ? parseFloat(getComputedStyle(zoomEl).zoom || '1') || 1 : 1
const startX = event.clientX
const startY = event.clientY
const initialX = Number(node.attrs.tblFloatXTwips) || 0
const initialY = Number(node.attrs.tblFloatYTwips) || 0
const priorTransform = visual.style.transform
const cleanup = () => {
window.removeEventListener('mousemove', onMove)
window.removeEventListener('mouseup', onUp)
stopFloatDrag = null
}
const delta = (e: MouseEvent) => ({
x: (e.clientX - startX) / zoom,
y: (e.clientY - startY) / zoom,
})
const onMove = (e: MouseEvent) => {
const { x, y } = delta(e)
visual.style.transform = `translate(${x.toFixed(1)}px,${y.toFixed(1)}px)`
}
const onUp = (e: MouseEvent) => {
cleanup()
visual.style.transform = priorTransform
const { x, y } = delta(e)
if (Math.hypot(x, y) < 3) return
suppressClick = true
window.setTimeout(() => {
suppressClick = false
}, 0)
const current = view.state.doc.nodeAt(dragPos)
if (!current || current.type.name !== 'docTable') return
view.dispatch(
view.state.tr.setNodeMarkup(dragPos, undefined, {
...current.attrs,
tblFloatSource: current.attrs.tblFloat,
tblFloatSuppressed: false,
tblFloatXTwips: Math.round(initialX + x * 15),
tblFloatYTwips: Math.round(initialY + y * 15),
tblFloatEdited: true,
}),
)
}
stopFloatDrag?.()
stopFloatDrag = cleanup
window.addEventListener('mousemove', onMove)
window.addEventListener('mouseup', onUp)
}
// the handle floats outside the table's corner, so reaching it always // the handle floats outside the table's corner, so reaching it always
// leaves the table box first — hide on a grace period, not instantly // leaves the table box first — hide on a grace period, not instantly
let hideTimer: number | null = null let hideTimer: number | null = null
@@ -147,6 +237,7 @@ function tableHandlePlugin(): Plugin {
handle.addEventListener('mousemove', (e) => e.stopPropagation()) handle.addEventListener('mousemove', (e) => e.stopPropagation())
handle.addEventListener('mouseenter', cancelHide) handle.addEventListener('mouseenter', cancelHide)
handle.addEventListener('mouseleave', scheduleHide) handle.addEventListener('mouseleave', scheduleHide)
handle.addEventListener('mousedown', onMouseDown)
handle.addEventListener('click', onClick) handle.addEventListener('click', onClick)
handle.addEventListener('dragstart', onDragStart) handle.addEventListener('dragstart', onDragStart)
document.addEventListener('scroll', onScroll, true) document.addEventListener('scroll', onScroll, true)
@@ -157,6 +248,7 @@ function tableHandlePlugin(): Plugin {
if (!prevState.doc.eq(view.state.doc)) hideHandle() if (!prevState.doc.eq(view.state.doc)) hideHandle()
}, },
destroy() { destroy() {
stopFloatDrag?.()
cancelHide() cancelHide()
view.dom.removeEventListener('mousemove', onMouseMove) view.dom.removeEventListener('mousemove', onMouseMove)
view.dom.removeEventListener('mouseleave', scheduleHide) view.dom.removeEventListener('mouseleave', scheduleHide)
@@ -0,0 +1,212 @@
import type { Node as PmNode } from '@tiptap/pm/model'
import type { Command, EditorState, Transaction } from '@tiptap/pm/state'
import { isInTable, selectedRect } from '@tiptap/pm/tables'
import type { TableAutoFitMode, TableLook } from '@genoffice/docx-engine'
interface SelectedTable {
node: PmNode
pos: number
tableStart: number
rect: ReturnType<typeof selectedRect>
}
function selectedTable(state: EditorState): SelectedTable | null {
if (!isInTable(state)) return null
try {
const rect = selectedRect(state)
const pos = rect.tableStart - 1
const node = state.doc.nodeAt(pos)
return node?.type.name === 'docTable' ? { node, pos, tableStart: rect.tableStart, rect } : null
} catch {
return null
}
}
export function updateSelectedTableAttrs(patch: Record<string, unknown>): Command {
return (state, dispatch) => {
const selected = selectedTable(state)
if (!selected) return false
dispatch?.(
state.tr.setNodeMarkup(selected.pos, undefined, {
...selected.node.attrs,
...patch,
}),
)
return true
}
}
function fixedGridWidths(table: PmNode, columnCount: number, contentWidthPx: number): number[] {
const firstRow = table.firstChild
const explicit: number[] = []
firstRow?.forEach((cell) => {
const widths = cell.attrs.colwidth as number[] | null
if (widths?.length) explicit.push(...widths)
})
if (explicit.length === columnCount && explicit.every((width) => width > 0)) return explicit
const pct = table.attrs.colWidthsPct as number[] | null
if (pct?.length === columnCount) {
const total = pct.reduce((sum, width) => sum + Math.max(0, width), 0) || 100
return pct.map((width) =>
Math.max(24, Math.round((Math.max(0, width) / total) * contentWidthPx)),
)
}
return Array.from({ length: columnCount }, () =>
Math.max(24, Math.floor(contentWidthPx / Math.max(1, columnCount))),
)
}
/**
* Word's AutoFit modes:
* - contents: auto layout with no preferred table width
* - window: auto layout with a 100% preferred width
* - fixed: fixed layout using the current grid
*/
export function setTableAutoFit(mode: TableAutoFitMode, contentWidthPx: number): Command {
return (state, dispatch) => {
const selected = selectedTable(state)
if (!selected) return false
let tr: Transaction = state.tr
const { node: table, rect, tableStart } = selected
const tablePatch: Record<string, unknown> = {
tblAutoFit: mode,
tblAutoFitEdited: true,
}
if (mode === 'contents') {
tablePatch.widthPx = null
tablePatch.widthPct = null
tablePatch.colWidthsPct = null
table.descendants((node, pos) => {
if (node.type.name !== 'docTableCell' && node.type.name !== 'docTableHeader') return
if (node.attrs.colwidth) {
tr = tr.setNodeMarkup(tableStart + pos, undefined, { ...node.attrs, colwidth: null })
}
})
} else if (mode === 'window') {
tablePatch.widthPx = null
tablePatch.widthPct = 100
} else {
const widths = fixedGridWidths(table, rect.map.width, contentWidthPx)
const total = widths.reduce((sum, width) => sum + width, 0)
tablePatch.widthPx = total
tablePatch.widthPct = null
tablePatch.colWidthsPct = widths.map((width) => (width / total) * 100)
table.descendants((node, pos) => {
if (node.type.name !== 'docTableCell' && node.type.name !== 'docTableHeader') return
try {
const cell = rect.map.findCell(pos)
tr = tr.setNodeMarkup(tableStart + pos, undefined, {
...node.attrs,
colwidth: widths.slice(cell.left, cell.right),
})
} catch {
// A malformed grid should not prevent the table-level mode switch.
}
})
}
tr = tr.setNodeMarkup(selected.pos, undefined, { ...table.attrs, ...tablePatch })
dispatch?.(tr)
return true
}
}
export interface RepeatHeaderState {
enabled: boolean
active: boolean
}
export function repeatHeaderState(state: EditorState): RepeatHeaderState {
const selected = selectedTable(state)
if (!selected || selected.rect.top !== 0) return { enabled: false, active: false }
let active = true
for (let row = 0; row < selected.rect.bottom; row++) {
if (!selected.node.child(row).attrs.repeatHeader) active = false
}
return { enabled: true, active }
}
/** Toggle the selected leading row(s) as repeating table headers. */
export function toggleRepeatHeaderRows(): Command {
return (state, dispatch) => {
const selected = selectedTable(state)
if (!selected || selected.rect.top !== 0) return false
const active = repeatHeaderState(state).active
let tr = state.tr
selected.node.forEach((row, offset, index) => {
if (index >= selected.rect.bottom) return
tr = tr.setNodeMarkup(selected.tableStart + offset, undefined, {
...row.attrs,
repeatHeader: !active,
repeatHeaderEdited: true,
})
})
dispatch?.(tr)
return true
}
}
export function setTableLookOption(key: keyof TableLook, value: boolean): Command {
return (state, dispatch) => {
const selected = selectedTable(state)
if (!selected) return false
const current = (selected.node.attrs.tblLook as TableLook | null) ?? {
firstRow: true,
lastRow: false,
firstColumn: true,
lastColumn: false,
bandedRows: true,
bandedColumns: false,
}
dispatch?.(
state.tr.setNodeMarkup(selected.pos, undefined, {
...selected.node.attrs,
tblLook: { ...current, [key]: value },
tblLookEdited: true,
}),
)
return true
}
}
export interface TablePreset {
headerFill: string | null
band1Fill: string | null
band2Fill: string | null
borderColor: string
}
/** Apply a self-contained visual preset without depending on styles.xml. */
export function applyTablePreset(preset: TablePreset): Command {
return (state, dispatch) => {
const selected = selectedTable(state)
if (!selected) return false
const border = { style: 'single', szEighths: 4, color: preset.borderColor }
const borders = { top: border, right: border, bottom: border, left: border }
let tr = state.tr
selected.node.forEach((row, rowOffset, rowIndex) => {
row.forEach((cell, cellOffset) => {
const fill =
rowIndex === 0
? preset.headerFill
: rowIndex % 2 === 0
? preset.band2Fill
: preset.band1Fill
tr = tr.setNodeMarkup(selected.tableStart + rowOffset + 1 + cellOffset, undefined, {
...cell.attrs,
fill,
borders,
})
})
})
tr = tr.setNodeMarkup(selected.pos, undefined, {
...selected.node.attrs,
// Direct formatting is portable even when the source document has no
// matching table style definition.
tblStyleId: null,
})
dispatch?.(tr)
return true
}
}
+3 -1
View File
@@ -5,7 +5,9 @@ Copyright (c) 2012 Red Hat, Inc.
Copyright (c) 2010-2013 by tyPoland Lukasz Dziedzic (team@latofonts.com) Copyright (c) 2010-2013 by tyPoland Lukasz Dziedzic (team@latofonts.com)
with Reserved Font Name "Carlito". with Reserved Font Name "Carlito".
Copyright 2014-2021 Adobe (http://www.adobe.com/), Google LLC Copyright 2014-2021 Adobe (http://www.adobe.com/), Google LLC
with Reserved Font Name "Source". (Noto Sans CJK / Noto Serif CJK) with Reserved Font Name "Source". (Noto Sans CJK)
Copyright 2017-2024 Adobe (http://www.adobe.com/)
with Reserved Font Name "Source". (Noto Serif CJK)
Copyright (c) 2010, NHN Corporation (http://www.nhncorp.com), Copyright (c) 2010, NHN Corporation (http://www.nhncorp.com),
with Reserved Font Name Nanum, Naver Nanum, NanumGothic, Naver with Reserved Font Name Nanum, Naver Nanum, NanumGothic, Naver
NanumGothic, NanumMyeongjo, Naver NanumMyeongjo, NanumBrush, Naver NanumGothic, NanumMyeongjo, Naver NanumMyeongjo, NanumBrush, Naver
+11 -10
View File
@@ -49,11 +49,11 @@ chain order; advances are 1.0em everywhere, so line breaking is unchanged.
## Korean fallback ## Korean fallback
| Font | Role | | Font | Role |
| ------------------------------------ | --------------------------------------------------------- | | ------------------------------------ | ----------------------------------------------------------- |
| GenOffice Serif KR (subset woff2) | Batang-metric stand-in for Korean serif families | | GenOffice Serif KR (subset woff2) | Batang-metric stand-in for Korean serif families |
| GenOffice Sans KR (subset woff2) | fallback for Korean sans families (Malgun etc.) | | GenOffice Sans KR (subset woff2) | fallback for Korean sans families (Malgun etc.) |
| GenOffice Che Latin KR (ASCII woff2) | half-width Latin for BatangChe/GulimChe/DotumChe families | | GenOffice Che Latin KR (ASCII woff2) | half-width Latin for BatangChe/GulimChe/DotumChe/GungsuhChe |
Source: Noto Serif/Sans CJK KR Regular from [notofonts/noto-cjk](https://github.com/notofonts/noto-cjk) Source: Noto Serif/Sans CJK KR Regular from [notofonts/noto-cjk](https://github.com/notofonts/noto-cjk)
(SIL OFL 1.1), subset with fonttools to the 2,350 KS X 1001 syllables + jamo (SIL OFL 1.1), subset with fonttools to the 2,350 KS X 1001 syllables + jamo
@@ -75,11 +75,12 @@ ink widths and side bearings of Batang/Malgun
`tools/build-kr-che-latin-font.py` gives its Noto-derived outlines fixed 0.5em `tools/build-kr-che-latin-font.py` gives its Noto-derived outlines fixed 0.5em
advances and transforms them to measured DotumChe ink boxes. Microsoft Office advances and transforms them to measured DotumChe ink boxes. Microsoft Office
fonts are build-time measurement references only; no Microsoft outlines are fonts are build-time measurement references only; no Microsoft outlines are
included. All three derivatives are renamed because OFL reserves the "Noto" included. All three derivatives are renamed because the upstream OFL notices
name for unmodified builds. Conjoining jamo keep native advances (shaping). reserve the name "Source"; "Noto" is the distribution family name, not the
Word counterpart line factors live in `lineHeightFactor()` of Reserved Font Name. Conjoining jamo keep native advances (shaping). Word
`line-metrics.ts`. The Adobe/Google copyright and full OFL 1.1 text are in counterpart line factors live in `lineHeightFactor()` of `line-metrics.ts`.
`LICENSE-OFL.txt`. The Sans/Che source copyright (Adobe 2014–2021 and Google LLC), Serif source
copyright (Adobe 2017–2024), and full OFL 1.1 text are in `LICENSE-OFL.txt`.
### GenOffice Gothic KR ### GenOffice Gothic KR
@@ -0,0 +1,54 @@
import { defineStrings } from '@genoffice/i18n'
const en = {
ribbonTableStyleOptions: 'Table Style Options',
ribbonTableFirstRow: 'Header Row',
ribbonTableLastRow: 'Total Row',
ribbonTableBandedRows: 'Banded Rows',
ribbonTableFirstColumn: 'First Column',
ribbonTableLastColumn: 'Last Column',
ribbonTableBandedColumns: 'Banded Columns',
ribbonTablePresetGrid: 'Plain Grid',
ribbonTablePresetBlueHeader: 'Blue Header',
ribbonTablePresetBlueBanded: 'Blue Banded',
ribbonTablePresetGrayBanded: 'Gray Banded',
ribbonTablePresetGreenHeader: 'Green Header',
ribbonAutoFit: 'AutoFit',
ribbonAutoFitContents: 'AutoFit Contents',
ribbonAutoFitWindow: 'AutoFit Window',
ribbonFixedColumnWidth: 'Fixed Column Width',
ribbonRepeatHeaderRows: 'Repeat Header Rows',
ribbonTableProperties: 'Table Properties',
ribbonTableData: 'Table',
ribbonHorizontalPosition: 'Horizontal position',
ribbonVerticalPosition: 'Vertical position',
ribbonDistanceFromText: 'Distance from text',
ribbonCellMargins: 'Default cell margins',
}
/**
* New table controls deliberately fall back to English until each locale has
* reviewed terminology. Keeping one complete key set prevents partially
* translated dialogs and lets language packs override the shard incrementally.
*/
export const tableStrings = defineStrings({
zh: en,
en,
ja: en,
ko: en,
fr: en,
de: en,
es: en,
th: en,
id: en,
ru: en,
ar: en,
pt: en,
it: en,
pl: en,
nl: en,
ms: en,
he: en,
hi: en,
'zh-TW': en,
})
+128 -18
View File
@@ -2,29 +2,139 @@ import { aiStrings } from './strings-ai'
import { appStrings } from './strings-app' import { appStrings } from './strings-app'
import { editorStrings } from './strings-editor' import { editorStrings } from './strings-editor'
import { ribbonStrings } from './strings-ribbon' import { ribbonStrings } from './strings-ribbon'
import { tableStrings } from './strings-table'
export const strings = { export const strings = {
zh: { ...appStrings.zh, ...ribbonStrings.zh, ...editorStrings.zh, ...aiStrings.zh }, zh: {
en: { ...appStrings.en, ...ribbonStrings.en, ...editorStrings.en, ...aiStrings.en }, ...appStrings.zh,
ja: { ...appStrings.ja, ...ribbonStrings.ja, ...editorStrings.ja, ...aiStrings.ja }, ...ribbonStrings.zh,
ko: { ...appStrings.ko, ...ribbonStrings.ko, ...editorStrings.ko, ...aiStrings.ko }, ...tableStrings.zh,
fr: { ...appStrings.fr, ...ribbonStrings.fr, ...editorStrings.fr, ...aiStrings.fr }, ...editorStrings.zh,
de: { ...appStrings.de, ...ribbonStrings.de, ...editorStrings.de, ...aiStrings.de }, ...aiStrings.zh,
es: { ...appStrings.es, ...ribbonStrings.es, ...editorStrings.es, ...aiStrings.es }, },
th: { ...appStrings.th, ...ribbonStrings.th, ...editorStrings.th, ...aiStrings.th }, en: {
id: { ...appStrings.id, ...ribbonStrings.id, ...editorStrings.id, ...aiStrings.id }, ...appStrings.en,
ru: { ...appStrings.ru, ...ribbonStrings.ru, ...editorStrings.ru, ...aiStrings.ru }, ...ribbonStrings.en,
ar: { ...appStrings.ar, ...ribbonStrings.ar, ...editorStrings.ar, ...aiStrings.ar }, ...tableStrings.en,
pt: { ...appStrings.pt, ...ribbonStrings.pt, ...editorStrings.pt, ...aiStrings.pt }, ...editorStrings.en,
it: { ...appStrings.it, ...ribbonStrings.it, ...editorStrings.it, ...aiStrings.it }, ...aiStrings.en,
pl: { ...appStrings.pl, ...ribbonStrings.pl, ...editorStrings.pl, ...aiStrings.pl }, },
nl: { ...appStrings.nl, ...ribbonStrings.nl, ...editorStrings.nl, ...aiStrings.nl }, ja: {
ms: { ...appStrings.ms, ...ribbonStrings.ms, ...editorStrings.ms, ...aiStrings.ms }, ...appStrings.ja,
he: { ...appStrings.he, ...ribbonStrings.he, ...editorStrings.he, ...aiStrings.he }, ...ribbonStrings.ja,
hi: { ...appStrings.hi, ...ribbonStrings.hi, ...editorStrings.hi, ...aiStrings.hi }, ...tableStrings.ja,
...editorStrings.ja,
...aiStrings.ja,
},
ko: {
...appStrings.ko,
...ribbonStrings.ko,
...tableStrings.ko,
...editorStrings.ko,
...aiStrings.ko,
},
fr: {
...appStrings.fr,
...ribbonStrings.fr,
...tableStrings.fr,
...editorStrings.fr,
...aiStrings.fr,
},
de: {
...appStrings.de,
...ribbonStrings.de,
...tableStrings.de,
...editorStrings.de,
...aiStrings.de,
},
es: {
...appStrings.es,
...ribbonStrings.es,
...tableStrings.es,
...editorStrings.es,
...aiStrings.es,
},
th: {
...appStrings.th,
...ribbonStrings.th,
...tableStrings.th,
...editorStrings.th,
...aiStrings.th,
},
id: {
...appStrings.id,
...ribbonStrings.id,
...tableStrings.id,
...editorStrings.id,
...aiStrings.id,
},
ru: {
...appStrings.ru,
...ribbonStrings.ru,
...tableStrings.ru,
...editorStrings.ru,
...aiStrings.ru,
},
ar: {
...appStrings.ar,
...ribbonStrings.ar,
...tableStrings.ar,
...editorStrings.ar,
...aiStrings.ar,
},
pt: {
...appStrings.pt,
...ribbonStrings.pt,
...tableStrings.pt,
...editorStrings.pt,
...aiStrings.pt,
},
it: {
...appStrings.it,
...ribbonStrings.it,
...tableStrings.it,
...editorStrings.it,
...aiStrings.it,
},
pl: {
...appStrings.pl,
...ribbonStrings.pl,
...tableStrings.pl,
...editorStrings.pl,
...aiStrings.pl,
},
nl: {
...appStrings.nl,
...ribbonStrings.nl,
...tableStrings.nl,
...editorStrings.nl,
...aiStrings.nl,
},
ms: {
...appStrings.ms,
...ribbonStrings.ms,
...tableStrings.ms,
...editorStrings.ms,
...aiStrings.ms,
},
he: {
...appStrings.he,
...ribbonStrings.he,
...tableStrings.he,
...editorStrings.he,
...aiStrings.he,
},
hi: {
...appStrings.hi,
...ribbonStrings.hi,
...tableStrings.hi,
...editorStrings.hi,
...aiStrings.hi,
},
'zh-TW': { 'zh-TW': {
...appStrings['zh-TW'], ...appStrings['zh-TW'],
...ribbonStrings['zh-TW'], ...ribbonStrings['zh-TW'],
...tableStrings['zh-TW'],
...editorStrings['zh-TW'], ...editorStrings['zh-TW'],
...aiStrings['zh-TW'], ...aiStrings['zh-TW'],
}, },
+5 -2
View File
@@ -187,6 +187,11 @@ export function lineHeightFactor(fontFamily: string): number {
if ((f.includes('楷体') || f.includes('kaiti')) && !/gb2312|_gbk|gbk/.test(f)) return 1.3029 if ((f.includes('楷体') || f.includes('kaiti')) && !/gb2312|_gbk|gbk/.test(f)) return 1.3029
if (f.includes('microsoft yahei') || f.includes('microsoftyahei') || f.includes('雅黑')) if (f.includes('microsoft yahei') || f.includes('microsoftyahei') || f.includes('雅黑'))
return 1.7143 return 1.7143
// DengXian ships with Office for Mac and renders real (text probe
// 2026-08-13 and empty-line probe 2026-08-25 both 16.32pt @12pt = 1.36;
// under a 15.6pt grid 10.5pt fits one cell and 12pt takes two, matching
// Word — the old 1.775 PingFang-class value doubled the 10.5pt rows)
if (f.includes('dengxian') || f.includes('等线')) return 1.36
// missing GB faces and other zh names substitute into the PingFang class // missing GB faces and other zh names substitute into the PingFang class
if ( if (
f.includes('楷体') || f.includes('楷体') ||
@@ -195,8 +200,6 @@ export function lineHeightFactor(fontFamily: string): number {
f.includes('microsoft yahei') || f.includes('microsoft yahei') ||
f.includes('microsoftyahei') || f.includes('microsoftyahei') ||
f.includes('雅黑') || f.includes('雅黑') ||
f.includes('dengxian') ||
f.includes('等线') ||
f.includes('simkai') f.includes('simkai')
) { ) {
return 1.775 return 1.775
+23 -3
View File
@@ -148,6 +148,16 @@ export interface PageSlice {
physHeight?: number physHeight?: number
} }
/**
* Page owning a page-pinned float: the page its anchor lands on (anchorTop and
* slices share gapless virtual coordinates); out-of-range anchors clamp.
*/
export function pinnedFloatPage(slices: PageSlice[], anchorTop: number): number {
const idx = slices.findIndex((s) => anchorTop >= s.start && anchorTop < s.end)
if (idx >= 0) return idx
return anchorTop < (slices[0]?.start ?? 0) ? 0 : Math.max(0, slices.length - 1)
}
/** Pagination geometry for one section */ /** Pagination geometry for one section */
export interface SectionGeom { export interface SectionGeom {
contentHeight: number contentHeight: number
@@ -1851,7 +1861,7 @@ export interface PageNoteItem {
strike?: boolean strike?: boolean
color?: string color?: string
sizeHalfPoints?: number sizeHalfPoints?: number
caps?: 'all' | 'small' caps?: 'all' | 'small' | 'none'
}> }>
> >
} }
@@ -2216,7 +2226,10 @@ export function fillLineBoxes(
block.docxIndex !== undefined ? metaOf?.(block.docxIndex)?.tableRowFlags : undefined block.docxIndex !== undefined ? metaOf?.(block.docxIndex)?.tableRowFlags : undefined
if (flags) if (flags)
rows.forEach((r, i) => { rows.forEach((r, i) => {
if (flags[i]?.isHeader) r.isHeader = true // Editable native tables publish an explicit live value on each tr;
// it must beat the source XML so turning repetition off takes effect
// before the document is saved and reopened.
if (r.isHeader === undefined && flags[i]?.isHeader) r.isHeader = true
if (flags[i]?.cantSplit) r.cantSplit = true if (flags[i]?.cantSplit) r.cantSplit = true
if (flags[i]?.minHPx) r.minHPx = flags[i].minHPx if (flags[i]?.minHPx) r.minHPx = flags[i].minHPx
}) })
@@ -2360,7 +2373,14 @@ function domTableRows(el: HTMLElement, blockHeight: number, zoomFactor: number):
gapAbove, gapAbove,
zoomFactor, zoomFactor,
) )
return { height: b.height, contentBottom, ...(cuts.length > 0 ? { cutYs: cuts } : {}) } return {
height: b.height,
contentBottom,
...(trs[i].hasAttribute('data-repeat-header')
? { isHeader: trs[i].getAttribute('data-repeat-header') === '1' }
: {}),
...(cuts.length > 0 ? { cutYs: cuts } : {}),
}
}) })
} }
+601 -36
View File
@@ -1792,6 +1792,9 @@ html.genoffice-popover-open .ribbon-tabs {
min-height in CSS table layout, so cells wrap content in this fixed-height box instead; min-height in CSS table layout, so cells wrap content in this fixed-height box instead;
clip (not hidden) so contenteditable's programmatic scrolls can't shift the content */ clip (not hidden) so contenteditable's programmatic scrolls can't shift the content */
.cell-clip { .cell-clip {
/* flow-root: overflow:clip alone is no BFC, so a first paragraph's
margin-top would collapse out and grow the exact row past its height */
display: flow-root;
overflow: clip; overflow: clip;
} }
@@ -3226,11 +3229,15 @@ th.cell-rev-del {
text-align: left; text-align: left;
} }
/* Word's built-in separator: a 2in rule (clamped to the column) on its own line;
the border sits at the bottom of the reserved row (11 + 1 + 4 = FOOTNOTE_SEPARATOR_H)
so it clears the last body line's descenders instead of underlining them */
.page-gap-notes::before { .page-gap-notes::before {
content: ''; content: '';
display: block; display: block;
width: 33%; width: min(2in, 100%);
border-top: 1px solid var(--docs-paper-ink-faint); height: 11px;
border-bottom: 1px solid var(--docs-paper-ink-faint);
margin-bottom: 4px; margin-bottom: 4px;
} }
@@ -3246,6 +3253,7 @@ th.cell-rev-del {
.page-gap-note sup { .page-gap-note sup {
margin-right: 4px; margin-right: 4px;
font-size: 0.65em;
} }
/* pagination preview: page-bottom footnote area (the referencing page; separator + small text); tiny overflow spills into the bottom margin */ /* pagination preview: page-bottom footnote area (the referencing page; separator + small text); tiny overflow spills into the bottom margin */
@@ -3258,16 +3266,22 @@ th.cell-rev-del {
color: var(--docs-paper-ink-dim); color: var(--docs-paper-ink-dim);
} }
/* same 2in bottom-anchored rule as .page-gap-notes::before; consuming the full
reserved row keeps the entries aligned with the engine's height reservation */
.pv-footnotes::before { .pv-footnotes::before {
content: ''; content: '';
display: block; display: block;
width: 33%; width: min(2in, 100%);
border-top: 1px solid var(--docs-paper-ink-faint); height: 11px;
border-bottom: 1px solid var(--docs-paper-ink-faint);
margin-bottom: 4px; margin-bottom: 4px;
} }
/* Word renders note markers with the reference character style: superscript at
~65% of the entry size (the UA's font-size:smaller left them oversized) */
.pv-footnote sup { .pv-footnote sup {
margin-right: 4px; margin-right: 4px;
font-size: 0.65em;
} }
/* endnote area: right after the body's end, separator above the first entry, continuation pages have no separator */ /* endnote area: right after the body's end, separator above the first entry, continuation pages have no separator */
@@ -3281,9 +3295,10 @@ th.cell-rev-del {
} }
.pv-endnote-separator { .pv-endnote-separator {
/* matches FOOTNOTE_SEPARATOR_H (16px): 11 + 1 border + 4 bottom spacing */ /* matches FOOTNOTE_SEPARATOR_H (16px): 11 box + 1 bottom border + 4 spacing —
width: 33%; the rule sits at the row's bottom, clear of the last body line above it */
border-top: 1px solid var(--docs-paper-ink-faint); width: min(2in, 100%);
border-bottom: 1px solid var(--docs-paper-ink-faint);
margin-bottom: 4px; margin-bottom: 4px;
height: 11px; height: 11px;
} }
@@ -3685,6 +3700,12 @@ th.cell-rev-del {
pointer-events: auto; pointer-events: auto;
} }
/* Pictures drag directly from their body. Their left-side chrome is the
paragraph anchor marker below, not the generic protected-block move button. */
.doc-protected[data-doc-protected='image'] > .doc-move-handle {
display: none;
}
/* pictures drag-move from anywhere on their body (Word parity) */ /* pictures drag-move from anywhere on their body (Word parity) */
.doc-protected[data-doc-protected='image'] .doc-img-wrap { .doc-protected[data-doc-protected='image'] .doc-img-wrap {
cursor: grab; cursor: grab;
@@ -3765,6 +3786,15 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
table-layout: fixed; table-layout: fixed;
} }
.doc-table.doc-table-autofit-contents,
.doc-table.doc-table-autofit-window {
table-layout: auto;
}
.doc-table.doc-table-autofit-contents {
max-width: 100%;
}
.doc-table td, .doc-table td,
.doc-table th { .doc-table th {
position: relative; position: relative;
@@ -3898,6 +3928,10 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
grid-template-columns: repeat(2, minmax(58px, auto)); grid-template-columns: repeat(2, minmax(58px, auto));
} }
.table-tool-grid-three {
grid-template-columns: repeat(3, minmax(94px, auto));
}
.table-tool-group button { .table-tool-group button {
min-height: 26px; min-height: 26px;
padding: 3px 8px; padding: 3px 8px;
@@ -3974,6 +4008,169 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
padding: 1px 5px; padding: 1px 5px;
} }
.table-style-options {
display: grid;
grid-template-columns: repeat(3, minmax(82px, auto));
gap: 2px;
align-content: center;
flex: 1;
}
.table-style-options button {
min-height: 22px;
padding: 1px 5px;
text-align: left;
}
.table-option-toggle {
display: flex;
align-items: center;
justify-content: flex-start;
gap: 5px;
}
.table-option-toggle > span:last-child {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.table-option-check {
position: relative;
box-sizing: border-box;
flex: 0 0 13px;
width: 13px;
height: 13px;
border: 1px solid var(--border-strong);
border-radius: 4px;
background: var(--surface);
}
.table-option-toggle.active .table-option-check {
border-color: var(--accent);
background: var(--accent);
}
.table-option-toggle.active .table-option-check::after {
position: absolute;
left: 3px;
top: 0;
width: 3px;
height: 7px;
border: solid var(--docs-on-accent);
border-width: 0 1.5px 1.5px 0;
content: '';
transform: rotate(45deg);
}
.table-tool-autofit {
min-width: 158px;
}
.table-autofit-wrap {
width: 100%;
}
.table-tool-group .table-command-button {
display: grid;
grid-template-columns: 20px minmax(0, 1fr) 12px;
align-items: center;
width: 100%;
min-height: 52px;
padding: 5px 7px;
gap: 6px;
border-color: var(--border);
background: var(--surface);
}
.table-command-button:hover:not(:disabled),
.table-command-button.active {
border-color: var(--border-strong);
background: var(--hover);
}
.table-command-copy {
display: flex;
min-width: 0;
flex-direction: column;
align-items: flex-start;
gap: 1px;
text-align: left;
}
.table-command-copy > span,
.table-command-copy > small {
display: block;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.table-command-copy > small {
color: var(--text-dim);
font-size: 10px;
}
.table-autofit-menu {
width: 238px;
padding: 6px;
}
.layout-menu.table-autofit-menu button {
display: grid;
grid-template-columns: 22px minmax(0, 1fr) 12px;
min-height: 36px;
padding: 6px 8px;
align-items: center;
gap: 7px;
border-radius: 6px;
text-align: left;
}
.layout-menu.table-autofit-menu button > span {
color: var(--text);
font-size: 12px;
}
.table-menu-state {
width: 7px;
height: 7px;
justify-self: center;
border-radius: 50%;
background: transparent;
}
.table-autofit-menu button.active .table-menu-state {
background: var(--accent);
}
.table-tool-advanced {
min-width: 146px;
}
.table-tool-stack {
display: grid;
grid-template-rows: repeat(2, minmax(25px, 1fr));
gap: 2px;
flex: 1;
}
.table-tool-group .table-command-row {
display: grid;
grid-template-columns: 18px minmax(0, 1fr);
min-height: 25px;
padding: 2px 7px;
align-items: center;
gap: 6px;
text-align: left;
}
.table-command-row > span {
overflow: hidden;
text-overflow: ellipsis;
}
/* anchored textboxes (code boxes, callout cards): render the box itself, /* anchored textboxes (code boxes, callout cards): render the box itself,
text edits happen in place */ text edits happen in place */
.doc-protected-textboxes { .doc-protected-textboxes {
@@ -4168,14 +4365,14 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
.doc-inline-img--wrap-tight-left, .doc-inline-img--wrap-tight-left,
.doc-inline-img--wrap-through-left { .doc-inline-img--wrap-through-left {
float: left; float: left;
margin: 2px 14px 6px 0; margin: 0 12px 0 0;
} }
.doc-inline-img--wrap-square-right, .doc-inline-img--wrap-square-right,
.doc-inline-img--wrap-tight-right, .doc-inline-img--wrap-tight-right,
.doc-inline-img--wrap-through-right { .doc-inline-img--wrap-through-right {
float: right; float: right;
margin: 2px 0 6px 14px; margin: 0 0 0 12px;
} }
.doc-inline-img--wrap-topBottom { .doc-inline-img--wrap-topBottom {
@@ -4380,6 +4577,14 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
line-height: inherit; line-height: inherit;
} }
/* field results keep their spaces (Word preserves them; collapsing reflows the
wrap column around anchored pictures) — must outrank prosemirror-view's
injected `.ProseMirror [contenteditable=false] { white-space: normal }` */
.ProseMirror [contenteditable='false'].doc-field-text,
.ProseMirror [contenteditable='false'] .doc-field-text {
white-space: pre-wrap;
}
.doc-content-editing .doc-toc-title, .doc-content-editing .doc-toc-title,
.doc-content-editing .doc-toc-page, .doc-content-editing .doc-toc-page,
.doc-content-editing .doc-field-text, .doc-content-editing .doc-field-text,
@@ -4709,10 +4914,15 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
line-height: 0; line-height: 0;
} }
.doc-protected[data-doc-protected='image'] .doc-img-wrap > img { .doc-protected[data-doc-protected='image'] .doc-img-wrap > img,
.doc-protected[data-doc-protected='image'] .doc-img-crop-viewport > img {
vertical-align: bottom; vertical-align: bottom;
} }
.doc-image-leading-space {
white-space: pre;
}
.doc-protected[data-doc-protected='image']:hover { .doc-protected[data-doc-protected='image']:hover {
border-color: var(--border); border-color: var(--border);
} }
@@ -4729,6 +4939,12 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
max-width: 100%; max-width: 100%;
} }
.doc-img-crop-viewport {
display: block;
width: 100%;
height: 100%;
}
/* find option toggles (match case / whole word) */ /* find option toggles (match case / whole word) */
.find-opt { .find-opt {
border: 1px solid var(--border); border: 1px solid var(--border);
@@ -4871,7 +5087,7 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
float: left; float: left;
width: fit-content; width: fit-content;
max-width: 60%; max-width: 60%;
margin: 2px 14px 6px 0; margin: 0 12px 0 0;
} }
.doc-protected.img-wrap-square-right, .doc-protected.img-wrap-square-right,
@@ -4880,7 +5096,7 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
float: right; float: right;
width: fit-content; width: fit-content;
max-width: 60%; max-width: 60%;
margin: 2px 0 6px 14px; margin: 0 0 0 12px;
} }
.doc-protected.img-wrap-topBottom { .doc-protected.img-wrap-topBottom {
@@ -4913,15 +5129,65 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
.img-resize-handle { .img-resize-handle {
display: none; display: none;
position: absolute; position: absolute;
right: -6px; box-sizing: border-box;
bottom: -6px; width: 9px;
width: 11px; height: 9px;
height: 11px;
background: var(--docs-paper); background: var(--docs-paper);
border: 2px solid var(--word-blue); border: 1px solid var(--word-blue);
border-radius: 50%; border-radius: 1px;
z-index: 6;
}
.img-resize-handle-nw {
top: -5px;
left: -5px;
cursor: nwse-resize; cursor: nwse-resize;
z-index: 2; }
.img-resize-handle-n {
top: -5px;
left: 50%;
transform: translateX(-50%);
cursor: ns-resize;
}
.img-resize-handle-ne {
top: -5px;
right: -5px;
cursor: nesw-resize;
}
.img-resize-handle-e {
top: 50%;
right: -5px;
transform: translateY(-50%);
cursor: ew-resize;
}
.img-resize-handle-se {
right: -5px;
bottom: -5px;
cursor: nwse-resize;
}
.img-resize-handle-s {
bottom: -5px;
left: 50%;
transform: translateX(-50%);
cursor: ns-resize;
}
.img-resize-handle-sw {
bottom: -5px;
left: -5px;
cursor: nesw-resize;
}
.img-resize-handle-w {
top: 50%;
left: -5px;
transform: translateY(-50%);
cursor: ew-resize;
} }
.ProseMirror-focused .ProseMirror-focused
@@ -4930,6 +5196,28 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
display: block; display: block;
} }
.doc-image-anchor-marker {
display: none;
position: absolute;
z-index: 6;
top: -11px;
left: -32px;
width: 22px;
height: 22px;
align-items: center;
justify-content: center;
color: var(--text);
font: 16px/1 sans-serif;
pointer-events: none;
user-select: none;
}
.ProseMirror-focused
.doc-protected[data-doc-protected='image'].ProseMirror-selectednode
> .doc-image-anchor-marker {
display: flex;
}
/* Crop owns the active image controls while its modal is open. */ /* Crop owns the active image controls while its modal is open. */
body.docs-crop-active body.docs-crop-active
.doc-protected[data-doc-protected='image'].ProseMirror-selectednode .doc-protected[data-doc-protected='image'].ProseMirror-selectednode
@@ -4940,6 +5228,9 @@ body.docs-crop-active
body.docs-crop-active body.docs-crop-active
.doc-protected[data-doc-protected='image'].ProseMirror-selectednode .doc-protected[data-doc-protected='image'].ProseMirror-selectednode
.img-resize-handle, .img-resize-handle,
body.docs-crop-active
.doc-protected[data-doc-protected='image'].ProseMirror-selectednode
> .doc-image-anchor-marker,
body.docs-crop-active body.docs-crop-active
.doc-protected[data-doc-protected='image'].ProseMirror-selectednode .doc-protected[data-doc-protected='image'].ProseMirror-selectednode
> .doc-move-handle { > .doc-move-handle {
@@ -6069,7 +6360,35 @@ body.docs-crop-active
box-shadow: var(--docs-shadow-menu); box-shadow: var(--docs-shadow-menu);
} }
.ai-ask-pop-close {
position: absolute;
top: 10px;
right: 10px;
display: inline-flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
padding: 0;
border: none;
border-radius: 6px;
background: transparent;
color: var(--text-dim);
cursor: pointer;
}
.ai-ask-pop-close:hover {
background: var(--hover);
color: var(--text);
}
.ai-ask-pop-close:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 1px;
}
.ai-ask-pop-title { .ai-ask-pop-title {
padding-right: 24px;
font-size: 12.5px; font-size: 12.5px;
font-weight: 600; font-weight: 600;
color: var(--text); color: var(--text);
@@ -7895,7 +8214,8 @@ body.docs-crop-active
padding: 0; padding: 0;
} }
.img-resize-handle { .img-resize-handle,
.doc-image-anchor-marker {
display: none !important; display: none !important;
} }
@@ -7923,6 +8243,13 @@ body.docs-crop-active
display: none !important; display: none !important;
} }
/* header/footer guide line is editor chrome: Word never prints it.
Keep the 2px padding so pagination geometry doesn't shift. */
.page-hf-header,
.page-hf-footer {
border-color: transparent !important;
}
.page-wrap.has-markup-area { .page-wrap.has-markup-area {
padding-right: 0 !important; padding-right: 0 !important;
} }
@@ -8216,6 +8543,9 @@ body.docs-crop-active
exports and change line widths); accent is a hover/selection-only affordance */ exports and change line widths); accent is a hover/selection-only affordance */
.doc-note-ref { .doc-note-ref {
cursor: default; cursor: default;
/* Word's reference-mark superscript is ~65% of the run size; the UA default
(font-size:smaller) rendered it visibly larger and taller than Word */
font-size: 0.65em;
} }
.doc-note-ref:hover { .doc-note-ref:hover {
@@ -8307,11 +8637,13 @@ ruby.doc-ruby rt {
color: var(--docs-paper-ink-dim); color: var(--docs-paper-ink-dim);
} }
/* canvas twin of the pv separators: Word's 2in rule, drawn at the row's bottom */
.page-notes::before { .page-notes::before {
content: ''; content: '';
display: block; display: block;
width: 33%; width: min(2in, 100%);
border-top: 1px solid var(--docs-paper-ink-faint); height: 11px;
border-bottom: 1px solid var(--docs-paper-ink-faint);
margin-bottom: 6px; margin-bottom: 6px;
} }
@@ -8346,6 +8678,7 @@ ruby.doc-ruby rt {
flex: none; flex: none;
position: relative; position: relative;
top: -0.33em; top: -0.33em;
font-size: 0.65em;
} }
.page-note-text { .page-note-text {
@@ -9041,44 +9374,62 @@ tr > .page-gap-cut {
/* table style gallery cards */ /* table style gallery cards */
.table-style-gallery { .table-style-gallery {
display: flex; display: flex;
gap: 6px; align-items: center;
flex-wrap: wrap; gap: 3px;
max-width: 420px; flex-wrap: nowrap;
max-width: 500px;
overflow-x: auto;
padding-bottom: 2px;
scrollbar-width: none;
}
.table-style-gallery::-webkit-scrollbar {
display: none;
} }
.table-style-card { .table-style-card {
display: flex; display: flex;
box-sizing: border-box;
flex: 0 0 76px;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
gap: 2px; gap: 3px;
padding: 4px 6px; padding: 4px 5px;
border: 1px solid var(--border); border: 1px solid transparent;
border-radius: 4px; border-radius: 7px;
background: var(--surface); background: transparent;
cursor: pointer; cursor: pointer;
font-size: 10px; font-size: 10px;
color: var(--text-dim); color: var(--text-dim);
max-width: 86px;
} }
.table-style-card span:last-child { .table-style-card span:last-child {
overflow: hidden; overflow: hidden;
white-space: nowrap; white-space: nowrap;
text-overflow: ellipsis; text-overflow: ellipsis;
max-width: 74px; max-width: 68px;
} }
.table-style-card:hover { .table-style-card:hover {
border-color: var(--word-blue); border-color: var(--border);
background: var(--hover);
}
.table-style-card.active {
border-color: var(--accent);
background: var(--accent-soft);
color: var(--text);
} }
.table-style-card-grid { .table-style-card-grid {
width: 40px; box-sizing: border-box;
height: 22px; width: 44px;
height: 24px;
border: 1px solid var(--docs-tstyle-border); border: 1px solid var(--docs-tstyle-border);
border-top: 5px solid var(--docs-tstyle-header); border-top: 5px solid var(--docs-tstyle-header);
background: repeating-linear-gradient(var(--surface) 0 4px, var(--docs-tstyle-row) 4px 8px); background: repeating-linear-gradient(var(--surface) 0 4px, var(--docs-tstyle-row) 4px 8px);
border-radius: 2px; border-radius: 3px;
box-shadow: var(--docs-shadow-chip);
} }
.table-style-card-grid.plain { .table-style-card-grid.plain {
@@ -9086,6 +9437,220 @@ tr > .page-gap-cut {
background: var(--surface); background: var(--surface);
} }
.table-properties-dialog {
width: min(620px, calc(100vw - 48px));
max-height: calc(100vh - 64px);
overflow-y: auto;
}
.table-properties-header {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 18px;
}
.table-properties-header-icon {
display: inline-flex;
flex: 0 0 40px;
width: 40px;
height: 40px;
align-items: center;
justify-content: center;
border-radius: 11px;
background: var(--accent-soft);
color: var(--accent);
}
.table-properties-header .modal-desc {
margin: 2px 0 0;
}
.table-properties-card {
margin-top: 10px;
padding: 14px;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--surface);
}
.table-properties-dialog h3 {
margin: 0 0 12px;
font-size: 13px;
font-weight: 600;
color: var(--text);
}
.table-properties-segments {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 3px;
padding: 3px;
border-radius: 9px;
background: var(--hover);
}
.table-properties-segment {
position: relative;
min-width: 0;
cursor: pointer;
}
.table-properties-segment input {
position: absolute;
opacity: 0;
pointer-events: none;
}
.table-properties-segment span {
display: flex;
min-height: 32px;
padding: 0 8px;
align-items: center;
justify-content: center;
border: 1px solid transparent;
border-radius: 7px;
color: var(--text-dim);
font-size: 12px;
text-align: center;
transition:
background var(--transition-fast),
border-color var(--transition-fast),
color var(--transition-fast);
}
.table-properties-segment input:checked + span {
border-color: var(--border);
background: var(--surface);
box-shadow: var(--docs-shadow-chip);
color: var(--text);
}
.table-properties-segment input:focus-visible + span {
box-shadow: 0 0 0 3px var(--docs-focus-ring);
}
.table-properties-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px 16px;
margin-top: 12px;
}
.table-properties-grid > label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
color: var(--text-dim);
font-size: 12px;
}
.table-properties-grid label > span {
display: inline-flex;
align-items: center;
gap: 4px;
}
.table-properties-grid input {
box-sizing: border-box;
width: 70px;
height: 30px;
padding: 0 8px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--surface);
color: var(--text);
outline: none;
}
.table-properties-grid input:hover {
border-color: var(--border-strong);
}
.table-properties-grid input:focus {
border-color: var(--accent);
box-shadow: 0 0 0 3px var(--docs-focus-ring);
}
.table-properties-margin-layout {
display: grid;
grid-template-columns: minmax(0, 1fr) 148px;
align-items: center;
gap: 20px;
}
.table-properties-margin-layout .table-properties-grid {
margin-top: 0;
}
.table-margin-preview {
position: relative;
box-sizing: border-box;
width: 132px;
height: 96px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--hover);
}
.table-margin-preview-cell {
position: absolute;
inset: 24px 30px;
border: 1px solid var(--accent);
border-radius: 4px;
background: var(--accent-soft);
}
.table-margin-value {
position: absolute;
color: var(--text-dim);
font-size: 10px;
line-height: 1;
}
.table-margin-value.top,
.table-margin-value.bottom {
left: 50%;
transform: translateX(-50%);
}
.table-margin-value.top {
top: 8px;
}
.table-margin-value.bottom {
bottom: 8px;
}
.table-margin-value.left,
.table-margin-value.right {
top: 50%;
transform: translateY(-50%);
}
.table-margin-value.left {
left: 8px;
}
.table-margin-value.right {
right: 8px;
}
@media (max-width: 620px) {
.table-properties-segments {
grid-template-columns: 1fr;
}
.table-properties-margin-layout {
grid-template-columns: 1fr;
}
.table-margin-preview {
display: none;
}
}
/* comment threads: replies and resolution */ /* comment threads: replies and resolution */
.comment-thread { .comment-thread {
border-bottom: 1px solid var(--border); border-bottom: 1px solid var(--border);
@@ -0,0 +1,121 @@
/**
* w:autoHyphenation → CSS hyphens, gated by w:suppressAutoHyphens (github run
* 20260825 samples 16/91: Word does not hyphenate when pPrDefault carries
* w:suppressAutoHyphens even though settings.xml enables autoHyphenation).
*/
import { describe, expect, it } from 'vitest'
import type { DocDefaults, ParsedDocFull, StyleInfo } from '@genoffice/docx-engine'
import { docStyleCss } from '../src/renderer/doc-style-css'
;(globalThis as { CSS?: unknown }).CSS ??= { escape: (s: string) => s }
function parsedDoc(opts: {
autoHyphenation?: boolean
docDefaults?: DocDefaults
styles?: StyleInfo[]
}): ParsedDocFull {
const styles = new Map<string, StyleInfo>()
for (const s of opts.styles ?? []) styles.set(s.styleId, s)
return {
styles,
docDefaults: opts.docDefaults ?? {},
blocks: [],
...(opts.autoHyphenation ? { autoHyphenation: true } : {}),
} as unknown as ParsedDocFull
}
const AUTO = '.doc-page { hyphens:auto; -webkit-hyphens:auto }'
describe('autoHyphenation CSS', () => {
it('emits document-wide hyphens:auto for plain autoHyphenation', () => {
expect(docStyleCss(parsedDoc({ autoHyphenation: true }))).toContain(AUTO)
})
it('emits nothing without autoHyphenation', () => {
expect(docStyleCss(parsedDoc({}))).not.toContain('hyphens')
})
it('pPrDefault suppressAutoHyphens turns the document-wide rule off', () => {
const css = docStyleCss(
parsedDoc({ autoHyphenation: true, docDefaults: { suppressAutoHyphens: true } }),
)
expect(css).not.toContain(AUTO)
})
it('default paragraph style suppressAutoHyphens turns the document-wide rule off', () => {
const css = docStyleCss(
parsedDoc({
autoHyphenation: true,
styles: [
{
styleId: 'Normal',
name: 'Normal',
type: 'paragraph',
isDefault: true,
display: { suppressAutoHyphens: true },
} as StyleInfo,
],
}),
)
expect(css).not.toContain(AUTO)
})
it("default style's explicit off overrides a suppressing pPrDefault", () => {
const css = docStyleCss(
parsedDoc({
autoHyphenation: true,
docDefaults: { suppressAutoHyphens: true },
styles: [
{
styleId: 'Normal',
name: 'Normal',
type: 'paragraph',
isDefault: true,
display: { suppressAutoHyphens: false },
} as StyleInfo,
],
}),
)
expect(css).toContain(AUTO)
})
it('styled paragraphs override per style in both directions', () => {
const css = docStyleCss(
parsedDoc({
autoHyphenation: true,
styles: [
{
styleId: 'NoHyph',
name: 'NoHyph',
type: 'paragraph',
display: { suppressAutoHyphens: true },
} as StyleInfo,
{
styleId: 'ReHyph',
name: 'ReHyph',
type: 'paragraph',
display: { suppressAutoHyphens: false },
} as StyleInfo,
],
}),
)
expect(css).toContain('[data-style="NoHyph"] { hyphens:manual;-webkit-hyphens:manual }')
expect(css).toContain('[data-style="ReHyph"] { hyphens:auto;-webkit-hyphens:auto }')
})
it('style values are inert without autoHyphenation', () => {
const css = docStyleCss(
parsedDoc({
styles: [
{
styleId: 'NoHyph',
name: 'NoHyph',
type: 'paragraph',
display: { suppressAutoHyphens: true },
} as StyleInfo,
],
}),
)
expect(css).not.toContain('hyphens')
})
})
+62
View File
@@ -2,9 +2,12 @@ import { Editor } from '@tiptap/core'
import { parseDocx, saveDocx } from '@genoffice/docx-engine' import { parseDocx, saveDocx } from '@genoffice/docx-engine'
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest'
import { buildDocx } from '../../../packages/docx-engine/tests/helpers/build-docx' import { buildDocx } from '../../../packages/docx-engine/tests/helpers/build-docx'
import { docStyleCss } from '../src/renderer/doc-style-css'
import { blocksToPmDoc, pmDocToSavePlan, type PmNode } from '../src/renderer/editor/convert' import { blocksToPmDoc, pmDocToSavePlan, type PmNode } from '../src/renderer/editor/convert'
import { editorExtensions } from '../src/renderer/editor/extensions' import { editorExtensions } from '../src/renderer/editor/extensions'
;(globalThis as { CSS?: unknown }).CSS ??= { escape: (s: string) => s }
const STYLES = const STYLES =
'<w:style w:type="character" w:styleId="Emphasis"><w:name w:val="Emphasis"/>' + '<w:style w:type="character" w:styleId="Emphasis"><w:name w:val="Emphasis"/>' +
'<w:rPr><w:i/><w:color w:val="C00000"/></w:rPr></w:style>' '<w:rPr><w:i/><w:color w:val="C00000"/></w:rPr></w:style>'
@@ -53,3 +56,62 @@ describe('character styles in the editor', () => {
editor.destroy() editor.destroy()
}) })
}) })
describe('explicit off (w:val="0") overrides style-inherited formatting', () => {
const OFF_STYLES =
'<w:style w:type="paragraph" w:styleId="BoldPara"><w:name w:val="Bold Para"/>' +
'<w:rPr><w:b/><w:i/><w:smallCaps/></w:rPr></w:style>'
const OFF_BODY =
'<w:p><w:pPr><w:pStyle w:val="BoldPara"/></w:pPr>' +
'<w:r><w:rPr><w:b w:val="0"/><w:i w:val="0"/><w:smallCaps w:val="0"/></w:rPr><w:t>plain</w:t></w:r>' +
'<w:r><w:t xml:space="preserve"> styled</w:t></w:r></w:p>'
async function openOff() {
const source = await buildDocx({ bodyXml: OFF_BODY, extraStylesXml: OFF_STYLES })
const parsed = await parseDocx(source)
const editor = new Editor({
element: document.createElement('div'),
extensions: editorExtensions,
content: blocksToPmDoc(parsed.blocks) as never,
})
return { editor, parsed, source }
}
it('run-level off renders counter styles so style CSS cannot re-apply them', async () => {
const { editor } = await openOff()
const span = editor.view.dom.querySelector<HTMLElement>('span[data-doc-style]')
expect(span?.textContent).toBe('plain')
expect(span!.style.fontWeight).toBe('normal')
expect(span!.style.fontStyle).toBe('normal')
expect(span!.style.fontVariantCaps).toBe('normal')
expect(span!.style.textTransform).toBe('none')
editor.destroy()
})
it('keeps the untouched document byte-identical', async () => {
const { editor, parsed, source } = await openOff()
const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
expect(plan.changedCount).toBe(0)
expect(await saveDocx(parsed, plan.saveBlocks)).toEqual(source)
editor.destroy()
})
it('style-level off emits reversing declarations in docStyleCss', async () => {
const source = await buildDocx({
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
extraStylesXml:
OFF_STYLES +
'<w:style w:type="paragraph" w:styleId="PlainChild"><w:name w:val="Plain Child"/><w:basedOn w:val="BoldPara"/>' +
'<w:rPr><w:b w:val="0"/><w:i w:val="0"/><w:smallCaps w:val="0"/></w:rPr></w:style>',
})
const css = docStyleCss(await parseDocx(source))
const rule = css
.split('\n')
.find((l) => l.includes('[data-style="PlainChild"]') && l.includes('font-weight'))
expect(rule).toContain('font-weight:400')
expect(rule).toContain('font-style:normal')
expect(rule).toContain('font-variant-caps:normal')
expect(rule).toContain('text-transform:none')
})
})
+87
View File
@@ -0,0 +1,87 @@
import type { ChartDisplay } from '@genoffice/docx-engine'
import { describe, expect, it } from 'vitest'
import { drawChartSvg } from '../src/renderer/editor/protected-render'
function draw(chart: ChartDisplay): HTMLElement {
const dom = document.createElement('div')
const canvas = document.createElement('div')
canvas.className = 'doc-chart-canvas'
dom.appendChild(canvas)
drawChartSvg(dom, chart)
return dom
}
describe('chart svg drawing', () => {
it('skips scatter points with a null cached x and keeps labels on their own points', () => {
const dom = draw({
partPath: 'word/charts/chart1.xml',
kind: 'scatter',
markers: true,
categories: ['Alpha', 'Beta', 'Gamma'],
series: [{ name: 'S1', values: [10, 20, 30], xValues: [1, null, 3] }],
})
// the Beta point (null x) is dropped, not plotted at index 2
expect(dom.querySelectorAll('circle').length).toBe(2)
const labels = [...dom.querySelectorAll('.doc-chart-axis-label')].map((t) => t.textContent)
expect(labels).toContain('Alpha')
expect(labels).toContain('Gamma')
expect(labels).not.toContain('Beta')
// Gamma anchors to the x=3 point (plot right edge), not to the second survivor slot
const gamma = [...dom.querySelectorAll('.doc-chart-axis-label')].find(
(t) => t.textContent === 'Gamma',
)!
const alpha = [...dom.querySelectorAll('.doc-chart-axis-label')].find(
(t) => t.textContent === 'Alpha',
)!
const circles = [...dom.querySelectorAll('circle')]
expect(Number(gamma.getAttribute('x'))).toBeCloseTo(Number(circles[1].getAttribute('cx')), 3)
expect(Number(alpha.getAttribute('x'))).toBeCloseTo(Number(circles[0].getAttribute('cx')), 3)
})
it('stacks percentStacked area charts and normalizes the axis to 0-100%', () => {
const dom = draw({
partPath: 'word/charts/chart1.xml',
kind: 'area',
grouping: 'percentStacked',
categories: ['A', 'B'],
series: [
{ name: 'S1', values: [1, 3] },
{ name: 'S2', values: [3, 1] },
],
})
const labels = [...dom.querySelectorAll('.doc-chart-axis-label')].map((t) => t.textContent)
expect(labels).toContain('100%')
expect(labels).toContain('0%')
const polygons = [...dom.querySelectorAll('polygon')]
expect(polygons.length).toBe(2)
// the top series' upper edge sits on the 100% line at both categories
const topLine = dom.querySelectorAll('polyline')[1]
const ys = topLine
.getAttribute('points')!
.split(' ')
.map((p) => Number(p.split(',')[1]))
expect(ys[0]).toBeCloseTo(ys[1], 3)
const hundred = [...dom.querySelectorAll('.doc-chart-axis-label')].find(
(t) => t.textContent === '100%',
)!
expect(ys[0]).toBeCloseTo(Number(hundred.getAttribute('y')) - 3, 3)
})
it('stacks plain stacked area charts cumulatively', () => {
const dom = draw({
partPath: 'word/charts/chart1.xml',
kind: 'area',
grouping: 'stacked',
categories: ['A', 'B'],
series: [
{ name: 'S1', values: [2, 2] },
{ name: 'S2', values: [2, 2] },
],
})
// axis labels carry no % suffix and reach the stacked total (4) or above
const labels = [...dom.querySelectorAll('.doc-chart-axis-label')].map((t) => t.textContent)
expect(labels.some((l) => l?.includes('%'))).toBe(false)
expect(labels).toContain('4')
expect(dom.querySelectorAll('polygon').length).toBe(2)
})
})
@@ -61,6 +61,10 @@ describe('runsToInline image runs', () => {
wrap: null, wrap: null,
offsetXEmu: null, offsetXEmu: null,
offsetYEmu: null, offsetYEmu: null,
wrapDistTopEmu: null,
wrapDistBottomEmu: null,
wrapDistLeftEmu: null,
wrapDistRightEmu: null,
border: null, border: null,
lineCenterV: false, lineCenterV: false,
}, },
@@ -83,6 +87,10 @@ describe('runsToInline image runs', () => {
wrap: null, wrap: null,
offsetXEmu: null, offsetXEmu: null,
offsetYEmu: null, offsetYEmu: null,
wrapDistTopEmu: null,
wrapDistBottomEmu: null,
wrapDistLeftEmu: null,
wrapDistRightEmu: null,
border: null, border: null,
lineCenterV: false, lineCenterV: false,
}, },
+278
View File
@@ -22,6 +22,177 @@ async function openImageDoc(bodyXml = IMAGE_PARAGRAPH_XML, extraRels?: string) {
} }
describe('image wrap in the editor', () => { describe('image wrap in the editor', () => {
it('renders eight resize handles plus a floating-image position marker', async () => {
const { editor } = await openImageDoc()
const directions = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w']
const imageBox = editor.view.dom.querySelector<HTMLElement>('.doc-img-wrap')!
expect(
[...imageBox.querySelectorAll<HTMLElement>('.img-resize-handle')].map(
(handle) => handle.dataset.resizeHandle,
),
).toEqual(directions)
expect(editor.view.dom.querySelector('.doc-image-anchor-marker')).toBeNull()
editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, 0)))
editor.commands.updateAttributes('docProtected', {
imageWrap: 'front',
imageOffsetYEmu: 40 * 9525,
})
const marker = editor.view.dom.querySelector<HTMLElement>('.doc-image-anchor-marker')!
expect(marker.textContent).toContain('⚓')
expect(marker.dataset.anchorY).toBeUndefined()
expect(marker.style.transform).toBe('')
editor.destroy()
})
it('keeps selection controls outside a cropped picture viewport', async () => {
const croppedXml = IMAGE_PARAGRAPH_XML.replace(
'</pic:blipFill>',
'<a:srcRect l="10000" t="5000" r="10000" b="5000"/></pic:blipFill>',
)
const { editor } = await openImageDoc(croppedXml)
const imageBox = editor.view.dom.querySelector<HTMLElement>('.doc-img-crop')!
const viewport = imageBox.querySelector<HTMLElement>('.doc-img-crop-viewport')!
expect(viewport.style.overflow).toBe('hidden')
expect(imageBox.style.overflow).toBe('')
expect(imageBox.querySelectorAll('.img-resize-handle')).toHaveLength(8)
expect(viewport.querySelector('.img-resize-handle')).toBeNull()
editor.destroy()
})
it('moves the anchor to the nearest paragraph and rebases the picture offset', async () => {
const paragraph = (text: string) => `<w:p><w:r><w:t>${text}</w:t></w:r></w:p>`
const { editor, parsed } = await openImageDoc(
paragraph('Anchor A') + IMAGE_PARAGRAPH_XML + paragraph('Anchor B') + paragraph('Anchor C'),
)
let imagePos = -1
const paragraphPositions: number[] = []
editor.state.doc.forEach((node, pos) => {
if (node.type.name === 'docProtected') imagePos = pos
else if (node.type.name === 'docParagraph') paragraphPositions.push(pos)
})
editor.view.dispatch(
editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, imagePos)),
)
editor.commands.updateAttributes('docProtected', {
imageWrap: 'front',
imageOffsetXEmu: 0,
imageOffsetYEmu: 0,
})
const rect = (left: number, top: number, width: number, height: number) =>
new DOMRect(left, top, width, height)
// B ends exactly where C begins. A drop on that shared edge must choose C.
const paragraphTops = [40, 100, 160]
paragraphPositions.forEach((pos, index) => {
const dom = editor.view.nodeDOM(pos) as HTMLElement
dom.getBoundingClientRect = () => rect(100, paragraphTops[index], 500, 60)
})
const wrapper = editor.view.nodeDOM(imagePos) as HTMLElement
wrapper.getBoundingClientRect = () => rect(100, 100, 500, 0)
const imageBox = wrapper.querySelector<HTMLElement>('.doc-img-wrap')!
imageBox.getBoundingClientRect = () => rect(200, 100, 100, 50)
imageBox.dispatchEvent(
new MouseEvent('mousedown', { bubbles: true, button: 0, clientX: 200, clientY: 100 }),
)
window.dispatchEvent(new MouseEvent('mousemove', { clientX: 200, clientY: 160 }))
const marker = wrapper.querySelector<HTMLElement>('.doc-image-anchor-marker')!
expect(marker.dataset.anchorTargetPos).toBe(String(paragraphPositions[2]))
expect(marker.style.transform).toContain('60')
window.dispatchEvent(new MouseEvent('mouseup', { clientX: 200, clientY: 160 }))
expect(editor.state.doc.content.content.map((node) => node.type.name)).toEqual([
'docParagraph',
'docParagraph',
'docProtected',
'docParagraph',
])
const movedImage =
editor.state.selection instanceof NodeSelection && editor.state.selection.node
expect(movedImage && movedImage.attrs.imageOffsetYEmu).toBe(0)
const saved = await saveDocx(
parsed,
pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks).saveBlocks,
)
const reparsed = await parseDocx(saved)
expect(reparsed.blocks.filter((block) => !block.hidden).map((block) => block.type)).toEqual([
'paragraph',
'paragraph',
'image',
'paragraph',
])
editor.destroy()
})
it('resizes from a northwest handle and keeps the opposite corner fixed', async () => {
const { editor } = await openImageDoc()
const emu = 9525
editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, 0)))
editor.commands.updateAttributes('docProtected', {
imageWidthPx: 100,
imageHeightPx: 50,
imageWrap: 'front',
imageOffsetXEmu: 100 * emu,
imageOffsetYEmu: 50 * emu,
})
editor.view.dom
.querySelector<HTMLElement>('.img-resize-handle-nw')!
.dispatchEvent(
new MouseEvent('mousedown', { bubbles: true, button: 0, clientX: 100, clientY: 100 }),
)
window.dispatchEvent(new MouseEvent('mouseup', { clientX: 90, clientY: 90 }))
const attrs = editor.state.doc.nodeAt(0)!.attrs
expect(attrs.imageWidthPx).toBe(112)
expect(attrs.imageHeightPx).toBe(56)
expect(attrs.imageOffsetXEmu).toBe(88 * emu)
expect(attrs.imageOffsetYEmu).toBe(44 * emu)
editor.destroy()
})
it('keeps the opposite edge fixed while previewing in-flow west and north resizes', async () => {
const { editor } = await openImageDoc()
const emu = 9525
editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, 0)))
editor.commands.updateAttributes('docProtected', {
imageWidthPx: 100,
imageHeightPx: 50,
imageWrap: 'square-left',
imageOffsetXEmu: 100 * emu,
imageOffsetYEmu: 0,
})
let imageBox = editor.view.dom.querySelector<HTMLElement>('.doc-img-wrap')!
imageBox
.querySelector<HTMLElement>('.img-resize-handle-w')!
.dispatchEvent(
new MouseEvent('mousedown', { bubbles: true, button: 0, clientX: 100, clientY: 100 }),
)
window.dispatchEvent(new MouseEvent('mousemove', { clientX: 90, clientY: 100 }))
expect(imageBox.style.left).toBe('-10px')
expect(imageBox.style.width).toBe('110px')
window.dispatchEvent(new MouseEvent('mouseup', { clientX: 90, clientY: 100 }))
expect(editor.state.doc.nodeAt(0)!.attrs.imageOffsetXEmu).toBe(90 * emu)
imageBox = editor.view.dom.querySelector<HTMLElement>('.doc-img-wrap')!
imageBox
.querySelector<HTMLElement>('.img-resize-handle-n')!
.dispatchEvent(
new MouseEvent('mousedown', { bubbles: true, button: 0, clientX: 100, clientY: 100 }),
)
window.dispatchEvent(new MouseEvent('mousemove', { clientX: 100, clientY: 90 }))
expect(imageBox.style.top).toBe('-10px')
expect(imageBox.style.height).toBe('60px')
window.dispatchEvent(new MouseEvent('mouseup', { clientX: 100, clientY: 90 }))
expect(editor.state.doc.nodeAt(0)!.attrs.imageOffsetYEmu).toBe(-10 * emu)
editor.destroy()
})
it('keeps an untouched image byte-identical', async () => { it('keeps an untouched image byte-identical', async () => {
const { editor, parsed, source } = await openImageDoc() const { editor, parsed, source } = await openImageDoc()
const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks) const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
@@ -331,6 +502,18 @@ describe('image wrap in the editor', () => {
'id="2" name="pic 2"', 'id="2" name="pic 2"',
) )
it('preserves a locked picture anchor for WPS/Word drag semantics', async () => {
const { editor, parsed, source } = await openImageDoc(
WILD_ANCHOR_XML.replace('locked="0"', 'locked="1"'),
)
expect(parsed.blocks[0].imageAnchorLocked).toBe(true)
expect(editor.state.doc.firstChild?.attrs.imageAnchorLocked).toBe(true)
const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
expect(plan.changedCount).toBe(0)
expect(await saveDocx(parsed, plan.saveBlocks)).toEqual(source)
editor.destroy()
})
it('untouched wild-relativeHeight anchors stay byte-identical on save', async () => { it('untouched wild-relativeHeight anchors stay byte-identical on save', async () => {
const { editor, parsed, source } = await openImageDoc(WILD_TWO_ANCHORS_XML) const { editor, parsed, source } = await openImageDoc(WILD_TWO_ANCHORS_XML)
expect(parsed.blocks[0].imageZOrder).toBeUndefined() // compact rank 0 expect(parsed.blocks[0].imageZOrder).toBeUndefined() // compact rank 0
@@ -479,6 +662,101 @@ describe('image wrap in the editor', () => {
editor.destroy() editor.destroy()
}) })
it('run-level square float honors posOffset X and sides by picture center (public issue #118)', async () => {
// text + anchor share the paragraph -> run-level docInlineImage path;
// left edge before mid-body but the wide body fills the right half
const bodyXml =
'<w:p><w:r><w:t>before</w:t></w:r><w:r><w:drawing>' +
'<wp:anchor distT="0" distB="0" distL="114300" distR="114300" simplePos="0" relativeHeight="1" behindDoc="0" locked="0" layoutInCell="1" allowOverlap="1">' +
'<wp:simplePos x="0" y="0"/>' +
'<wp:positionH relativeFrom="column"><wp:posOffset>2407073</wp:posOffset></wp:positionH>' +
'<wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV>' +
'<wp:extent cx="2851200" cy="2138400"/>' +
'<wp:wrapSquare wrapText="bothSides"/>' +
'<wp:docPr id="1" name="pic 1"/>' +
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
'<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill></pic:pic>' +
'</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>' +
'<w:r><w:t>after</w:t></w:r></w:p>'
const { editor } = await openImageDoc(bodyXml)
const img = editor.view.dom.querySelector<HTMLImageElement>(
'img.doc-inline-img--wrap-square-right',
)!
expect(img).toBeTruthy()
// colW − x − width from the right edge: x=2407073 EMU ≈ 252.7px, w ≈ 299px
expect(img.style.marginRight).toMatch(/calc\(100% - 55[12](\.\d)?px\)/)
expect(img.style.maxWidth).toBe('none')
expect(img.style.marginTop).toBe('0px')
expect(img.style.marginBottom).toBe('0px')
expect(img.style.marginLeft).toBe('12px')
editor.destroy()
})
it('positions an atomic inline picture after its spaces and first-line indent (public issue #118)', async () => {
const bodyXml = IMAGE_PARAGRAPH_XML.replace(
'<w:p>',
'<w:p><w:pPr><w:ind w:firstLine="420"/>' +
'<w:rPr><w:rFonts w:eastAsia="SimSun"/><w:sz w:val="24"/></w:rPr></w:pPr>' +
'<w:r><w:t xml:space="preserve"> </w:t></w:r>',
)
const { editor } = await openImageDoc(bodyXml)
const imageBlock = editor.view.dom.firstElementChild as HTMLElement
expect(editor.getJSON().content?.[0]?.type).toBe('docProtected')
expect(imageBlock.style.textIndent).toBe('')
expect(imageBlock.querySelector('.doc-image-leading-space')).toBeNull()
expect(imageBlock.querySelector<HTMLElement>('.doc-img-wrap')?.style.marginLeft).toBe(
'calc(2em + 28px)',
)
expect(imageBlock.querySelector('.doc-protected-img')).toBeTruthy()
editor.destroy()
})
it('wrap distances must not clobber the vertical posOffset (Bugbot)', async () => {
const { editor } = await openImageDoc()
editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, 0)))
editor.commands.updateAttributes('docProtected', {
imageWrap: 'square-left',
imageOffsetYEmu: 40 * 9525,
imageWrapDistTopEmu: 0,
imageWrapDistBottomEmu: 0,
imageWrapDistLeftEmu: 114300,
imageWrapDistRightEmu: 114300,
})
const el = editor.view.dom.querySelector<HTMLElement>('.doc-protected.img-wrap-square-left')!
// the position margin survives the distT=0 clearance; distB/distR still apply
expect(el.style.marginTop).toBe('40px')
expect(el.style.marginBottom).toBe('0px')
expect(el.style.marginRight).toBe('12px')
editor.destroy()
})
it('front/behind anchors ignore wrap distances (zero-height wrapper keeps no margins)', async () => {
const { editor } = await openImageDoc()
editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, 0)))
editor.commands.updateAttributes('docProtected', {
imageWrap: 'front',
imageWrapDistTopEmu: 114300,
imageWrapDistBottomEmu: 114300,
})
const el = editor.view.dom.querySelector<HTMLElement>('.doc-protected.doc-img-float')!
expect(el.style.marginTop).toBe('')
expect(el.style.marginBottom).toBe('')
editor.destroy()
})
it('applies paragraph indents to an image-only paragraph without leading text (Bugbot)', async () => {
const bodyXml = IMAGE_PARAGRAPH_XML.replace(
'<w:p>',
'<w:p><w:pPr><w:ind w:left="720" w:firstLine="420"/></w:pPr>',
)
const { editor } = await openImageDoc(bodyXml)
const imageBlock = editor.view.dom.firstElementChild as HTMLElement
expect(editor.getJSON().content?.[0]?.type).toBe('docProtected')
expect(imageBlock.style.marginInlineStart).toBe('36pt')
expect(imageBlock.style.textIndent).toBe('21pt')
editor.destroy()
})
it('topBottom wrap with an explicit X leaves the centered slot', async () => { it('topBottom wrap with an explicit X leaves the centered slot', async () => {
const { editor } = await openImageDoc() const { editor } = await openImageDoc()
editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, 0))) editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, 0)))
+6 -4
View File
@@ -328,7 +328,7 @@ describe('empty paragraph line size (emptyRunSize attr)', () => {
editor.destroy() editor.destroy()
}) })
it('lays the empty line with the paragraph-mark face metrics (Western only)', () => { it('lays the empty line with the paragraph-mark face metrics (CJK included)', () => {
const editor = new Editor({ const editor = new Editor({
element: document.createElement('div'), element: document.createElement('div'),
extensions: editorExtensions, extensions: editorExtensions,
@@ -337,14 +337,16 @@ describe('empty paragraph line size (emptyRunSize attr)', () => {
content: [ content: [
{ type: 'docParagraph', attrs: { emptyRunFont: 'Times New Roman' } }, { type: 'docParagraph', attrs: { emptyRunFont: 'Times New Roman' } },
{ type: 'docParagraph', attrs: { emptyRunFont: '맑은 고딕' } }, { type: 'docParagraph', attrs: { emptyRunFont: '맑은 고딕' } },
{ type: 'docParagraph', attrs: { emptyRunFont: '\u5b8b\u4f53' } },
], ],
} as never, } as never,
}) })
const [tnr, malgun] = Array.from(editor.view.dom.querySelectorAll('p')) as HTMLElement[] const [tnr, malgun, simsun] = Array.from(editor.view.dom.querySelectorAll('p')) as HTMLElement[]
expect(tnr.style.getPropertyValue('--doc-line-factor')).toBe('1.15') expect(tnr.style.getPropertyValue('--doc-line-factor')).toBe('1.15')
expect(tnr.style.fontFamily).toContain('Times New Roman') expect(tnr.style.fontFamily).toContain('Times New Roman')
// CJK mark faces keep the document factor (empty cells stay on the Latin rule) // empty-line probe 2026-08-25: CJK marks size by their own face too
expect(malgun.style.getPropertyValue('--doc-line-factor')).toBe('') expect(malgun.style.getPropertyValue('--doc-line-factor')).toBe('1.7371')
expect(simsun.style.getPropertyValue('--doc-line-factor')).toBe('1.3029')
editor.destroy() editor.destroy()
}) })
}) })
+4 -2
View File
@@ -884,8 +884,10 @@ describe('Korean line metrics', () => {
it('Chinese/Japanese factors follow the Word probe (unprobed names keep LO values)', () => { it('Chinese/Japanese factors follow the Word probe (unprobed names keep LO values)', () => {
expect(lineHeightFactor('SimSun')).toBe(1.3029) expect(lineHeightFactor('SimSun')).toBe(1.3029)
expect(lineHeightFactor('宋体')).toBe(1.3029) expect(lineHeightFactor('宋体')).toBe(1.3029)
expect(lineHeightFactor('DengXian')).toBe(1.775) // DengXian renders real in Office for Mac (probes 2026-08-13/25: 16.32pt @12pt)
expect(lineHeightFactor('等线')).toBe(1.775) expect(lineHeightFactor('DengXian')).toBe(1.36)
expect(lineHeightFactor('\u7b49\u7ebf')).toBe(1.36)
expect(lineHeightFactor('DengXian Light')).toBe(1.36)
// FangSong renders in the SimSun class (Word probe 2026-08-22) // FangSong renders in the SimSun class (Word probe 2026-08-22)
expect(lineHeightFactor('FangSong')).toBe(1.3029) expect(lineHeightFactor('FangSong')).toBe(1.3029)
expect(lineHeightFactor('仿宋')).toBe(1.3029) expect(lineHeightFactor('仿宋')).toBe(1.3029)
+2
View File
@@ -93,6 +93,8 @@ describe('native editable tables', () => {
shading: null, shading: null,
vertAlign: null, vertAlign: null,
em: null, em: null,
boldOff: null,
italicOff: null,
caps: null, caps: null,
cs: null, cs: null,
styleId: null, styleId: null,
@@ -0,0 +1,46 @@
/**
* Footnote/endnote separator geometry (github run 20260825 samples 18/20/21/22):
* Word draws a 2in rule on its own row above the note area; the row height is
* reserved by the pagination engine (FOOTNOTE_SEPARATOR_H), so the CSS must
* consume exactly that height with the rule at the row's bottom — a top border
* used to paint straight through the last body line like an underline.
*/
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { FOOTNOTE_SEPARATOR_H } from '../src/renderer/line-metrics'
const css = readFileSync(join(__dirname, '../src/renderer/styles.css'), 'utf8')
function ruleOf(selector: string): string {
const m = css.match(new RegExp(`${selector.replace(/[.:]/g, '\\$&')}\\s*\\{([^}]*)\\}`))
expect(m, `rule for ${selector}`).toBeTruthy()
return m![1]
}
const SEPARATORS = ['.page-gap-notes::before', '.pv-footnotes::before', '.pv-endnote-separator']
describe('note separator CSS', () => {
it.each(SEPARATORS)('%s draws Word’s 2in rule at the bottom of the reserved row', (sel) => {
const rule = ruleOf(sel)
expect(rule).toContain('width: min(2in, 100%)')
expect(rule).toContain('border-bottom: 1px solid')
expect(rule).not.toContain('border-top')
// height + 1px border + bottom spacing must equal the engine's reservation
const height = Number(/height:\s*(\d+)px/.exec(rule)?.[1])
const spacing = Number(/margin-bottom:\s*(\d+)px/.exec(rule)?.[1])
expect(height + 1 + spacing).toBe(FOOTNOTE_SEPARATOR_H)
})
it('canvas end-of-document notes use the same 2in bottom-border rule', () => {
const rule = ruleOf('.page-notes::before')
expect(rule).toContain('width: min(2in, 100%)')
expect(rule).toContain('border-bottom: 1px solid')
})
it('note markers render at Word’s superscript scale', () => {
for (const sel of ['.doc-note-ref', '.pv-footnote sup', '.page-gap-note sup']) {
expect(ruleOf(sel)).toContain('font-size: 0.65em')
}
})
})
@@ -0,0 +1,68 @@
import { describe, expect, it } from 'vitest'
import { pinnedFloatPage, type PageSlice } from '../src/renderer/pagination'
import { pinnedCloneCss } from '../src/renderer/components/PaginationPreview'
const slice = (start: number, end: number): PageSlice => ({ start, end, section: 0 })
describe('pinnedFloatPage', () => {
const slices = [slice(0, 900), slice(900, 1800), slice(1800, 2700)]
it('maps an anchor to its containing slice', () => {
expect(pinnedFloatPage(slices, 0)).toBe(0)
expect(pinnedFloatPage(slices, 899.9)).toBe(0)
expect(pinnedFloatPage(slices, 900)).toBe(1)
expect(pinnedFloatPage(slices, 2000)).toBe(2)
})
it('clamps out-of-range anchors', () => {
expect(pinnedFloatPage(slices, -5)).toBe(0)
expect(pinnedFloatPage(slices, 2700)).toBe(2)
expect(pinnedFloatPage(slices, 99999)).toBe(2)
expect(pinnedFloatPage([], 100)).toBe(0)
})
})
describe('pinnedCloneCss', () => {
const page = (index: number, html: string): HTMLElement => {
const el = document.createElement('div')
el.className = 'pv-page'
el.dataset.pvPage = String(index)
el.innerHTML = html
return el
}
const pinned = (pin?: number) =>
`<div class="doc-protected doc-protected-floating doc-protected-pagepinned"${
pin === undefined ? '' : ` data-pin-page="${pin}"`
}><div class="doc-textbox"></div></div>`
const boxes = (el: HTMLElement): HTMLElement[] =>
Array.from(el.querySelectorAll('.doc-protected-pagepinned'))
const matches = (root: HTMLElement, css: string): boolean[] => {
const selectors = css
.split('\n')
.filter(Boolean)
.map((r) => r.slice(0, r.indexOf('{')))
return boxes(root).map((b) => selectors.some((s) => b.matches(s)))
}
it('hides clones owned by other pages, keeps the owning page copy', () => {
const css = pinnedCloneCss(2)
// visibility, not display: stray-run wrappers keep their measured flow height
expect(css).toContain('visibility:hidden')
expect(css).not.toContain('display')
// full-document clone: every page carries both covers (pin 0 and pin 1)
const p0 = page(0, pinned(0) + pinned(1) + '<p>body</p>')
const p1 = page(1, pinned(0) + pinned(1) + '<p>body</p>')
expect(matches(p0, css)).toEqual([false, true])
expect(matches(p1, css)).toEqual([true, false])
})
it('never targets unstamped wrappers', () => {
const css = pinnedCloneCss(3)
const p = page(2, pinned() + pinned(2) + pinned(0))
expect(matches(p, css)).toEqual([false, false, true])
})
it('emits no rules for an empty preview', () => {
expect(pinnedCloneCss(0)).toBe('')
})
})
@@ -78,4 +78,34 @@ describe('protected field and formula editing', () => {
expect(saved).toEqual(source) expect(saved).toEqual(source)
editor.destroy() editor.destroy()
}) })
it('text-field passthrough carries run face/size and preserves spaces (public issue #118)', async () => {
const rpr =
'<w:rPr><w:rFonts w:ascii="\u5b8b\u4f53" w:eastAsia="\u5b8b\u4f53"/><w:sz w:val="24"/></w:rPr>'
const bodyXml =
`<w:p><w:pPr><w:jc w:val="left"/>${rpr}</w:pPr>` +
`<w:r>${rpr}<w:t>\u9636\u8d70\u5230\u6cb3</w:t></w:r>` +
`<w:r>${rpr}<w:t xml:space="preserve"> </w:t></w:r>` +
`<w:r>${rpr}<w:fldChar w:fldCharType="begin"/></w:r>` +
`<w:r>${rpr}<w:instrText xml:space="preserve"> INCLUDEPICTURE "/tmp/x.jpeg" \\* MERGEFORMATINET </w:instrText></w:r>` +
`<w:r>${rpr}<w:fldChar w:fldCharType="end"/></w:r>` +
`<w:r>${rpr}<w:t>\u5cb8\u8fb9</w:t></w:r></w:p>`
const parsed = await parseDocx(await buildDocx({ bodyXml }))
const editor = new Editor({
element: document.createElement('div'),
extensions: editorExtensions,
content: blocksToPmDoc(parsed.blocks) as never,
})
const el = editor.view.dom.querySelector<HTMLElement>('.doc-field-text')!
expect(el).toBeTruthy()
// mid-paragraph space run must survive into the DOM (pre-wrap keeps it)
expect(el.textContent).toContain('\u6cb3 \u5cb8')
expect(el.style.fontSize).toBe('12pt')
expect(el.style.getPropertyValue('--doc-line-factor')).toBe('1.3029')
expect(el.style.lineHeight).toContain('--doc-line-grid')
expect(el.style.textAlign).toBe('left')
// inline: prosemirror-view injects a higher-specificity white-space:normal
expect(el.style.whiteSpace).toBe('pre-wrap')
editor.destroy()
})
}) })
+248
View File
@@ -0,0 +1,248 @@
import { Editor } from '@tiptap/core'
import { TextSelection } from '@tiptap/pm/state'
import { parseDocx } from '@genoffice/docx-engine'
import { describe, expect, it, vi } from 'vitest'
import { buildDocx } from '../../../packages/docx-engine/tests/helpers/build-docx'
import { blocksToPmDoc, pmTableToModel, type PmNode } from '../src/renderer/editor/convert'
import { editorExtensions } from '../src/renderer/editor/extensions'
import {
applyTablePreset,
repeatHeaderState,
setTableAutoFit,
setTableLookOption,
toggleRepeatHeaderRows,
updateSelectedTableAttrs,
} from '../src/renderer/editor/table-properties'
const TABLE =
'<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/>' +
'<w:tblW w:w="5000" w:type="pct"/><w:tblLayout w:type="autofit"/>' +
'<w:tblCellMar><w:left w:w="120" w:type="dxa"/><w:right w:w="120" w:type="dxa"/></w:tblCellMar>' +
'<w:tblLook w:firstRow="1" w:lastRow="0" w:firstColumn="1" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/>' +
'</w:tblPr><w:tblGrid><w:gridCol w:w="3000"/><w:gridCol w:w="3000"/></w:tblGrid>' +
'<w:tr><w:trPr><w:tblHeader/></w:trPr>' +
'<w:tc><w:p><w:r><w:t>A</w:t></w:r></w:p></w:tc>' +
'<w:tc><w:p><w:r><w:t>B</w:t></w:r></w:p></w:tc></w:tr>' +
'<w:tr><w:tc><w:p><w:r><w:t>C</w:t></w:r></w:p></w:tc>' +
'<w:tc><w:p><w:r><w:t>D</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
async function openTable(): Promise<Editor> {
const parsed = await parseDocx(await buildDocx({ bodyXml: TABLE }))
const editor = new Editor({
element: document.createElement('div'),
extensions: editorExtensions,
content: blocksToPmDoc(parsed.blocks) as never,
})
let firstCell = -1
editor.state.doc.descendants((node, pos) => {
if (
firstCell < 0 &&
(node.type.name === 'docTableCell' || node.type.name === 'docTableHeader')
) {
firstCell = pos
}
})
editor.view.dispatch(
editor.state.tr.setSelection(TextSelection.near(editor.state.doc.resolve(firstCell + 1))),
)
return editor
}
describe('editable table properties', () => {
it('loads AutoFit, margins, style options, and repeat-header state', async () => {
const editor = await openTable()
const table = editor.getJSON().content![0] as unknown as PmNode
expect(table.attrs).toMatchObject({
tblAutoFit: 'window',
cellMar: { left: 120, right: 120 },
tblLook: {
firstRow: true,
lastRow: false,
firstColumn: true,
lastColumn: false,
bandedRows: true,
bandedColumns: false,
},
})
expect(table.content![0].attrs).toMatchObject({ repeatHeader: true })
expect(repeatHeaderState(editor.state)).toEqual({ enabled: true, active: true })
editor.destroy()
})
it('toggles leading header rows and persists the edited model flag', async () => {
const editor = await openTable()
expect(toggleRepeatHeaderRows()(editor.state, editor.view.dispatch)).toBe(true)
const table = editor.getJSON().content![0] as unknown as PmNode
expect(table.content![0].attrs).toMatchObject({
repeatHeader: false,
repeatHeaderEdited: true,
})
expect(pmTableToModel(table as PmNode).repeatHeaderRows).toEqual([false, null])
editor.destroy()
})
it('switches all three AutoFit modes and materializes a fixed grid', async () => {
const editor = await openTable()
expect(setTableAutoFit('contents', 600)(editor.state, editor.view.dispatch)).toBe(true)
let table = editor.getJSON().content![0] as unknown as PmNode
expect(table.attrs).toMatchObject({
tblAutoFit: 'contents',
tblAutoFitEdited: true,
widthPx: null,
widthPct: null,
colWidthsPct: null,
})
expect(setTableAutoFit('window', 600)(editor.state, editor.view.dispatch)).toBe(true)
expect((editor.getJSON().content![0] as unknown as PmNode).attrs).toMatchObject({
tblAutoFit: 'window',
widthPct: 100,
})
expect(setTableAutoFit('fixed', 600)(editor.state, editor.view.dispatch)).toBe(true)
table = editor.getJSON().content![0] as unknown as PmNode
expect(table.attrs).toMatchObject({ tblAutoFit: 'fixed', widthPct: null })
expect(table.content![0].content![0].attrs?.colwidth).toEqual([300])
expect(pmTableToModel(table as PmNode).autoFit).toBe('fixed')
editor.destroy()
})
it('updates cell margins, floating position, and table style options', async () => {
const editor = await openTable()
expect(
updateSelectedTableAttrs({
cellMar: { top: 40, right: 100, bottom: 50, left: 110 },
cellMarEdited: true,
tblFloat: 'left',
tblFloatXTwips: 720,
tblFloatYTwips: 360,
tblFloatHorzAnchor: 'margin',
tblFloatVertAnchor: 'text',
tblFloatDistance: { top: 60, right: 120, bottom: 70, left: 130 },
tblFloatEdited: true,
})(editor.state, editor.view.dispatch),
).toBe(true)
expect(setTableLookOption('lastRow', true)(editor.state, editor.view.dispatch)).toBe(true)
const table = editor.getJSON().content![0] as PmNode
const model = pmTableToModel(table)
expect(model.cellMarTwips).toEqual({ top: 40, right: 100, bottom: 50, left: 110 })
expect(model.floatSide).toBe('left')
expect(model.floatPos).toMatchObject({
xTwips: 720,
yTwips: 360,
horzAnchor: 'margin',
vertAnchor: 'text',
})
expect(model.tableLook?.lastRow).toBe(true)
editor.destroy()
})
it('positions a right AutoFit float without restoring fixed widthPx', async () => {
const editor = await openTable()
expect(setTableAutoFit('contents', 600)(editor.state, editor.view.dispatch)).toBe(true)
expect(
updateSelectedTableAttrs({
tblFloat: 'right',
tblFloatSource: 'right',
tblFloatXTwips: 3000,
tblFloatWidthPx: 240,
tblFloatEdited: true,
})(editor.state, editor.view.dispatch),
).toBe(true)
const table = editor.state.doc.firstChild!
expect(table.attrs).toMatchObject({
tblAutoFit: 'contents',
widthPx: null,
tblFloatWidthPx: 240,
})
const spec = editor.schema.nodes.docTable.spec.toDOM!(table) as [string, Record<string, string>]
expect(spec[1].class).toContain('doc-table-autofit-contents')
expect(spec[1].style).toContain('width:auto')
expect(spec[1].style).toContain(
'margin-right:max(0px,calc(var(--doc-content-w,100%) - 200.0px - 240.0px))',
)
editor.destroy()
})
it('keeps a pagination-suppressed float in the saved table model', async () => {
const editor = await openTable()
expect(
updateSelectedTableAttrs({
tblFloat: null,
tblFloatSource: 'right',
tblFloatSuppressed: true,
tblFloatXTwips: 4800,
tblFloatYTwips: 240,
tblFloatEdited: true,
})(editor.state, editor.view.dispatch),
).toBe(true)
const model = pmTableToModel(editor.getJSON().content![0] as unknown as PmNode)
expect(model.floatSide).toBe('right')
expect(model.floatPos).toMatchObject({ xTwips: 4800, yTwips: 240 })
editor.destroy()
})
it('applies portable built-in shading and border presets', async () => {
const editor = await openTable()
expect(
applyTablePreset({
headerFill: 'BDD7EE',
band1Fill: 'DDEBF7',
band2Fill: 'FFFFFF',
borderColor: '9DC3E6',
})(editor.state, editor.view.dispatch),
).toBe(true)
const table = editor.getJSON().content![0] as unknown as PmNode
expect(table.attrs?.tblStyleId).toBeNull()
expect(table.content![0].content![0].attrs).toMatchObject({
fill: 'BDD7EE',
borders: { top: { style: 'single', color: '9DC3E6' } },
})
expect(table.content![1].content![0].attrs?.fill).toBe('DDEBF7')
const model = pmTableToModel(table)
expect(model.rows[0][0].fill).toBe('BDD7EE')
expect(model.rows[1][0].borders?.left?.color).toBe('9DC3E6')
editor.destroy()
})
it('drags a floating table handle into persisted x/y offsets', async () => {
const editor = await openTable()
updateSelectedTableAttrs({
tblFloat: 'left',
tblFloatSource: 'left',
tblFloatXTwips: 0,
tblFloatYTwips: 0,
tblFloatEdited: true,
})(editor.state, editor.view.dispatch)
let firstCell = -1
editor.state.doc.descendants((node, pos) => {
if (
firstCell < 0 &&
(node.type.name === 'docTableCell' || node.type.name === 'docTableHeader')
) {
firstCell = pos
}
})
vi.spyOn(editor.view, 'posAtCoords').mockReturnValue({ pos: firstCell, inside: firstCell })
editor.view.dom.dispatchEvent(
new MouseEvent('mousemove', { bubbles: true, clientX: 10, clientY: 10 }),
)
const handle =
editor.view.dom.parentElement!.querySelector<HTMLButtonElement>('.doc-table-handle')!
handle.dispatchEvent(
new MouseEvent('mousedown', { bubbles: true, button: 0, clientX: 10, clientY: 10 }),
)
window.dispatchEvent(new MouseEvent('mousemove', { clientX: 40, clientY: 30 }))
window.dispatchEvent(new MouseEvent('mouseup', { clientX: 40, clientY: 30 }))
expect((editor.getJSON().content![0] as unknown as PmNode).attrs).toMatchObject({
tblFloatXTwips: 450,
tblFloatYTwips: 300,
tblFloatEdited: true,
})
editor.destroy()
})
})
@@ -279,6 +279,22 @@ export function AiAskPopover({
} }
}} }}
> >
<button
type="button"
className="ai-ask-pop-close"
data-tip={t('aiCancel')}
aria-label={t('aiCancel')}
onClick={close}
>
<svg viewBox="0 0 24 24" width="12" height="12" fill="none" aria-hidden>
<path
d="M6 6l12 12M18 6L6 18"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
/>
</svg>
</button>
<div className="ai-ask-pop-title"> <div className="ai-ask-pop-title">
{t(open.mode === 'edit' ? 'aiAskEditTitle' : 'aiAskTitle')} {t(open.mode === 'edit' ? 'aiAskEditTitle' : 'aiAskTitle')}
</div> </div>
+28
View File
@@ -2397,7 +2397,35 @@ div.tiptap-mathematics-render {
box-shadow: var(--md-pop-shadow); box-shadow: var(--md-pop-shadow);
} }
.ai-ask-pop-close {
position: absolute;
top: 10px;
right: 10px;
display: inline-flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
padding: 0;
border: none;
border-radius: 6px;
background: transparent;
color: var(--text-dim);
cursor: pointer;
}
.ai-ask-pop-close:hover {
background: var(--hover);
color: var(--text);
}
.ai-ask-pop-close:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 1px;
}
.ai-ask-pop-title { .ai-ask-pop-title {
padding-right: 24px;
font-size: 12.5px; font-size: 12.5px;
font-weight: 600; font-weight: 600;
color: var(--text); color: var(--text);
+16
View File
@@ -103,6 +103,22 @@ export function AiAskPopover({
} }
}} }}
> >
<button
type="button"
className="ai-ask-pop-close"
data-tip={t('noteClose')}
aria-label={t('noteClose')}
onClick={onClose}
>
<svg viewBox="0 0 24 24" width="12" height="12" fill="none" aria-hidden>
<path
d="M6 6l12 12M18 6L6 18"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
/>
</svg>
</button>
<div className="ai-ask-pop-title">{t('aiAskTitle')}</div> <div className="ai-ask-pop-title">{t('aiAskTitle')}</div>
{shortExcerpt && ( {shortExcerpt && (
<div className="ai-ask-pop-sub"> <div className="ai-ask-pop-sub">
+5 -2
View File
@@ -5299,8 +5299,11 @@ export default function App() {
const onWheel = (e: WheelEvent) => { const onWheel = (e: WheelEvent) => {
if (!e.ctrlKey && !e.metaKey) return if (!e.ctrlKey && !e.metaKey) return
e.preventDefault() e.preventDefault()
if (e.deltaY < 0) zoomIn() if (e.deltaY === 0) return
else zoomOut() fitModeRef.current = null
// Match Docs: accumulate against the latest queued scale and avoid the
// per-event scroll anchoring that makes a continuous pinch oscillate.
setScale((current) => clampScale(current - e.deltaY * 0.006))
} }
el.addEventListener('wheel', onWheel, { passive: false }) el.addEventListener('wheel', onWheel, { passive: false })
return () => el.removeEventListener('wheel', onWheel) return () => el.removeEventListener('wheel', onWheel)
+28
View File
@@ -3553,7 +3553,35 @@ button {
box-shadow: var(--pdf-shadow-popup); box-shadow: var(--pdf-shadow-popup);
} }
.ai-ask-pop-close {
position: absolute;
top: 10px;
right: 10px;
display: inline-flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
padding: 0;
border: none;
border-radius: 6px;
background: transparent;
color: var(--text-dim);
cursor: pointer;
}
.ai-ask-pop-close:hover {
background: var(--hover);
color: var(--text);
}
.ai-ask-pop-close:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 1px;
}
.ai-ask-pop-title { .ai-ask-pop-title {
padding-right: 24px;
font-size: 12.5px; font-size: 12.5px;
font-weight: 600; font-weight: 600;
color: var(--text); color: var(--text);
+1 -1
View File
@@ -1,7 +1,7 @@
// cmaps/standard fonts/wasm are statically copied by the build into pdfjs/ of the renderer output (same path on the dev server) // cmaps/standard fonts/wasm are statically copied by the build into pdfjs/ of the renderer output (same path on the dev server)
export const ASSET_BASE = new URL('pdfjs/', document.baseURI).href export const ASSET_BASE = new URL('pdfjs/', document.baseURI).href
export const ZOOM_STEPS = [0.5, 0.67, 0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4] export const ZOOM_STEPS = [0.1, 0.25, 0.5, 0.67, 0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4]
export const MIN_SCALE = ZOOM_STEPS[0] export const MIN_SCALE = ZOOM_STEPS[0]
export const MAX_SCALE = ZOOM_STEPS[ZOOM_STEPS.length - 1] export const MAX_SCALE = ZOOM_STEPS[ZOOM_STEPS.length - 1]
export const PAGE_GAP = 16 export const PAGE_GAP = 16
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,175 @@
//! Excel in-cell rich-value pictures ("place picture in cell"). The cell
//! carries a `vm` index and a cached #VALUE! error; the picture itself lives
//! behind xl/metadata.xml → xl/richData/richValueRel.xml → xl/media/*.
use std::collections::HashMap;
use std::fs::File;
use roxmltree::Node;
use zip::ZipArchive;
use crate::SidecarError;
use crate::visuals::{parse_document, read_optional_xml, read_relationships, resolve_part_target};
/// `vm` attribute value (1-based valueMetadata record index) → media part
/// path, for records whose rich value is a `_localImage`. Absent or
/// malformed richData parts degrade to "no in-cell pictures".
pub fn read_rich_value_images(archive: &mut ZipArchive<File>) -> HashMap<u32, String> {
read_rich_value_images_inner(archive).unwrap_or_default()
}
fn read_rich_value_images_inner(
archive: &mut ZipArchive<File>,
) -> Result<HashMap<u32, String>, SidecarError> {
let workbook_rels = read_relationships(archive, "xl/workbook.xml")?;
let part_by_type = |suffix: &str| {
workbook_rels
.values()
.find(|relationship| relationship.relationship_type.ends_with(suffix))
.map(|relationship| resolve_part_target("xl/workbook.xml", &relationship.target))
.transpose()
};
let (Some(metadata_path), Some(rel_part_path), Some(value_path), Some(structure_path)) = (
part_by_type("/sheetMetadata")?,
part_by_type("/richValueRel")?,
part_by_type("/rdRichValue")?,
part_by_type("/rdRichValueStructure")?,
) else {
return Ok(HashMap::new());
};
// Structure index → position of the local-image key among its <k> keys.
let Some(structure_xml) = read_optional_xml(archive, &structure_path)? else {
return Ok(HashMap::new());
};
let structure_doc = parse_document(&structure_xml, &structure_path)?;
let structures: Vec<Option<usize>> = structure_doc
.descendants()
.filter(|node| node.has_tag_name("s"))
.map(|node| {
if node.attribute("t") != Some("_localImage") {
return None;
}
node.children()
.filter(|child| child.has_tag_name("k"))
.position(|key| key.attribute("n") == Some("_rvRel:LocalImageIdentifier"))
})
.collect();
// Rich value index → richValueRel entry index (image rich values only).
let Some(value_xml) = read_optional_xml(archive, &value_path)? else {
return Ok(HashMap::new());
};
let value_doc = parse_document(&value_xml, &value_path)?;
let rich_values: Vec<Option<usize>> = value_doc
.descendants()
.filter(|node| node.has_tag_name("rv"))
.map(|node| {
let structure = node.attribute("s")?.parse::<usize>().ok()?;
let key_position = (*structures.get(structure)?)?;
let value = node
.children()
.filter(|child| child.has_tag_name("v"))
.nth(key_position)?;
value.text()?.trim().parse::<usize>().ok()
})
.collect();
// richValueRel entry index → media part path (through the part's rels).
let Some(rel_xml) = read_optional_xml(archive, &rel_part_path)? else {
return Ok(HashMap::new());
};
let rel_doc = parse_document(&rel_xml, &rel_part_path)?;
let part_rels = read_relationships(archive, &rel_part_path)?;
let media_paths: Vec<Option<String>> = rel_doc
.descendants()
.filter(|node| node.has_tag_name("rel"))
.map(|node| {
let id = relationship_id(node)?;
let relationship = part_rels.get(&id)?;
resolve_part_target(&rel_part_path, &relationship.target).ok()
})
.collect();
// valueMetadata record index (vm is that plus one) → media part path.
let Some(metadata_xml) = read_optional_xml(archive, &metadata_path)? else {
return Ok(HashMap::new());
};
let metadata_doc = parse_document(&metadata_xml, &metadata_path)?;
let type_names: Vec<String> = metadata_doc
.descendants()
.filter(|node| node.has_tag_name("metadataType"))
.map(|node| node.attribute("name").unwrap_or_default().to_owned())
.collect();
// futureMetadata bk records carry the rich value index (xlrd:rvb i=);
// a record without one falls back to the identity mapping.
let future_rich_value: Vec<Option<usize>> = metadata_doc
.descendants()
.find(|node| {
node.has_tag_name("futureMetadata") && node.attribute("name") == Some("XLRICHVALUE")
})
.map(|future| {
future
.descendants()
.filter(|node| node.has_tag_name("bk"))
.map(|record| {
record
.descendants()
.find(|node| node.has_tag_name("rvb"))
.and_then(|rvb| rvb.attribute("i"))
.and_then(|index| index.parse::<usize>().ok())
})
.collect()
})
.unwrap_or_default();
let mut by_vm = HashMap::new();
let Some(value_metadata) = metadata_doc
.descendants()
.find(|node| node.has_tag_name("valueMetadata"))
else {
return Ok(by_vm);
};
for (index, record) in value_metadata
.children()
.filter(|node| node.has_tag_name("bk"))
.enumerate()
{
// rc t= is a 1-based metadataTypes index; a bk may carry one rc per
// metadata type, so find the XLRICHVALUE one wherever it sits.
let Some(future_index) = record
.children()
.filter(|node| node.has_tag_name("rc"))
.find(|rc| {
rc.attribute("t")
.and_then(|value| value.parse::<usize>().ok())
.and_then(|value| value.checked_sub(1))
.and_then(|value| type_names.get(value))
.is_some_and(|name| name == "XLRICHVALUE")
})
.and_then(|rc| rc.attribute("v"))
.and_then(|value| value.parse::<usize>().ok())
else {
continue;
};
let rich_value_index = future_rich_value
.get(future_index)
.copied()
.flatten()
.unwrap_or(future_index);
let Some(rel_index) = rich_values.get(rich_value_index).copied().flatten() else {
continue;
};
let Some(media_path) = media_paths.get(rel_index).cloned().flatten() else {
continue;
};
by_vm.insert(index as u32 + 1, media_path);
}
Ok(by_vm)
}
fn relationship_id(node: Node<'_, '_>) -> Option<String> {
node.attributes()
.find(|attribute| attribute.name() == "id")
.map(|attribute| attribute.value().to_owned())
}
File diff suppressed because it is too large Load Diff
+25 -8
View File
@@ -50,9 +50,14 @@ export interface ChartSeriesVisualState {
pointExplosions?: { index: number; pct: number }[] | undefined pointExplosions?: { index: number; pct: number }[] | undefined
/// spPr/a:ln color; "none" = explicit no line. /// spPr/a:ln color; "none" = explicit no line.
lineColor?: string | undefined lineColor?: string | undefined
/// spPr/a:ln/@w in CSS px (EMU / 12700 pt · 96/72).
lineWidth?: number | undefined
smooth?: boolean | undefined smooth?: boolean | undefined
/// c:marker symbol; "none" hides scatter/line markers. /// c:marker symbol; "none" hides scatter/line markers.
marker?: string | undefined marker?: string | undefined
/// First outer multiLvlStrCache level; start/end index the compacted
/// `categories` (end exclusive).
categoryGroups?: { label: string; start: number; end: number }[] | undefined
} }
/// One plot axis keyed by its side (b/t → x, l/r → y). /// One plot axis keyed by its side (b/t → x, l/r → y).
@@ -65,6 +70,8 @@ export interface ChartAxisInfoState {
majorGridlines: boolean majorGridlines: boolean
/// c:delete — scales its series but is not drawn. /// c:delete — scales its series but is not drawn.
hidden: boolean hidden: boolean
/// c:scaling/c:orientation val="maxMin".
reversed: boolean
} }
export interface ChartVisualState { export interface ChartVisualState {
@@ -97,6 +104,8 @@ export interface ChartVisualState {
secondaryYAxis?: ChartAxisInfoState | undefined secondaryYAxis?: ChartAxisInfoState | undefined
/// c:scatterStyle — whether scatter points connect with lines. /// c:scatterStyle — whether scatter points connect with lines.
scatterStyle?: string | undefined scatterStyle?: string | undefined
/// Plot-level c:lineChart/c:marker flag; per-series symbols refine it.
lineMarkers?: boolean | undefined
/// c:title/c:txPr//a:defRPr shorthand. /// c:title/c:txPr//a:defRPr shorthand.
titleStyle?: titleStyle?:
| { size?: number | undefined; bold?: boolean | undefined; color?: string | undefined } | { size?: number | undefined; bold?: boolean | undefined; color?: string | undefined }
@@ -152,10 +161,12 @@ export function scatterAxisBounds(
return { min, max, ticks } return { min, max, ticks }
} }
/// Excel-like value-axis scale. Explicit bounds/unit win; the auto unit is /// Excel-like value-axis scale. Explicit bounds/unit win. Excel's auto max
/// the smallest 1/2/5×10^n giving at most 8 intervals, and the max rounds /// leaves ~5% headroom above the data: with bumped = span · 1.05, the unit
/// up to a unit multiple (11162 → 0..12000 step 2000; 3750 → 0..4000 step /// is the smallest 1/2/5×10^n giving at most 10 intervals of bumped, and
/// 500; 13 → 0..14 step 2 — matching Excel's defaults on the run5 corpus). /// max = min + unit · ceil(bumped / unit). Calibrated on Excel-rendered
/// refs: 18 → 20 step 2, 148 → 160 step 20, 877 → 1000 step 100, 1000 →
/// 1200 step 200, 289753.76 → 350000 step 50000 (real-run1 + prod corpora).
export function valueAxisScale( export function valueAxisScale(
dataMax: number, dataMax: number,
explicit?: { min?: number | undefined; max?: number | undefined; majorUnit?: number | undefined }, explicit?: { min?: number | undefined; max?: number | undefined; majorUnit?: number | undefined },
@@ -166,8 +177,9 @@ export function valueAxisScale(
if (!(span > 0)) { if (!(span > 0)) {
return { min, max: min + 1, ticks: [min, min + 0.5, min + 1] } return { min, max: min + 1, ticks: [min, min + 0.5, min + 1] }
} }
const unit = explicit?.majorUnit ?? autoAxisUnit(span) const bumped = explicit?.max === undefined ? span * 1.05 : span
const max = explicit?.max ?? min + Math.ceil(span / unit - 1e-9) * unit const unit = explicit?.majorUnit ?? autoAxisUnit(bumped)
const max = explicit?.max ?? min + Math.ceil(bumped / unit - 1e-9) * unit
return { min, max: max > min ? max : min + unit, ticks: unitTicks(min, max, unit) } return { min, max: max > min ? max : min + unit, ticks: unitTicks(min, max, unit) }
} }
@@ -176,7 +188,9 @@ function autoAxisUnit(span: number): number {
for (let guard = 0; guard < 6; guard += 1) { for (let guard = 0; guard < 6; guard += 1) {
for (const base of [1, 2, 5]) { for (const base of [1, 2, 5]) {
const unit = base * 10 ** exponent const unit = base * 10 ** exponent
if (span / unit <= 8 + 1e-9) return unit // Excel allows up to 10 intervals (877 bumps to 920.85 → unit 100 /
// max 1000; 1000 bumps to 1050 → 11 intervals reject 100, unit 200).
if (span / unit <= 10 + 1e-9) return unit
} }
exponent += 1 exponent += 1
} }
@@ -422,7 +436,10 @@ export function applyChartStateEdit(
: {}), : {}),
...(data?.name === undefined ? {} : { name: data.name }), ...(data?.name === undefined ? {} : { name: data.name }),
...(data?.values === undefined ? {} : { values: data.values }), ...(data?.values === undefined ? {} : { values: data.values }),
...(data?.categories === undefined ? {} : { categories: data.categories }), // Replacing the categories orphans the parsed outer-level spans.
...(data?.categories === undefined
? {}
: { categories: data.categories, categoryGroups: undefined }),
...(data?.valuesRef === undefined ? {} : { valuesRef: data.valuesRef }), ...(data?.valuesRef === undefined ? {} : { valuesRef: data.valuesRef }),
...(data?.categoriesRef === undefined ? {} : { categoriesRef: data.categoriesRef }), ...(data?.categoriesRef === undefined ? {} : { categoriesRef: data.categoriesRef }),
} }
+45
View File
@@ -0,0 +1,45 @@
import { randomBytes } from 'node:crypto'
import { rename, unlink, writeFile } from 'node:fs/promises'
import { basename, dirname, join } from 'node:path'
/** Transient Windows codes: antivirus/indexer briefly locks the rename target. */
const RETRYABLE_RENAME_CODES = new Set(['EPERM', 'EACCES', 'EBUSY'])
const RENAME_RETRIES = 4
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
/**
* Same-directory temp file + rename prevents observers from reading a partial
* export. Windows rename-over-existing can fail transiently, so retry with
* backoff and finally fall back to the prior in-place write behavior.
*/
export async function atomicWriteFile(filePath: string, data: Buffer): Promise<void> {
const tmp = join(
dirname(filePath),
`.${basename(filePath)}.${randomBytes(6).toString('hex')}.tmp`,
)
try {
await writeFile(tmp, data)
for (let attempt = 0; ; attempt += 1) {
try {
await rename(tmp, filePath)
return
} catch (error) {
const code = (error as NodeJS.ErrnoException).code ?? ''
if (!RETRYABLE_RENAME_CODES.has(code) || attempt >= RENAME_RETRIES) throw error
await sleep(50 * 2 ** attempt)
}
}
} catch (error) {
const retryable = RETRYABLE_RENAME_CODES.has((error as NodeJS.ErrnoException).code ?? '')
if (retryable) {
// Preserve the completed temp until the non-atomic fallback succeeds.
// If that write fails or the process exits, the new bytes still exist.
await writeFile(filePath, data)
await unlink(tmp).catch(() => {})
return
}
await unlink(tmp).catch(() => {})
throw error
}
}
+11
View File
@@ -34,12 +34,23 @@ export async function exportPdf(
try { try {
await writeFile(htmlPath, request.html, 'utf8') await writeFile(htmlPath, request.html, 'utf8')
await window.loadFile(htmlPath) await window.loadFile(htmlPath)
const displayHeaderFooter =
request.headerTemplate !== undefined || request.footerTemplate !== undefined
const pdf = await window.webContents.printToPDF({ const pdf = await window.webContents.printToPDF({
landscape: request.landscape, landscape: request.landscape,
pageSize: request.pageSize, pageSize: request.pageSize,
margins: request.margins, margins: request.margins,
scale: request.scale, scale: request.scale,
printBackground: true, printBackground: true,
...(displayHeaderFooter
? {
displayHeaderFooter: true,
// Chromium falls back to its own date/title header when a
// template is missing, so always pass both.
headerTemplate: request.headerTemplate ?? '<span></span>',
footerTemplate: request.footerTemplate ?? '<span></span>',
}
: {}),
}) })
await writeFile(selection.filePath, pdf) await writeFile(selection.filePath, pdf)
return { canceled: false, path: selection.filePath } return { canceled: false, path: selection.filePath }
+415 -22
View File
@@ -110,6 +110,7 @@ import {
screenCaptureResultSchema, screenCaptureResultSchema,
screenSourcesResultSchema, screenSourcesResultSchema,
workbookPivotDefinitionSchema, workbookPivotDefinitionSchema,
workbookExportCsvRequestSchema,
workbookExportPdfRequestSchema, workbookExportPdfRequestSchema,
workbookRangeRequestSchema, workbookRangeRequestSchema,
workbookRangeResultSchema, workbookRangeResultSchema,
@@ -120,6 +121,7 @@ import {
type WorkbookSaveRequest, type WorkbookSaveRequest,
} from '../shared/desktop-api' } from '../shared/desktop-api'
import { IPC_CHANNELS } from '../shared/ipc-channels' import { IPC_CHANNELS } from '../shared/ipc-channels'
import { atomicWriteFile } from './atomic-write'
import { closeGuardDecision } from './close-guard' import { closeGuardDecision } from './close-guard'
import { SaveEditsTransferStore } from './save-edits-transfer' import { SaveEditsTransferStore } from './save-edits-transfer'
import { exportPdf } from './pdf-export' import { exportPdf } from './pdf-export'
@@ -185,6 +187,16 @@ const tMain = createI18n({
btnDontSave: '不保存', btnDontSave: '不保存',
btnCancel: '取消', btnCancel: '取消',
csvSaveAsNotice: 'CSV 格式不保留样式等格式修改——另存为 .xlsx 可保留全部内容。', csvSaveAsNotice: 'CSV 格式不保留样式等格式修改——另存为 .xlsx 可保留全部内容。',
menuExportCsv: '导出 CSV…',
filterCsv: 'CSV (逗号分隔)',
csvFormulaLossMsg: '当前工作表包含公式,CSV 格式无法保留。',
csvFormulaLossDetail: 'CSV 只保留纯文本值——公式会被替换为当前计算结果,格式也会丢失。',
csvKeepXlsxBtn: '另存为 .xlsx',
csvContinueBtn: '继续保存为 CSV',
csvActiveSheetOnlyNotice: 'CSV 文件只包含一张工作表——只会导出当前工作表“{name}”。',
csvKeepFormatMsg: '继续以 CSV 格式保存吗?',
csvKeepFormatDetail:
'CSV 只保留单张工作表的纯文本值——公式、格式和其他工作表不会存入 .csv 文件。',
}, },
en: { en: {
filterSpreadsheets: 'Spreadsheets', filterSpreadsheets: 'Spreadsheets',
@@ -231,6 +243,18 @@ const tMain = createI18n({
btnDontSave: "Don't Save", btnDontSave: "Don't Save",
btnCancel: 'Cancel', btnCancel: 'Cancel',
csvSaveAsNotice: "CSV files can't keep formatting — saving as .xlsx keeps all your changes.", csvSaveAsNotice: "CSV files can't keep formatting — saving as .xlsx keeps all your changes.",
menuExportCsv: 'Export CSV…',
filterCsv: 'CSV (Comma delimited)',
csvFormulaLossMsg: 'This sheet contains formulas that CSV cannot keep.',
csvFormulaLossDetail:
'CSV keeps plain values only — formulas are flattened to their current results, and formatting is lost.',
csvKeepXlsxBtn: 'Save as .xlsx',
csvContinueBtn: 'Continue as CSV',
csvActiveSheetOnlyNotice:
'CSV files hold a single sheet — only the active sheet "{name}" will be exported.',
csvKeepFormatMsg: 'Keep saving in CSV format?',
csvKeepFormatDetail:
'CSV keeps plain values of a single sheet only — formulas, formatting, and any additional sheets are not saved to the .csv file.',
}, },
ja: { ja: {
filterSpreadsheets: 'スプレッドシート', filterSpreadsheets: 'スプレッドシート',
@@ -280,6 +304,18 @@ const tMain = createI18n({
btnCancel: 'キャンセル', btnCancel: 'キャンセル',
csvSaveAsNotice: csvSaveAsNotice:
'CSV 形式は書式を保持できません。.xlsx として保存すると変更をすべて保持できます。', 'CSV 形式は書式を保持できません。.xlsx として保存すると変更をすべて保持できます。',
menuExportCsv: 'CSV をエクスポート…',
filterCsv: 'CSV (コンマ区切り)',
csvFormulaLossMsg: 'このシートには CSV 形式では保持できない数式が含まれています。',
csvFormulaLossDetail:
'CSV は値のみを保持します。数式は現在の計算結果に置き換えられ、書式も失われます。',
csvKeepXlsxBtn: '.xlsx として保存',
csvContinueBtn: 'CSV のまま保存',
csvActiveSheetOnlyNotice:
'CSV ファイルには 1 枚のシートしか含められません — アクティブなシート「{name}」のみがエクスポートされます。',
csvKeepFormatMsg: 'CSV 形式のまま保存しますか?',
csvKeepFormatDetail:
'CSV は 1 枚のシートの値のみを保持します。数式、書式、追加のシートは .csv ファイルには保存されません。',
}, },
ko: { ko: {
filterSpreadsheets: '스프레드시트', filterSpreadsheets: '스프레드시트',
@@ -329,6 +365,18 @@ const tMain = createI18n({
btnCancel: '취소', btnCancel: '취소',
csvSaveAsNotice: csvSaveAsNotice:
'CSV 형식은 서식을 저장할 수 없습니다. .xlsx로 저장하면 모든 변경 내용이 유지됩니다.', 'CSV 형식은 서식을 저장할 수 없습니다. .xlsx로 저장하면 모든 변경 내용이 유지됩니다.',
menuExportCsv: 'CSV 내보내기…',
filterCsv: 'CSV (쉼표로 분리)',
csvFormulaLossMsg: '현재 시트에 CSV 형식이 유지할 수 없는 수식이 포함되어 있습니다.',
csvFormulaLossDetail:
'CSV는 값만 유지합니다 — 수식은 현재 계산 결과로 바뀌고 서식은 손실됩니다.',
csvKeepXlsxBtn: '.xlsx로 저장',
csvContinueBtn: 'CSV로 계속 저장',
csvActiveSheetOnlyNotice:
'CSV 파일에는 시트 하나만 포함됩니다 — 활성 시트 "{name}"만 내보냅니다.',
csvKeepFormatMsg: 'CSV 형식으로 계속 저장하시겠습니까?',
csvKeepFormatDetail:
'CSV는 시트 하나의 값만 유지합니다 — 수식, 서식, 추가 시트는 .csv 파일에 저장되지 않습니다.',
}, },
fr: { fr: {
filterSpreadsheets: 'Feuilles de calcul', filterSpreadsheets: 'Feuilles de calcul',
@@ -378,6 +426,19 @@ const tMain = createI18n({
btnCancel: 'Annuler', btnCancel: 'Annuler',
csvSaveAsNotice: csvSaveAsNotice:
'Le format CSV ne conserve pas la mise en forme — enregistrez en .xlsx pour conserver toutes vos modifications.', 'Le format CSV ne conserve pas la mise en forme — enregistrez en .xlsx pour conserver toutes vos modifications.',
menuExportCsv: 'Exporter en CSV…',
filterCsv: 'CSV (délimité par des virgules)',
csvFormulaLossMsg:
'Cette feuille contient des formules que le format CSV ne peut pas conserver.',
csvFormulaLossDetail:
'Le CSV ne conserve que les valeurs — les formules sont remplacées par leur résultat actuel et la mise en forme est perdue.',
csvKeepXlsxBtn: 'Enregistrer en .xlsx',
csvContinueBtn: 'Continuer en CSV',
csvActiveSheetOnlyNotice:
"Les fichiers CSV ne contiennent qu'une seule feuille — seule la feuille active « {name} » sera exportée.",
csvKeepFormatMsg: 'Continuer à enregistrer au format CSV ?',
csvKeepFormatDetail:
"Le CSV ne conserve que les valeurs d'une seule feuille — les formules, la mise en forme et les feuilles supplémentaires ne sont pas enregistrées dans le fichier .csv.",
}, },
de: { de: {
filterSpreadsheets: 'Tabellenkalkulationen', filterSpreadsheets: 'Tabellenkalkulationen',
@@ -427,6 +488,18 @@ const tMain = createI18n({
btnCancel: 'Abbrechen', btnCancel: 'Abbrechen',
csvSaveAsNotice: csvSaveAsNotice:
'CSV-Dateien können keine Formatierung speichern – als .xlsx speichern, um alle Änderungen zu behalten.', 'CSV-Dateien können keine Formatierung speichern – als .xlsx speichern, um alle Änderungen zu behalten.',
menuExportCsv: 'CSV exportieren…',
filterCsv: 'CSV (Trennzeichen-getrennt)',
csvFormulaLossMsg: 'Dieses Blatt enthält Formeln, die das CSV-Format nicht speichern kann.',
csvFormulaLossDetail:
'CSV speichert nur reine Werte – Formeln werden durch ihre aktuellen Ergebnisse ersetzt, und die Formatierung geht verloren.',
csvKeepXlsxBtn: 'Als .xlsx speichern',
csvContinueBtn: 'Als CSV fortfahren',
csvActiveSheetOnlyNotice:
'CSV-Dateien enthalten nur ein Blatt – nur das aktive Blatt „{name}“ wird exportiert.',
csvKeepFormatMsg: 'Weiter im CSV-Format speichern?',
csvKeepFormatDetail:
'CSV speichert nur die Werte eines einzelnen Blatts – Formeln, Formatierungen und weitere Blätter werden nicht in der .csv-Datei gespeichert.',
}, },
es: { es: {
filterSpreadsheets: 'Hojas de cálculo', filterSpreadsheets: 'Hojas de cálculo',
@@ -475,6 +548,18 @@ const tMain = createI18n({
btnCancel: 'Cancelar', btnCancel: 'Cancelar',
csvSaveAsNotice: csvSaveAsNotice:
'El formato CSV no conserva el formato: guarda como .xlsx para conservar todos tus cambios.', 'El formato CSV no conserva el formato: guarda como .xlsx para conservar todos tus cambios.',
menuExportCsv: 'Exportar a CSV…',
filterCsv: 'CSV (delimitado por comas)',
csvFormulaLossMsg: 'Esta hoja contiene fórmulas que el formato CSV no puede conservar.',
csvFormulaLossDetail:
'El CSV solo conserva valores: las fórmulas se sustituyen por sus resultados actuales y el formato se pierde.',
csvKeepXlsxBtn: 'Guardar como .xlsx',
csvContinueBtn: 'Continuar como CSV',
csvActiveSheetOnlyNotice:
'Los archivos CSV solo contienen una hoja: solo se exportará la hoja activa «{name}».',
csvKeepFormatMsg: '¿Seguir guardando en formato CSV?',
csvKeepFormatDetail:
'CSV solo conserva los valores de una única hoja: las fórmulas, el formato y las hojas adicionales no se guardan en el archivo .csv.',
}, },
th: { th: {
filterSpreadsheets: 'สเปรดชีต', filterSpreadsheets: 'สเปรดชีต',
@@ -523,6 +608,18 @@ const tMain = createI18n({
btnCancel: 'ยกเลิก', btnCancel: 'ยกเลิก',
csvSaveAsNotice: csvSaveAsNotice:
'ไฟล์ CSV ไม่สามารถเก็บการจัดรูปแบบได้ — บันทึกเป็น .xlsx เพื่อเก็บการเปลี่ยนแปลงทั้งหมดของคุณ', 'ไฟล์ CSV ไม่สามารถเก็บการจัดรูปแบบได้ — บันทึกเป็น .xlsx เพื่อเก็บการเปลี่ยนแปลงทั้งหมดของคุณ',
menuExportCsv: 'ส่งออก CSV…',
filterCsv: 'CSV (คั่นด้วยเครื่องหมายจุลภาค)',
csvFormulaLossMsg: 'ชีตนี้มีสูตรที่รูปแบบ CSV เก็บไว้ไม่ได้',
csvFormulaLossDetail:
'CSV เก็บเฉพาะค่าเท่านั้น — สูตรจะถูกแทนที่ด้วยผลลัพธ์ปัจจุบัน และการจัดรูปแบบจะหายไป',
csvKeepXlsxBtn: 'บันทึกเป็น .xlsx',
csvContinueBtn: 'บันทึกเป็น CSV ต่อไป',
csvActiveSheetOnlyNotice:
'ไฟล์ CSV มีได้เพียงชีตเดียว — จะส่งออกเฉพาะชีตที่ใช้งานอยู่ “{name}” เท่านั้น',
csvKeepFormatMsg: 'บันทึกเป็นรูปแบบ CSV ต่อไปหรือไม่',
csvKeepFormatDetail:
'CSV เก็บเฉพาะค่าของชีตเดียวเท่านั้น — สูตร การจัดรูปแบบ และชีตอื่น ๆ จะไม่ถูกบันทึกลงในไฟล์ .csv',
}, },
id: { id: {
filterSpreadsheets: 'Lembar bentang', filterSpreadsheets: 'Lembar bentang',
@@ -569,6 +666,18 @@ const tMain = createI18n({
btnCancel: 'Batal', btnCancel: 'Batal',
csvSaveAsNotice: csvSaveAsNotice:
'File CSV tidak dapat menyimpan pemformatan — simpan sebagai .xlsx untuk mempertahankan semua perubahan Anda.', 'File CSV tidak dapat menyimpan pemformatan — simpan sebagai .xlsx untuk mempertahankan semua perubahan Anda.',
menuExportCsv: 'Ekspor CSV…',
filterCsv: 'CSV (dipisahkan koma)',
csvFormulaLossMsg: 'Lembar ini berisi rumus yang tidak dapat disimpan dalam format CSV.',
csvFormulaLossDetail:
'CSV hanya menyimpan nilai — rumus diganti dengan hasil saat ini, dan pemformatan akan hilang.',
csvKeepXlsxBtn: 'Simpan sebagai .xlsx',
csvContinueBtn: 'Lanjutkan sebagai CSV',
csvActiveSheetOnlyNotice:
'File CSV hanya memuat satu lembar — hanya lembar aktif “{name}” yang akan diekspor.',
csvKeepFormatMsg: 'Terus menyimpan dalam format CSV?',
csvKeepFormatDetail:
'CSV hanya menyimpan nilai dari satu lembar — rumus, pemformatan, dan lembar tambahan tidak disimpan ke file .csv.',
}, },
ru: { ru: {
filterSpreadsheets: 'Электронные таблицы', filterSpreadsheets: 'Электронные таблицы',
@@ -617,6 +726,18 @@ const tMain = createI18n({
btnCancel: 'Отмена', btnCancel: 'Отмена',
csvSaveAsNotice: csvSaveAsNotice:
'Формат CSV не сохраняет форматирование — сохраните в .xlsx, чтобы не потерять изменения.', 'Формат CSV не сохраняет форматирование — сохраните в .xlsx, чтобы не потерять изменения.',
menuExportCsv: 'Экспорт в CSV…',
filterCsv: 'CSV (разделители — запятые)',
csvFormulaLossMsg: 'Этот лист содержит формулы, которые формат CSV не сохраняет.',
csvFormulaLossDetail:
'CSV сохраняет только значения — формулы заменяются текущими результатами, а форматирование теряется.',
csvKeepXlsxBtn: 'Сохранить как .xlsx',
csvContinueBtn: 'Продолжить в CSV',
csvActiveSheetOnlyNotice:
'Файлы CSV содержат только один лист — будет экспортирован только активный лист «{name}».',
csvKeepFormatMsg: 'Продолжить сохранение в формате CSV?',
csvKeepFormatDetail:
'CSV сохраняет только значения одного листа — формулы, форматирование и дополнительные листы не сохраняются в файле .csv.',
}, },
ar: { ar: {
filterSpreadsheets: 'جداول البيانات', filterSpreadsheets: 'جداول البيانات',
@@ -663,6 +784,17 @@ const tMain = createI18n({
btnDontSave: 'عدم الحفظ', btnDontSave: 'عدم الحفظ',
btnCancel: 'إلغاء', btnCancel: 'إلغاء',
csvSaveAsNotice: 'ملفات CSV لا تحتفظ بالتنسيق — احفظ بصيغة ‎.xlsx للاحتفاظ بجميع تغييراتك.', csvSaveAsNotice: 'ملفات CSV لا تحتفظ بالتنسيق — احفظ بصيغة ‎.xlsx للاحتفاظ بجميع تغييراتك.',
menuExportCsv: 'تصدير CSV…',
filterCsv: 'CSV (محدد بفواصل)',
csvFormulaLossMsg: 'تحتوي هذه الورقة على صيغ لا يمكن لتنسيق CSV الاحتفاظ بها.',
csvFormulaLossDetail: 'يحتفظ CSV بالقيم فقط — تُستبدل الصيغ بنتائجها الحالية ويُفقد التنسيق.',
csvKeepXlsxBtn: 'حفظ بصيغة .xlsx',
csvContinueBtn: 'المتابعة بتنسيق CSV',
csvActiveSheetOnlyNotice:
'ملفات CSV تحتوي على ورقة واحدة فقط — سيتم تصدير الورقة النشطة «{name}» فقط.',
csvKeepFormatMsg: 'هل تريد متابعة الحفظ بتنسيق CSV؟',
csvKeepFormatDetail:
'يحتفظ CSV بقيم ورقة واحدة فقط — لا تُحفظ الصيغ والتنسيق والأوراق الإضافية في ملف .csv.',
}, },
pt: { pt: {
filterSpreadsheets: 'Planilhas', filterSpreadsheets: 'Planilhas',
@@ -711,6 +843,18 @@ const tMain = createI18n({
btnCancel: 'Cancelar', btnCancel: 'Cancelar',
csvSaveAsNotice: csvSaveAsNotice:
'Arquivos CSV não mantêm a formatação — salve como .xlsx para manter todas as suas alterações.', 'Arquivos CSV não mantêm a formatação — salve como .xlsx para manter todas as suas alterações.',
menuExportCsv: 'Exportar CSV…',
filterCsv: 'CSV (separado por vírgulas)',
csvFormulaLossMsg: 'Esta planilha contém fórmulas que o formato CSV não pode manter.',
csvFormulaLossDetail:
'O CSV mantém apenas valores — as fórmulas são substituídas pelos resultados atuais e a formatação é perdida.',
csvKeepXlsxBtn: 'Salvar como .xlsx',
csvContinueBtn: 'Continuar como CSV',
csvActiveSheetOnlyNotice:
'Arquivos CSV contêm apenas uma planilha — apenas a planilha ativa “{name}” será exportada.',
csvKeepFormatMsg: 'Continuar salvando no formato CSV?',
csvKeepFormatDetail:
'O CSV mantém apenas os valores de uma única planilha — fórmulas, formatação e planilhas adicionais não são salvas no arquivo .csv.',
}, },
it: { it: {
filterSpreadsheets: 'Fogli di calcolo', filterSpreadsheets: 'Fogli di calcolo',
@@ -760,6 +904,18 @@ const tMain = createI18n({
btnCancel: 'Annulla', btnCancel: 'Annulla',
csvSaveAsNotice: csvSaveAsNotice:
'I file CSV non conservano la formattazione: salva come .xlsx per mantenere tutte le modifiche.', 'I file CSV non conservano la formattazione: salva come .xlsx per mantenere tutte le modifiche.',
menuExportCsv: 'Esporta CSV…',
filterCsv: 'CSV (delimitato da virgole)',
csvFormulaLossMsg: 'Questo foglio contiene formule che il formato CSV non può conservare.',
csvFormulaLossDetail:
'Il CSV conserva solo i valori: le formule vengono sostituite dai risultati attuali e la formattazione viene persa.',
csvKeepXlsxBtn: 'Salva come .xlsx',
csvContinueBtn: 'Continua come CSV',
csvActiveSheetOnlyNotice:
'I file CSV contengono un solo foglio: verrà esportato solo il foglio attivo “{name}”.',
csvKeepFormatMsg: 'Continuare a salvare in formato CSV?',
csvKeepFormatDetail:
'Il CSV conserva solo i valori di un singolo foglio: formule, formattazione e fogli aggiuntivi non vengono salvati nel file .csv.',
}, },
pl: { pl: {
filterSpreadsheets: 'Arkusze kalkulacyjne', filterSpreadsheets: 'Arkusze kalkulacyjne',
@@ -808,6 +964,18 @@ const tMain = createI18n({
btnCancel: 'Anuluj', btnCancel: 'Anuluj',
csvSaveAsNotice: csvSaveAsNotice:
'Pliki CSV nie zachowują formatowania — zapisz jako .xlsx, aby zachować wszystkie zmiany.', 'Pliki CSV nie zachowują formatowania — zapisz jako .xlsx, aby zachować wszystkie zmiany.',
menuExportCsv: 'Eksportuj CSV…',
filterCsv: 'CSV (rozdzielany przecinkami)',
csvFormulaLossMsg: 'Ten arkusz zawiera formuły, których format CSV nie zachowuje.',
csvFormulaLossDetail:
'CSV zachowuje tylko wartości — formuły są zastępowane bieżącymi wynikami, a formatowanie jest tracone.',
csvKeepXlsxBtn: 'Zapisz jako .xlsx',
csvContinueBtn: 'Kontynuuj jako CSV',
csvActiveSheetOnlyNotice:
'Pliki CSV zawierają tylko jeden arkusz — wyeksportowany zostanie tylko aktywny arkusz „{name}”.',
csvKeepFormatMsg: 'Kontynuować zapisywanie w formacie CSV?',
csvKeepFormatDetail:
'CSV zachowuje tylko wartości jednego arkusza — formuły, formatowanie i dodatkowe arkusze nie są zapisywane w pliku .csv.',
}, },
nl: { nl: {
filterSpreadsheets: 'Spreadsheets', filterSpreadsheets: 'Spreadsheets',
@@ -857,6 +1025,18 @@ const tMain = createI18n({
btnCancel: 'Annuleren', btnCancel: 'Annuleren',
csvSaveAsNotice: csvSaveAsNotice:
'CSV-bestanden bewaren geen opmaak — sla op als .xlsx om al uw wijzigingen te behouden.', 'CSV-bestanden bewaren geen opmaak — sla op als .xlsx om al uw wijzigingen te behouden.',
menuExportCsv: 'CSV exporteren…',
filterCsv: 'CSV (kommagescheiden)',
csvFormulaLossMsg: 'Dit blad bevat formules die het CSV-formaat niet kan bewaren.',
csvFormulaLossDetail:
'CSV bewaart alleen waarden — formules worden vervangen door hun huidige resultaten en opmaak gaat verloren.',
csvKeepXlsxBtn: 'Opslaan als .xlsx',
csvContinueBtn: 'Doorgaan als CSV',
csvActiveSheetOnlyNotice:
'CSV-bestanden bevatten slechts één blad — alleen het actieve blad “{name}” wordt geëxporteerd.',
csvKeepFormatMsg: 'Doorgaan met opslaan in CSV-indeling?',
csvKeepFormatDetail:
'CSV bewaart alleen de waarden van één blad — formules, opmaak en extra bladen worden niet in het .csv-bestand opgeslagen.',
}, },
ms: { ms: {
filterSpreadsheets: 'Hamparan', filterSpreadsheets: 'Hamparan',
@@ -904,6 +1084,19 @@ const tMain = createI18n({
btnCancel: 'Batal', btnCancel: 'Batal',
csvSaveAsNotice: csvSaveAsNotice:
'Fail CSV tidak dapat menyimpan pemformatan — simpan sebagai .xlsx untuk mengekalkan semua perubahan anda.', 'Fail CSV tidak dapat menyimpan pemformatan — simpan sebagai .xlsx untuk mengekalkan semua perubahan anda.',
menuExportCsv: 'Eksport CSV…',
filterCsv: 'CSV (dipisahkan koma)',
csvFormulaLossMsg:
'Helaian ini mengandungi formula yang tidak dapat disimpan dalam format CSV.',
csvFormulaLossDetail:
'CSV hanya menyimpan nilai — formula digantikan dengan hasil semasa, dan pemformatan akan hilang.',
csvKeepXlsxBtn: 'Simpan sebagai .xlsx',
csvContinueBtn: 'Teruskan sebagai CSV',
csvActiveSheetOnlyNotice:
'Fail CSV hanya mengandungi satu helaian — hanya helaian aktif “{name}” akan dieksport.',
csvKeepFormatMsg: 'Terus simpan dalam format CSV?',
csvKeepFormatDetail:
'CSV hanya menyimpan nilai satu helaian — formula, pemformatan dan helaian tambahan tidak disimpan ke fail .csv.',
}, },
he: { he: {
filterSpreadsheets: 'גיליונות אלקטרוניים', filterSpreadsheets: 'גיליונות אלקטרוניים',
@@ -949,6 +1142,17 @@ const tMain = createI18n({
btnDontSave: 'אל תשמור', btnDontSave: 'אל תשמור',
btnCancel: 'ביטול', btnCancel: 'ביטול',
csvSaveAsNotice: 'קובצי CSV אינם שומרים עיצוב — שמרו כ‑.xlsx כדי לשמור על כל השינויים.', csvSaveAsNotice: 'קובצי CSV אינם שומרים עיצוב — שמרו כ‑.xlsx כדי לשמור על כל השינויים.',
menuExportCsv: 'ייצוא CSV…',
filterCsv: 'CSV (מופרד באמצעות פסיקים)',
csvFormulaLossMsg: 'גיליון זה מכיל נוסחאות שתבנית CSV אינה יכולה לשמור.',
csvFormulaLossDetail:
'CSV שומר ערכים בלבד — נוסחאות מוחלפות בתוצאות הנוכחיות שלהן, והעיצוב אובד.',
csvKeepXlsxBtn: 'שמירה כ-.xlsx',
csvContinueBtn: 'המשך שמירה כ-CSV',
csvActiveSheetOnlyNotice: 'קובצי CSV מכילים גיליון אחד בלבד — רק הגיליון הפעיל "{name}" ייוצא.',
csvKeepFormatMsg: 'להמשיך לשמור בתבנית CSV?',
csvKeepFormatDetail:
'CSV שומר רק את הערכים של גיליון אחד — נוסחאות, עיצוב וגיליונות נוספים אינם נשמרים בקובץ ה-.csv.',
}, },
hi: { hi: {
filterSpreadsheets: 'स्प्रेडशीट', filterSpreadsheets: 'स्प्रेडशीट',
@@ -997,6 +1201,18 @@ const tMain = createI18n({
btnCancel: 'रद्द करें', btnCancel: 'रद्द करें',
csvSaveAsNotice: csvSaveAsNotice:
'CSV फ़ाइलें फ़ॉर्मेटिंग सहेज नहीं सकतीं — सभी बदलाव बनाए रखने के लिए .xlsx के रूप में सहेजें।', 'CSV फ़ाइलें फ़ॉर्मेटिंग सहेज नहीं सकतीं — सभी बदलाव बनाए रखने के लिए .xlsx के रूप में सहेजें।',
menuExportCsv: 'CSV निर्यात करें…',
filterCsv: 'CSV (अल्पविराम द्वारा सीमांकित)',
csvFormulaLossMsg: 'इस शीट में ऐसे सूत्र हैं जिन्हें CSV प्रारूप सहेज नहीं सकता।',
csvFormulaLossDetail:
'CSV केवल मान रखता है — सूत्र उनके वर्तमान परिणामों से बदल दिए जाते हैं और फ़ॉर्मेटिंग खो जाती है।',
csvKeepXlsxBtn: '.xlsx के रूप में सहेजें',
csvContinueBtn: 'CSV के रूप में जारी रखें',
csvActiveSheetOnlyNotice:
'CSV फ़ाइलों में केवल एक शीट होती है — केवल सक्रिय शीट “{name}” निर्यात की जाएगी।',
csvKeepFormatMsg: 'CSV प्रारूप में सहेजना जारी रखें?',
csvKeepFormatDetail:
'CSV केवल एक शीट के मान रखता है — सूत्र, स्वरूपण और अतिरिक्त शीट .csv फ़ाइल में सहेजे नहीं जाते।',
}, },
'zh-TW': { 'zh-TW': {
filterSpreadsheets: '電子試算表', filterSpreadsheets: '電子試算表',
@@ -1042,6 +1258,15 @@ const tMain = createI18n({
btnDontSave: '不儲存', btnDontSave: '不儲存',
btnCancel: '取消', btnCancel: '取消',
csvSaveAsNotice: 'CSV 格式不保留樣式等格式修改——另存為 .xlsx 可保留全部內容。', csvSaveAsNotice: 'CSV 格式不保留樣式等格式修改——另存為 .xlsx 可保留全部內容。',
menuExportCsv: '匯出 CSV…',
filterCsv: 'CSV (逗號分隔)',
csvFormulaLossMsg: '目前工作表包含公式,CSV 格式無法保留。',
csvFormulaLossDetail: 'CSV 只保留純文字值——公式會被取代為目前計算結果,格式也會遺失。',
csvKeepXlsxBtn: '另存為 .xlsx',
csvContinueBtn: '繼續儲存為 CSV',
csvActiveSheetOnlyNotice: 'CSV 檔案只包含一張工作表——只會匯出目前工作表「{name}」。',
csvKeepFormatMsg: '要繼續以 CSV 格式儲存嗎?',
csvKeepFormatDetail: 'CSV 只保留單張工作表的純值——公式、格式和其他工作表不會存入 .csv 檔案。',
}, },
}) })
const tm = (key: Parameters<typeof tMain>[1], params?: Parameters<typeof tMain>[2]) => const tm = (key: Parameters<typeof tMain>[1], params?: Parameters<typeof tMain>[2]) =>
@@ -1058,12 +1283,19 @@ interface SessionInfo {
readonly sha256: string readonly sha256: string
readonly sheetNames: ReadonlyMap<string, string> readonly sheetNames: ReadonlyMap<string, string>
readonly automaticRecoveryDisabled: boolean readonly automaticRecoveryDisabled: boolean
/// Set when the session opened a converted copy (.xls/.csv import): the /// Set when the session opened a converted copy (.xls import): the
/// first save routes through Save As, defaulting to this .xlsx path. /// first save routes through Save As, defaulting to this .xlsx path.
readonly suggestSaveAs?: string readonly suggestSaveAs?: string
/// The converted copy came from a CSV: the Save As dialog explains that /// The converted copy came from a CSV: the Save As dialog explains that
/// formatting requires .xlsx (CSV keeps values only). /// formatting requires .xlsx (CSV keeps values only).
readonly csvImport?: boolean readonly csvImport?: boolean
/// CSV session: the original .csv on disk. Save keeps the CSV identity —
/// the xlsx save lands on the temp copy and the serialized csvContent is
/// written back here.
readonly csvSourcePath?: string
/// Digest of the original .csv at open/save time — guards the write-back
/// against external modification, like restoreTargetSha.
readonly csvSourceSha?: string
/// App-owned directory containing the converted CSV/XLS copy. Removed only /// App-owned directory containing the converted CSV/XLS copy. Removed only
/// after the sidecar session and its independent snapshot are closed. /// after the sidecar session and its independent snapshot are closed.
readonly importTempDir?: string readonly importTempDir?: string
@@ -1273,7 +1505,7 @@ export function setSheetsWorkbookOpenedHook(
/** forward an application-menu File command into the sheets renderer */ /** forward an application-menu File command into the sheets renderer */
export function sendSheetsMenuAction( export function sendSheetsMenuAction(
action: 'open' | 'save' | 'save-as' | 'export-pdf' | 'undo' | 'redo', action: 'open' | 'save' | 'save-as' | 'export-pdf' | 'export-csv' | 'undo' | 'redo',
): void { ): void {
activeSheetsWebContents?.send(IPC_CHANNELS.menuAction, action) activeSheetsWebContents?.send(IPC_CHANNELS.menuAction, action)
} }
@@ -1447,6 +1679,7 @@ function startCaptureServer(): void {
action === 'save' || action === 'save' ||
action === 'save-as' || action === 'save-as' ||
action === 'export-pdf' || action === 'export-pdf' ||
action === 'export-csv' ||
action === 'undo' || action === 'undo' ||
action === 'redo' action === 'redo'
) { ) {
@@ -1908,6 +2141,7 @@ export function registerSheetsIpc(): void {
const result = await openWorkbookSession(entry.client, prepared.openPath, entry.sessions, { const result = await openWorkbookSession(entry.client, prepared.openPath, entry.sessions, {
suggestSaveAs: prepared.suggestSaveAs, suggestSaveAs: prepared.suggestSaveAs,
csvImport: prepared.csvImport, csvImport: prepared.csvImport,
csvSourcePath: prepared.csvSourcePath,
importTempDir: prepared.importTempDir, importTempDir: prepared.importTempDir,
restoreTarget: prepared.restoreTarget, restoreTarget: prepared.restoreTarget,
}) })
@@ -2154,6 +2388,87 @@ export function registerSheetsIpc(): void {
return result return result
}) })
ipcMain.handle(IPC_CHANNELS.exportCsv, async (event, input: unknown) => {
const entry = sessionFor(event)
const request = workbookExportCsvRequestSchema.parse(input)
const parent = dialogParent(event)
if (request.hasFormulas) {
// Excel's CSV warning flow: offer keeping the formulas via .xlsx first.
const options = {
type: 'warning' as const,
message: tm('csvFormulaLossMsg'),
detail: tm('csvFormulaLossDetail'),
buttons: [tm('csvKeepXlsxBtn'), tm('csvContinueBtn'), tm('btnCancel')],
defaultId: 0,
cancelId: 2,
noLink: true,
}
const { response } = parent
? await dialog.showMessageBox(parent, options)
: await dialog.showMessageBox(options)
if (response === 0) return { canceled: true, saveAsXlsxInstead: true }
if (response === 2) return { canceled: true }
}
let pickedPath = request.targetPath
if (pickedPath === undefined) {
const selection = await saveFileDialog(event, {
defaultPath: request.fileName,
filters: [{ name: tm('filterCsv'), extensions: ['csv'] }],
...(request.activeSheetName
? {
title: tm('csvActiveSheetOnlyNotice', { name: request.activeSheetName }),
message: tm('csvActiveSheetOnlyNotice', { name: request.activeSheetName }),
}
: {}),
})
if (selection.canceled || !selection.filePath) return { canceled: true }
pickedPath = selection.filePath
}
const targetPath = pickedPath.toLowerCase().endsWith('.csv') ? pickedPath : `${pickedPath}.csv`
// UTF-8 BOM so Excel decodes the reopened file correctly. Written beside
// the destination and renamed into place: a plain writeFile creates the
// (empty) file before the data lands, and anything watching for the
// export — the e2e retry loop included — can read zero bytes in that
// window.
const csvBytes = Buffer.concat([
Buffer.from([0xef, 0xbb, 0xbf]),
Buffer.from(request.content, 'utf8'),
])
await atomicWriteFile(targetPath, csvBytes)
// An export can land on a CSV session's own source file — refresh that
// session's guard digest so its next Save doesn't mistake this write for
// an external change.
const writtenSha = await sha256File(targetPath).catch(() => undefined)
if (writtenSha !== undefined) {
for (const [sessionId, session] of entry.sessions) {
if (session.csvSourcePath === targetPath) {
entry.sessions.set(sessionId, { ...session, csvSourceSha: writtenSha })
}
}
}
return { canceled: false, path: targetPath }
})
// First Save of a CSV session: Excel's "keep this format?" question. The
// renderer remembers the answer for the file, so it is asked once.
ipcMain.handle(IPC_CHANNELS.csvSaveConfirm, async (event) => {
sessionFor(event)
const options = {
type: 'warning' as const,
message: tm('csvKeepFormatMsg'),
detail: tm('csvKeepFormatDetail'),
buttons: [tm('csvContinueBtn'), tm('csvKeepXlsxBtn'), tm('btnCancel')],
defaultId: 0,
cancelId: 2,
noLink: true,
}
const parent = dialogParent(event)
const { response } = parent
? await dialog.showMessageBox(parent, options)
: await dialog.showMessageBox(options)
return response === 0 ? 'csv' : response === 1 ? 'xlsx' : 'cancel'
})
ipcMain.handle(IPC_CHANNELS.saveWorkbook, async (event, input: unknown) => { ipcMain.handle(IPC_CHANNELS.saveWorkbook, async (event, input: unknown) => {
const entry = sessionFor(event) const entry = sessionFor(event)
const client = entry.client const client = entry.client
@@ -2161,9 +2476,13 @@ export function registerSheetsIpc(): void {
const session = entry.sessions.get(request.sessionId) const session = entry.sessions.get(request.sessionId)
if (!session) throw new Error('Unknown workbook session.') if (!session) throw new Error('Unknown workbook session.')
// A CSV session's plain Save keeps the CSV identity: the xlsx save lands
// on the temp copy and the serialized csvContent is written back to the
// original .csv afterwards.
const csvInPlace = request.mode === 'save' && session.csvSourcePath !== undefined
let targetPath = session.path let targetPath = session.path
// Converted imports (.xls/.csv) never save silently over the temp copy — // Converted .xls imports never save silently over the temp copy — the
// the first save always asks where the .xlsx should live. // first save always asks where the .xlsx should live.
if (request.mode === 'save-as' || session.suggestSaveAs !== undefined) { if (request.mode === 'save-as' || session.suggestSaveAs !== undefined) {
// .xlsm keeps its extension: untouched archive entries (vbaProject.bin, // .xlsm keeps its extension: untouched archive entries (vbaProject.bin,
// the macro-enabled content type) round-trip verbatim through the save. // the macro-enabled content type) round-trip verbatim through the save.
@@ -2172,14 +2491,28 @@ export function registerSheetsIpc(): void {
) )
const ext = macroEnabled ? 'xlsm' : 'xlsx' const ext = macroEnabled ? 'xlsm' : 'xlsx'
const selection = await saveFileDialog(event, { const selection = await saveFileDialog(event, {
defaultPath: session.suggestSaveAs ?? session.restoreTarget ?? session.path, defaultPath:
filters: [{ name: tm(macroEnabled ? 'filterXlsm' : 'filterXlsx'), extensions: [ext] }], session.suggestSaveAs ??
session.csvSourcePath?.replace(/\.[^.]+$/, '.xlsx') ??
session.restoreTarget ??
session.path,
filters: macroEnabled
? [{ name: tm('filterXlsm'), extensions: ['xlsm'] }]
: [
{ name: tm('filterXlsx'), extensions: ['xlsx'] },
{ name: tm('filterCsv'), extensions: ['csv'] },
],
// CSV import: explain why the save goes through .xlsx (CSV keeps values only) // CSV import: explain why the save goes through .xlsx (CSV keeps values only)
...(session.csvImport ...(session.csvImport
? { title: tm('csvSaveAsNotice'), message: tm('csvSaveAsNotice') } ? { title: tm('csvSaveAsNotice'), message: tm('csvSaveAsNotice') }
: {}), : {}),
}) })
if (selection.canceled || !selection.filePath) return { canceled: true } if (selection.canceled || !selection.filePath) return { canceled: true }
// A CSV pick can't ride the xlsx pipeline: hand the path back so the
// renderer serializes the active sheet through the CSV export channel.
if (!macroEnabled && selection.filePath.toLowerCase().endsWith('.csv')) {
return { canceled: true, csvSaveAsPath: selection.filePath }
}
targetPath = selection.filePath.toLowerCase().endsWith(`.${ext}`) targetPath = selection.filePath.toLowerCase().endsWith(`.${ext}`)
? selection.filePath ? selection.filePath
: `${selection.filePath}.${ext}` : `${selection.filePath}.${ext}`
@@ -2204,23 +2537,64 @@ export function registerSheetsIpc(): void {
throw new Error(tm('errDiskChanged')) throw new Error(tm('errDiskChanged'))
} }
} }
// The CSV write-back gets the same external-change guard as restoreTarget;
// a deleted .csv is fine — the write recreates it.
if (csvInPlace && session.csvSourcePath !== undefined) {
const csvSha = await sha256File(session.csvSourcePath).catch(() => undefined)
if (csvSha !== undefined && csvSha !== session.csvSourceSha) {
throw new Error(tm('errDiskChanged'))
}
}
const mutation = await writeWorkbookTo(client, session, request, targetPath) const mutation = await writeWorkbookTo(client, session, request, targetPath)
if (csvInPlace && session.csvSourcePath !== undefined && request.csvContent !== undefined) {
// The temp copy already holds the saved bytes: refresh the session's
// guard digest first, so a failed CSV write-back below leaves a
// retryable session instead of stranding the next Save on
// errDiskChanged against its own write.
const savedSha = await sha256File(session.path).catch(() => undefined)
if (savedSha !== undefined && entry.sessions.has(request.sessionId)) {
entry.sessions.set(request.sessionId, { ...session, sha256: savedSha })
}
// UTF-8 BOM so Excel decodes the reopened file correctly.
await writeFile(
session.csvSourcePath,
Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from(request.csvContent, 'utf8')]),
)
}
// The sidecar session still streams the pre-save bytes; swap it for a // The sidecar session still streams the pre-save bytes; swap it for a
// fresh session over the saved file so future reads match the disk state. // fresh session over the saved file so future reads match the disk state.
entry.sessions.delete(request.sessionId) entry.sessions.delete(request.sessionId)
await cleanupSessionResources({ await cleanupSessionResources({
tempRoot: app.getPath('temp'), tempRoot: app.getPath('temp'),
snapshotPath: session.snapshotPath, snapshotPath: session.snapshotPath,
importTempDir: session.importTempDir, // A CSV in-place save keeps saving into the temp copy — its directory
// must survive the session swap.
importTempDir: csvInPlace ? undefined : session.importTempDir,
closeSidecar: () => client.close(request.sessionId), closeSidecar: () => client.close(request.sessionId),
}) })
const file = await openWorkbookSession(client, targetPath, entry.sessions) const file = await openWorkbookSession(
client,
targetPath,
entry.sessions,
csvInPlace
? {
csvImport: true,
csvSourcePath: session.csvSourcePath,
importTempDir: session.importTempDir,
}
: undefined,
)
// Notify shell (if running) so it can update the tab title and record the // Notify shell (if running) so it can update the tab title and record the
// saved path in recent files (mirrors the open hook; covers Save As + first // saved path in recent files (mirrors the open hook; covers Save As + first
// save after converting an .xls/.csv import). // save after converting an .xls/.csv import). A CSV session's user-visible
workbookOpenedHook?.(event.sender, targetPath) // file is the original .csv, not the temp copy the xlsx save landed on.
workbookOpenedHook?.(
event.sender,
(csvInPlace ? session.csvSourcePath : undefined) ?? targetPath,
)
// The file on disk now carries these edits // The file on disk now carries these edits
clearWorkbookRecovery(targetPath) clearWorkbookRecovery(targetPath)
if (session.suggestSaveAs !== undefined) clearWorkbookRecovery(session.suggestSaveAs) if (session.suggestSaveAs !== undefined) clearWorkbookRecovery(session.suggestSaveAs)
@@ -2260,10 +2634,16 @@ export function registerSheetsIpc(): void {
const entry = sessionFor(event) const entry = sessionFor(event)
const request = resolveTransferredEdits(entry, workbookSaveRequestSchema.parse(input)) const request = resolveTransferredEdits(entry, workbookSaveRequestSchema.parse(input))
const session = entry.sessions.get(request.sessionId) const session = entry.sessions.get(request.sessionId)
// A converted import has no original file to recover into; a restored // A converted import has no original file to recover into (and a CSV
// recovery session is backed by the recovery copy itself — writing over // session's original can't hold the workbook bytes); a restored recovery
// the file the sidecar streams from would corrupt the open session. // session is backed by the recovery copy itself — writing over the file
if (!session || session.suggestSaveAs !== undefined || session.restoreTarget !== undefined) // the sidecar streams from would corrupt the open session.
if (
!session ||
session.suggestSaveAs !== undefined ||
session.csvSourcePath !== undefined ||
session.restoreTarget !== undefined
)
return { ok: false } return { ok: false }
if (session.automaticRecoveryDisabled) return { ok: false } if (session.automaticRecoveryDisabled) return { ok: false }
try { try {
@@ -2523,6 +2903,7 @@ export function registerSheetsAiIpc(): void {
await streamForProvider(provider, config, system, messages, tools, maxTokens, { await streamForProvider(provider, config, system, messages, tools, maxTokens, {
signal: controller.signal, signal: controller.signal,
onDelta: (text) => send({ requestId, type: 'delta', text }), onDelta: (text) => send({ requestId, type: 'delta', text }),
onReasoningDelta: (text) => send({ requestId, type: 'reasoning', text }),
onToolCall: (toolCall) => send({ requestId, type: 'tool-call', toolCall }), onToolCall: (toolCall) => send({ requestId, type: 'tool-call', toolCall }),
onActivity: ping, onActivity: ping,
}) })
@@ -3025,18 +3406,19 @@ async function openWorkbookSession(
options?: { options?: {
suggestSaveAs?: string | undefined suggestSaveAs?: string | undefined
csvImport?: boolean | undefined csvImport?: boolean | undefined
csvSourcePath?: string | undefined
importTempDir?: string | undefined importTempDir?: string | undefined
restoreTarget?: string | undefined restoreTarget?: string | undefined
}, },
): Promise<WorkbookFile> { ): Promise<WorkbookFile> {
const { suggestSaveAs, csvImport, importTempDir, restoreTarget } = options ?? {} const { suggestSaveAs, csvImport, csvSourcePath, importTempDir, restoreTarget } = options ?? {}
// Snapshot first, then the sidecar opens the snapshot (not the live path): // Snapshot first, then the sidecar opens the snapshot (not the live path):
// everything the session serves — cell reads, media, recalc, saves — comes // everything the session serves — cell reads, media, recalc, saves — comes
// from the same bytes, even if the file on disk changes right after the // from the same bytes, even if the file on disk changes right after the
// copy. The digest also describes exactly those bytes. // copy. The digest also describes exactly those bytes.
const snapshotPath = await snapshotWorkbook(path) const snapshotPath = await snapshotWorkbook(path)
try { try {
const [opened, digest, restoreTargetSha] = await Promise.all([ const [opened, digest, restoreTargetSha, csvSourceSha] = await Promise.all([
client client
.open(snapshotPath, getUiLang(), systemShortDate()) .open(snapshotPath, getUiLang(), systemShortDate())
.then((result) => sidecarOpenResultSchema.parse(result)), .then((result) => sidecarOpenResultSchema.parse(result)),
@@ -3045,6 +3427,9 @@ async function openWorkbookSession(
restoreTarget === undefined restoreTarget === undefined
? Promise.resolve(undefined) ? Promise.resolve(undefined)
: sha256File(restoreTarget).catch(() => undefined), : sha256File(restoreTarget).catch(() => undefined),
csvSourcePath === undefined
? Promise.resolve(undefined)
: sha256File(csvSourcePath).catch(() => undefined),
]) ])
sessions.set(opened.sessionId, { sessions.set(opened.sessionId, {
path, path,
@@ -3054,6 +3439,8 @@ async function openWorkbookSession(
automaticRecoveryDisabled: !allowsAutomaticWorkbookRecovery(opened.sheets), automaticRecoveryDisabled: !allowsAutomaticWorkbookRecovery(opened.sheets),
...(suggestSaveAs === undefined ? {} : { suggestSaveAs }), ...(suggestSaveAs === undefined ? {} : { suggestSaveAs }),
...(csvImport ? { csvImport } : {}), ...(csvImport ? { csvImport } : {}),
...(csvSourcePath === undefined ? {} : { csvSourcePath }),
...(csvSourceSha === undefined ? {} : { csvSourceSha }),
...(importTempDir === undefined ? {} : { importTempDir }), ...(importTempDir === undefined ? {} : { importTempDir }),
...(restoreTarget === undefined ? {} : { restoreTarget }), ...(restoreTarget === undefined ? {} : { restoreTarget }),
...(restoreTargetSha === undefined ? {} : { restoreTargetSha }), ...(restoreTargetSha === undefined ? {} : { restoreTargetSha }),
@@ -3066,6 +3453,7 @@ async function openWorkbookSession(
sha256: digest, sha256: digest,
readOnly: false, readOnly: false,
needsSaveAs: suggestSaveAs !== undefined, needsSaveAs: suggestSaveAs !== undefined,
...(csvSourcePath === undefined ? {} : { csvPath: csvSourcePath }),
restoredFromRecovery: restoreTarget !== undefined, restoredFromRecovery: restoreTarget !== undefined,
automaticRecoveryDisabled: !allowsAutomaticWorkbookRecovery(opened.sheets), automaticRecoveryDisabled: !allowsAutomaticWorkbookRecovery(opened.sheets),
}) })
@@ -3100,6 +3488,7 @@ async function prepareWorkbookForOpen(
openPath: string openPath: string
suggestSaveAs?: string suggestSaveAs?: string
csvImport?: boolean csvImport?: boolean
csvSourcePath?: string
importTempDir?: string importTempDir?: string
restoreTarget?: string restoreTarget?: string
}> { }> {
@@ -3137,12 +3526,12 @@ async function prepareWorkbookForOpen(
await cleanupImportTempDirectory(app.getPath('temp'), directory) await cleanupImportTempDirectory(app.getPath('temp'), directory)
throw error throw error
} }
return { // CSV keeps its file identity: Save writes the values back to the original
openPath, // .csv (Excel's behavior), so no Save As detour is suggested. Legacy .xls
importTempDir: directory, // still routes the first save through Save As to a fresh .xlsx.
suggestSaveAs: path.replace(/\.[^.]+$/, '.xlsx'), return extension === 'csv'
...(extension === 'csv' ? { csvImport: true } : {}), ? { openPath, importTempDir: directory, csvImport: true, csvSourcePath: path }
} : { openPath, importTempDir: directory, suggestSaveAs: path.replace(/\.[^.]+$/, '.xlsx') }
} }
/** shell-injected items appended to the File menu (e.g. Back to Home) */ /** shell-injected items appended to the File menu (e.g. Back to Home) */
@@ -3192,6 +3581,10 @@ function installApplicationMenu(): void {
label: tm('menuExportPdf'), label: tm('menuExportPdf'),
click: () => sendMenuAction('export-pdf'), click: () => sendMenuAction('export-pdf'),
}, },
{
label: tm('menuExportCsv'),
click: () => sendMenuAction('export-csv'),
},
{ type: 'separator' }, { type: 'separator' },
closeActiveTabHook closeActiveTabHook
? { ? {
+196 -5
View File
@@ -24,6 +24,7 @@ import type {
WorkbookFormulaCellsResult, WorkbookFormulaCellsResult,
WorkbookMediaRequest, WorkbookMediaRequest,
WorkbookMediaResult, WorkbookMediaResult,
WorkbookPagePrintSettings,
WorkbookPivotDefinition, WorkbookPivotDefinition,
WorkbookPivotRequest, WorkbookPivotRequest,
WorkbookRangeRequest, WorkbookRangeRequest,
@@ -40,6 +41,7 @@ import type {
} from '../shared/desktop-api' } from '../shared/desktop-api'
import { import {
IPC_CHANNELS, IPC_CHANNELS,
MAX_CSV_EXPORT_CHARS,
MAX_SAVE_EDITS, MAX_SAVE_EDITS,
MAX_SAVE_EDITS_TOTAL, MAX_SAVE_EDITS_TOTAL,
SAVE_EDITS_CHUNK_MAX, SAVE_EDITS_CHUNK_MAX,
@@ -254,7 +256,9 @@ const desktopApi: DesktopApi = {
}) || }) ||
typeof request.scale !== 'number' || typeof request.scale !== 'number' ||
request.scale < 0.1 || request.scale < 0.1 ||
request.scale > 2 request.scale > 2 ||
(request.headerTemplate !== undefined && !isBoundedString(request.headerTemplate, 50_000)) ||
(request.footerTemplate !== undefined && !isBoundedString(request.footerTemplate, 50_000))
) { ) {
throw new Error('Invalid PDF export request.') throw new Error('Invalid PDF export request.')
} }
@@ -268,6 +272,43 @@ const desktopApi: DesktopApi = {
} }
return result as { canceled: true } | { canceled: false; path: string } return result as { canceled: true } | { canceled: false; path: string }
}, },
async exportCsv(request) {
if (
!isRecord(request) ||
typeof request.fileName !== 'string' ||
request.fileName.length === 0 ||
request.fileName.length > 255 ||
typeof request.content !== 'string' ||
request.content.length > MAX_CSV_EXPORT_CHARS ||
typeof request.hasFormulas !== 'boolean' ||
(request.activeSheetName !== undefined &&
(typeof request.activeSheetName !== 'string' || request.activeSheetName.length > 255)) ||
(request.targetPath !== undefined &&
(typeof request.targetPath !== 'string' || request.targetPath.length === 0))
) {
throw new Error('Invalid CSV export request.')
}
const result: unknown = await ipcRenderer.invoke(IPC_CHANNELS.exportCsv, request)
if (
!isRecord(result) ||
typeof result.canceled !== 'boolean' ||
(result.canceled === false && typeof result.path !== 'string') ||
(result.canceled === true &&
result.saveAsXlsxInstead !== undefined &&
typeof result.saveAsXlsxInstead !== 'boolean')
) {
throw new Error('Invalid CSV export response.')
}
return result as
{ canceled: true; saveAsXlsxInstead?: boolean } | { canceled: false; path: string }
},
async confirmCsvSave() {
const result: unknown = await ipcRenderer.invoke(IPC_CHANNELS.csvSaveConfirm)
if (result !== 'csv' && result !== 'xlsx' && result !== 'cancel') {
throw new Error('Invalid CSV save confirmation response.')
}
return result
},
async closeWorkbook(sessionId) { async closeWorkbook(sessionId) {
if (!isUuid(sessionId)) throw new Error('Invalid workbook session.') if (!isUuid(sessionId)) throw new Error('Invalid workbook session.')
await ipcRenderer.invoke(IPC_CHANNELS.closeWorkbook, sessionId) await ipcRenderer.invoke(IPC_CHANNELS.closeWorkbook, sessionId)
@@ -285,6 +326,7 @@ const desktopApi: DesktopApi = {
action === 'save' || action === 'save' ||
action === 'save-as' || action === 'save-as' ||
action === 'export-pdf' || action === 'export-pdf' ||
action === 'export-csv' ||
action === 'undo' || action === 'undo' ||
action === 'redo' action === 'redo'
) )
@@ -564,6 +606,7 @@ function parseWorkbookFile(input: unknown): WorkbookFile {
definedNames, definedNames,
readOnly, readOnly,
needsSaveAs, needsSaveAs,
csvPath,
restoredFromRecovery, restoredFromRecovery,
} = input } = input
if ( if (
@@ -580,6 +623,7 @@ function parseWorkbookFile(input: unknown): WorkbookFile {
!Array.isArray(definedNames) || !Array.isArray(definedNames) ||
typeof readOnly !== 'boolean' || typeof readOnly !== 'boolean' ||
(needsSaveAs !== undefined && typeof needsSaveAs !== 'boolean') || (needsSaveAs !== undefined && typeof needsSaveAs !== 'boolean') ||
(csvPath !== undefined && (typeof csvPath !== 'string' || csvPath.length === 0)) ||
(restoredFromRecovery !== undefined && typeof restoredFromRecovery !== 'boolean') (restoredFromRecovery !== undefined && typeof restoredFromRecovery !== 'boolean')
) { ) {
throw new Error('Invalid workbook response.') throw new Error('Invalid workbook response.')
@@ -781,6 +825,7 @@ function parseWorkbookFile(input: unknown): WorkbookFile {
// mean "use the built-in size". // mean "use the built-in size".
defaultRowHeight: normalizedDefaultSize(sheet.defaultRowHeight), defaultRowHeight: normalizedDefaultSize(sheet.defaultRowHeight),
defaultColumnWidth: normalizedDefaultSize(sheet.defaultColumnWidth), defaultColumnWidth: normalizedDefaultSize(sheet.defaultColumnWidth),
baseColumnWidth: normalizedDefaultSize(sheet.baseColumnWidth),
freeze: parseFreeze(sheet.freeze), freeze: parseFreeze(sheet.freeze),
hidden: sheet.hidden, hidden: sheet.hidden,
tabColor: sheet.tabColor, tabColor: sheet.tabColor,
@@ -793,6 +838,9 @@ function parseWorkbookFile(input: unknown): WorkbookFile {
pivotRanges: sheet.pivotRanges.map(parseCellArea), pivotRanges: sheet.pivotRanges.map(parseCellArea),
pivotTables: parsePivotTableInfos(sheet.pivotTables ?? []), pivotTables: parsePivotTableInfos(sheet.pivotTables ?? []),
sparklines: parseSparklineGroups(sheet.sparklines ?? []), sparklines: parseSparklineGroups(sheet.sparklines ?? []),
cellImages: parseCellImages(sheet.cellImages ?? []),
...(isBoundedString(sheet.printArea, 2_000) ? { printArea: sheet.printArea } : {}),
...(isBoundedString(sheet.printTitles, 2_000) ? { printTitles: sheet.printTitles } : {}),
} }
}) })
if (parsedSheets.length === 0) throw new Error('Workbook contains no worksheets.') if (parsedSheets.length === 0) throw new Error('Workbook contains no worksheets.')
@@ -852,6 +900,7 @@ function parseWorkbookFile(input: unknown): WorkbookFile {
definedNames: parsedDefinedNames, definedNames: parsedDefinedNames,
readOnly, readOnly,
...(needsSaveAs === undefined ? {} : { needsSaveAs }), ...(needsSaveAs === undefined ? {} : { needsSaveAs }),
...(csvPath === undefined ? {} : { csvPath }),
...(restoredFromRecovery === undefined ? {} : { restoredFromRecovery }), ...(restoredFromRecovery === undefined ? {} : { restoredFromRecovery }),
...(themeColors === undefined ? {} : { themeColors: themeColors as string[] }), ...(themeColors === undefined ? {} : { themeColors: themeColors as string[] }),
...(parsedThemeFonts === undefined ? {} : { themeFonts: parsedThemeFonts }), ...(parsedThemeFonts === undefined ? {} : { themeFonts: parsedThemeFonts }),
@@ -1195,11 +1244,70 @@ function parseRangeResult(input: unknown): WorkbookRangeResult {
rowBreaks: parseBreaks(input.rowBreaks, 'row breaks'), rowBreaks: parseBreaks(input.rowBreaks, 'row breaks'),
colBreaks: parseBreaks(input.colBreaks, 'column breaks'), colBreaks: parseBreaks(input.colBreaks, 'column breaks'),
protectedRanges, protectedRanges,
pageSetup: parsePagePrintSettings(input.pageSetup),
indexedThroughRow: input.indexedThroughRow, indexedThroughRow: input.indexedThroughRow,
indexingComplete: input.indexingComplete, indexingComplete: input.indexingComplete,
} }
} }
function parsePagePrintSettings(input: unknown): WorkbookRangeResult['pageSetup'] {
if (input === null || input === undefined) return null
const boundedInt = (value: unknown, min: number, max: number): boolean =>
typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max
if (
!isRecord(input) ||
(input.orientation !== undefined &&
input.orientation !== 'portrait' &&
input.orientation !== 'landscape') ||
(input.paperSize !== undefined && !boundedInt(input.paperSize, 1, 256)) ||
(input.scale !== undefined && !boundedInt(input.scale, 10, 400)) ||
(input.fitToWidth !== undefined && !boundedInt(input.fitToWidth, 0, 32_767)) ||
(input.fitToHeight !== undefined && !boundedInt(input.fitToHeight, 0, 32_767)) ||
(input.fitToPage !== undefined && typeof input.fitToPage !== 'boolean') ||
(input.printGridlines !== undefined && typeof input.printGridlines !== 'boolean') ||
(input.printHeadings !== undefined && typeof input.printHeadings !== 'boolean') ||
(input.oddHeader !== undefined && !isBoundedString(input.oddHeader, 500)) ||
(input.oddFooter !== undefined && !isBoundedString(input.oddFooter, 500))
) {
throw new Error('Invalid workbook page setup response.')
}
let margins: WorkbookPagePrintSettings['margins']
if (input.margins !== undefined) {
const record = input.margins
if (
!isRecord(record) ||
!['left', 'right', 'top', 'bottom', 'header', 'footer'].every((edge) => {
const value = record[edge]
return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 10
})
) {
throw new Error('Invalid workbook page margins response.')
}
margins = {
left: record.left as number,
right: record.right as number,
top: record.top as number,
bottom: record.bottom as number,
header: record.header as number,
footer: record.footer as number,
}
}
const validated = input as WorkbookPagePrintSettings
return {
...(validated.orientation === undefined ? {} : { orientation: validated.orientation }),
...(validated.paperSize === undefined ? {} : { paperSize: validated.paperSize }),
...(validated.scale === undefined ? {} : { scale: validated.scale }),
...(validated.fitToWidth === undefined ? {} : { fitToWidth: validated.fitToWidth }),
...(validated.fitToHeight === undefined ? {} : { fitToHeight: validated.fitToHeight }),
...(validated.fitToPage === undefined ? {} : { fitToPage: validated.fitToPage }),
...(margins === undefined ? {} : { margins }),
...(validated.printGridlines === undefined ? {} : { printGridlines: validated.printGridlines }),
...(validated.printHeadings === undefined ? {} : { printHeadings: validated.printHeadings }),
...(validated.oddHeader === undefined ? {} : { oddHeader: validated.oddHeader }),
...(validated.oddFooter === undefined ? {} : { oddFooter: validated.oddFooter }),
}
}
function parseRichRuns(input: unknown): WorkbookRichRun[] { function parseRichRuns(input: unknown): WorkbookRichRun[] {
if (!Array.isArray(input)) throw new Error('Invalid workbook rich text response.') if (!Array.isArray(input)) throw new Error('Invalid workbook rich text response.')
return input.map((run) => { return input.map((run) => {
@@ -1344,6 +1452,11 @@ function parseSaveRequest(input: WorkbookSaveRequest): WorkbookSaveRequest {
if (input.mode !== 'save' && input.mode !== 'save-as') invalid('mode') if (input.mode !== 'save' && input.mode !== 'save-as') invalid('mode')
if (input.restoreWriteBack !== undefined && typeof input.restoreWriteBack !== 'boolean') if (input.restoreWriteBack !== undefined && typeof input.restoreWriteBack !== 'boolean')
invalid('restore flag') invalid('restore flag')
if (
input.csvContent !== undefined &&
(typeof input.csvContent !== 'string' || input.csvContent.length > MAX_CSV_EXPORT_CHARS)
)
invalid('csv content')
if (input.editsTransferId !== undefined && !isUuid(input.editsTransferId)) if (input.editsTransferId !== undefined && !isUuid(input.editsTransferId))
invalid('edits transfer id') invalid('edits transfer id')
cappedArray('cell edits', input.edits, MAX_SAVE_EDITS) cappedArray('cell edits', input.edits, MAX_SAVE_EDITS)
@@ -2114,7 +2227,15 @@ function isDefinedNamesState(input: unknown): boolean {
function parseSaveResult(input: unknown): WorkbookSaveResult { function parseSaveResult(input: unknown): WorkbookSaveResult {
if (!isRecord(input)) throw new Error('Invalid workbook save response.') if (!isRecord(input)) throw new Error('Invalid workbook save response.')
if (input.canceled === true) return { canceled: true } if (input.canceled === true) {
if (input.csvSaveAsPath !== undefined) {
if (typeof input.csvSaveAsPath !== 'string' || input.csvSaveAsPath.length === 0) {
throw new Error('Invalid workbook save response.')
}
return { canceled: true, csvSaveAsPath: input.csvSaveAsPath }
}
return { canceled: true }
}
if ( if (
input.canceled !== false || input.canceled !== false ||
!Array.isArray(input.touchedEntries) || !Array.isArray(input.touchedEntries) ||
@@ -2190,6 +2311,24 @@ function parseSparklineGroups(input: unknown): {
}) })
} }
function parseCellImages(input: unknown): { id: string; row: number; column: number }[] {
if (!Array.isArray(input) || input.length > 500) {
throw new Error('Invalid worksheet cell-image metadata.')
}
return input.map((entry) => {
if (
!isRecord(entry) ||
typeof entry.id !== 'string' ||
entry.id.length === 0 ||
!isNonnegativeInteger(entry.row) ||
!isNonnegativeInteger(entry.column)
) {
throw new Error('Invalid worksheet cell-image metadata.')
}
return { id: entry.id, row: entry.row, column: entry.column }
})
}
function parsePivotTableInfos(input: unknown): { function parsePivotTableInfos(input: unknown): {
path: string path: string
cachePath: string | null cachePath: string | null
@@ -2198,6 +2337,7 @@ function parsePivotTableInfos(input: unknown): {
headerFontColor?: string headerFontColor?: string
wholeTableFill?: string wholeTableFill?: string
stripeFill?: string stripeFill?: string
styled?: boolean
firstDataRow?: number firstDataRow?: number
rowGrandTotals?: boolean rowGrandTotals?: boolean
}[] { }[] {
@@ -2216,6 +2356,7 @@ function parsePivotTableInfos(input: unknown): {
(entry.headerFontColor !== undefined && typeof entry.headerFontColor !== 'string') || (entry.headerFontColor !== undefined && typeof entry.headerFontColor !== 'string') ||
(entry.wholeTableFill !== undefined && typeof entry.wholeTableFill !== 'string') || (entry.wholeTableFill !== undefined && typeof entry.wholeTableFill !== 'string') ||
(entry.stripeFill !== undefined && typeof entry.stripeFill !== 'string') || (entry.stripeFill !== undefined && typeof entry.stripeFill !== 'string') ||
(entry.styled !== undefined && typeof entry.styled !== 'boolean') ||
(entry.firstDataRow !== undefined && !isNonnegativeInteger(entry.firstDataRow)) || (entry.firstDataRow !== undefined && !isNonnegativeInteger(entry.firstDataRow)) ||
(entry.rowGrandTotals !== undefined && typeof entry.rowGrandTotals !== 'boolean') (entry.rowGrandTotals !== undefined && typeof entry.rowGrandTotals !== 'boolean')
) { ) {
@@ -2229,6 +2370,7 @@ function parsePivotTableInfos(input: unknown): {
...(entry.headerFontColor === undefined ? {} : { headerFontColor: entry.headerFontColor }), ...(entry.headerFontColor === undefined ? {} : { headerFontColor: entry.headerFontColor }),
...(entry.wholeTableFill === undefined ? {} : { wholeTableFill: entry.wholeTableFill }), ...(entry.wholeTableFill === undefined ? {} : { wholeTableFill: entry.wholeTableFill }),
...(entry.stripeFill === undefined ? {} : { stripeFill: entry.stripeFill }), ...(entry.stripeFill === undefined ? {} : { stripeFill: entry.stripeFill }),
...(entry.styled === undefined ? {} : { styled: entry.styled }),
...(entry.firstDataRow === undefined ? {} : { firstDataRow: entry.firstDataRow }), ...(entry.firstDataRow === undefined ? {} : { firstDataRow: entry.firstDataRow }),
...(entry.rowGrandTotals === undefined ? {} : { rowGrandTotals: entry.rowGrandTotals }), ...(entry.rowGrandTotals === undefined ? {} : { rowGrandTotals: entry.rowGrandTotals }),
} }
@@ -2409,6 +2551,13 @@ function parseVisualObject(input: unknown): WorkbookVisualObject {
const customPath = input.customPath === undefined ? undefined : parseCustomPath(input.customPath) const customPath = input.customPath === undefined ? undefined : parseCustomPath(input.customPath)
if ( if (
!isOptionalString(input.shapeType) || !isOptionalString(input.shapeType) ||
(input.opacity !== undefined &&
(typeof input.opacity !== 'number' ||
!Number.isFinite(input.opacity) ||
input.opacity < 0 ||
input.opacity > 1)) ||
!isOptionalString(input.fillMediaPath) ||
!isOptionalString(input.fillMediaType) ||
!isOptionalString(input.fillColor) || !isOptionalString(input.fillColor) ||
!isOptionalString(input.lineColor) || !isOptionalString(input.lineColor) ||
(input.lineWidth !== undefined && (input.lineWidth !== undefined &&
@@ -2447,6 +2596,9 @@ function parseVisualObject(input: unknown): WorkbookVisualObject {
...(typeof input.chartPath === 'string' ? { chartPath: input.chartPath } : {}), ...(typeof input.chartPath === 'string' ? { chartPath: input.chartPath } : {}),
...(typeof input.mediaPath === 'string' ? { mediaPath: input.mediaPath } : {}), ...(typeof input.mediaPath === 'string' ? { mediaPath: input.mediaPath } : {}),
...(typeof input.mediaType === 'string' ? { mediaType: input.mediaType } : {}), ...(typeof input.mediaType === 'string' ? { mediaType: input.mediaType } : {}),
...(input.opacity === undefined ? {} : { opacity: input.opacity }),
...(input.fillMediaPath === undefined ? {} : { fillMediaPath: input.fillMediaPath }),
...(input.fillMediaType === undefined ? {} : { fillMediaType: input.fillMediaType }),
...(typeof input.name === 'string' ? { name: input.name } : {}), ...(typeof input.name === 'string' ? { name: input.name } : {}),
...(input.shapeType === undefined ? {} : { shapeType: input.shapeType }), ...(input.shapeType === undefined ? {} : { shapeType: input.shapeType }),
...(customPath === undefined ? {} : { customPath }), ...(customPath === undefined ? {} : { customPath }),
@@ -2571,7 +2723,8 @@ function parseDrawingAnchor(input: Record<string, unknown>): WorkbookVisualObjec
] ]
if ( if (
values.some((value) => !isNonnegativeInteger(value)) || values.some((value) => !isNonnegativeInteger(value)) ||
offsets.some((value) => typeof value !== 'number' || !Number.isInteger(value)) offsets.some((value) => typeof value !== 'number' || !Number.isInteger(value)) ||
(input.explicitTo !== undefined && typeof input.explicitTo !== 'boolean')
) { ) {
throw new Error('Invalid workbook drawing anchor.') throw new Error('Invalid workbook drawing anchor.')
} }
@@ -2584,6 +2737,7 @@ function parseDrawingAnchor(input: Record<string, unknown>): WorkbookVisualObjec
fromColumnOffset: input.fromColumnOffset as number, fromColumnOffset: input.fromColumnOffset as number,
toRowOffset: input.toRowOffset as number, toRowOffset: input.toRowOffset as number,
toColumnOffset: input.toColumnOffset as number, toColumnOffset: input.toColumnOffset as number,
...(input.explicitTo === undefined ? {} : { explicitTo: input.explicitTo }),
} }
} }
@@ -2612,8 +2766,10 @@ function parseChart(input: unknown): NonNullable<WorkbookVisualObject['chart']>
!isOptionalString(input.dataLabelFormat) || !isOptionalString(input.dataLabelFormat) ||
!isOptionalEnum(input.grouping, CHART_GROUPINGS) || !isOptionalEnum(input.grouping, CHART_GROUPINGS) ||
(input.gridlines !== undefined && typeof input.gridlines !== 'boolean') || (input.gridlines !== undefined && typeof input.gridlines !== 'boolean') ||
!isOptionalString(input.categoryAxisFormat) ||
!isOptionalFiniteNumber(input.gapWidthPct) || !isOptionalFiniteNumber(input.gapWidthPct) ||
!isOptionalFiniteNumber(input.holeSizePct) !isOptionalFiniteNumber(input.holeSizePct) ||
(input.lineMarkers !== undefined && typeof input.lineMarkers !== 'boolean')
) { ) {
throw new Error('Invalid workbook chart response.') throw new Error('Invalid workbook chart response.')
} }
@@ -2636,12 +2792,14 @@ function parseChart(input: unknown): NonNullable<WorkbookVisualObject['chart']>
!Array.isArray(entry.values) || !Array.isArray(entry.values) ||
entry.values.some((value) => typeof value !== 'number' || !Number.isFinite(value)) || entry.values.some((value) => typeof value !== 'number' || !Number.isFinite(value)) ||
!isOptionalString(entry.numberFormat) || !isOptionalString(entry.numberFormat) ||
!isOptionalString(entry.categoryFormat) ||
!isOptionalString(entry.color) || !isOptionalString(entry.color) ||
!isOptionalString(entry.trendline) || !isOptionalString(entry.trendline) ||
!isOptionalString(entry.valuesRef) || !isOptionalString(entry.valuesRef) ||
!isOptionalString(entry.categoriesRef) || !isOptionalString(entry.categoriesRef) ||
!isOptionalFiniteNumber(entry.explosionPct) || !isOptionalFiniteNumber(entry.explosionPct) ||
!isOptionalString(entry.lineColor) || !isOptionalString(entry.lineColor) ||
!isOptionalFiniteNumber(entry.lineWidth) ||
(entry.smooth !== undefined && typeof entry.smooth !== 'boolean') || (entry.smooth !== undefined && typeof entry.smooth !== 'boolean') ||
!isOptionalString(entry.marker) !isOptionalString(entry.marker)
) { ) {
@@ -2649,12 +2807,14 @@ function parseChart(input: unknown): NonNullable<WorkbookVisualObject['chart']>
} }
const pointColors = parseChartPointColors(entry.pointColors) const pointColors = parseChartPointColors(entry.pointColors)
const pointExplosions = parseChartPointExplosions(entry.pointExplosions) const pointExplosions = parseChartPointExplosions(entry.pointExplosions)
const categoryGroups = parseChartCategoryGroups(entry.categoryGroups)
return { return {
name: entry.name, name: entry.name,
...(entry.nameRef === undefined ? {} : { nameRef: entry.nameRef }), ...(entry.nameRef === undefined ? {} : { nameRef: entry.nameRef }),
categories: entry.categories, categories: entry.categories,
values: entry.values, values: entry.values,
...(entry.numberFormat === undefined ? {} : { numberFormat: entry.numberFormat }), ...(entry.numberFormat === undefined ? {} : { numberFormat: entry.numberFormat }),
...(entry.categoryFormat === undefined ? {} : { categoryFormat: entry.categoryFormat }),
...(entry.color === undefined ? {} : { color: entry.color }), ...(entry.color === undefined ? {} : { color: entry.color }),
...(entry.trendline === undefined ? {} : { trendline: entry.trendline }), ...(entry.trendline === undefined ? {} : { trendline: entry.trendline }),
...(entry.valuesRef === undefined ? {} : { valuesRef: entry.valuesRef }), ...(entry.valuesRef === undefined ? {} : { valuesRef: entry.valuesRef }),
@@ -2663,8 +2823,10 @@ function parseChart(input: unknown): NonNullable<WorkbookVisualObject['chart']>
...(entry.explosionPct === undefined ? {} : { explosionPct: entry.explosionPct }), ...(entry.explosionPct === undefined ? {} : { explosionPct: entry.explosionPct }),
...(pointExplosions === undefined ? {} : { pointExplosions }), ...(pointExplosions === undefined ? {} : { pointExplosions }),
...(entry.lineColor === undefined ? {} : { lineColor: entry.lineColor }), ...(entry.lineColor === undefined ? {} : { lineColor: entry.lineColor }),
...(entry.lineWidth === undefined ? {} : { lineWidth: entry.lineWidth }),
...(entry.smooth === undefined ? {} : { smooth: entry.smooth }), ...(entry.smooth === undefined ? {} : { smooth: entry.smooth }),
...(entry.marker === undefined ? {} : { marker: entry.marker }), ...(entry.marker === undefined ? {} : { marker: entry.marker }),
...(categoryGroups === undefined ? {} : { categoryGroups }),
} }
}) })
return { return {
@@ -2681,6 +2843,9 @@ function parseChart(input: unknown): NonNullable<WorkbookVisualObject['chart']>
...(input.dataLabelFormat === undefined ? {} : { dataLabelFormat: input.dataLabelFormat }), ...(input.dataLabelFormat === undefined ? {} : { dataLabelFormat: input.dataLabelFormat }),
...(input.grouping === undefined ? {} : { grouping: input.grouping }), ...(input.grouping === undefined ? {} : { grouping: input.grouping }),
...(input.gridlines === undefined ? {} : { gridlines: input.gridlines }), ...(input.gridlines === undefined ? {} : { gridlines: input.gridlines }),
...(input.categoryAxisFormat === undefined
? {}
: { categoryAxisFormat: input.categoryAxisFormat }),
...(valueAxis === undefined ? {} : { valueAxis }), ...(valueAxis === undefined ? {} : { valueAxis }),
...(input.gapWidthPct === undefined ? {} : { gapWidthPct: input.gapWidthPct }), ...(input.gapWidthPct === undefined ? {} : { gapWidthPct: input.gapWidthPct }),
...(input.holeSizePct === undefined ? {} : { holeSizePct: input.holeSizePct }), ...(input.holeSizePct === undefined ? {} : { holeSizePct: input.holeSizePct }),
@@ -2689,6 +2854,7 @@ function parseChart(input: unknown): NonNullable<WorkbookVisualObject['chart']>
...(secondaryYAxis === undefined ? {} : { secondaryYAxis }), ...(secondaryYAxis === undefined ? {} : { secondaryYAxis }),
...(titleStyle === undefined ? {} : { titleStyle }), ...(titleStyle === undefined ? {} : { titleStyle }),
...(input.scatterStyle === undefined ? {} : { scatterStyle: input.scatterStyle }), ...(input.scatterStyle === undefined ? {} : { scatterStyle: input.scatterStyle }),
...(input.lineMarkers === undefined ? {} : { lineMarkers: input.lineMarkers }),
} }
} }
@@ -2720,6 +2886,7 @@ function parseChartAxisInfo(input: unknown):
numFmt?: string numFmt?: string
majorGridlines: boolean majorGridlines: boolean
hidden: boolean hidden: boolean
reversed: boolean
} }
| undefined { | undefined {
if (input === undefined) return undefined if (input === undefined) return undefined
@@ -2731,7 +2898,8 @@ function parseChartAxisInfo(input: unknown):
!isOptionalFiniteNumber(input.majorUnit) || !isOptionalFiniteNumber(input.majorUnit) ||
!isOptionalString(input.numFmt) || !isOptionalString(input.numFmt) ||
typeof input.majorGridlines !== 'boolean' || typeof input.majorGridlines !== 'boolean' ||
(input.hidden !== undefined && typeof input.hidden !== 'boolean') (input.hidden !== undefined && typeof input.hidden !== 'boolean') ||
(input.reversed !== undefined && typeof input.reversed !== 'boolean')
) { ) {
throw new Error('Invalid workbook chart axis.') throw new Error('Invalid workbook chart axis.')
} }
@@ -2743,6 +2911,7 @@ function parseChartAxisInfo(input: unknown):
...(input.numFmt === undefined ? {} : { numFmt: input.numFmt }), ...(input.numFmt === undefined ? {} : { numFmt: input.numFmt }),
majorGridlines: input.majorGridlines, majorGridlines: input.majorGridlines,
hidden: input.hidden === true, hidden: input.hidden === true,
reversed: input.reversed === true,
} }
} }
@@ -2791,6 +2960,24 @@ function parseChartPointColors(
}) })
} }
function parseChartCategoryGroups(
input: unknown,
): Array<{ label: string; start: number; end: number }> | undefined {
if (input === undefined) return undefined
if (!Array.isArray(input)) throw new Error('Invalid workbook chart category groups.')
return input.map((entry) => {
if (
!isRecord(entry) ||
typeof entry.label !== 'string' ||
!isNonnegativeInteger(entry.start) ||
!isNonnegativeInteger(entry.end)
) {
throw new Error('Invalid workbook chart category groups.')
}
return { label: entry.label, start: entry.start, end: entry.end }
})
}
function parseChartPointExplosions( function parseChartPointExplosions(
input: unknown, input: unknown,
): Array<{ index: number; pct: number }> | undefined { ): Array<{ index: number; pct: number }> | undefined {
@@ -2842,6 +3029,10 @@ function isOptionalString(input: unknown): input is string | undefined {
return input === undefined || typeof input === 'string' return input === undefined || typeof input === 'string'
} }
function isBoundedString(input: unknown, maxLength: number): input is string {
return typeof input === 'string' && input.length >= 1 && input.length <= maxLength
}
function isOptionalNullableString(input: unknown): input is string | null | undefined { function isOptionalNullableString(input: unknown): input is string | null | undefined {
return input === undefined || input === null || typeof input === 'string' return input === undefined || input === null || typeof input === 'string'
} }
+33 -9
View File
@@ -109,7 +109,7 @@ import '@univerjs/preset-sheets-note/lib/index.css'
import { UniverSheetsSortPreset } from '@univerjs/preset-sheets-sort' import { UniverSheetsSortPreset } from '@univerjs/preset-sheets-sort'
import UniverPresetSheetsSortEnUS from '@univerjs/preset-sheets-sort/locales/en-US' import UniverPresetSheetsSortEnUS from '@univerjs/preset-sheets-sort/locales/en-US'
import '@univerjs/preset-sheets-sort/lib/index.css' import '@univerjs/preset-sheets-sort/lib/index.css'
import { UniverSheetsTablePreset } from '@univerjs/preset-sheets-table' import { UniverSheetsTablePreset, UniverSheetsTableUIPlugin } from '@univerjs/preset-sheets-table'
import UniverPresetSheetsTableEnUS from '@univerjs/preset-sheets-table/locales/en-US' import UniverPresetSheetsTableEnUS from '@univerjs/preset-sheets-table/locales/en-US'
import '@univerjs/preset-sheets-table/lib/index.css' import '@univerjs/preset-sheets-table/lib/index.css'
import { greenTheme } from '@univerjs/themes' import { greenTheme } from '@univerjs/themes'
@@ -301,7 +301,7 @@ import { installMultiRowAutofit } from './autofit-multi-row'
import { installCopyMaterialize } from './copy-materialize' import { installCopyMaterialize } from './copy-materialize'
import { applyUniverLocale } from './univer-locales' import { applyUniverLocale } from './univer-locales'
import { installRuleDetail } from './univer-rule-detail' import { installRuleDetail } from './univer-rule-detail'
import { installPopulatedDataValidationArrow } from './data-validation-arrow' import { installActiveCellDataValidationChrome } from './data-validation-dropdown'
import { installFormulaNullResultFix } from './formula-null-result' import { installFormulaNullResultFix } from './formula-null-result'
import { installNumberFormatFix } from './numfmt-fix' import { installNumberFormatFix } from './numfmt-fix'
import { installIfsEmptySetFix } from './ifs-empty-set' import { installIfsEmptySetFix } from './ifs-empty-set'
@@ -316,6 +316,7 @@ import {
handlePageLayoutCommand as handlePageLayoutCommandImpl, handlePageLayoutCommand as handlePageLayoutCommandImpl,
type PageLayoutContext, type PageLayoutContext,
} from './page-layout-actions' } from './page-layout-actions'
import { handleExportCsv as handleExportCsvImpl, type CsvExportContext } from './csv-export'
import { effectivePageBreaks, installPageBreakPreview } from './page-break-preview' import { effectivePageBreaks, installPageBreakPreview } from './page-break-preview'
import { mapProtectedRanges } from './protected-ranges' import { mapProtectedRanges } from './protected-ranges'
import { handleSave as handleSaveImpl, type SaveContext } from './save-actions' import { handleSave as handleSaveImpl, type SaveContext } from './save-actions'
@@ -489,9 +490,11 @@ export function App(): React.JSX.Element {
const state = lazyWorkbookRef.current const state = lazyWorkbookRef.current
if (saving || !state || journalSize(state.editJournal) === 0) return if (saving || !state || journalSize(state.editJournal) === 0) return
// Never while the in-cell editor is open (saving reloads the workbook // Never while the in-cell editor is open (saving reloads the workbook
// and would wipe the edit), and never for converted .xls/.csv imports // and would wipe the edit), never for converted .xls imports whose
// whose first save opens a Save As dialog. // first save opens a Save As dialog, and never for CSV sessions —
if (editingCellRef.current || state.file.needsSaveAs) return // AutoSave would silently flatten the user's file.
if (editingCellRef.current || state.file.needsSaveAs || state.file.csvPath !== undefined)
return
saving = true saving = true
void handleSaveRef.current('save', true).finally(() => { void handleSaveRef.current('save', true).finally(() => {
saving = false saving = false
@@ -520,6 +523,7 @@ export function App(): React.JSX.Element {
if ( if (
editingCellRef.current || editingCellRef.current ||
state.file.needsSaveAs || state.file.needsSaveAs ||
state.file.csvPath !== undefined ||
state.file.restoredFromRecovery || state.file.restoredFromRecovery ||
state.file.automaticRecoveryDisabled state.file.automaticRecoveryDisabled
) )
@@ -698,6 +702,15 @@ export function App(): React.JSX.Element {
} }
} }
function csvExportContext(): CsvExportContext {
return {
univerRef,
lazyWorkbookRef,
setMessage,
requestSaveAs: () => void handleSaveRef.current('save-as'),
}
}
function saveContext(): SaveContext { function saveContext(): SaveContext {
return { return {
univerRef, univerRef,
@@ -1418,6 +1431,9 @@ export function App(): React.JSX.Element {
UniverSheetsFindReplacePreset(), UniverSheetsFindReplacePreset(),
UniverSheetsSortPreset(), UniverSheetsSortPreset(),
UniverSheetsTablePreset(), UniverSheetsTablePreset(),
// No floating table-name chip: its 32px gap above row-0 tables shifts
// the grid vs Excel and strands the filter overlay at pre-gap coords.
{ plugins: [[UniverSheetsTableUIPlugin, { hideAnchor: true }]] },
], ],
}) })
loadSnapshotIntoUniver(runtime, initialSnapshot, 'new-workbook', 'Untitled') loadSnapshotIntoUniver(runtime, initialSnapshot, 'new-workbook', 'Untitled')
@@ -1521,7 +1537,9 @@ export function App(): React.JSX.Element {
// imports (needsSaveAs) count as never-saved, like Excel. // imports (needsSaveAs) count as never-saved, like Excel.
const cellFilenameDisposable = installCellFilenameFunction(runtime, () => { const cellFilenameDisposable = installCellFilenameFunction(runtime, () => {
const file = lazyWorkbookRef.current?.file const file = lazyWorkbookRef.current?.file
return file && !file.needsSaveAs ? (file.path ?? null) : null // A CSV session's on-disk identity is the original .csv, not the
// converted temp copy the session streams from.
return file && !file.needsSaveAs ? (file.csvPath ?? file.path ?? null) : null
}) })
// RATE converges near -100% via bisection instead of erroring. // RATE converges near -100% via bisection instead of erroring.
const rateFallbackDisposable = installRateFallback(runtime) const rateFallbackDisposable = installRateFallback(runtime)
@@ -1542,8 +1560,8 @@ export function App(): React.JSX.Element {
// Copy/cut load their selection into the lazy window first so streamed // Copy/cut load their selection into the lazy window first so streamed
// workbooks don't serialize blanks for never-viewed rows. // workbooks don't serialize blanks for never-viewed rows.
const copyMaterializeDisposable = installCopyMaterialize(runtime, lazyWorkbookRef, setMessage) const copyMaterializeDisposable = installCopyMaterialize(runtime, lazyWorkbookRef, setMessage)
// List-validation arrows stay discoverable on values without cluttering empty template rows. // Validation dropdowns and input messages follow the active cell, matching Excel.
const dataValidationArrowDisposable = installPopulatedDataValidationArrow(runtime) const dataValidationChromeDisposable = installActiveCellDataValidationChrome(runtime)
// Univer's own UI (rule-management panels, dialogs) follows the app // Univer's own UI (rule-management panels, dialogs) follows the app
// language instead of hard-coded English. // language instead of hard-coded English.
void applyUniverLocale(runtime, getLang()) void applyUniverLocale(runtime, getLang())
@@ -2499,7 +2517,7 @@ export function App(): React.JSX.Element {
multiRowAutofitDisposable.dispose() multiRowAutofitDisposable.dispose()
nullResultDisposable.dispose() nullResultDisposable.dispose()
copyMaterializeDisposable.dispose() copyMaterializeDisposable.dispose()
dataValidationArrowDisposable.dispose() dataValidationChromeDisposable.dispose()
ruleDetailDisposable() ruleDetailDisposable()
lazyFindDisposable.dispose() lazyFindDisposable.dispose()
crossHighlightRef.current?.dispose() crossHighlightRef.current?.dispose()
@@ -4046,6 +4064,7 @@ export function App(): React.JSX.Element {
rowColStyleKeys: new Map(), rowColStyleKeys: new Map(),
sheetProtections: new Map(), sheetProtections: new Map(),
sheetPageBreaks: new Map(), sheetPageBreaks: new Map(),
sheetFilePageSetups: new Map(),
sheetProtectedRanges: new Map(), sheetProtectedRanges: new Map(),
uninstalledDefinedNames: new Set(), uninstalledDefinedNames: new Set(),
appliedCfSheets: new Set(), appliedCfSheets: new Set(),
@@ -4074,6 +4093,9 @@ export function App(): React.JSX.Element {
failures: 0, failures: 0,
formulaCells: new Map(), formulaCells: new Map(),
overlay: new Map(), overlay: new Map(),
follow: new Map(),
running: false,
lastRunAt: 0,
}, },
} }
// Column outline levels arrive with the sheet metadata; seed them now. // Column outline levels arrive with the sheet metadata; seed them now.
@@ -4314,6 +4336,8 @@ export function App(): React.JSX.Element {
void handleInspectWorkbook() void handleInspectWorkbook()
} else if (action === 'export-pdf') { } else if (action === 'export-pdf') {
void handleExportPdfImpl(pageLayoutContext()) void handleExportPdfImpl(pageLayoutContext())
} else if (action === 'export-csv') {
void handleExportCsvImpl(csvExportContext())
} else if (action === 'undo' || action === 'redo') { } else if (action === 'undo' || action === 'redo') {
// The shell's own text fields (AI prompt, dialog inputs) keep native // The shell's own text fields (AI prompt, dialog inputs) keep native
// text undo; everywhere else ⌘Z means workbook history. // text undo; everywhere else ⌘Z means workbook history.
+521 -121
View File
@@ -1,4 +1,4 @@
import { useEffect, useId, useRef, useState, useSyncExternalStore } from 'react' import { Fragment, useEffect, useId, useRef, useState, useSyncExternalStore } from 'react'
import { createPortal } from 'react-dom' import { createPortal } from 'react-dom'
import { BooleanNumber, numfmt } from '@univerjs/core' import { BooleanNumber, numfmt } from '@univerjs/core'
import { isMetafileMime, metafileToDataUrl } from '@genoffice/docx-engine/metafile' import { isMetafileMime, metafileToDataUrl } from '@genoffice/docx-engine/metafile'
@@ -156,14 +156,15 @@ export function installWorkbookVisuals(
const rowHeight = (index: number): number => Math.max(worksheet.getRowHeight(index), 1) const rowHeight = (index: number): number => Math.max(worksheet.getRowHeight(index), 1)
let marginX = Math.max(0, visual.anchor.fromColumnOffset / EMU_PER_PIXEL) let marginX = Math.max(0, visual.anchor.fromColumnOffset / EMU_PER_PIXEL)
let marginY = Math.max(0, visual.anchor.fromRowOffset / EMU_PER_PIXEL) let marginY = Math.max(0, visual.anchor.fromRowOffset / EMU_PER_PIXEL)
const explicitTo = visual.anchor.explicitTo === true
let width = markerSpan( let width = markerSpan(
{ index: fromColumn, offset: marginX }, { index: fromColumn, offset: marginX },
markerFrom(toColumn, visual.anchor.toColumnOffset), clampExplicitTo(markerFrom(toColumn, visual.anchor.toColumnOffset), explicitTo, columnWidth),
columnWidth, columnWidth,
) )
let height = markerSpan( let height = markerSpan(
{ index: fromRow, offset: marginY }, { index: fromRow, offset: marginY },
markerFrom(toRow, visual.anchor.toRowOffset), clampExplicitTo(markerFrom(toRow, visual.anchor.toRowOffset), explicitTo, rowHeight),
rowHeight, rowHeight,
) )
// A rotated shape's anchor holds its rotated bounds while xfrm ext keeps // A rotated shape's anchor holds its rotated bounds while xfrm ext keeps
@@ -328,6 +329,63 @@ export function installSparklines(
return disposables return disposables
} }
export interface CellImageState {
readonly id: string
readonly row: number
readonly column: number
}
/// In-cell rich-value pictures ("place picture in cell"): one pass-through
/// float DOM per host cell, bytes fetched through the same media IPC as
/// floating images.
export function installCellImages(
runtime: UniverRuntime,
sessionId: string,
images: readonly CellImageState[],
sheetId: string,
): Disposable[] {
const workbook = runtime.univerAPI.getActiveWorkbook()
const worksheet = workbook?.getSheetBySheetId(sheetId)
if (!workbook || !worksheet) return []
const disposables: Disposable[] = []
for (const image of images) {
if (image.row >= worksheet.getMaxRows() || image.column >= worksheet.getMaxColumns()) continue
const componentKey = `cell-image-${sessionId}-${sheetId}-${image.id}`
disposables.push(
runtime.univerAPI.registerComponent(componentKey, () => (
<CellImage sessionId={sessionId} imageId={image.id} />
)),
)
const range = worksheet.getRange(image.row, image.column, 1, 1)
const floating = worksheet.addFloatDomToRange(
range,
{ componentKey, allowTransform: false, eventPassThrough: true },
{},
componentKey,
)
if (floating) disposables.push(floating)
}
return disposables
}
/// Excel fits the picture inside the cell box, preserving its aspect ratio;
/// while the bytes load the cell just stays blank.
function CellImage({
sessionId,
imageId,
}: {
readonly sessionId: string
readonly imageId: string
}): React.JSX.Element | null {
const { url, unavailable } = useWorkbookMediaUrl(sessionId, imageId)
if (unavailable || !url) return null
return (
<div className="xlsx-cell-image">
<img src={url} alt="" />
</div>
)
}
function Sparkline({ function Sparkline({
values, values,
type, type,
@@ -419,7 +477,7 @@ function WorkbookVisual({
if (visual.kind === 'image') { if (visual.kind === 'image') {
return <ImageVisual file={file} visual={visual} /> return <ImageVisual file={file} visual={visual} />
} }
return <ShapeVisual visual={visual} frame={frame} /> return <ShapeVisual file={file} visual={visual} frame={frame} />
} }
/// A drag commit tears down and re-registers every float DOM, dropping the /// A drag commit tears down and re-registers every float DOM, dropping the
@@ -634,6 +692,20 @@ export function walkMarker(
return { index, offset } return { index, offset }
} }
/// A real `<xdr:to>` marker never reaches past its own cell: Excel clamps
/// the offset at the cell edge (broken writers store the picture's full
/// size there, e.g. ClosedXML). Synthesized to markers (oneCellAnchor ext,
/// absoluteAnchor, group children) encode sizes as offsets past the edge
/// and must keep walking, so only explicit-to anchors clamp.
export function clampExplicitTo(
to: AnchorMarker,
explicitTo: boolean,
sizeOf: (index: number) => number,
): AnchorMarker {
if (!explicitTo || to.offset <= sizeOf(to.index)) return to
return { index: to.index, offset: sizeOf(to.index) }
}
/// Pixel distance between two markers (negative when `to` sits before `from`). /// Pixel distance between two markers (negative when `to` sits before `from`).
function markerSpan( function markerSpan(
from: AnchorMarker, from: AnchorMarker,
@@ -735,8 +807,17 @@ function EditableShapeVisual({
const maxRow = XLSX_MAX_ROW const maxRow = XLSX_MAX_ROW
let fromX = markerFrom(anchor.fromColumn, anchor.fromColumnOffset) let fromX = markerFrom(anchor.fromColumn, anchor.fromColumnOffset)
let fromY = markerFrom(anchor.fromRow, anchor.fromRowOffset) let fromY = markerFrom(anchor.fromRow, anchor.fromRowOffset)
let toX = markerFrom(anchor.toColumn, anchor.toColumnOffset) // Drag from the clamped geometry the user sees, not the raw overflowing
let toY = markerFrom(anchor.toRow, anchor.toRowOffset) // offsets — otherwise walkMarker re-expands an explicit-to anchor to its
// walked size on commit. The rebuilt anchor is fully normalized, so it
// rightly drops the explicitTo flag.
const explicitTo = anchor.explicitTo === true
let toX = clampExplicitTo(
markerFrom(anchor.toColumn, anchor.toColumnOffset),
explicitTo,
columnWidth,
)
let toY = clampExplicitTo(markerFrom(anchor.toRow, anchor.toRowOffset), explicitTo, rowHeight)
// RTL sheets render mirrored geometry from logical anchors, so a screen // RTL sheets render mirrored geometry from logical anchors, so a screen
// drag maps to the opposite logical x-shift and the opposite logical edge. // drag maps to the opposite logical x-shift and the opposite logical edge.
const rtl = config.rightToLeft === BooleanNumber.TRUE const rtl = config.rightToLeft === BooleanNumber.TRUE
@@ -995,7 +1076,11 @@ function EditableShapeVisual({
) : visual.kind === 'image' ? ( ) : visual.kind === 'image' ? (
<ImageVisual file={file} visual={visual} /> <ImageVisual file={file} visual={visual} />
) : ( ) : (
<ShapeVisual visual={textEditing ? { ...visual, text: '' } : visual} frame={frame} /> <ShapeVisual
file={file}
visual={textEditing ? { ...visual, text: '' } : visual}
frame={frame}
/>
)} )}
{!textEditing && ( {!textEditing && (
<button <button
@@ -1107,14 +1192,23 @@ function gradientEndpoints(angle: number): { x1: number; y1: number; x2: number;
} }
function ShapeVisual({ function ShapeVisual({
file,
visual, visual,
frame, frame,
}: { }: {
readonly file?: VisualHost | undefined
readonly visual: WorkbookVisualObject readonly visual: WorkbookVisualObject
readonly frame?: ShapeFrame | undefined readonly frame?: ShapeFrame | undefined
}): React.JSX.Element { }): React.JSX.Element {
// useId's delimiters (":"/"«») are hostile to url(#…) parsing. // useId's delimiters (":"/"«») are hostile to url(#…) parsing.
const gradientId = `shape-fill-${useId().replace(/[^A-Za-z0-9]/g, '')}` const shapeId = useId().replace(/[^A-Za-z0-9]/g, '')
const gradientId = `shape-fill-${shapeId}`
const clipId = `shape-clip-${shapeId}`
// a:blipFill: the image paints clipped to the geometry, under the stroke.
const { url: fillImage } = useWorkbookMediaUrl(
visual.fillMediaPath && file ? file.sessionId : undefined,
visual.id,
)
const type = visual.shapeType ?? '' const type = visual.shapeType ?? ''
const gradient = visual.fillGradient const gradient = visual.fillGradient
const customPath = visual.customPath const customPath = visual.customPath
@@ -1220,10 +1314,35 @@ function ShapeVisual({
transform={`scale(${boxWidth / customPath.width}, ${boxHeight / customPath.height})`} transform={`scale(${boxWidth / customPath.width}, ${boxHeight / customPath.height})`}
/> />
)} )}
{fillImage && !isStraightLine && (
<>
<clipPath id={clipId}>
<path
d={d}
{...(customPath
? {
transform: `scale(${boxWidth / customPath.width}, ${boxHeight / customPath.height})`,
}
: {})}
/>
</clipPath>
<image
href={fillImage}
x={0}
y={0}
width={boxWidth}
height={boxHeight}
preserveAspectRatio="none"
clipPath={`url(#${clipId})`}
/>
</>
)}
<path <path
d={d} d={d}
fill={ fill={
isStraightLine || customPath?.strokeOnly || customPath?.fillD ? 'transparent' : fill isStraightLine || customPath?.strokeOnly || customPath?.fillD || fillImage
? 'transparent'
: fill
} }
{...(customPath {...(customPath
? { ? {
@@ -1332,6 +1451,42 @@ function base64ToBytes(base64: string): Uint8Array {
return bytes return bytes
} }
/// Lazily fetches a visual's media bytes as a data URL (metafiles rasterize
/// to PNG first). Pass an undefined sessionId to skip fetching.
function useWorkbookMediaUrl(
sessionId: string | undefined,
visualId: string,
): { url: string | null; unavailable: boolean } {
const [url, setUrl] = useState<string | null>(null)
const [unavailable, setUnavailable] = useState(false)
useEffect(() => {
if (sessionId === undefined) return
let isCurrent = true
void window.desktopApi
.readWorkbookMedia({ sessionId, visualId })
.then(async (media) => {
const next = isMetafileMime(media.mediaType)
? await metafileToDataUrl(base64ToBytes(media.base64), media.mediaType)
: `data:${media.mediaType};base64,${media.base64}`
if (!isCurrent) return
if (next) setUrl(next)
else setUnavailable(true)
})
.catch((reason: unknown) => {
// Unsupported or unreadable media degrades to an empty frame; the
// grid must never show the failure text.
console.warn(`workbook media unavailable (${visualId})`, reason)
if (isCurrent) setUnavailable(true)
})
return () => {
isCurrent = false
}
}, [sessionId, visualId])
return { url, unavailable }
}
function ImageVisual({ function ImageVisual({
file, file,
visual, visual,
@@ -1339,40 +1494,25 @@ function ImageVisual({
readonly file: VisualHost readonly file: VisualHost
readonly visual: WorkbookVisualObject readonly visual: WorkbookVisualObject
}): React.JSX.Element { }): React.JSX.Element {
const [source, setSource] = useState<string | null>(visual.mediaDataUrl ?? null) // Session-added images carry their bytes inline; nothing to fetch.
const [unavailable, setUnavailable] = useState(false) const { url, unavailable } = useWorkbookMediaUrl(
visual.mediaDataUrl ? undefined : file.sessionId,
useEffect(() => { visual.id,
// Session-added images carry their bytes inline; nothing to fetch. )
if (visual.mediaDataUrl) return const source = visual.mediaDataUrl ?? url
let isCurrent = true
void window.desktopApi
.readWorkbookMedia({
sessionId: file.sessionId,
visualId: visual.id,
})
.then(async (media) => {
const url = isMetafileMime(media.mediaType)
? await metafileToDataUrl(base64ToBytes(media.base64), media.mediaType)
: `data:${media.mediaType};base64,${media.base64}`
if (!isCurrent) return
if (url) setSource(url)
else setUnavailable(true)
})
.catch((reason: unknown) => {
// Unsupported or unreadable media degrades to an empty frame; the
// grid must never show the failure text.
console.warn(`workbook media unavailable (${visual.id})`, reason)
if (isCurrent) setUnavailable(true)
})
return () => {
isCurrent = false
}
}, [file.sessionId, visual.id, visual.mediaDataUrl])
if (unavailable) return <div className="xlsx-visual-unavailable" /> if (unavailable) return <div className="xlsx-visual-unavailable" />
if (!source) return <div className="xlsx-visual-loading">{t('appImageLoading')}</div> if (!source) return <div className="xlsx-visual-loading">{t('appImageLoading')}</div>
return <img className="xlsx-image" src={source} alt={visual.name ?? t('appWorkbookImageAlt')} /> return (
<img
className="xlsx-image"
src={source}
alt={visual.name ?? t('appWorkbookImageAlt')}
style={
visual.opacity !== undefined && visual.opacity < 1 ? { opacity: visual.opacity } : undefined
}
/>
)
} }
type ChartMetadata = NonNullable<WorkbookVisualObject['chart']> type ChartMetadata = NonNullable<WorkbookVisualObject['chart']>
@@ -1605,11 +1745,13 @@ function ChartVisual({
category: (isHorizontalBar ? chart.yAxis : chart.xAxis)?.title ?? chart.axisTitles?.category, category: (isHorizontalBar ? chart.yAxis : chart.xAxis)?.title ?? chart.axisTitles?.category,
value: (isHorizontalBar ? chart.xAxis : chart.yAxis)?.title ?? chart.axisTitles?.value, value: (isHorizontalBar ? chart.xAxis : chart.yAxis)?.title ?? chart.axisTitles?.value,
} }
// The value axis sits on the bottom (xAxis slot) for horizontal bars.
const valueAxisSide = isHorizontalBar ? chart.xAxis : chart.yAxis
const valueScaleInput = { const valueScaleInput = {
min: chart.yAxis?.min ?? chart.valueAxis?.min, min: valueAxisSide?.min ?? chart.valueAxis?.min,
max: chart.yAxis?.max ?? chart.valueAxis?.max, max: valueAxisSide?.max ?? chart.valueAxis?.max,
majorUnit: chart.yAxis?.majorUnit, majorUnit: valueAxisSide?.majorUnit,
numFmt: chart.yAxis?.numFmt, numFmt: valueAxisSide?.numFmt,
} }
return ( return (
<figure <figure
@@ -1730,6 +1872,7 @@ function ChartVisual({
gridlines={chart.gridlines} gridlines={chart.gridlines}
valueAxis={valueScaleInput} valueAxis={valueScaleInput}
categoryFormat={categoryFormat} categoryFormat={categoryFormat}
lineMarkers={chart.lineMarkers}
onElement={selectElement} onElement={selectElement}
selectedEl={selectedEl} selectedEl={selectedEl}
/> />
@@ -1750,6 +1893,7 @@ function ChartVisual({
secondaryAxis={chart.secondaryYAxis} secondaryAxis={chart.secondaryYAxis}
gapWidthPct={chart.gapWidthPct} gapWidthPct={chart.gapWidthPct}
categoryFormat={categoryFormat} categoryFormat={categoryFormat}
categoryReversed={(isHorizontalBar ? chart.yAxis : chart.xAxis)?.reversed === true}
onElement={selectElement} onElement={selectElement}
selectedEl={selectedEl} selectedEl={selectedEl}
/> />
@@ -1759,6 +1903,7 @@ function ChartVisual({
(chart.legend !== undefined || populated.length > 1) && ( (chart.legend !== undefined || populated.length > 1) && (
<SeriesLegend <SeriesLegend
seriesList={populated} seriesList={populated}
lineSwatches={legendUsesLineSwatches(types)}
selected={selectedEl?.kind === 'legend'} selected={selectedEl?.kind === 'legend'}
onSelect={ onSelect={
selectElement selectElement
@@ -1871,14 +2016,18 @@ type ChartGrouping = ChartMetadata['grouping']
function AxisTitleTexts({ function AxisTitleTexts({
bottom, bottom,
left, left,
bottomY = 317,
}: { }: {
readonly bottom?: string | null | undefined readonly bottom?: string | null | undefined
readonly left?: string | null | undefined readonly left?: string | null | undefined
/// Charts with an outer category tier extend the viewBox and push the
/// bottom title below the group-label band.
readonly bottomY?: number
}): React.JSX.Element { }): React.JSX.Element {
return ( return (
<g> <g>
{bottom ? ( {bottom ? (
<text x="320" y="317" textAnchor="middle" className="axis-title"> <text x="320" y={bottomY} textAnchor="middle" className="axis-title">
{truncateLabel(bottom, 60)} {truncateLabel(bottom, 60)}
</text> </text>
) : null} ) : null}
@@ -2136,16 +2285,19 @@ function SeriesLegend({
seriesList, seriesList,
selected, selected,
onSelect, onSelect,
lineSwatches = false,
}: { }: {
readonly seriesList: readonly ChartSeries[] readonly seriesList: readonly ChartSeries[]
readonly selected?: boolean | undefined readonly selected?: boolean | undefined
readonly onSelect?: ((event: React.MouseEvent) => void) | undefined readonly onSelect?: ((event: React.MouseEvent) => void) | undefined
/// Line-family charts: swatches mirror the drawn stroke color.
readonly lineSwatches?: boolean | undefined
}): React.JSX.Element { }): React.JSX.Element {
return ( return (
<div className={`chart-legend${selected ? ' chart-el-selected' : ''}`} onClick={onSelect}> <div className={`chart-legend${selected ? ' chart-el-selected' : ''}`} onClick={onSelect}>
{seriesList.slice(0, 8).map((series, index) => ( {seriesList.slice(0, 8).map((series, index) => (
<span key={`${series.name}-${index}`}> <span key={`${series.name}-${index}`}>
<i style={{ background: seriesColor(series, index) }} /> <i style={{ background: legendSwatchColor(series, index, lineSwatches) }} />
{truncateLabel(series.name, 18)} {truncateLabel(series.name, 18)}
</span> </span>
))} ))}
@@ -2168,12 +2320,16 @@ function BarChart({
secondaryAxis, secondaryAxis,
gapWidthPct, gapWidthPct,
categoryFormat, categoryFormat,
categoryReversed,
onElement, onElement,
selectedEl, selectedEl,
}: { }: {
readonly seriesList: readonly ChartSeries[] readonly seriesList: readonly ChartSeries[]
readonly lineSeries?: ChartSeries | undefined readonly lineSeries?: ChartSeries | undefined
readonly isHorizontal: boolean readonly isHorizontal: boolean
/// c:catAx orientation maxMin — categories read top-down (bar) /
/// right-to-left (column) instead of Excel's minMax default.
readonly categoryReversed?: boolean | undefined
readonly axisTitles?: ChartAxisTitles readonly axisTitles?: ChartAxisTitles
readonly dataLabels?: ChartDataLabels readonly dataLabels?: ChartDataLabels
readonly dataLabelPosition?: ChartLabelPosition readonly dataLabelPosition?: ChartLabelPosition
@@ -2249,15 +2405,58 @@ function BarChart({
: undefined : undefined
if (isHorizontal) { if (isHorizontal) {
const rowHeight = 280 / visibleCount const rowHeight = 270 / visibleCount
const rowGroups = visibleCategoryGroups(primary.categoryGroups, visibleCount)
// The outer tier owns the x ≤ 99 column; tick labels (end-anchored at
// 148) shrink so the two never share pixels.
const categoryBudget = rowGroups.length > 0 ? 8 : 14
const barHeight = Math.max( const barHeight = Math.max(
3, 3,
isStacked ? rowHeight / (1 + gap) : rowHeight / (seriesList.length + gap), isStacked ? rowHeight / (1 + gap) : rowHeight / (seriesList.length + gap),
) )
// Excel draws bar-chart categories bottom-up and series 0 nearest the
// category axis under the default minMax orientation; maxMin flips both
// back to top-down reading order.
const rowSlot = (index: number): number => (categoryReversed ? index : visibleCount - 1 - index)
const seriesSlot = (seriesIndex: number): number =>
categoryReversed ? seriesIndex : seriesList.length - 1 - seriesIndex
const groupTop = (index: number): number => const groupTop = (index: number): number =>
14 + rowHeight * index + (rowHeight - barHeight * (isStacked ? 1 : seriesList.length)) / 2 14 +
rowHeight * rowSlot(index) +
(rowHeight - barHeight * (isStacked ? 1 : seriesList.length)) / 2
const plotX = (value: number): number => const plotX = (value: number): number =>
158 + Math.max(0, Math.min(1, (value - bounds.min) / (bounds.max - bounds.min || 1))) * 390 158 + Math.max(0, Math.min(1, (value - bounds.min) / (bounds.max - bounds.min || 1))) * 390
const labelFor = (
value: number,
y: number,
numberFormat?: string,
): React.JSX.Element | null => {
const width = norm(value) * 390
const inside = dataLabelPosition === 'center' || dataLabelPosition === 'inside-end'
const x =
dataLabelPosition === 'center'
? 158 + width / 2
: dataLabelPosition === 'inside-end'
? 154 + width
: 164 + width
return (
<text
x={x}
y={y}
textAnchor={
dataLabelPosition === 'center'
? 'middle'
: dataLabelPosition === 'inside-end'
? 'end'
: 'start'
}
className="axis-label"
{...(inside ? { fill: '#fff' } : {})}
>
{formatLabelValue(value, dataLabelFormat, numberFormat)}
</text>
)
}
return ( return (
<svg className="chart-svg" viewBox="0 0 600 320" role="img"> <svg className="chart-svg" viewBox="0 0 600 320" role="img">
{bounds.ticks.map((tick, index) => ( {bounds.ticks.map((tick, index) => (
@@ -2267,12 +2466,13 @@ function BarChart({
x1={plotX(tick)} x1={plotX(tick)}
y1="12" y1="12"
x2={plotX(tick)} x2={plotX(tick)}
y2="298" y2="286"
stroke="#e3e3e3" stroke="#e3e3e3"
strokeWidth="1" strokeWidth="1"
/> />
)} )}
<text x={plotX(tick)} y="10" textAnchor="middle" className="axis-label"> {/* Excel draws the bar-chart value axis along the bottom. */}
<text x={plotX(tick)} y="298" textAnchor="middle" className="axis-label">
{formatAxisValue(tick, axisNumberFormat)} {formatAxisValue(tick, axisNumberFormat)}
</text> </text>
</g> </g>
@@ -2283,11 +2483,11 @@ function BarChart({
<g key={`${categories[index] ?? index}-${index}`}> <g key={`${categories[index] ?? index}-${index}`}>
<text <text
x="148" x="148"
y={26 + rowHeight * index} y={26 + rowHeight * rowSlot(index)}
textAnchor="end" textAnchor="end"
onClick={selectCategoryAxis} onClick={selectCategoryAxis}
> >
{truncateLabel(categories[index] ?? String(index + 1))} {truncateLabel(categories[index] ?? String(index + 1), categoryBudget)}
</text> </text>
{seriesList.map((series, seriesIndex) => { {seriesList.map((series, seriesIndex) => {
const share = isStacked const share = isStacked
@@ -2299,7 +2499,7 @@ function BarChart({
<rect <rect
key={seriesIndex} key={seriesIndex}
x={x} x={x}
y={groupTop(index) + (isStacked ? 0 : barHeight * seriesIndex)} y={groupTop(index) + (isStacked ? 0 : barHeight * seriesSlot(seriesIndex))}
width={share * 390} width={share * 390}
height={barHeight} height={barHeight}
fill={seriesColor(series, seriesIndex)} fill={seriesColor(series, seriesIndex)}
@@ -2310,38 +2510,36 @@ function BarChart({
})} })}
{dataLabels === 'value' && {dataLabels === 'value' &&
!isStacked && !isStacked &&
(() => { seriesList.map((series, seriesIndex) => (
const width = norm(primary.values[index] ?? bounds.min) * 390 <Fragment key={`lbl-${seriesIndex}`}>
const inside = {labelFor(
dataLabelPosition === 'center' || dataLabelPosition === 'inside-end' series.values[index] ?? 0,
const x = groupTop(index) + barHeight * seriesSlot(seriesIndex) + barHeight / 2 + 3,
dataLabelPosition === 'center' series.numberFormat,
? 158 + width / 2 )}
: dataLabelPosition === 'inside-end' </Fragment>
? 154 + width ))}
: 164 + width </g>
return ( )
<text })}
x={x} {/* Outer multiLvlStrCache level: a rotated label column left of the
y={groupTop(index) + barHeight / 2 + 3} category labels with separator lines at the group edges. */}
textAnchor={ {rowGroups.map((group, groupIndex) => {
dataLabelPosition === 'center' const first = rowSlot(group.start)
? 'middle' const last = rowSlot(group.end - 1)
: dataLabelPosition === 'inside-end' const yTop = 14 + rowHeight * Math.min(first, last)
? 'end' const yBottom = 14 + rowHeight * (Math.max(first, last) + 1)
: 'start' const cy = (yTop + yBottom) / 2
} return (
className="axis-label" <g key={`grp-${groupIndex}`} onClick={selectCategoryAxis}>
{...(inside ? { fill: '#fff' } : {})} <line x1="86" y1={yTop} x2="158" y2={yTop} stroke="#d9d9d9" strokeWidth="1" />
> <line x1="86" y1={yBottom} x2="158" y2={yBottom} stroke="#d9d9d9" strokeWidth="1" />
{formatLabelValue( <text x="94" y={cy} transform={`rotate(-90 94 ${cy})`} textAnchor="middle">
primary.values[index] ?? 0, {truncateLabel(
dataLabelFormat, group.label,
primary.numberFormat, Math.max(3, Math.floor((yBottom - yTop) / AXIS_LABEL_CHAR_UNITS)),
)} )}
</text> </text>
)
})()}
</g> </g>
) )
})} })}
@@ -2358,8 +2556,12 @@ function BarChart({
isStacked ? columnWidth / (1 + gap) : columnWidth / (seriesList.length + gap), isStacked ? columnWidth / (1 + gap) : columnWidth / (seriesList.length + gap),
) )
const groupWidth = barWidth * (isStacked ? 1 : seriesList.length) const groupWidth = barWidth * (isStacked ? 1 : seriesList.length)
// maxMin mirrors the column order (and the series order inside a group).
const catSlot = (index: number): number => (categoryReversed ? visibleCount - 1 - index : index)
const seriesSlot = (seriesIndex: number): number =>
categoryReversed ? seriesList.length - 1 - seriesIndex : seriesIndex
const groupLeft = (index: number): number => const groupLeft = (index: number): number =>
62 + columnWidth * index + (columnWidth - groupWidth) / 2 62 + columnWidth * catSlot(index) + (columnWidth - groupWidth) / 2
// The combo line rides the secondary value axis (its own Excel-like auto // The combo line rides the secondary value axis (its own Excel-like auto
// scale when the file has no explicit bounds). // scale when the file has no explicit bounds).
const lineScale = lineSeries const lineScale = lineSeries
@@ -2386,8 +2588,12 @@ function BarChart({
!isStacked && !isStacked &&
(dataLabels === 'value' || (dataLabels === 'value' ||
(dataLabels === undefined && visibleCount <= 12 && seriesList.length === 1)) (dataLabels === undefined && visibleCount <= 12 && seriesList.length === 1))
const columnGroups = visibleCategoryGroups(primary.categoryGroups, visibleCount)
// The group band occupies y 284-314; a bottom axis title moves below it
// on an extended canvas instead of overprinting.
const shiftBottomTitle = columnGroups.length > 0 && Boolean(axisTitles?.category)
return ( return (
<svg className="chart-svg" viewBox="0 0 600 320" role="img"> <svg className="chart-svg" viewBox={`0 0 600 ${shiftBottomTitle ? 336 : 320}`} role="img">
<VerticalAxis <VerticalAxis
minimum={bounds.min} minimum={bounds.min}
maximum={bounds.max} maximum={bounds.max}
@@ -2410,7 +2616,7 @@ function BarChart({
return ( return (
<rect <rect
key={seriesIndex} key={seriesIndex}
x={groupLeft(index) + (isStacked ? 0 : barWidth * seriesIndex)} x={groupLeft(index) + (isStacked ? 0 : barWidth * seriesSlot(seriesIndex))}
y={y} y={y}
width={barWidth} width={barWidth}
height={height} height={height}
@@ -2421,8 +2627,8 @@ function BarChart({
) )
})} })}
{showValueLabels && {showValueLabels &&
(() => { seriesList.map((series, seriesIndex) => {
const share = norm(primary.values[index] ?? bounds.min) const share = norm(series.values[index] ?? bounds.min)
const inside = dataLabelPosition === 'center' || dataLabelPosition === 'inside-end' const inside = dataLabelPosition === 'center' || dataLabelPosition === 'inside-end'
const y = const y =
dataLabelPosition === 'center' dataLabelPosition === 'center'
@@ -2430,24 +2636,26 @@ function BarChart({
: dataLabelPosition === 'inside-end' : dataLabelPosition === 'inside-end'
? 292 - share * 240 ? 292 - share * 240
: 272 - share * 240 : 272 - share * 240
const x = groupLeft(index) + barWidth * seriesSlot(seriesIndex) + barWidth / 2
return ( return (
<text <text
x={groupLeft(index) + groupWidth / 2} key={`lbl-${seriesIndex}`}
x={x}
y={y} y={y}
textAnchor="middle" textAnchor="middle"
className="axis-label" className="axis-label"
{...(inside ? { fill: '#fff' } : {})} {...(inside ? { fill: '#fff' } : {})}
> >
{formatLabelValue( {formatLabelValue(
primary.values[index] ?? 0, series.values[index] ?? 0,
dataLabelFormat, dataLabelFormat,
primary.numberFormat, series.numberFormat,
)} )}
</text> </text>
) )
})()} })}
<CategoryTick <CategoryTick
x={62 + columnWidth * index + columnWidth / 2} x={62 + columnWidth * catSlot(index) + columnWidth / 2}
label={categories[index] ?? String(index + 1)} label={categories[index] ?? String(index + 1)}
slotWidth={columnWidth} slotWidth={columnWidth}
stride={tickStride} stride={tickStride}
@@ -2475,9 +2683,21 @@ function BarChart({
points={points} points={points}
fill="none" fill="none"
stroke={seriesColor(lineSeries, seriesList.length)} stroke={seriesColor(lineSeries, seriesList.length)}
strokeWidth="3" strokeWidth={lineSeries?.lineWidth ?? 3}
/> />
)} )}
<CategoryGroupBand
spans={columnGroups.map((group) => {
const first = catSlot(group.start)
const last = catSlot(group.end - 1)
return {
label: group.label,
xStart: 62 + columnWidth * Math.min(first, last),
xEnd: 62 + columnWidth * (Math.max(first, last) + 1),
}
})}
onClick={selectCategoryAxis}
/>
{lineSeries && {lineSeries &&
lineScale && lineScale &&
secondaryAxis?.hidden !== true && secondaryAxis?.hidden !== true &&
@@ -2493,7 +2713,11 @@ function BarChart({
</text> </text>
))} ))}
<TruncationNote shown={visibleCount} total={primary.values.length} /> <TruncationNote shown={visibleCount} total={primary.values.length} />
<AxisTitleTexts bottom={axisTitles?.category} left={axisTitles?.value} /> <AxisTitleTexts
bottom={axisTitles?.category}
left={axisTitles?.value}
bottomY={shiftBottomTitle ? 333 : 317}
/>
</svg> </svg>
) )
} }
@@ -2541,6 +2765,70 @@ function TrendLine({
) )
} }
/// Excel's automatic marker cycle when the plot flag is on but the series
/// sets no symbol (diamond, square, triangle, then repeat).
const AUTO_MARKER_SYMBOLS = ['diamond', 'square', 'triangle'] as const
function MarkerGlyph({
x,
y,
symbol,
color,
}: {
readonly x: number
readonly y: number
readonly symbol: string
readonly color: string
}): React.JSX.Element {
const r = 4
if (symbol === 'diamond') {
return (
<polygon points={`${x},${y - r} ${x + r},${y} ${x},${y + r} ${x - r},${y}`} fill={color} />
)
}
if (symbol === 'square') {
return <rect x={x - r} y={y - r} width={2 * r} height={2 * r} fill={color} />
}
if (symbol === 'triangle') {
return <polygon points={`${x},${y - r} ${x + r},${y + r} ${x - r},${y + r}`} fill={color} />
}
return <circle cx={x} cy={y} r={r} fill={color} />
}
/// Series line stroke: an explicit spPr/a:ln color wins over the fill/accent
/// default; null for an explicit noFill line.
export function lineStroke(
series: SeriesLike & { readonly lineColor?: string | undefined },
index: number,
): string | null {
if (series.lineColor === 'none') return null
return series.lineColor ?? seriesColor(series, index)
}
/// Whether the legend mirrors stroke colors: only when a line-drawing
/// component wins the render cascade (pie → radar → scatter → area → line →
/// bar) — a chart that also carries an areaChart/scatterChart paints fills.
export function legendUsesLineSwatches(types: readonly string[]): boolean {
if (types.includes('pieChart') || types.includes('doughnutChart')) return false
const noBar = !types.includes('barChart')
if (types.includes('radarChart') && noBar) return true
if (types.includes('scatterChart')) return false
if (types.includes('areaChart') && noBar) return false
return types.includes('lineChart') && noBar
}
/// Legend swatch color: line-family charts mirror the drawn stroke (an
/// explicit noFill line keeps the series color); everything else keeps the
/// fill resolution.
export function legendSwatchColor(
series: SeriesLike & { readonly lineColor?: string | undefined },
index: number,
lineSwatches: boolean,
): string {
if (!lineSwatches) return seriesColor(series, index)
return lineStroke(series, index) ?? seriesColor(series, index)
}
function linePoints(values: readonly number[], maximum: number, minimum = 0): string { function linePoints(values: readonly number[], maximum: number, minimum = 0): string {
const count = Math.max(1, values.length - 1) const count = Math.max(1, values.length - 1)
const span = maximum - minimum || 1 const span = maximum - minimum || 1
@@ -2687,6 +2975,51 @@ function CategoryTick({
) )
} }
/// Clamp parsed outer-level category spans to the drawn category count.
function visibleCategoryGroups(
groups: ChartSeries['categoryGroups'],
visibleCount: number,
): { label: string; start: number; end: number }[] {
return (groups ?? [])
.map((group) => ({ ...group, end: Math.min(group.end, visibleCount) }))
.filter((group) => group.start < group.end && group.start < visibleCount)
}
/// Outer multiLvlStrCache level under the tick labels: each group label
/// centered under its span with separator ticks at the span edges (Excel's
/// grouped category axis).
function CategoryGroupBand({
spans,
onClick,
}: {
readonly spans: readonly { label: string; xStart: number; xEnd: number }[]
readonly onClick?: ((event: React.MouseEvent) => void) | undefined
}): React.JSX.Element {
return (
<g onClick={onClick}>
{spans.map((span, index) => (
<Fragment key={index}>
<line
x1={span.xStart}
y1="284"
x2={span.xStart}
y2="314"
stroke="#d9d9d9"
strokeWidth="1"
/>
<line x1={span.xEnd} y1="284" x2={span.xEnd} y2="314" stroke="#d9d9d9" strokeWidth="1" />
<text x={(span.xStart + span.xEnd) / 2} y="312" textAnchor="middle">
{truncateLabel(
span.label,
Math.max(3, Math.floor((span.xEnd - span.xStart) / AXIS_LABEL_CHAR_UNITS)),
)}
</text>
</Fragment>
))}
</g>
)
}
function formatAxisValue(value: number, numberFormat: string | undefined): string { function formatAxisValue(value: number, numberFormat: string | undefined): string {
if (numberFormat && numberFormat !== 'General' && !numberFormat.includes('%')) { if (numberFormat && numberFormat !== 'General' && !numberFormat.includes('%')) {
try { try {
@@ -2770,6 +3103,7 @@ function LineChart({
gridlines, gridlines,
valueAxis, valueAxis,
categoryFormat, categoryFormat,
lineMarkers,
onElement, onElement,
selectedEl, selectedEl,
}: { }: {
@@ -2780,6 +3114,7 @@ function LineChart({
readonly gridlines?: boolean | undefined readonly gridlines?: boolean | undefined
readonly valueAxis?: ChartValueAxis readonly valueAxis?: ChartValueAxis
readonly categoryFormat?: string | undefined readonly categoryFormat?: string | undefined
readonly lineMarkers?: boolean | undefined
} & ChartElementProps): React.JSX.Element { } & ChartElementProps): React.JSX.Element {
const primary = seriesList[0] const primary = seriesList[0]
if (!primary) return <></> if (!primary) return <></>
@@ -2817,8 +3152,12 @@ function LineChart({
const span = bounds.max - bounds.min const span = bounds.max - bounds.min
const categories = primary.categories.map((value) => formatCategoryLabel(value, categoryFormat)) const categories = primary.categories.map((value) => formatCategoryLabel(value, categoryFormat))
const count = Math.max(1, primary.values.length - 1) const count = Math.max(1, primary.values.length - 1)
const categoryGroups = visibleCategoryGroups(primary.categoryGroups, primary.values.length)
// The group band occupies y 284-314; a bottom axis title moves below it
// on an extended canvas instead of overprinting.
const shiftBottomTitle = categoryGroups.length > 0 && Boolean(axisTitles?.category)
return ( return (
<svg className="chart-svg" viewBox="0 0 600 320" role="img"> <svg className="chart-svg" viewBox={`0 0 600 ${shiftBottomTitle ? 336 : 320}`} role="img">
<VerticalAxis <VerticalAxis
minimum={bounds.min} minimum={bounds.min}
maximum={bounds.max} maximum={bounds.max}
@@ -2834,25 +3173,59 @@ function LineChart({
: undefined : undefined
} }
/> />
{seriesList.map((series, seriesIndex) => ( {seriesList.map((series, seriesIndex) => {
<polyline const stroke = lineStroke(series, seriesIndex)
key={seriesIndex} if (stroke === null) return null
points={linePoints(displayValues(seriesIndex), bounds.max, bounds.min)} const width = series.lineWidth ?? 3
fill="none" return (
stroke={seriesColor(series, seriesIndex)} <polyline
strokeWidth={ key={seriesIndex}
selectedEl?.kind === 'series' && selectedEl.seriesIndex === seriesIndex ? '5' : '3' points={linePoints(displayValues(seriesIndex), bounds.max, bounds.min)}
} fill="none"
onClick={ stroke={stroke}
onElement strokeWidth={
? (event) => { selectedEl?.kind === 'series' && selectedEl.seriesIndex === seriesIndex
event.stopPropagation() ? Math.max(5, width + 2)
onElement({ kind: 'series', seriesIndex }) : width
} }
: undefined onClick={
} onElement
/> ? (event) => {
))} event.stopPropagation()
onElement({ kind: 'series', seriesIndex })
}
: undefined
}
/>
)
})}
{seriesList.map((series, seriesIndex) => {
// Plot flag on or explicit symbol; a series-level "none" always wins.
if (series.marker === 'none') return null
if (lineMarkers !== true && series.marker === undefined) return null
const symbol =
series.marker !== undefined && series.marker !== 'auto'
? series.marker
: (AUTO_MARKER_SYMBOLS[seriesIndex % AUTO_MARKER_SYMBOLS.length] ?? 'circle')
const values = displayValues(seriesIndex)
const pointCount = Math.max(1, values.length - 1)
// Markers match the polyline stroke; an explicit noFill line keeps
// its markers in the series color.
const color = lineStroke(series, seriesIndex) ?? seriesColor(series, seriesIndex)
return (
<g key={`markers-${seriesIndex}`}>
{values.map((value, index) => (
<MarkerGlyph
key={index}
x={60 + (index / pointCount) * 500}
y={280 - Math.max(0, Math.min(1, (value - bounds.min) / (span || 1))) * 240}
symbol={symbol}
color={color}
/>
))}
</g>
)
})}
{seriesList.map((series, seriesIndex) => {seriesList.map((series, seriesIndex) =>
series.trendline === 'linear' ? ( series.trendline === 'linear' ? (
<TrendLine <TrendLine
@@ -2895,7 +3268,32 @@ function LineChart({
{formatAxisValue(primary.values[index] ?? 0, primary.numberFormat)} {formatAxisValue(primary.values[index] ?? 0, primary.numberFormat)}
</text> </text>
))} ))}
<AxisTitleTexts bottom={axisTitles?.category} left={axisTitles?.value} /> <CategoryGroupBand
spans={categoryGroups.map((group) => {
const xAt = (index: number): number => 60 + (index / count) * 500
// Group edges fall midway between the last point of one group
// and the first point of the next (plot edges at the ends).
return {
label: group.label,
xStart: group.start === 0 ? 60 : (xAt(group.start - 1) + xAt(group.start)) / 2,
xEnd:
group.end >= primary.values.length ? 560 : (xAt(group.end - 1) + xAt(group.end)) / 2,
}
})}
onClick={
onElement
? (event) => {
event.stopPropagation()
onElement({ kind: 'category-axis' })
}
: undefined
}
/>
<AxisTitleTexts
bottom={axisTitles?.category}
left={axisTitles?.value}
bottomY={shiftBottomTitle ? 333 : 317}
/>
</svg> </svg>
) )
} }
@@ -3124,8 +3522,10 @@ function RadarChart({
points={seriesPoints(series)} points={seriesPoints(series)}
fill={seriesColor(series, seriesIndex)} fill={seriesColor(series, seriesIndex)}
fillOpacity="0.18" fillOpacity="0.18"
stroke={isSel ? '#107C41' : seriesColor(series, seriesIndex)} stroke={isSel ? '#107C41' : (lineStroke(series, seriesIndex) ?? 'none')}
strokeWidth={isSel ? '4' : '2.5'} strokeWidth={
isSel ? Math.max(4, (series.lineWidth ?? 2.5) + 1.5) : (series.lineWidth ?? 2.5)
}
onClick={ onClick={
onElement onElement
? (event) => { ? (event) => {
@@ -3270,7 +3670,7 @@ function ScatterChart({
? series.lineColor ? series.lineColor
: seriesColor(series, seriesIndex) : seriesColor(series, seriesIndex)
} }
strokeWidth="2" strokeWidth={series.lineWidth ?? 2}
/> />
)} )}
{series.marker !== 'none' && {series.marker !== 'none' &&
+25 -1
View File
@@ -20,7 +20,25 @@ const SERIF_INTENT =
/// Generic families never cover emoji code points on the canvas — without an /// Generic families never cover emoji code points on the canvas — without an
/// explicit color-emoji face at the end of every chain, U+274C & friends draw /// explicit color-emoji face at the end of every chain, U+274C & friends draw
/// as tofu. Listed after the generic so primary-font metrics never change. /// as tofu. Listed after the generic so primary-font metrics never change.
const EMOJI_FALLBACK = '"Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji"' /// Emoji=Yes but Emoji_Presentation=No dingbats (✔✖❄❤ card suits …) render
/// as text glyphs in the cell color in Excel, while a color-emoji bitmap
/// ignores fillStyle (prod_016's CF-red ✖ drew charcoal) — a monochrome
/// symbols face intercepts exactly those codepoints ahead of the emoji
/// chain; EPres=Yes codepoints (U+274C …) stay on the color font.
const TEXT_DINGBATS_FAMILY = 'Cell Text Dingbats'
/// Faces that carry real outline glyphs for these codepoints (canvas-probed:
/// Apple Symbols and Hiragino draw the color-emoji bitmap instead).
const TEXT_DINGBATS_SOURCES = [
'Segoe UI Symbol',
'Arial Unicode MS',
'Zapf Dingbats',
'Menlo',
] as const
const TEXT_DINGBATS_RANGE =
'U+2611, U+2660, U+2663, U+2665-2666, U+2702, U+2708-2709, U+270C, U+270F, ' +
'U+2712, U+2714, U+2716, U+271D, U+2721, U+2733-2734, U+2744, U+2747, U+2763-2764'
const EMOJI_FALLBACK =
'"Cell Text Dingbats", "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji"'
/// The family name inside one comma segment of a ctx.font string: the quoted /// The family name inside one comma segment of a ctx.font string: the quoted
/// name if quoted, otherwise the last whitespace token (the first segment /// name if quoted, otherwise the last whitespace token (the first segment
@@ -411,6 +429,12 @@ function registerAlias(alias: CellFontAlias, loads: Promise<unknown>[]): void {
export function registerCellFontAliases(): Promise<unknown> { export function registerCellFontAliases(): Promise<unknown> {
const loads: Promise<unknown>[] = [] const loads: Promise<unknown>[] = []
const gated: Promise<unknown>[] = [] const gated: Promise<unknown>[] = []
addFace(
TEXT_DINGBATS_FAMILY,
TEXT_DINGBATS_SOURCES,
{ weight: '400', unicodeRange: TEXT_DINGBATS_RANGE },
loads,
)
for (const alias of CELL_FONT_ALIASES) { for (const alias of CELL_FONT_ALIASES) {
if (alias.skipIfLocal) { if (alias.skipIfLocal) {
gated.push( gated.push(
+157
View File
@@ -0,0 +1,157 @@
/// CSV export of the active sheet: display strings from the live Univer model
/// (number formats applied, formula results, values only), Excel-style
/// quoting, CRLF rows. The main process runs the loss warning + save dialog
/// and writes UTF-8 with a BOM so Excel reopens it correctly.
import { MAX_CSV_EXPORT_CHARS } from '../shared/ipc-channels'
import { formulaViewSheets } from './formula-view'
import { t } from './i18n/locale'
import type { LazyWorkbookState, UniverRuntime } from './univer-state'
/// Rows fetched per getDisplayValues call, bounding the facade's allocation.
const EXPORT_ROW_BLOCK = 4096
/** The App refs/state the CSV export needs; built fresh per call. */
export interface CsvExportContext {
univerRef: { readonly current: UniverRuntime | null }
lazyWorkbookRef: { readonly current: LazyWorkbookState | null }
setMessage: (message: string) => void
/// Routes into the regular Save As flow when the user picks "Save as .xlsx"
/// in the formula-loss warning.
requestSaveAs: () => void
}
/// The slice of the Univer facade the export reads (structural, so the
/// caller passes the FWorksheet through a cast — same pattern as print-html).
interface CsvWorksheet {
getLastRow(): number
getLastColumn(): number
getSheetId(): string
getSheetName(): string
getRange(
row: number,
column: number,
numRows: number,
numColumns: number,
): { getDisplayValues(): string[][] }
getSheet(): {
getCellMatrix(): {
forValue(
callback: (row: number, column: number, cell: { f?: string | null } | null) => unknown,
): void
}
}
}
export function csvField(text: string): string {
const normalized = text.replace(/\r\n|\r/g, '\n')
return /[",\n]/.test(normalized) ? `"${normalized.replace(/"/g, '""')}"` : normalized
}
export function csvFromDisplayRows(rows: readonly (readonly string[])[]): string {
return rows.map((row) => row.map(csvField).join(',') + '\r\n').join('')
}
/// Runs `read` with the sheet dropped from the formula-view set, restoring it
/// afterwards: CSV always exports calculated values, and in formula view the
/// display interceptor would hand getDisplayValues the formula text instead.
/// The read is synchronous, so the grid never repaints while the flag is off.
export function withoutFormulaView<T>(sheets: Set<string>, sheetId: string, read: () => T): T {
const hadFormulaView = sheets.delete(sheetId)
try {
return read()
} finally {
if (hadFormulaView) sheets.add(sheetId)
}
}
/// Serializes the active sheet's display grid; 'too-large' when the text
/// exceeds the IPC cap. Callers gate on preloadComplete first.
export function serializeActiveSheetCsv(
sheet: CsvWorksheet,
state: LazyWorkbookState | null,
): string | 'too-large' {
const rowCount = Math.max(sheet.getLastRow(), 0) + 1
const columnCount = Math.max(sheet.getLastColumn(), 0) + 1
const parts: string[] = []
let length = 0
const tooLarge = withoutFormulaView(formulaViewSheets(state), sheet.getSheetId(), () => {
for (let start = 0; start < rowCount; start += EXPORT_ROW_BLOCK) {
const blockRows = Math.min(EXPORT_ROW_BLOCK, rowCount - start)
const part = csvFromDisplayRows(
sheet.getRange(start, 0, blockRows, columnCount).getDisplayValues(),
)
length += part.length
if (length > MAX_CSV_EXPORT_CHARS) return true
parts.push(part)
}
return false
})
return tooLarge ? 'too-large' : parts.join('')
}
/// The active FWorksheet through the structural CsvWorksheet slice, plus the
/// live sheet count — shared by the menu export and the save flows.
export function activeCsvSheet(
runtime: UniverRuntime | null,
): { sheet: CsvWorksheet; sheetCount: number } | null {
const workbook = runtime?.univerAPI.getActiveWorkbook()
const worksheet = workbook?.getActiveSheet()
if (!workbook || !worksheet) return null
return {
sheet: worksheet as unknown as CsvWorksheet,
sheetCount: workbook.getSheets().length,
}
}
function sheetHasFormulas(sheet: CsvWorksheet): boolean {
let found = false
sheet
.getSheet()
.getCellMatrix()
.forValue((_row, _column, cell) => {
if (!cell?.f) return undefined
found = true
return false
})
return found
}
export async function handleExportCsv(ctx: CsvExportContext, targetPath?: string): Promise<void> {
const runtime = ctx.univerRef.current
const active = activeCsvSheet(runtime)
if (!runtime || !active) return
const { sheet, sheetCount } = active
const state = ctx.lazyWorkbookRef.current
if (state && !state.flags.preloadComplete) {
ctx.setMessage(t('appCsvExportNeedsFullLoad'))
return
}
try {
const content = serializeActiveSheetCsv(sheet, state)
if (content === 'too-large') {
ctx.setMessage(t('appCsvExportTooLarge'))
return
}
const baseName = (state?.file.name ?? 'Book1').replace(/\.[^.]+$/, '')
const result = await window.desktopApi.exportCsv({
fileName: `${baseName}.csv`,
content,
hasFormulas: sheetHasFormulas(sheet),
...(sheetCount > 1 ? { activeSheetName: sheet.getSheetName() } : {}),
...(targetPath === undefined ? {} : { targetPath }),
})
if (result.canceled) {
if (result.saveAsXlsxInstead) ctx.requestSaveAs()
else ctx.setMessage(t('appCsvExportCanceled'))
return
}
ctx.setMessage(
sheetCount > 1
? t('appCsvExportedActiveOnly', { name: sheet.getSheetName(), path: result.path })
: t('appCsvExported', { path: result.path }),
)
} catch (error: unknown) {
ctx.setMessage(error instanceof Error ? error.message : t('appCsvExportFailed'))
}
}
@@ -1,155 +1,4 @@
import { DataValidationRenderMode, getOriginCellValue } from '@univerjs/core' export {
import { DataValidatorRegistryService } from '@univerjs/data-validation' installActiveCellDataValidationChrome,
installActiveCellDataValidationDropdown,
import type { UniverRuntime } from './univer-state' } from './data-validation-dropdown'
interface ValidationCanvasRenderer {
drawWith: ((...args: unknown[]) => unknown) | undefined
isHit: ((...args: unknown[]) => unknown) | undefined
_dataValidationModel?: {
getRuleByLocation(
unitId: string,
subUnitId: string,
row: number,
col: number,
): { renderMode: DataValidationRenderMode } | undefined
}
}
interface ListValidator {
canvasRender?: ValidationCanvasRenderer | null
}
function hasValue(value: unknown): boolean {
return value !== undefined && value !== null && value !== ''
}
function rendererHasValue(info: unknown): boolean {
if (!info || typeof info !== 'object') return false
const data = (info as { data?: unknown }).data
return hasValue(getOriginCellValue(data as never))
}
/**
* Keep validated cells in TEXT mode so their workbook styling and text layout
* stay untouched. For populated cells only, invoke Univer's arrow renderer
* with an empty display value: this adds the arrow and hit target without
* repainting the text or background.
*/
export function installPopulatedDataValidationArrow(runtime: UniverRuntime): { dispose(): void } {
const registry = runtime.univer.__getInjector().get(DataValidatorRegistryService)
const wrappedRenderers = new WeakSet<ValidationCanvasRenderer>()
const restoreRenderers: Array<() => void> = []
let animationFrame: number | undefined
let attempts = 0
let disposed = false
const install = () => {
if (disposed) return
const validator = registry.getValidatorItem('list') as ListValidator | undefined
const renderer = validator?.canvasRender
// Univer assigns its final canvas renderer during the Rendered lifecycle.
// Check for a replacement for the first second instead of wrapping a
// short-lived bootstrap instance.
if (renderer && !wrappedRenderers.has(renderer)) {
wrappedRenderers.add(renderer)
const originalDraw = renderer.drawWith
const originalIsHit = renderer.isHit
if (originalDraw) {
renderer.drawWith = function (...args: unknown[]) {
const info = args[1] as
| {
data?: Record<string, unknown>
unitId?: string
subUnitId?: string
row?: number
col?: number
}
| undefined
if (
!rendererHasValue(info) ||
!info?.data ||
info.unitId === undefined ||
info.subUnitId === undefined ||
info.row === undefined ||
info.col === undefined
) {
return
}
const rule = renderer._dataValidationModel?.getRuleByLocation(
info.unitId,
info.subUnitId,
info.row,
info.col,
)
if (!rule) return
const previousMode = rule.renderMode
rule.renderMode = DataValidationRenderMode.ARROW
try {
const arrowInfo = { ...info, data: { ...info.data, v: '' } }
return originalDraw.apply(this, [args[0], arrowInfo, ...args.slice(2)])
} finally {
rule.renderMode = previousMode
}
}
}
if (originalIsHit) {
renderer.isHit = function (...args: unknown[]) {
const info = args[1] as
| {
data?: Record<string, unknown>
unitId?: string
subUnitId?: string
row?: number
col?: number
}
| undefined
if (
!rendererHasValue(info) ||
info?.unitId === undefined ||
info.subUnitId === undefined ||
info.row === undefined ||
info.col === undefined
) {
return false
}
const rule = renderer._dataValidationModel?.getRuleByLocation(
info.unitId,
info.subUnitId,
info.row,
info.col,
)
if (!rule) return false
const previousMode = rule.renderMode
rule.renderMode = DataValidationRenderMode.ARROW
try {
return originalIsHit.apply(this, args)
} finally {
rule.renderMode = previousMode
}
}
}
restoreRenderers.push(() => {
renderer.drawWith = originalDraw
renderer.isHit = originalIsHit
})
}
attempts += 1
if (attempts < 60 && typeof globalThis.requestAnimationFrame === 'function') {
animationFrame = globalThis.requestAnimationFrame(install)
}
}
install()
return {
dispose: () => {
disposed = true
if (animationFrame !== undefined) globalThis.cancelAnimationFrame(animationFrame)
for (const restore of restoreRenderers) restore()
},
}
}
@@ -0,0 +1,286 @@
import type { PointerEvent as ReactPointerEvent } from 'react'
import type { UniverRuntime, UniverWorksheet } from './univer-state'
const DROPDOWN_COMPONENT_KEY = 'genoffice-active-data-validation-dropdown'
const INPUT_MESSAGE_COMPONENT_KEY = 'genoffice-active-data-validation-input-message'
const SHOW_DROPDOWN_COMMAND = 'sheet.operation.show-data-validation-dropdown'
const DROPDOWN_SIZE = 14
const INPUT_MESSAGE_WIDTH = 108
const INPUT_MESSAGE_LINE_HEIGHT = 12
const INPUT_MESSAGE_PADDING_HEIGHT = 16
const INPUT_MESSAGE_MAX_HEIGHT = 180
const INPUT_MESSAGE_UNITS_PER_LINE = 20
interface ValidationLike {
readonly rule?: {
readonly showDropDown?: boolean
readonly showInputMessage?: boolean
readonly promptTitle?: string
readonly prompt?: string
}
getCriteriaType(): string
}
interface ActiveValidationTarget {
readonly unitId: string
readonly sheetId: string
readonly row: number
readonly column: number
readonly validation: ValidationLike
readonly range: ReturnType<UniverWorksheet['getRange']>
readonly worksheet: UniverWorksheet
}
export interface DataValidationInputMessage {
readonly title: string
readonly prompt: string
}
function rangePixelHeight(target: ActiveValidationTarget): number {
let height = 0
for (let row = target.range.getRow(); row <= target.range.getLastRow(); row += 1) {
height += target.worksheet.getRowHeight(row)
}
return height
}
export function shouldShowDataValidationDropdown(
validation: ValidationLike | null | void,
): boolean {
return validation?.getCriteriaType() === 'list' && validation.rule?.showDropDown !== false
}
export function getDataValidationInputMessage(
validation: ValidationLike | null | void,
): DataValidationInputMessage | null {
if (validation?.rule?.showInputMessage !== true) return null
const title = validation.rule.promptTitle ?? ''
const prompt = validation.rule.prompt ?? ''
return title || prompt ? { title, prompt } : null
}
function textDisplayUnits(value: string): number {
let units = 0
for (const character of value) units += character.codePointAt(0)! > 0xff ? 2 : 1
return units
}
export function dataValidationInputMessageHeight(message: DataValidationInputMessage): number {
const linesFor = (value: string): number =>
value
? value
.split(/\r\n?|\n/)
.reduce(
(total, line) =>
total + Math.max(1, Math.ceil(textDisplayUnits(line) / INPUT_MESSAGE_UNITS_PER_LINE)),
0,
)
: 0
const lines = Math.max(1, linesFor(message.title) + linesFor(message.prompt))
return Math.min(
INPUT_MESSAGE_MAX_HEIGHT,
INPUT_MESSAGE_PADDING_HEIGHT + lines * INPUT_MESSAGE_LINE_HEIGHT,
)
}
function resolveActiveValidationTarget(runtime: UniverRuntime): ActiveValidationTarget | null {
try {
const workbook = runtime.univerAPI.getActiveWorkbook()
const worksheet = workbook?.getActiveSheet()
const cell = workbook?.getActiveCell()
if (!workbook || !worksheet || !cell) return null
const row = cell.getRow()
const column = cell.getColumn()
if (!Number.isInteger(row) || !Number.isInteger(column) || row < 0 || column < 0) return null
const range = worksheet.getCellMergeData(row, column) ?? worksheet.getRange(row, column, 1, 1)
const validation = range.getDataValidation()
if (!validation) return null
return {
unitId: workbook.getId(),
sheetId: worksheet.getSheetId(),
row,
column,
validation,
range,
worksheet,
}
} catch {
return null
}
}
function resolveActiveDropdownTarget(runtime: UniverRuntime): ActiveValidationTarget | null {
const target = resolveActiveValidationTarget(runtime)
return target && shouldShowDataValidationDropdown(target.validation) ? target : null
}
export function openActiveDataValidationDropdown(
runtime: UniverRuntime,
event?: Pick<ReactPointerEvent<HTMLButtonElement>, 'preventDefault' | 'stopPropagation'>,
): void {
event?.preventDefault()
event?.stopPropagation()
const target = resolveActiveDropdownTarget(runtime)
if (!target) return
void runtime.univerAPI.executeCommand(SHOW_DROPDOWN_COMMAND, {
unitId: target.unitId,
subUnitId: target.sheetId,
row: target.row,
column: target.column,
})
}
function DataValidationDropdownButton({
runtime,
}: {
readonly runtime: UniverRuntime
}): React.JSX.Element {
return (
<button
type="button"
className="data-validation-dropdown-button"
aria-label="Open dropdown"
tabIndex={-1}
onPointerDown={(event) => openActiveDataValidationDropdown(runtime, event)}
>
<svg aria-hidden="true" viewBox="0 0 10 10">
<path d="M1.5 3.25 5 6.75l3.5-3.5Z" />
</svg>
</button>
)
}
function DataValidationInputMessage({
runtime,
}: {
readonly runtime: UniverRuntime
}): React.JSX.Element | null {
const target = resolveActiveValidationTarget(runtime)
const message = getDataValidationInputMessage(target?.validation)
if (!message) return null
return (
<div className="data-validation-input-message" role="note">
{message.title ? (
<div className="data-validation-input-message-title">{message.title}</div>
) : null}
{message.prompt ? <div>{message.prompt}</div> : null}
</div>
)
}
/**
* Excel renders validation UI as active-cell chrome: the dropdown is attached
* outside the right edge and the optional input message starts at the cell's
* horizontal midpoint below it. Anchored DOM layers follow scroll and zoom.
*/
export function installActiveCellDataValidationChrome(runtime: UniverRuntime): {
dispose(): void
} {
let dropdownFloating: { dispose(): void } | null = null
let inputMessageFloating: { dispose(): void } | null = null
let targetKey = ''
let disposed = false
const componentDisposables = [
runtime.univerAPI.registerComponent(DROPDOWN_COMPONENT_KEY, () => (
<DataValidationDropdownButton runtime={runtime} />
)),
runtime.univerAPI.registerComponent(INPUT_MESSAGE_COMPONENT_KEY, () => (
<DataValidationInputMessage runtime={runtime} />
)),
]
const clear = (): void => {
dropdownFloating?.dispose()
inputMessageFloating?.dispose()
dropdownFloating = null
inputMessageFloating = null
targetKey = ''
}
const sync = (force = false): void => {
if (disposed) return
const target = resolveActiveValidationTarget(runtime)
const inputMessage = getDataValidationInputMessage(target?.validation)
const showDropdown = target ? shouldShowDataValidationDropdown(target.validation) : false
const nextKey = target
? JSON.stringify([
target.unitId,
target.sheetId,
target.row,
target.column,
showDropdown,
inputMessage?.title ?? '',
inputMessage?.prompt ?? '',
])
: ''
if (!force && (dropdownFloating || inputMessageFloating) && nextKey === targetKey) return
clear()
if (!target) return
if (showDropdown) {
const cellHeight = rangePixelHeight(target)
const height = Math.min(DROPDOWN_SIZE, Math.max(1, cellHeight))
dropdownFloating =
target.worksheet.addFloatDomToRange(
target.range,
{
componentKey: DROPDOWN_COMPONENT_KEY,
allowTransform: false,
eventPassThrough: false,
},
{
width: DROPDOWN_SIZE,
height,
marginX: '100%',
marginY: 0,
verticalOffsetAlign: 'bottom',
},
DROPDOWN_COMPONENT_KEY,
) ?? null
}
if (inputMessage) {
inputMessageFloating =
target.worksheet.addFloatDomToRange(
target.range,
{
componentKey: INPUT_MESSAGE_COMPONENT_KEY,
allowTransform: false,
eventPassThrough: true,
},
{
width: INPUT_MESSAGE_WIDTH,
height: dataValidationInputMessageHeight(inputMessage),
marginX: '50%',
marginY: '100%',
},
INPUT_MESSAGE_COMPONENT_KEY,
) ?? null
}
if (dropdownFloating || inputMessageFloating) targetKey = nextKey
}
const disposables = [
runtime.univerAPI.addEvent(runtime.univerAPI.Event.SelectionChanged, () => sync()),
runtime.univerAPI.addEvent(runtime.univerAPI.Event.ActiveSheetChanged, () => sync()),
runtime.univerAPI.addEvent(runtime.univerAPI.Event.CommandExecuted, ({ id }) => {
if (id.includes('data-validation')) sync(true)
}),
]
sync()
return {
dispose: () => {
disposed = true
clear()
for (const disposable of disposables) disposable.dispose()
for (const disposable of componentDisposables) disposable.dispose()
},
}
}
export function installActiveCellDataValidationDropdown(runtime: UniverRuntime): {
dispose(): void
} {
return installActiveCellDataValidationChrome(runtime)
}
+51 -11
View File
@@ -53,27 +53,47 @@ export function pickNextError(
return ordered.find((error) => compare(rank(error), activeRank) > 0) ?? ordered[0]! return ordered.find((error) => compare(rank(error), activeRank) > 0) ?? ordered[0]!
} }
export interface StreamedErrorScanOptions {
/** Live sheet ids in workbook order: session-added sheets included, deleted
ones absent. Defaults to the file metas (tests). */
liveSheetIds?: readonly string[]
/** Computed result of a journal formula entry — the journal stores value:null
and the result lives in Univer, same backfill as findCells. */
resolveFormulaValue?: (sheetId: string, row: number, column: number) => unknown
/** The workbook was swapped mid-scan: stop paging right away. */
isStale?: () => boolean
}
/** Pages every sheet of the underlying file collecting #REF!-style errors. */ /** Pages every sheet of the underlying file collecting #REF!-style errors. */
export async function scanStreamedWorkbookErrors( export async function scanStreamedWorkbookErrors(
state: LazyWorkbookState, state: LazyWorkbookState,
options?: StreamedErrorScanOptions,
): Promise<StreamedErrorScan> { ): Promise<StreamedErrorScan> {
const errors: SheetError[] = [] const errors: SheetError[] = []
let truncated = false let truncated = false
for (const meta of state.file.sheets) { // Same budget semantics as Ctrl+F: cap by cells scanned, not by hits found.
const sheetId = meta.id let scanBudget = MAX_SCAN_CELLS
// Journal edits first — they shadow file cells at the same coordinates, const sheetIds = options?.liveSheetIds ?? state.file.sheets.map((meta) => meta.id)
// so an edit that clears or overwrites an error cell hides the file hit. for (const sheetId of sheetIds) {
const meta = state.file.sheets.find((candidate) => candidate.id === sheetId)
// Journal edits first — value edits shadow file cells at the same
// coordinates (style-only entries leave the file content standing), and
// formula errors are read back from Univer since the journal stores null.
const shadowed = new Set<string>() const shadowed = new Set<string>()
const journal = state.editJournal.cells.get(sheetId) const journal = state.editJournal.cells.get(sheetId)
for (const entry of journal?.values() ?? []) { for (const entry of journal?.values() ?? []) {
shadowed.add(`${entry.row}:${entry.column}`)
if (!entry.hasValue) continue if (!entry.hasValue) continue
if (typeof entry.value === 'string' && ERROR_VALUE_RE.test(entry.value)) { shadowed.add(`${entry.row}:${entry.column}`)
errors.push({ sheetId, row: entry.row, column: entry.column, value: entry.value }) let value: unknown = entry.value
if (entry.formula && value === null) {
value = options?.resolveFormulaValue?.(sheetId, entry.row, entry.column) ?? null
}
if (typeof value === 'string' && ERROR_VALUE_RE.test(value)) {
errors.push({ sheetId, row: entry.row, column: entry.column, value })
} }
} }
// Sheets added this session live entirely in the journal. // Sheets added this session live entirely in the journal.
if (meta.rowCount <= 0 || meta.columnCount <= 0) continue if (!meta || meta.rowCount <= 0 || meta.columnCount <= 0) continue
const ops = state.editJournal.structuralOps.get(sheetId) ?? [] const ops = state.editJournal.structuralOps.get(sheetId) ?? []
const screenRows = Math.max(meta.rowCount + netAxisDelta(ops, 'row'), 0) const screenRows = Math.max(meta.rowCount + netAxisDelta(ops, 'row'), 0)
const screenColumns = Math.max(meta.columnCount + netAxisDelta(ops, 'column'), 0) const screenColumns = Math.max(meta.columnCount + netAxisDelta(ops, 'column'), 0)
@@ -81,11 +101,15 @@ export async function scanStreamedWorkbookErrors(
const batchRows = Math.max(1, Math.floor(FILE_READ_BATCH_CELLS / screenColumns)) const batchRows = Math.max(1, Math.floor(FILE_READ_BATCH_CELLS / screenColumns))
for (let startRow = 0; startRow < screenRows; startRow += batchRows) { for (let startRow = 0; startRow < screenRows; startRow += batchRows) {
if (truncated) break if (truncated) break
if (errors.length >= MAX_SCAN_CELLS) { // The workbook was swapped mid-scan (file switch/reload): stop paging
// right away so the in-flight guard frees up for the new book.
if (options?.isStale?.()) return { errors, truncated: true }
if (scanBudget <= 0) {
truncated = true truncated = true
break break
} }
const endRow = Math.min(startRow + batchRows - 1, screenRows - 1) const endRow = Math.min(startRow + batchRows - 1, screenRows - 1)
scanBudget -= (endRow - startRow + 1) * screenColumns
let mapped let mapped
try { try {
mapped = await readSheetRangeMapped( mapped = await readSheetRangeMapped(
@@ -140,9 +164,25 @@ export async function runStreamedErrorCheck(deps: StreamedErrorCheckDeps): Promi
scanInFlight.current = true scanInFlight.current = true
try { try {
deps.setMessage(t('appCheckingErrors')) deps.setMessage(t('appCheckingErrors'))
const scan = await scanStreamedWorkbookErrors(state)
const workbook = deps.runtime.univerAPI.getActiveWorkbook() const workbook = deps.runtime.univerAPI.getActiveWorkbook()
if (!workbook) return if (!workbook) return
const sheets = workbook.getSheets()
// Identity guard, same as the other lazy paths: a file switch during the
// paged scan must not drive selection on the new workbook with the old
// file's error coordinates.
const stale = () => deps.lazyWorkbookRef.current !== state
const scan = await scanStreamedWorkbookErrors(state, {
liveSheetIds: sheets.map((sheet) => sheet.getSheetId()),
resolveFormulaValue: (sheetId, row, column) => {
try {
return workbook.getSheetBySheetId(sheetId)?.getRange(row, column, 1, 1).getValue()
} catch {
return null
}
},
isStale: stale,
})
if (stale()) return
if (scan.errors.length === 0) { if (scan.errors.length === 0) {
deps.setMessage( deps.setMessage(
scan.truncated scan.truncated
@@ -151,7 +191,6 @@ export async function runStreamedErrorCheck(deps: StreamedErrorCheckDeps): Promi
) )
return return
} }
const sheets = workbook.getSheets()
const order = new Map(sheets.map((sheet, index) => [sheet.getSheetId(), index] as const)) const order = new Map(sheets.map((sheet, index) => [sheet.getSheetId(), index] as const))
const activeSheet = workbook.getActiveSheet() const activeSheet = workbook.getActiveSheet()
let activeRow = -1 let activeRow = -1
@@ -186,6 +225,7 @@ export async function runStreamedErrorCheck(deps: StreamedErrorCheckDeps): Promi
endColumn: next.column, endColumn: next.column,
} }
await ensureLazyRangeLoaded(deps.runtime, deps.lazyWorkbookRef, target, bounds, deps.setMessage) await ensureLazyRangeLoaded(deps.runtime, deps.lazyWorkbookRef, target, bounds, deps.setMessage)
if (stale()) return
target.getRange(next.row, next.column, 1, 1).activate() target.getRange(next.row, next.column, 1, 1).activate()
// Programmatic selection emits no SelectionChanged; refresh the echo. // Programmatic selection emits no SelectionChanged; refresh the echo.
deps.refreshSelectionEcho() deps.refreshSelectionEcho()
@@ -461,6 +461,12 @@ export const appStrings = defineStrings({
appPdfCanceled: 'PDF 导出已取消。', appPdfCanceled: 'PDF 导出已取消。',
appPdfExported: '已导出 {path}。', appPdfExported: '已导出 {path}。',
appPdfExportFailed: '无法导出 PDF。', appPdfExportFailed: '无法导出 PDF。',
appCsvExportNeedsFullLoad: 'CSV 导出需要工作簿完整加载——请等待加载完成。',
appCsvExportTooLarge: '工作表太大,无法导出 CSV。',
appCsvExportCanceled: 'CSV 导出已取消。',
appCsvExported: '已导出 {path}。',
appCsvExportedActiveOnly: 'CSV 只包含一张工作表——已导出当前工作表“{name}”到 {path}。',
appCsvExportFailed: '无法导出 CSV。',
appDemoNoSave: '演示模式的编辑只保存在内存——打开 XLSX 文件才能保存到磁盘。', appDemoNoSave: '演示模式的编辑只保存在内存——打开 XLSX 文件才能保存到磁盘。',
appFilterSnapshotFailed: '无法快照筛选状态。', appFilterSnapshotFailed: '无法快照筛选状态。',
appColorFiltersUnsaveable: '颜色筛选暂时无法保存为 XLSX——请先清除再保存。', appColorFiltersUnsaveable: '颜色筛选暂时无法保存为 XLSX——请先清除再保存。',
@@ -1744,6 +1750,14 @@ export const appStrings = defineStrings({
appPdfCanceled: 'PDF export canceled.', appPdfCanceled: 'PDF export canceled.',
appPdfExported: 'Exported {path}.', appPdfExported: 'Exported {path}.',
appPdfExportFailed: 'Unable to export the PDF.', appPdfExportFailed: 'Unable to export the PDF.',
appCsvExportNeedsFullLoad:
'CSV export needs the fully loaded workbook — wait for loading to finish.',
appCsvExportTooLarge: 'The sheet is too large to export as CSV.',
appCsvExportCanceled: 'CSV export canceled.',
appCsvExported: 'Exported {path}.',
appCsvExportedActiveOnly:
'CSV holds a single sheet — exported the active sheet "{name}" to {path}.',
appCsvExportFailed: 'Unable to export the CSV.',
appDemoNoSave: 'Demo edits stay in memory — open an XLSX file to save to disk.', appDemoNoSave: 'Demo edits stay in memory — open an XLSX file to save to disk.',
appFilterSnapshotFailed: 'Unable to snapshot the filters.', appFilterSnapshotFailed: 'Unable to snapshot the filters.',
appColorFiltersUnsaveable: appColorFiltersUnsaveable:
@@ -3074,6 +3088,14 @@ export const appStrings = defineStrings({
appPdfCanceled: 'PDF エクスポートをキャンセルしました。', appPdfCanceled: 'PDF エクスポートをキャンセルしました。',
appPdfExported: '{path} をエクスポートしました。', appPdfExported: '{path} をエクスポートしました。',
appPdfExportFailed: 'PDF をエクスポートできません。', appPdfExportFailed: 'PDF をエクスポートできません。',
appCsvExportNeedsFullLoad:
'CSV エクスポートにはブックの完全読み込みが必要です — 読み込みの完了をお待ちください。',
appCsvExportTooLarge: 'シートが大きすぎるため、CSV をエクスポートできません。',
appCsvExportCanceled: 'CSV エクスポートをキャンセルしました。',
appCsvExported: '{path} をエクスポートしました。',
appCsvExportedActiveOnly:
'CSV ファイルには 1 枚のシートしか含められません — アクティブなシート「{name}」を {path} にエクスポートしました。',
appCsvExportFailed: 'CSV をエクスポートできません。',
appDemoNoSave: appDemoNoSave:
'デモモードの編集はメモリ内にのみ保存されます — ディスクに保存するには XLSX ファイルを開いてください。', 'デモモードの編集はメモリ内にのみ保存されます — ディスクに保存するには XLSX ファイルを開いてください。',
appFilterSnapshotFailed: 'フィルターの状態をスナップショットできません。', appFilterSnapshotFailed: 'フィルターの状態をスナップショットできません。',
@@ -4397,6 +4419,14 @@ export const appStrings = defineStrings({
appPdfCanceled: 'PDF 내보내기를 취소했습니다.', appPdfCanceled: 'PDF 내보내기를 취소했습니다.',
appPdfExported: '{path}을(를) 내보냈습니다.', appPdfExported: '{path}을(를) 내보냈습니다.',
appPdfExportFailed: 'PDF를 내보낼 수 없습니다.', appPdfExportFailed: 'PDF를 내보낼 수 없습니다.',
appCsvExportNeedsFullLoad:
'CSV 내보내기에는 통합 문서 전체 로드가 필요합니다 — 로드가 완료될 때까지 기다리십시오.',
appCsvExportTooLarge: '시트가 너무 커서 CSV로 내보낼 수 없습니다.',
appCsvExportCanceled: 'CSV 내보내기를 취소했습니다.',
appCsvExported: '{path}을(를) 내보냈습니다.',
appCsvExportedActiveOnly:
'CSV는 시트 하나만 포함합니다 — 활성 시트 "{name}"을(를) {path}(으)로 내보냈습니다.',
appCsvExportFailed: 'CSV를 내보낼 수 없습니다.',
appDemoNoSave: appDemoNoSave:
'데모 모드의 편집은 메모리에만 저장됩니다 — 디스크에 저장하려면 XLSX 파일을 여십시오.', '데모 모드의 편집은 메모리에만 저장됩니다 — 디스크에 저장하려면 XLSX 파일을 여십시오.',
appFilterSnapshotFailed: '필터 상태의 스냅숏을 만들 수 없습니다.', appFilterSnapshotFailed: '필터 상태의 스냅숏을 만들 수 없습니다.',
@@ -5762,6 +5792,14 @@ export const appStrings = defineStrings({
appPdfCanceled: 'Export PDF annulé.', appPdfCanceled: 'Export PDF annulé.',
appPdfExported: '{path} exporté.', appPdfExported: '{path} exporté.',
appPdfExportFailed: "Impossible d'exporter le PDF.", appPdfExportFailed: "Impossible d'exporter le PDF.",
appCsvExportNeedsFullLoad:
"L'export CSV nécessite un classeur entièrement chargé — attendez la fin du chargement.",
appCsvExportTooLarge: 'La feuille est trop grande pour être exportée en CSV.',
appCsvExportCanceled: 'Export CSV annulé.',
appCsvExported: '{path} exporté.',
appCsvExportedActiveOnly:
"Les fichiers CSV ne contiennent qu'une seule feuille — la feuille active « {name} » a été exportée vers {path}.",
appCsvExportFailed: "Impossible d'exporter le CSV.",
appDemoNoSave: appDemoNoSave:
'Les modifications en mode démo restent en mémoire — ouvrez un fichier XLSX pour enregistrer sur le disque.', 'Les modifications en mode démo restent en mémoire — ouvrez un fichier XLSX pour enregistrer sur le disque.',
appFilterSnapshotFailed: 'Impossible de prendre un instantané des filtres.', appFilterSnapshotFailed: 'Impossible de prendre un instantané des filtres.',
@@ -7110,6 +7148,14 @@ export const appStrings = defineStrings({
appPdfCanceled: 'PDF-Export abgebrochen.', appPdfCanceled: 'PDF-Export abgebrochen.',
appPdfExported: '{path} exportiert.', appPdfExported: '{path} exportiert.',
appPdfExportFailed: 'PDF kann nicht exportiert werden.', appPdfExportFailed: 'PDF kann nicht exportiert werden.',
appCsvExportNeedsFullLoad:
'Der CSV-Export erfordert die vollständig geladene Arbeitsmappe — warten Sie, bis das Laden abgeschlossen ist.',
appCsvExportTooLarge: 'Das Blatt ist zu groß für den CSV-Export.',
appCsvExportCanceled: 'CSV-Export abgebrochen.',
appCsvExported: '{path} exportiert.',
appCsvExportedActiveOnly:
'CSV-Dateien enthalten nur ein Blatt — das aktive Blatt „{name}“ wurde nach {path} exportiert.',
appCsvExportFailed: 'CSV kann nicht exportiert werden.',
appDemoNoSave: appDemoNoSave:
'Demo-Bearbeitungen bleiben im Speicher — öffnen Sie eine XLSX-Datei, um auf die Festplatte zu speichern.', 'Demo-Bearbeitungen bleiben im Speicher — öffnen Sie eine XLSX-Datei, um auf die Festplatte zu speichern.',
appFilterSnapshotFailed: 'Momentaufnahme der Filter nicht möglich.', appFilterSnapshotFailed: 'Momentaufnahme der Filter nicht möglich.',
@@ -8452,6 +8498,14 @@ export const appStrings = defineStrings({
appPdfCanceled: 'Exportación a PDF cancelada.', appPdfCanceled: 'Exportación a PDF cancelada.',
appPdfExported: 'Se exportó {path}.', appPdfExported: 'Se exportó {path}.',
appPdfExportFailed: 'No se puede exportar el PDF.', appPdfExportFailed: 'No se puede exportar el PDF.',
appCsvExportNeedsFullLoad:
'La exportación a CSV requiere el libro completamente cargado — espere a que termine la carga.',
appCsvExportTooLarge: 'La hoja es demasiado grande para exportarla como CSV.',
appCsvExportCanceled: 'Exportación a CSV cancelada.',
appCsvExported: 'Se exportó {path}.',
appCsvExportedActiveOnly:
'Los archivos CSV solo contienen una hoja — se exportó la hoja activa «{name}» a {path}.',
appCsvExportFailed: 'No se puede exportar el CSV.',
appDemoNoSave: appDemoNoSave:
'Las ediciones de demostración permanecen en memoria — abra un archivo XLSX para guardar en disco.', 'Las ediciones de demostración permanecen en memoria — abra un archivo XLSX para guardar en disco.',
appFilterSnapshotFailed: 'No se puede tomar una instantánea de los filtros.', appFilterSnapshotFailed: 'No se puede tomar una instantánea de los filtros.',
@@ -9735,6 +9789,13 @@ export const appStrings = defineStrings({
appPdfCanceled: 'ยกเลิกการส่งออก PDF แล้ว', appPdfCanceled: 'ยกเลิกการส่งออก PDF แล้ว',
appPdfExported: 'ส่งออก {path} แล้ว', appPdfExported: 'ส่งออก {path} แล้ว',
appPdfExportFailed: 'ส่งออก PDF ไม่ได้', appPdfExportFailed: 'ส่งออก PDF ไม่ได้',
appCsvExportNeedsFullLoad: 'การส่งออก CSV ต้องรอให้เวิร์กบุ๊กโหลดเต็มก่อน — รอให้โหลดเสร็จ',
appCsvExportTooLarge: 'ชีตใหญ่เกินไป ส่งออกเป็น CSV ไม่ได้',
appCsvExportCanceled: 'ยกเลิกการส่งออก CSV แล้ว',
appCsvExported: 'ส่งออก {path} แล้ว',
appCsvExportedActiveOnly:
'ไฟล์ CSV มีได้เพียงชีตเดียว — ส่งออกชีตที่ใช้งานอยู่ “{name}” ไปยัง {path} แล้ว',
appCsvExportFailed: 'ส่งออก CSV ไม่ได้',
appDemoNoSave: appDemoNoSave:
'การแก้ไขในโหมดสาธิตอยู่ในหน่วยความจำเท่านั้น — เปิดไฟล์ XLSX เพื่อบันทึกลงดิสก์', 'การแก้ไขในโหมดสาธิตอยู่ในหน่วยความจำเท่านั้น — เปิดไฟล์ XLSX เพื่อบันทึกลงดิสก์',
appFilterSnapshotFailed: 'บันทึกภาพรวมสถานะตัวกรองไม่ได้', appFilterSnapshotFailed: 'บันทึกภาพรวมสถานะตัวกรองไม่ได้',
@@ -11023,6 +11084,14 @@ export const appStrings = defineStrings({
appPdfCanceled: 'Ekspor PDF dibatalkan.', appPdfCanceled: 'Ekspor PDF dibatalkan.',
appPdfExported: '{path} diekspor.', appPdfExported: '{path} diekspor.',
appPdfExportFailed: 'Tidak dapat mengekspor PDF.', appPdfExportFailed: 'Tidak dapat mengekspor PDF.',
appCsvExportNeedsFullLoad:
'Ekspor CSV memerlukan buku kerja termuat penuh — tunggu pemuatan selesai.',
appCsvExportTooLarge: 'Lembar terlalu besar untuk diekspor sebagai CSV.',
appCsvExportCanceled: 'Ekspor CSV dibatalkan.',
appCsvExported: '{path} diekspor.',
appCsvExportedActiveOnly:
'File CSV hanya memuat satu lembar — lembar aktif “{name}” diekspor ke {path}.',
appCsvExportFailed: 'Tidak dapat mengekspor CSV.',
appDemoNoSave: 'Pengeditan demo tetap di memori — buka file XLSX untuk menyimpan ke disk.', appDemoNoSave: 'Pengeditan demo tetap di memori — buka file XLSX untuk menyimpan ke disk.',
appFilterSnapshotFailed: 'Tidak dapat mengambil cuplikan status filter.', appFilterSnapshotFailed: 'Tidak dapat mengambil cuplikan status filter.',
appColorFiltersUnsaveable: appColorFiltersUnsaveable:
@@ -12337,6 +12406,14 @@ export const appStrings = defineStrings({
appPdfCanceled: 'Экспорт в PDF отменён.', appPdfCanceled: 'Экспорт в PDF отменён.',
appPdfExported: 'Экспортировано: {path}.', appPdfExported: 'Экспортировано: {path}.',
appPdfExportFailed: 'Не удаётся экспортировать PDF.', appPdfExportFailed: 'Не удаётся экспортировать PDF.',
appCsvExportNeedsFullLoad:
'Экспорт в CSV требует полностью загруженной книги — дождитесь завершения загрузки.',
appCsvExportTooLarge: 'Лист слишком большой для экспорта в CSV.',
appCsvExportCanceled: 'Экспорт в CSV отменён.',
appCsvExported: 'Экспортировано: {path}.',
appCsvExportedActiveOnly:
'Файлы CSV содержат только один лист — активный лист «{name}» экспортирован в {path}.',
appCsvExportFailed: 'Не удаётся экспортировать CSV.',
appDemoNoSave: appDemoNoSave:
'Изменения в демо-режиме остаются в памяти — откройте файл XLSX, чтобы сохранить на диск.', 'Изменения в демо-режиме остаются в памяти — откройте файл XLSX, чтобы сохранить на диск.',
appFilterSnapshotFailed: 'Не удаётся сделать снимок состояния фильтров.', appFilterSnapshotFailed: 'Не удаётся сделать снимок состояния фильтров.',
@@ -13621,6 +13698,13 @@ export const appStrings = defineStrings({
appPdfCanceled: 'أُلغي تصدير PDF.', appPdfCanceled: 'أُلغي تصدير PDF.',
appPdfExported: 'تم التصدير: {path}.', appPdfExported: 'تم التصدير: {path}.',
appPdfExportFailed: 'يتعذر تصدير PDF.', appPdfExportFailed: 'يتعذر تصدير PDF.',
appCsvExportNeedsFullLoad: 'يتطلب تصدير CSV مصنفًا محمّلاً بالكامل — انتظر حتى ينتهي التحميل.',
appCsvExportTooLarge: 'الورقة كبيرة جدًا ولا يمكن تصديرها بتنسيق CSV.',
appCsvExportCanceled: 'أُلغي تصدير CSV.',
appCsvExported: 'تم التصدير: {path}.',
appCsvExportedActiveOnly:
'ملفات CSV تحتوي على ورقة واحدة فقط — تم تصدير الورقة النشطة «{name}» إلى {path}.',
appCsvExportFailed: 'يتعذر تصدير CSV.',
appDemoNoSave: 'تبقى تعديلات الوضع التجريبي في الذاكرة — افتح ملف XLSX للحفظ على القرص.', appDemoNoSave: 'تبقى تعديلات الوضع التجريبي في الذاكرة — افتح ملف XLSX للحفظ على القرص.',
appFilterSnapshotFailed: 'يتعذر أخذ لقطة لحالة عوامل التصفية.', appFilterSnapshotFailed: 'يتعذر أخذ لقطة لحالة عوامل التصفية.',
appColorFiltersUnsaveable: appColorFiltersUnsaveable:
@@ -14941,6 +15025,14 @@ export const appStrings = defineStrings({
appPdfCanceled: 'Exportação de PDF cancelada.', appPdfCanceled: 'Exportação de PDF cancelada.',
appPdfExported: '{path} exportado.', appPdfExported: '{path} exportado.',
appPdfExportFailed: 'Não foi possível exportar o PDF.', appPdfExportFailed: 'Não foi possível exportar o PDF.',
appCsvExportNeedsFullLoad:
'A exportação de CSV requer a pasta de trabalho totalmente carregada — aguarde o carregamento terminar.',
appCsvExportTooLarge: 'A planilha é grande demais para exportar como CSV.',
appCsvExportCanceled: 'Exportação de CSV cancelada.',
appCsvExported: '{path} exportado.',
appCsvExportedActiveOnly:
'Arquivos CSV contêm apenas uma planilha — a planilha ativa “{name}” foi exportada para {path}.',
appCsvExportFailed: 'Não foi possível exportar o CSV.',
appDemoNoSave: appDemoNoSave:
'Edições de demonstração ficam na memória — abra um arquivo XLSX para salvar no disco.', 'Edições de demonstração ficam na memória — abra um arquivo XLSX para salvar no disco.',
appFilterSnapshotFailed: 'Não foi possível capturar o estado dos filtros.', appFilterSnapshotFailed: 'Não foi possível capturar o estado dos filtros.',
@@ -16272,6 +16364,14 @@ export const appStrings = defineStrings({
appPdfCanceled: 'Esportazione PDF annullata.', appPdfCanceled: 'Esportazione PDF annullata.',
appPdfExported: '{path} esportato.', appPdfExported: '{path} esportato.',
appPdfExportFailed: 'Impossibile esportare il PDF.', appPdfExportFailed: 'Impossibile esportare il PDF.',
appCsvExportNeedsFullLoad:
"L'esportazione in CSV richiede la cartella di lavoro completamente caricata — attendi la fine del caricamento.",
appCsvExportTooLarge: 'Il foglio è troppo grande per essere esportato come CSV.',
appCsvExportCanceled: 'Esportazione CSV annullata.',
appCsvExported: '{path} esportato.',
appCsvExportedActiveOnly:
'I file CSV contengono un solo foglio — il foglio attivo “{name}” è stato esportato in {path}.',
appCsvExportFailed: 'Impossibile esportare il CSV.',
appDemoNoSave: 'Le modifiche demo restano in memoria — apri un file XLSX per salvare su disco.', appDemoNoSave: 'Le modifiche demo restano in memoria — apri un file XLSX per salvare su disco.',
appFilterSnapshotFailed: 'Impossibile acquisire lo stato dei filtri.', appFilterSnapshotFailed: 'Impossibile acquisire lo stato dei filtri.',
appColorFiltersUnsaveable: appColorFiltersUnsaveable:
@@ -17599,6 +17699,14 @@ export const appStrings = defineStrings({
appPdfCanceled: 'Anulowano eksport do PDF.', appPdfCanceled: 'Anulowano eksport do PDF.',
appPdfExported: 'Wyeksportowano {path}.', appPdfExported: 'Wyeksportowano {path}.',
appPdfExportFailed: 'Nie można wyeksportować pliku PDF.', appPdfExportFailed: 'Nie można wyeksportować pliku PDF.',
appCsvExportNeedsFullLoad:
'Eksport do CSV wymaga w pełni załadowanego skoroszytu — poczekaj na zakończenie ładowania.',
appCsvExportTooLarge: 'Arkusz jest za duży, aby wyeksportować go do CSV.',
appCsvExportCanceled: 'Anulowano eksport do CSV.',
appCsvExported: 'Wyeksportowano {path}.',
appCsvExportedActiveOnly:
'Pliki CSV zawierają tylko jeden arkusz — aktywny arkusz „{name}” wyeksportowano do {path}.',
appCsvExportFailed: 'Nie można wyeksportować pliku CSV.',
appDemoNoSave: appDemoNoSave:
'Zmiany w trybie demo pozostają w pamięci — otwórz plik XLSX, aby zapisać na dysku.', 'Zmiany w trybie demo pozostają w pamięci — otwórz plik XLSX, aby zapisać na dysku.',
appFilterSnapshotFailed: 'Nie można wykonać migawki stanu filtrów.', appFilterSnapshotFailed: 'Nie można wykonać migawki stanu filtrów.',
@@ -18934,6 +19042,14 @@ export const appStrings = defineStrings({
appPdfCanceled: 'PDF-export geannuleerd.', appPdfCanceled: 'PDF-export geannuleerd.',
appPdfExported: '{path} geëxporteerd.', appPdfExported: '{path} geëxporteerd.',
appPdfExportFailed: 'Kan de PDF niet exporteren.', appPdfExportFailed: 'Kan de PDF niet exporteren.',
appCsvExportNeedsFullLoad:
'CSV-export vereist een volledig geladen werkmap — wacht tot het laden is voltooid.',
appCsvExportTooLarge: 'Het blad is te groot om als CSV te exporteren.',
appCsvExportCanceled: 'CSV-export geannuleerd.',
appCsvExported: '{path} geëxporteerd.',
appCsvExportedActiveOnly:
'CSV-bestanden bevatten slechts één blad — het actieve blad “{name}” is geëxporteerd naar {path}.',
appCsvExportFailed: 'Kan de CSV niet exporteren.',
appDemoNoSave: appDemoNoSave:
'Demobewerkingen blijven in het geheugen — open een XLSX-bestand om op schijf op te slaan.', 'Demobewerkingen blijven in het geheugen — open een XLSX-bestand om op schijf op te slaan.',
appFilterSnapshotFailed: 'Kan geen momentopname van de filters maken.', appFilterSnapshotFailed: 'Kan geen momentopname van de filters maken.',
@@ -20239,6 +20355,14 @@ export const appStrings = defineStrings({
appPdfCanceled: 'Eksport PDF dibatalkan.', appPdfCanceled: 'Eksport PDF dibatalkan.',
appPdfExported: '{path} dieksport.', appPdfExported: '{path} dieksport.',
appPdfExportFailed: 'Tidak dapat mengeksport PDF.', appPdfExportFailed: 'Tidak dapat mengeksport PDF.',
appCsvExportNeedsFullLoad:
'Eksport CSV memerlukan buku kerja dimuatkan sepenuhnya — tunggu pemuatan selesai.',
appCsvExportTooLarge: 'Helaian terlalu besar untuk dieksport sebagai CSV.',
appCsvExportCanceled: 'Eksport CSV dibatalkan.',
appCsvExported: '{path} dieksport.',
appCsvExportedActiveOnly:
'Fail CSV hanya mengandungi satu helaian — helaian aktif “{name}” dieksport ke {path}.',
appCsvExportFailed: 'Tidak dapat mengeksport CSV.',
appDemoNoSave: 'Suntingan demo kekal dalam memori — buka fail XLSX untuk menyimpan ke cakera.', appDemoNoSave: 'Suntingan demo kekal dalam memori — buka fail XLSX untuk menyimpan ke cakera.',
appFilterSnapshotFailed: 'Tidak dapat mengambil syot kilat penapis.', appFilterSnapshotFailed: 'Tidak dapat mengambil syot kilat penapis.',
appColorFiltersUnsaveable: appColorFiltersUnsaveable:
@@ -21503,6 +21627,13 @@ export const appStrings = defineStrings({
appPdfCanceled: 'ייצוא ה-PDF בוטל.', appPdfCanceled: 'ייצוא ה-PDF בוטל.',
appPdfExported: '{path} יוצא.', appPdfExported: '{path} יוצא.',
appPdfExportFailed: 'לא ניתן לייצא את ה-PDF.', appPdfExportFailed: 'לא ניתן לייצא את ה-PDF.',
appCsvExportNeedsFullLoad: 'ייצוא CSV דורש חוברת עבודה טעונה במלואה — המתן לסיום הטעינה.',
appCsvExportTooLarge: 'הגיליון גדול מדי לייצוא כ-CSV.',
appCsvExportCanceled: 'ייצוא ה-CSV בוטל.',
appCsvExported: '{path} יוצא.',
appCsvExportedActiveOnly:
'קובצי CSV מכילים גיליון אחד בלבד — הגיליון הפעיל "{name}" יוצא אל {path}.',
appCsvExportFailed: 'לא ניתן לייצא את ה-CSV.',
appDemoNoSave: 'עריכות הדגמה נשארות בזיכרון — פתח קובץ XLSX כדי לשמור לדיסק.', appDemoNoSave: 'עריכות הדגמה נשארות בזיכרון — פתח קובץ XLSX כדי לשמור לדיסק.',
appFilterSnapshotFailed: 'לא ניתן לצלם את מצב המסננים.', appFilterSnapshotFailed: 'לא ניתן לצלם את מצב המסננים.',
appColorFiltersUnsaveable: 'מסנני צבע אינם ניתנים לשמירה כ-XLSX עדיין — נקה אותם לפני השמירה.', appColorFiltersUnsaveable: 'מסנני צבע אינם ניתנים לשמירה כ-XLSX עדיין — נקה אותם לפני השמירה.',
@@ -22789,6 +22920,14 @@ export const appStrings = defineStrings({
appPdfCanceled: 'PDF निर्यात रद्द किया गया।', appPdfCanceled: 'PDF निर्यात रद्द किया गया।',
appPdfExported: '{path} निर्यात किया गया।', appPdfExported: '{path} निर्यात किया गया।',
appPdfExportFailed: 'PDF निर्यात नहीं किया जा सका।', appPdfExportFailed: 'PDF निर्यात नहीं किया जा सका।',
appCsvExportNeedsFullLoad:
'CSV निर्यात के लिए पूरी तरह लोड की गई कार्यपुस्तिका चाहिए — लोडिंग पूरी होने तक प्रतीक्षा करें।',
appCsvExportTooLarge: 'शीट बहुत बड़ी है, CSV के रूप में निर्यात नहीं की जा सकती।',
appCsvExportCanceled: 'CSV निर्यात रद्द किया गया।',
appCsvExported: '{path} निर्यात किया गया।',
appCsvExportedActiveOnly:
'CSV फ़ाइलों में केवल एक शीट होती है — सक्रिय शीट “{name}” को {path} पर निर्यात किया गया।',
appCsvExportFailed: 'CSV निर्यात नहीं किया जा सका।',
appDemoNoSave: 'डेमो संपादन स्मृति में रहते हैं — डिस्क पर सहेजने के लिए XLSX फ़ाइल खोलें।', appDemoNoSave: 'डेमो संपादन स्मृति में रहते हैं — डिस्क पर सहेजने के लिए XLSX फ़ाइल खोलें।',
appFilterSnapshotFailed: 'फ़िल्टर की स्थिति का स्नैपशॉट नहीं लिया जा सका।', appFilterSnapshotFailed: 'फ़िल्टर की स्थिति का स्नैपशॉट नहीं लिया जा सका।',
appColorFiltersUnsaveable: appColorFiltersUnsaveable:
@@ -24029,6 +24168,12 @@ export const appStrings = defineStrings({
appPdfCanceled: 'PDF 匯出已取消。', appPdfCanceled: 'PDF 匯出已取消。',
appPdfExported: '已匯出 {path}。', appPdfExported: '已匯出 {path}。',
appPdfExportFailed: '無法匯出 PDF。', appPdfExportFailed: '無法匯出 PDF。',
appCsvExportNeedsFullLoad: 'CSV 匯出需要活頁簿完整載入——請等待載入完成。',
appCsvExportTooLarge: '工作表太大,無法匯出 CSV。',
appCsvExportCanceled: 'CSV 匯出已取消。',
appCsvExported: '已匯出 {path}。',
appCsvExportedActiveOnly: 'CSV 只包含一張工作表——已匯出目前工作表「{name}」到 {path}。',
appCsvExportFailed: '無法匯出 CSV。',
appDemoNoSave: '示範模式的編輯只保存在記憶體——開啟 XLSX 檔案才能儲存到磁碟。', appDemoNoSave: '示範模式的編輯只保存在記憶體——開啟 XLSX 檔案才能儲存到磁碟。',
appFilterSnapshotFailed: '無法擷取篩選狀態快照。', appFilterSnapshotFailed: '無法擷取篩選狀態快照。',
appColorFiltersUnsaveable: '色彩篩選暫時無法儲存為 XLSX——請先清除再儲存。', appColorFiltersUnsaveable: '色彩篩選暫時無法儲存為 XLSX——請先清除再儲存。',
+20 -8
View File
@@ -471,6 +471,7 @@ export class LazyExtendedFindModel extends FindModel {
/** Extras that are still outside the (evolving) loaded window. */ /** Extras that are still outside the (evolving) loaded window. */
private currentExtras(): LazyCellMatch[] { private currentExtras(): LazyCellMatch[] {
const isRowHidden = this.rowHiddenTest()
return this.extras.filter((match) => { return this.extras.filter((match) => {
if ( if (
coveredByWindow( coveredByWindow(
@@ -485,22 +486,33 @@ export class LazyExtendedFindModel extends FindModel {
// The in-memory scan skips rows hidden by an active filter; hold // The in-memory scan skips rows hidden by an active filter; hold
// out-of-window hits to the same visibility rules. Fails open when the // out-of-window hits to the same visibility rules. Fails open when the
// filter state is not reachable (sheet gone mid-session). // filter state is not reachable (sheet gone mid-session).
return !this.isRowHidden(match.range.subUnitId, match.range.range.startRow) return !isRowHidden(match.range.subUnitId, match.range.range.startRow)
}) })
} }
/// Mirrors the built-in scan's worksheet.getRowFiltered check for cells /// Mirrors the built-in scan's worksheet.getRowFiltered check for cells
/// that never streamed into Univer's matrix: the filter model lives on the /// that never streamed into Univer's matrix: the filter model lives on the
/// workbook instance, not the grid, so it answers regardless of loading. /// workbook instance, not the grid, so it answers regardless of loading.
private isRowHidden(subUnitId: string, row: number): boolean { /// The workbook resolves once per call — currentExtras runs on every
/// match-list read and extras can number in the thousands.
private rowHiddenTest(): (subUnitId: string, row: number) => boolean {
let resolved: Workbook | null = null
try { try {
const workbook = this.deps.runtime.univer resolved =
.__getInjector() this.deps.runtime.univer
.get(IUniverInstanceService) .__getInjector()
.getUnit<Workbook>(this.unitId) .get(IUniverInstanceService)
return workbook?.getSheetBySheetId(subUnitId)?.getRowFiltered(row) === true .getUnit<Workbook>(this.unitId) ?? null
} catch { } catch {
return false resolved = null
}
if (!resolved) return () => false
return (subUnitId, row) => {
try {
return resolved.getSheetBySheetId(subUnitId)?.getRowFiltered(row) === true
} catch {
return false
}
} }
} }
@@ -20,6 +20,7 @@ import { effectivePageBreaks } from './page-break-preview'
import { COLOR_SCHEMES, FONT_SCHEMES, rethemeStyles, THEME_PRESETS } from './themes' import { COLOR_SCHEMES, FONT_SCHEMES, rethemeStyles, THEME_PRESETS } from './themes'
import { loadVisibleRange } from './univer-sync' import { loadVisibleRange } from './univer-sync'
import { buildSheetPrintPayload, type PrintWorksheet } from './print-html' import { buildSheetPrintPayload, type PrintWorksheet } from './print-html'
import { resolveEffectivePageSetup } from './print-settings'
import type { LazyWorkbookState, UniverRuntime } from './univer-state' import type { LazyWorkbookState, UniverRuntime } from './univer-state'
const PAPER_NAMES: Record<string, string> = { const PAPER_NAMES: Record<string, string> = {
@@ -300,11 +301,23 @@ export async function handleExportPdf(ctx: PageLayoutContext): Promise<void> {
return return
} }
try { try {
const pageSetup = state?.editJournal.pageSetup.get(worksheet.getSheetId()) ?? {} const sheetId = worksheet.getSheetId()
const journal = state?.editJournal.pageSetup.get(sheetId) ?? {}
const fileSetup = state?.sheetFilePageSetups.get(sheetId) ?? null
const fileSheet = state?.file.sheets.find((sheet) => sheet.id === sheetId)
const setup = resolveEffectivePageSetup(
journal,
fileSetup,
{
...(fileSheet?.printArea === undefined ? {} : { printArea: fileSheet.printArea }),
...(fileSheet?.printTitles === undefined ? {} : { printTitles: fileSheet.printTitles }),
},
state?.editJournal.structuralOps.get(sheetId) ?? [],
)
const baseName = (state?.file.name ?? 'Book1').replace(/\.[^.]+$/, '') const baseName = (state?.file.name ?? 'Book1').replace(/\.[^.]+$/, '')
const payload = buildSheetPrintPayload( const payload = buildSheetPrintPayload(
worksheet as unknown as PrintWorksheet, worksheet as unknown as PrintWorksheet,
pageSetup, setup,
`${baseName}.pdf`, `${baseName}.pdf`,
worksheet.getSheetName(), worksheet.getSheetName(),
) )
+14 -7
View File
@@ -13,7 +13,12 @@ import type { OoXmlPivotConfig, PivotEditSeed, PivotField } from './PivotDialog'
import type { SlicerMember, SlicerUiState } from './SlicerPanel' import type { SlicerMember, SlicerUiState } from './SlicerPanel'
import type { TimelineUiState } from './TimelinePanel' import type { TimelineUiState } from './TimelinePanel'
import type { LazyWorkbookState, UniverRuntime } from './univer-state' import type { LazyWorkbookState, UniverRuntime } from './univer-state'
import { applyAiPivotAdd, applyGrownPivotOutput, pivotConfigToOpParts } from './workbook-ops' import {
applyAiPivotAdd,
applyGrownPivotOutput,
pivotConfigToOpParts,
readPivotSourceGrid,
} from './workbook-ops'
/// A3 editing of an existing pivot: context locked when the dialog opens, used /// A3 editing of an existing pivot: context locked when the dialog opens, used
/// on Apply. /// on Apply.
@@ -123,9 +128,10 @@ export function refreshPivotTables(ctx: PivotActionContext, sheetId: string): nu
if (!sourceSheet) { if (!sourceSheet) {
throw new Error(t('appPivotSourceSheetMissing', { name: definition.sourceSheet })) throw new Error(t('appPivotSourceSheetMissing', { name: definition.sourceSheet }))
} }
const sourceValues = sourceSheet.getRange(definition.sourceRef).getValues() as ( const sourceValues = readPivotSourceGrid(
string | number | boolean | null | undefined sourceSheet.getRange(definition.sourceRef),
)[][] ctx.lazyWorkbookRef.current?.file.date1904 === true,
)
// (3) Automatic layout growth: when source data has new categories outside // (3) Automatic layout growth: when source data has new categories outside
// the cache, first fold the new members into the layout (in memory), then // the cache, first fold the new members into the layout (in memory), then
// recompute; without new categories, take the existing data-area-only // recompute; without new categories, take the existing data-area-only
@@ -560,9 +566,10 @@ export function applySlicerSelection(
.find((sheet) => sheet.getSheetName() === definition.sourceSheet) .find((sheet) => sheet.getSheetName() === definition.sourceSheet)
if (!sourceSheet) return t('appPivotSourceSheetMissing', { name: definition.sourceSheet }) if (!sourceSheet) return t('appPivotSourceSheetMissing', { name: definition.sourceSheet })
try { try {
const sourceValues = sourceSheet.getRange(definition.sourceRef).getValues() as ( const sourceValues = readPivotSourceGrid(
string | number | boolean | null | undefined sourceSheet.getRange(definition.sourceRef),
)[][] ctx.lazyWorkbookRef.current?.file.date1904 === true,
)
const next = applyPivotSlicer(definition, sourceValues, slicer.field, selectedMembers) const next = applyPivotSlicer(definition, sourceValues, slicer.field, selectedMembers)
if (next === definition) return null if (next === definition) return null
const { data } = recomputePivotData(next, sourceValues) const { data } = recomputePivotData(next, sourceValues)
+182 -137
View File
@@ -1,13 +1,14 @@
/// Lays the active sheet out as print HTML from the live Univer model — /// Lays the active sheet out as print HTML from the live Univer model —
/// display strings (number formats applied), cell styles, merges, and the /// display strings (number formats applied), cell styles, merges, and the
/// sheet's Page Layout settings (print area, repeated title rows, gridlines, /// sheet's effective page setup (print areas, repeated title rows, gridlines,
/// headings). The main process turns the HTML into a PDF. /// headings, header/footer). The main process turns the HTML into a PDF.
import { htmlLang, type Lang } from '@genoffice/i18n' import { htmlLang, type Lang } from '@genoffice/i18n'
import { columnIndex, columnLabel } from '../domain/cell-address' import { columnIndex, columnLabel } from '../domain/cell-address'
import type { WorkbookExportPdfRequest } from '../shared/desktop-api' import type { WorkbookExportPdfRequest } from '../shared/desktop-api'
import type { HeaderFooterParts, PageSetupJournalState } from './edit-journal' import type { HeaderFooterParts } from './edit-journal'
import type { EffectivePageSetup, PrintMargins } from './print-settings'
import { getLang, t } from './i18n/locale' import { getLang, t } from './i18n/locale'
export class PrintError extends Error {} export class PrintError extends Error {}
@@ -71,13 +72,6 @@ interface PrintCellStyle {
> | null > | null
} }
/// Inches, mirroring the gateway's Margins presets.
const MARGIN_PRESETS = {
normal: { left: 0.7, right: 0.7, top: 0.75, bottom: 0.75 },
wide: { left: 1, right: 1, top: 1, bottom: 1 },
narrow: { left: 0.25, right: 0.25, top: 0.75, bottom: 0.75 },
} as const
/// OOXML paper-size code → Electron pageSize (custom sizes in inches). /// OOXML paper-size code → Electron pageSize (custom sizes in inches).
const PAPER_SIZES: Record<number, WorkbookExportPdfRequest['pageSize']> = { const PAPER_SIZES: Record<number, WorkbookExportPdfRequest['pageSize']> = {
1: 'Letter', 1: 'Letter',
@@ -100,185 +94,236 @@ const PAPER_WIDTH_INCHES: Record<string, number> = {
export function buildSheetPrintPayload( export function buildSheetPrintPayload(
worksheet: PrintWorksheet, worksheet: PrintWorksheet,
pageSetup: PageSetupJournalState, setup: EffectivePageSetup,
fileName: string, fileName: string,
sheetName: string, sheetName: string,
): WorkbookExportPdfRequest { ): WorkbookExportPdfRequest {
const area = pageSetup.printArea ? parseArea(pageSetup.printArea) : usedArea(worksheet) const areas =
const rows = area.endRow - area.startRow + 1 setup.printAreas.length > 0 ? setup.printAreas.map(parseArea) : [usedArea(worksheet)]
const columns = area.endColumn - area.startColumn + 1 const titles = setup.printTitles ? parseTitleRows(setup.printTitles) : null
if (rows < 1 || columns < 1) throw new PrintError(t('appPrintNothing')) const headings = setup.printHeadings
if (rows * columns > MAX_PRINT_CELLS) { const gridlines = setup.printGridlines
throw new PrintError(t('appPrintTooLarge'))
}
const titles = pageSetup.printTitles ? parseTitleRows(pageSetup.printTitles) : null
const grid = worksheet.getRange(area.startRow, area.startColumn, rows, columns)
const display = grid.getDisplayValues()
const raw = grid.getValues()
const merges = mergeMaps(worksheet, area)
const headings = pageSetup.printHeadings === true
const gridlines = pageSetup.printGridlines === true
const columnWidthsPt = Array.from(
{ length: columns },
(_, offset) => worksheet.getColumnWidth(area.startColumn + offset) * 0.75,
)
const rowHeaderPt = headings ? 24 : 0 const rowHeaderPt = headings ? 24 : 0
const bodyRow = (row: number): string => { let totalCells = 0
const cells: string[] = [] for (const area of areas) {
if (headings) { const rows = area.endRow - area.startRow + 1
cells.push(`<th class="hd">${row + 1}</th>`) const columns = area.endColumn - area.startColumn + 1
} if (rows < 1 || columns < 1) throw new PrintError(t('appPrintNothing'))
for (let column = area.startColumn; column <= area.endColumn; column += 1) { totalCells += rows * columns
const key = `${row}:${column}`
if (merges.covered.has(key)) continue
const anchor = merges.anchors.get(key)
const span = anchor
? ` rowspan="${Math.min(anchor.rows, area.endRow - row + 1)}"` +
` colspan="${Math.min(anchor.columns, area.endColumn - column + 1)}"`
: ''
const inArea = row >= area.startRow && row <= area.endRow
const text = inArea
? (display[row - area.startRow]?.[column - area.startColumn] ?? '')
: cellDisplay(worksheet, row, column)
const rawValue = inArea ? raw[row - area.startRow]?.[column - area.startColumn] : undefined
const style = worksheet.getRange(row, column).getCellStyleData()
cells.push(
`<td${span} style="${cellCss(style, rawValue, gridlines)}">${escapeHtml(text)}</td>`,
)
}
const heightPt = Math.max(worksheet.getRowHeight(row) * 0.75, 10)
return `<tr style="height:${round(heightPt)}pt">${cells.join('')}</tr>`
} }
if (totalCells > MAX_PRINT_CELLS) throw new PrintError(t('appPrintTooLarge'))
// Session header/footer ride the table's thead/tfoot, which Chromium let maxContentWidthPt = 0
// repeats at the top/bottom of every printed page. const tables: string[] = []
const totalColumns = columns + (headings ? 1 : 0) for (const area of areas) {
const resolveCodes = (text: string): string => const rows = area.endRow - area.startRow + 1
resolveHeaderFooterText(text, fileName.replace(/\.pdf$/, ''), sheetName, new Date()) const columns = area.endColumn - area.startColumn + 1
const headerRow = headerFooterRow(pageSetup.header, 'th', totalColumns, resolveCodes) const grid = worksheet.getRange(area.startRow, area.startColumn, rows, columns)
const footerRow = headerFooterRow(pageSetup.footer, 'td', totalColumns, resolveCodes) const display = grid.getDisplayValues()
const raw = grid.getValues()
const headParts: string[] = [] const merges = mergeMaps(worksheet, area)
if (headerRow !== '') headParts.push(headerRow) const columnWidthsPt = Array.from(
if (headings) {
const letters = Array.from(
{ length: columns }, { length: columns },
(_, offset) => `<th class="hd">${columnLabel(area.startColumn + offset)}</th>`, (_, offset) => worksheet.getColumnWidth(area.startColumn + offset) * 0.75,
)
maxContentWidthPt = Math.max(
maxContentWidthPt,
rowHeaderPt + columnWidthsPt.reduce((total, width) => total + width, 0),
)
const bodyRow = (row: number): string => {
const cells: string[] = []
if (headings) {
cells.push(`<th class="hd">${row + 1}</th>`)
}
for (let column = area.startColumn; column <= area.endColumn; column += 1) {
const key = `${row}:${column}`
if (merges.covered.has(key)) continue
const anchor = merges.anchors.get(key)
const span = anchor
? ` rowspan="${Math.min(anchor.rows, area.endRow - row + 1)}"` +
` colspan="${Math.min(anchor.columns, area.endColumn - column + 1)}"`
: ''
const inArea = row >= area.startRow && row <= area.endRow
const text = inArea
? (display[row - area.startRow]?.[column - area.startColumn] ?? '')
: cellDisplay(worksheet, row, column)
const rawValue = inArea ? raw[row - area.startRow]?.[column - area.startColumn] : undefined
const style = worksheet.getRange(row, column).getCellStyleData()
cells.push(
`<td${span} style="${cellCss(style, rawValue, gridlines)}">${escapeHtml(text)}</td>`,
)
}
const heightPt = Math.max(worksheet.getRowHeight(row) * 0.75, 10)
return `<tr style="height:${round(heightPt)}pt">${cells.join('')}</tr>`
}
const headParts: string[] = []
if (headings) {
const letters = Array.from(
{ length: columns },
(_, offset) => `<th class="hd">${columnLabel(area.startColumn + offset)}</th>`,
)
headParts.push(`<tr><th class="hd"></th>${letters.join('')}</tr>`)
}
if (titles) {
for (let row = titles.start; row <= titles.end; row += 1) headParts.push(bodyRow(row))
}
const bodyParts: string[] = []
for (let row = area.startRow; row <= area.endRow; row += 1) {
// Title rows already repeat via the table header.
if (titles && row >= titles.start && row <= titles.end) continue
bodyParts.push(bodyRow(row))
}
const colgroup = `<colgroup>${headings ? `<col style="width:${rowHeaderPt}pt">` : ''}${columnWidthsPt
.map((width) => `<col style="width:${round(width)}pt">`)
.join('')}</colgroup>`
tables.push(
`<table>${colgroup}<thead>${headParts.join('')}</thead><tbody>${bodyParts.join('')}</tbody></table>`,
) )
headParts.push(`<tr>${headings ? '<th class="hd"></th>' : ''}${letters.join('')}</tr>`)
}
if (titles) {
for (let row = titles.start; row <= titles.end; row += 1) headParts.push(bodyRow(row))
} }
const bodyParts: string[] = []
for (let row = area.startRow; row <= area.endRow; row += 1) {
// Title rows already repeat via the table header.
if (titles && row >= titles.start && row <= titles.end) continue
bodyParts.push(bodyRow(row))
}
const colgroup = `<colgroup>${headings ? `<col style="width:${rowHeaderPt}pt">` : ''}${columnWidthsPt
.map((width) => `<col style="width:${round(width)}pt">`)
.join('')}</colgroup>`
const html = const html =
`<!doctype html><html lang="${htmlLang(getLang())}"><head><meta charset="utf-8"><style> `<!doctype html><html lang="${htmlLang(getLang())}"><head><meta charset="utf-8"><style>
* { box-sizing: border-box; } * { box-sizing: border-box; }
body { margin: 0; font-family: Calibri, 'Helvetica Neue', Arial, ${printCjkFonts(getLang())}, sans-serif; } body { margin: 0; font-family: Calibri, 'Helvetica Neue', Arial, ${printCjkFonts(getLang())}, sans-serif; }
table { border-collapse: collapse; table-layout: fixed; } table { border-collapse: collapse; table-layout: fixed; }
table + table { break-before: page; }
thead { display: table-header-group; } thead { display: table-header-group; }
tfoot { display: table-footer-group; }
td, th { overflow: hidden; padding: 1pt 3pt; font-size: 11pt; vertical-align: bottom; } td, th { overflow: hidden; padding: 1pt 3pt; font-size: 11pt; vertical-align: bottom; }
th.hd { background: #f1f1f1; border: 0.5pt solid #b7b7b7; color: #444; th.hd { background: #f1f1f1; border: 0.5pt solid #b7b7b7; color: #444;
font-size: 8.5pt; font-weight: 400; text-align: center; vertical-align: middle; } font-size: 8.5pt; font-weight: 400; text-align: center; vertical-align: middle; }
th.hf, td.hf { padding: 2pt 0 6pt; font-weight: 400; } </style></head><body>` +
td.hf { padding: 6pt 0 0; } tables.join('') +
.hf > div { display: flex; font-size: 9pt; color: #333; } `</body></html>`
.hf span { flex: 1; white-space: pre; }
.hf span:nth-child(2) { text-align: center; }
.hf span:last-child { text-align: right; }
</style></head><body><table>${colgroup}<thead>${headParts.join('')}</thead>` +
`<tbody>${bodyParts.join('')}</tbody>` +
`${footerRow === '' ? '' : `<tfoot>${footerRow}</tfoot>`}</table></body></html>`
const margins = MARGIN_PRESETS[pageSetup.margins ?? 'normal'] const margins = setup.margins
const pageSize = PAPER_SIZES[pageSetup.paperSize ?? 9] ?? 'A4' const pageSize = PAPER_SIZES[setup.paperSize] ?? 'A4'
const landscape = pageSetup.orientation === 'landscape' const landscape = setup.orientation === 'landscape'
const now = new Date()
const baseName = fileName.replace(/\.pdf$/, '')
const headerTemplate = setup.header
? buildHeaderFooterTemplate(setup.header, 'header', margins, baseName, sheetName, now)
: undefined
const footerTemplate = setup.footer
? buildHeaderFooterTemplate(setup.footer, 'footer', margins, baseName, sheetName, now)
: undefined
return { return {
fileName, fileName,
html, html,
landscape, landscape,
pageSize, pageSize,
margins: { top: margins.top, bottom: margins.bottom, left: margins.left, right: margins.right }, margins: { top: margins.top, bottom: margins.bottom, left: margins.left, right: margins.right },
scale: computeScale( scale: computeScale(setup, pageSize, landscape, margins, maxContentWidthPt),
pageSetup, ...(headerTemplate === undefined ? {} : { headerTemplate }),
pageSize, ...(footerTemplate === undefined ? {} : { footerTemplate }),
landscape,
margins,
rowHeaderPt + columnWidthsPt.reduce((total, width) => total + width, 0),
),
} }
} }
/// Resolves the field codes a static layout can know (&D date, &T time, /// One left/center/right header or footer as a Chromium print template
/// &F file name, &A sheet name, && literal &); page-dependent codes (&P, /// (rendered in the page's margin box; undefined when the parts are empty).
/// &N) render empty — the HTML-to-PDF path has no page counter. export function buildHeaderFooterTemplate(
function resolveHeaderFooterText( parts: HeaderFooterParts,
kind: 'header' | 'footer',
margins: PrintMargins,
fileName: string,
sheetName: string,
now: Date,
): string | undefined {
const sections = [parts.left ?? '', parts.center ?? '', parts.right ?? '']
if (sections.every((text) => text === '')) return undefined
const rendered = sections.map((text) => renderHeaderFooterHtml(text, fileName, sheetName, now))
// Excel offsets the header/footer from the paper edge by its own margin.
const offset =
kind === 'header'
? `padding-top:${round(margins.header)}in`
: `padding-bottom:${round(margins.footer)}in`
const spanStyle = 'flex:1;white-space:pre-wrap'
// Chromium's template document is content-box; without an inline
// border-box the width:100% + side padding overflows the page and
// shifts/clips the sections.
return (
`<div style="box-sizing:border-box;display:flex;width:100%;font-size:9pt;color:#000;` +
`font-family:Calibri,'Helvetica Neue',Arial,sans-serif;` +
`padding-left:${round(margins.left)}in;padding-right:${round(margins.right)}in;${offset}">` +
`<span style="${spanStyle}">${rendered[0]}</span>` +
`<span style="${spanStyle};text-align:center">${rendered[1]}</span>` +
`<span style="${spanStyle};text-align:right">${rendered[2]}</span></div>`
)
}
/// Field codes → template HTML: &P/&N become Chromium's live pageNumber/
/// totalPages spans, static codes (&D &T &F &A, && literal) resolve now,
/// everything else is HTML-escaped verbatim.
export function renderHeaderFooterHtml(
text: string, text: string,
fileName: string, fileName: string,
sheetName: string, sheetName: string,
now: Date, now: Date,
): string { ): string {
return text.replace(/&(&|[A-Za-z])/g, (match, code: string) => { let html = ''
let literal = ''
const flush = (): void => {
html += escapeHtml(literal)
literal = ''
}
for (let index = 0; index < text.length; index += 1) {
const character = text[index] ?? ''
if (character !== '&') {
literal += character
continue
}
const code = text[index + 1]
if (code === undefined) {
literal += '&'
break
}
index += 1
switch (code) { switch (code) {
case '&': case '&':
return '&' literal += '&'
break
case 'P': case 'P':
flush()
html += '<span class="pageNumber"></span>'
break
case 'N': case 'N':
return '' flush()
html += '<span class="totalPages"></span>'
break
case 'D': case 'D':
return now.toLocaleDateString() literal += now.toLocaleDateString()
break
case 'T': case 'T':
return now.toLocaleTimeString() literal += now.toLocaleTimeString()
break
case 'F': case 'F':
return fileName literal += fileName
break
case 'A': case 'A':
return sheetName literal += sheetName
break
default: default:
return match literal += `&${code}`
} }
}) }
} flush()
return html
/// One left/center/right header or footer row spanning the whole table
/// ('' when the parts are empty).
function headerFooterRow(
parts: HeaderFooterParts | null | undefined,
cell: 'th' | 'td',
colspan: number,
resolveCodes: (text: string) => string,
): string {
const sections = [parts?.left, parts?.center, parts?.right].map((text) =>
resolveCodes(text ?? ''),
)
if (sections.every((text) => text === '')) return ''
const spans = sections.map((text) => `<span>${escapeHtml(text)}</span>`).join('')
return `<tr><${cell} class="hf" colspan="${colspan}"><div>${spans}</div></${cell}></tr>`
} }
/// Excel's fit-to-width only shrinks; an explicit scale applies as-is. /// Excel's fit-to-width only shrinks; an explicit scale applies as-is.
function computeScale( function computeScale(
pageSetup: PageSetupJournalState, setup: EffectivePageSetup,
pageSize: WorkbookExportPdfRequest['pageSize'], pageSize: WorkbookExportPdfRequest['pageSize'],
landscape: boolean, landscape: boolean,
margins: { left: number; right: number; top: number; bottom: number }, margins: { left: number; right: number; top: number; bottom: number },
contentWidthPt: number, contentWidthPt: number,
): number { ): number {
const fitPages = pageSetup.fitToPage === true ? (pageSetup.fitToWidth ?? 0) : 0 const fitPages = setup.fitToPage ? setup.fitToWidth : 0
if (fitPages > 0) { if (fitPages > 0 && contentWidthPt > 0) {
const paperWidthIn = const paperWidthIn =
typeof pageSize === 'string' typeof pageSize === 'string'
? landscape ? landscape
@@ -290,8 +335,8 @@ function computeScale(
const printableWidthPt = (paperWidthIn - margins.left - margins.right) * 72 const printableWidthPt = (paperWidthIn - margins.left - margins.right) * 72
return clamp((printableWidthPt * fitPages) / contentWidthPt, 0.1, 1) return clamp((printableWidthPt * fitPages) / contentWidthPt, 0.1, 1)
} }
if (pageSetup.fitToPage !== true && pageSetup.scale !== undefined) { if (!setup.fitToPage) {
return clamp(pageSetup.scale / 100, 0.1, 2) return clamp(setup.scale / 100, 0.1, 2)
} }
return 1 return 1
} }
+294
View File
@@ -0,0 +1,294 @@
/**
* Effective print settings for the PDF export: the session's Page Layout
* journal overlaid on the workbook's saved page setup (worksheet pageSetup /
* pageMargins / printOptions / headerFooter plus the workbook-level
* _xlnm.Print_Area / _xlnm.Print_Titles defined names).
*/
import { columnLabel, parseRange } from '../domain/cell-address'
import type { WorkbookPagePrintSettings } from '../shared/desktop-api'
import type { HeaderFooterParts, PageSetupJournalState, StructuralJournalOp } from './edit-journal'
import { fileRangeToScreenRange, fileToScreen } from './view-transform'
export interface PrintMargins {
readonly left: number
readonly right: number
readonly top: number
readonly bottom: number
readonly header: number
readonly footer: number
}
/// Concrete values the print layout consumes; every field resolved.
export interface EffectivePageSetup {
readonly orientation: 'portrait' | 'landscape'
/// OOXML paper-size code.
readonly paperSize: number
/// Percent; applies only when fitToPage is off.
readonly scale: number
/// Pages across; 0 = automatic. Applies only when fitToPage is on.
readonly fitToWidth: number
readonly fitToPage: boolean
/// Inches.
readonly margins: PrintMargins
readonly printGridlines: boolean
readonly printHeadings: boolean
/// Plain A1 ranges to print ([] = the used range).
readonly printAreas: readonly string[]
/// Rows repeated at the top of every page ("1:2"), or null.
readonly printTitles: string | null
readonly header: HeaderFooterParts | null
readonly footer: HeaderFooterParts | null
}
/// Inches, mirroring the gateway's margin presets.
const MARGIN_PRESETS: Record<'normal' | 'wide' | 'narrow', PrintMargins> = {
normal: { left: 0.7, right: 0.7, top: 0.75, bottom: 0.75, header: 0.3, footer: 0.3 },
wide: { left: 1, right: 1, top: 1, bottom: 1, header: 0.5, footer: 0.5 },
narrow: { left: 0.25, right: 0.25, top: 0.75, bottom: 0.75, header: 0.3, footer: 0.3 },
}
/// The export wire caps margins at 3in per side.
const MAX_MARGIN_INCHES = 3
export interface FilePrintNames {
readonly printArea?: string | undefined
readonly printTitles?: string | undefined
}
/// File-space A1 areas → this session's screen space (envelope semantics,
/// like streamed merges). Fully deleted areas drop out; when nothing
/// survives the caller falls back to the used range.
function mapAreasToScreen(areas: readonly string[], ops: readonly StructuralJournalOp[]): string[] {
if (ops.length === 0) return [...areas]
const mapped: string[] = []
for (const area of areas) {
let bounds
try {
bounds = parseRange(area)
} catch {
continue
}
const screen = fileRangeToScreenRange(ops, bounds)
if (screen === null) continue
mapped.push(
`${columnLabel(screen.startColumn)}${screen.startRow + 1}` +
`:${columnLabel(screen.endColumn)}${screen.endRow + 1}`,
)
}
return mapped
}
/// File-space title rows → screen space (row axis only — column edits must
/// not drop them). Deleted rows shrink the span; all deleted → null.
function mapTitleRowsToScreen(
titles: string | null,
ops: readonly StructuralJournalOp[],
): string | null {
if (titles === null || ops.length === 0) return titles
const match = /^([0-9]{1,7}):([0-9]{1,7})$/.exec(titles)
if (!match) return null
const rows: number[] = []
for (let row = Number(match[1]) - 1; row <= Number(match[2]) - 1; row += 1) {
const screen = fileToScreen(ops, 'row', row)
if (screen !== null) rows.push(screen)
}
if (rows.length === 0) return null
const start = Math.min(...rows)
const end = Math.max(...rows)
// Inserts/moves between title rows can stretch the surviving span past
// the layout's 21-row cap (parseTitleRows would throw): drop the titles
// instead, matching the cap semantics at parse time.
if (end - start > 20) return null
return `${start + 1}:${end + 1}`
}
export function resolveEffectivePageSetup(
journal: PageSetupJournalState,
file: WorkbookPagePrintSettings | null,
names: FilePrintNames | null,
/// This session's structural edits: file-sourced print names live in
/// original workbook coordinates and must shift into screen space
/// (journal-sourced values are already screen space).
ops: readonly StructuralJournalOp[] = [],
): EffectivePageSetup {
const clampMargin = (value: number): number => Math.min(Math.max(value, 0), MAX_MARGIN_INCHES)
const fileMargins = file?.margins
const margins =
journal.margins !== undefined
? MARGIN_PRESETS[journal.margins]
: fileMargins !== undefined
? {
left: clampMargin(fileMargins.left),
right: clampMargin(fileMargins.right),
top: clampMargin(fileMargins.top),
bottom: clampMargin(fileMargins.bottom),
header: clampMargin(fileMargins.header),
footer: clampMargin(fileMargins.footer),
}
: MARGIN_PRESETS.normal
const fitToPage = journal.fitToPage ?? file?.fitToPage ?? false
// OOXML default when fitToPage is on and fitToWidth absent is 1 page.
const fitToWidth = journal.fitToWidth ?? file?.fitToWidth ?? (file?.fitToPage === true ? 1 : 0)
const printArea =
journal.printArea !== undefined
? journal.printArea === null
? []
: [journal.printArea]
: mapAreasToScreen(printAreasFromFormula(names?.printArea), ops)
const printTitles =
journal.printTitles !== undefined
? journal.printTitles
: mapTitleRowsToScreen(printTitleRowsFromFormula(names?.printTitles), ops)
const header =
journal.header !== undefined
? journal.header
: file?.oddHeader !== undefined
? decodeHeaderFooter(file.oddHeader)
: null
const footer =
journal.footer !== undefined
? journal.footer
: file?.oddFooter !== undefined
? decodeHeaderFooter(file.oddFooter)
: null
return {
orientation: journal.orientation ?? file?.orientation ?? 'portrait',
paperSize: journal.paperSize ?? file?.paperSize ?? 9,
scale: journal.scale ?? file?.scale ?? 100,
fitToWidth,
fitToPage,
margins,
printGridlines: journal.printGridlines ?? file?.printGridlines ?? false,
printHeadings: journal.printHeadings ?? file?.printHeadings ?? false,
printAreas: printArea,
printTitles,
header,
footer,
}
}
/// Splits a defined-name formula on commas outside quoted sheet names.
function splitAreas(formula: string): string[] {
const parts: string[] = []
let current = ''
let quoted = false
for (const character of formula) {
if (character === "'") quoted = !quoted
if (character === ',' && !quoted) {
parts.push(current)
current = ''
} else {
current += character
}
}
parts.push(current)
return parts
}
/// Strips the (optional) sheet qualifier and `$` anchors of one reference.
function plainReference(part: string): string {
return part
.slice(part.lastIndexOf('!') + 1)
.replace(/\$/g, '')
.trim()
}
/// `'S 1'!$A$1:$K$84,'S 1'!$M$1:$N$9` → ['A1:K84', 'M1:N9']. Anything the
/// print layout cannot crop to (full-column spans, 3-D refs, #REF!) yields
/// [] so the export falls back to the used range instead of dropping content.
export function printAreasFromFormula(formula: string | undefined): string[] {
if (formula === undefined || formula === '') return []
const areas: string[] = []
for (const part of splitAreas(formula)) {
const reference = plainReference(part).toUpperCase()
if (/^[A-Z]{1,3}[0-9]{1,7}$/.test(reference)) {
areas.push(`${reference}:${reference}`)
continue
}
if (/^[A-Z]{1,3}[0-9]{1,7}:[A-Z]{1,3}[0-9]{1,7}$/.test(reference)) {
areas.push(reference)
continue
}
return []
}
return areas
}
/// `'S'!$1:$2` → '1:2'; column-repeat parts are skipped (unsupported), spans
/// beyond the layout's 21-row title cap are dropped.
export function printTitleRowsFromFormula(formula: string | undefined): string | null {
if (formula === undefined || formula === '') return null
for (const part of splitAreas(formula)) {
const match = /^([0-9]{1,7}):([0-9]{1,7})$/.exec(plainReference(part))
if (!match) continue
const start = Number(match[1])
const end = Number(match[2])
if (start <= end && end - start <= 20) return `${start}:${end}`
}
return null
}
/// Excel's encoded header/footer → left/center/right parts. Field codes the
/// layout resolves (&P &N &D &T &F &A, && literal) stay verbatim; formatting
/// codes (font/size/color/bold/…) and unsupported codes (&G picture, &Z
/// path) are stripped. Text before the first section marker is centered.
export function decodeHeaderFooter(encoded: string): HeaderFooterParts | null {
const sections = { L: '', C: '', R: '' }
let current: 'L' | 'C' | 'R' = 'C'
let index = 0
while (index < encoded.length) {
const character = encoded[index] ?? ''
if (character !== '&') {
sections[current] += character
index += 1
continue
}
const next = encoded[index + 1]
if (next === undefined) break
if (next === '&') {
sections[current] += '&&'
index += 2
continue
}
// &"Font Name,Style" — skip the whole quoted spec.
if (next === '"') {
const close = encoded.indexOf('"', index + 2)
index = close === -1 ? encoded.length : close + 1
continue
}
// &nn font size.
if (/[0-9]/.test(next)) {
index += 2
while (index < encoded.length && /[0-9]/.test(encoded[index] ?? '')) index += 1
continue
}
const code = next.toUpperCase()
// &K followed by an RRGGBB or theme color spec.
if (code === 'K') {
index += 8
continue
}
if (code === 'L' || code === 'C' || code === 'R') {
current = code
index += 2
continue
}
if (
code === 'P' ||
code === 'N' ||
code === 'D' ||
code === 'T' ||
code === 'F' ||
code === 'A'
) {
sections[current] += `&${code}`
}
index += 2
}
if (sections.L === '' && sections.C === '' && sections.R === '') return null
return {
...(sections.L === '' ? {} : { left: sections.L }),
...(sections.C === '' ? {} : { center: sections.C }),
...(sections.R === '' ? {} : { right: sections.R }),
}
}
+55
View File
@@ -21,6 +21,7 @@ import {
toSaveVisualAdds, toSaveVisualAdds,
toSaveVisualEdits, toSaveVisualEdits,
} from './edit-journal' } from './edit-journal'
import { activeCsvSheet, handleExportCsv, serializeActiveSheetCsv } from './csv-export'
import { t } from './i18n/locale' import { t } from './i18n/locale'
import { abortStagedEditsTransfer, stageEditsForSave, type StagedEdits } from './save-edits-staging' import { abortStagedEditsTransfer, stageEditsForSave, type StagedEdits } from './save-edits-staging'
import { showToast } from './toast-bus' import { showToast } from './toast-bus'
@@ -57,6 +58,10 @@ export interface SaveContext {
) => void ) => void
} }
/// CSV files whose "keep this format?" question was already answered with
/// "Continue as CSV" — asked once per file, like modern Excel's banner.
const confirmedCsvSaves = new Set<string>()
/** /**
* mode 'recovery': assemble the very same payload but hand it to the * mode 'recovery': assemble the very same payload but hand it to the
* crash-recovery writer instead of the save pipeline — no dialogs, no status * crash-recovery writer instead of the save pipeline — no dialogs, no status
@@ -228,6 +233,40 @@ export async function handleSave(
if (mode !== 'recovery') ctx.setMessage(t('appNoEditsToSave')) if (mode !== 'recovery') ctx.setMessage(t('appNoEditsToSave'))
return return
} }
// CSV session: Save keeps the CSV identity — Excel's "keep this format?"
// question once per file, then the active sheet rides the save request as
// serialized CSV text for the main process to write back.
let csvContent: string | undefined
if (mode === 'save' && state.file.csvPath !== undefined) {
const csvPath = state.file.csvPath
if (!state.flags.preloadComplete) {
ctx.setMessage(t('appCsvExportNeedsFullLoad'))
return
}
if (!confirmedCsvSaves.has(csvPath)) {
const choice = await window.desktopApi.confirmCsvSave()
if (choice === 'cancel') {
ctx.setMessage(t('appSaveCanceled'))
return
}
if (choice === 'xlsx') {
await handleSave(ctx, 'save-as', quiet)
return
}
confirmedCsvSaves.add(csvPath)
}
const active = activeCsvSheet(ctx.univerRef.current)
const serialized = active === null ? null : serializeActiveSheetCsv(active.sheet, state)
if (serialized === 'too-large') {
ctx.setMessage(t('appCsvExportTooLarge'))
return
}
if (serialized === null) {
ctx.setMessage(t('appSaveFailed'))
return
}
csvContent = serialized
}
// Sheet ops rebuild workbook.xml's tab list, so the save needs the final // Sheet ops rebuild workbook.xml's tab list, so the save needs the final
// on-screen order. // on-screen order.
const sheetOrder = const sheetOrder =
@@ -306,6 +345,7 @@ export async function handleSave(
sessionId: state.file.sessionId, sessionId: state.file.sessionId,
mode, mode,
...(restoreWriteBack ? { restoreWriteBack: true } : {}), ...(restoreWriteBack ? { restoreWriteBack: true } : {}),
...(csvContent === undefined ? {} : { csvContent }),
edits: staged.edits, edits: staged.edits,
bulkConstantFills, bulkConstantFills,
...(staged.editsTransferId === undefined ? {} : { editsTransferId: staged.editsTransferId }), ...(staged.editsTransferId === undefined ? {} : { editsTransferId: staged.editsTransferId }),
@@ -335,6 +375,21 @@ export async function handleSave(
}) })
if (ctx.lazyWorkbookRef.current !== state) return if (ctx.lazyWorkbookRef.current !== state) return
if (result.canceled) { if (result.canceled) {
if (result.csvSaveAsPath !== undefined) {
// The user picked CSV in the Save As dialog: no xlsx was written —
// serialize the active sheet to the chosen path instead. The journal
// stays pending; the session keeps its identity (a copy semantics).
await handleExportCsv(
{
univerRef: ctx.univerRef,
lazyWorkbookRef: ctx.lazyWorkbookRef,
setMessage: ctx.setMessage,
requestSaveAs: () => void handleSave(ctx, 'save-as', quiet),
},
result.csvSaveAsPath,
)
return
}
ctx.setMessage(t('appSaveCanceled')) ctx.setMessage(t('appSaveCanceled'))
return return
} }
+95
View File
@@ -39,6 +39,10 @@
--sheets-chip-bg: #f3f7f4; --sheets-chip-bg: #f3f7f4;
--sheets-member-bg: #f6f8f7; --sheets-member-bg: #f6f8f7;
--sheets-member-ink: #5c6660; --sheets-member-ink: #5c6660;
--sheets-validation-prompt-bg: #ffffe1;
--sheets-validation-prompt-border: #808080;
--sheets-validation-prompt-ink: #555;
--sheets-validation-prompt-shadow: rgb(0 0 0 / 18%);
/* content-side constants: charts, shapes and their selection chrome sit on /* content-side constants: charts, shapes and their selection chrome sit on
* the paper-like grid and never follow the theme */ * the paper-like grid and never follow the theme */
@@ -124,6 +128,10 @@
--sheets-chip-bg: #24312a; --sheets-chip-bg: #24312a;
--sheets-member-bg: #2f2f2f; --sheets-member-bg: #2f2f2f;
--sheets-member-ink: #a9b2ac; --sheets-member-ink: #a9b2ac;
--sheets-validation-prompt-bg: #3c3826;
--sheets-validation-prompt-border: #8f8663;
--sheets-validation-prompt-ink: #f2ecd0;
--sheets-validation-prompt-shadow: rgb(0 0 0 / 45%);
} }
@media (prefers-color-scheme: dark) { @media (prefers-color-scheme: dark) {
@@ -152,6 +160,10 @@
--sheets-chip-bg: #24312a; --sheets-chip-bg: #24312a;
--sheets-member-bg: #2f2f2f; --sheets-member-bg: #2f2f2f;
--sheets-member-ink: #a9b2ac; --sheets-member-ink: #a9b2ac;
--sheets-validation-prompt-bg: #3c3826;
--sheets-validation-prompt-border: #8f8663;
--sheets-validation-prompt-ink: #f2ecd0;
--sheets-validation-prompt-shadow: rgb(0 0 0 / 45%);
} }
} }
@@ -2160,6 +2172,9 @@ textarea:focus {
.chart-svg { .chart-svg {
width: 100%; width: 100%;
/* Wide anchors: without a height cap the aspect-derived height overflows
the frame and clips the bottom axis rows (side-legend layouts). */
max-height: 100%;
min-height: 0; min-height: 0;
flex: 1 1 auto; flex: 1 1 auto;
} }
@@ -2396,6 +2411,69 @@ textarea:focus {
pointer-events: none; pointer-events: none;
} }
.data-validation-dropdown-button {
width: 100%;
height: 100%;
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
border: 1px solid var(--border-strong);
border-radius: 0;
background: var(--surface-subtle);
color: var(--text-muted);
cursor: default;
appearance: none;
}
.univer-z-10:has(.data-validation-dropdown-button),
.univer-z-10:has(.data-validation-input-message) {
overflow: visible !important;
}
.univer-z-10:has(.data-validation-input-message) > .univer-overflow-hidden {
overflow: visible !important;
}
.data-validation-dropdown-button:hover {
border-color: var(--border-hover);
background: var(--hover);
color: var(--text);
}
.data-validation-dropdown-button svg {
width: 8px;
height: 8px;
display: block;
fill: currentcolor;
pointer-events: none;
}
.data-validation-input-message {
width: 100%;
height: 100%;
box-sizing: border-box;
padding: 4px;
overflow: hidden;
border: 1px solid var(--sheets-validation-prompt-border);
background: var(--sheets-validation-prompt-bg);
box-shadow: 1px 1px 2px var(--sheets-validation-prompt-shadow);
color: var(--sheets-validation-prompt-ink);
font-family: inherit;
font-size: 9px;
line-height: 12px;
white-space: pre-wrap;
overflow-wrap: anywhere;
pointer-events: none;
user-select: none;
transform: translateY(4px);
}
.data-validation-input-message-title {
font-weight: 600;
}
.page-break-line { .page-break-line {
width: 100%; width: 100%;
height: 100%; height: 100%;
@@ -2806,6 +2884,23 @@ textarea:focus {
object-fit: contain; object-fit: contain;
} }
/* In-cell rich-value picture: fits the cell box, aspect preserved (Excel). */
.xlsx-cell-image {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
pointer-events: none;
}
.xlsx-cell-image img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
.xlsx-shape, .xlsx-shape,
.xlsx-visual-loading { .xlsx-visual-loading {
display: flex; display: flex;
+18 -1
View File
@@ -7,7 +7,11 @@
import { BorderType, LocalUndoRedoService, type IRange } from '@univerjs/core' import { BorderType, LocalUndoRedoService, type IRange } from '@univerjs/core'
import { SheetInterceptorService } from '@univerjs/sheets' import { SheetInterceptorService } from '@univerjs/sheets'
import type { WorkbookFile, WorkbookPivotDefinition } from '../shared/desktop-api' import type {
WorkbookFile,
WorkbookPagePrintSettings,
WorkbookPivotDefinition,
} from '../shared/desktop-api'
import type { createUniver } from './create-univer' import type { createUniver } from './create-univer'
import type { EditJournal } from './edit-journal' import type { EditJournal } from './edit-journal'
import { netAxisDelta } from './view-transform' import { netAxisDelta } from './view-transform'
@@ -43,6 +47,9 @@ export interface LazyWorkbookState {
/// File-side manual page breaks (0-based index of the row/column after the /// File-side manual page breaks (0-based index of the row/column after the
/// break, file coordinates), known once a sheet finishes indexing. /// break, file coordinates), known once a sheet finishes indexing.
readonly sheetPageBreaks: Map<string, { rowBreaks: number[]; colBreaks: number[] }> readonly sheetPageBreaks: Map<string, { rowBreaks: number[]; colBreaks: number[] }>
/// File-side saved print settings (pageSetup / margins / headerFooter),
/// known once a sheet finishes indexing.
readonly sheetFilePageSetups: Map<string, WorkbookPagePrintSettings>
/// File-side allow-edit ranges, known once a sheet finishes indexing. /// File-side allow-edit ranges, known once a sheet finishes indexing.
readonly sheetProtectedRanges: Map< readonly sheetProtectedRanges: Map<
string, string,
@@ -104,6 +111,16 @@ export interface LazyWorkbookState {
failures: number failures: number
readonly formulaCells: Map<string, ReadonlySet<number>> readonly formulaCells: Map<string, ReadonlySet<number>>
readonly overlay: Map<string, Map<string, PinnedClosureCell>> readonly overlay: Map<string, Map<string, PinnedClosureCell>>
/// per-sheet: viewport row the last SUCCESSFUL overlay window was
/// anchored at and whether it covered every formula band; a partial
/// window re-anchors when the user scrolls far from it (alpha ledger
/// r141). Written only after the sidecar run succeeds — early writes
/// latched stale flags on failure (bugbot).
readonly follow: Map<string, { anchorRow: number; complete: boolean }>
/// re-anchor throttle: no new run while one is in flight, and at most
/// one every few seconds — each run reads thousands of sidecar cells
running: boolean
lastRunAt: number
} }
} }
+218 -51
View File
@@ -100,6 +100,7 @@ import {
type AdvancedFilterCondition, type AdvancedFilterCondition,
} from './AdvancedFilterDialog' } from './AdvancedFilterDialog'
import { import {
installCellImages,
installSparklines, installSparklines,
installWorkbookVisuals, installWorkbookVisuals,
isChartEditorOpen, isChartEditorOpen,
@@ -388,9 +389,14 @@ export function loadWorkbookSkeleton(runtime: UniverRuntime | null, file: Workbo
...(sheet.defaultRowHeight === null ...(sheet.defaultRowHeight === null
? {} ? {}
: { defaultRowHeight: (sheet.defaultRowHeight * 96) / 72 }), : { defaultRowHeight: (sheet.defaultRowHeight * 96) / 72 }),
...(sheet.defaultColumnWidth === null // No defaultColWidth in the file ≠ Univer's 88px default: Excel
? {} // derives its built-in width from baseColWidth (default 8) plus
: { defaultColumnWidth: characterWidthToPixels(sheet.defaultColumnWidth) }), // cell padding, snapped to 1/256 chars (~74px at MDW 8, live
// Excel shows 8.0 chars). The narrower column matters: General
// numbers switch to scientific when the digits stop fitting.
defaultColumnWidth: characterWidthToPixels(
sheet.defaultColumnWidth ?? paddedBaseColumnWidth(sheet.baseColumnWidth),
),
...(sheet.freeze === null ...(sheet.freeze === null
? {} ? {}
: { : {
@@ -424,6 +430,15 @@ export function characterWidthToPixels(width: number): number {
return width === 0 ? 0 : Math.floor(((256 * width + Math.floor(128 / mdw)) / 256) * mdw) + 5 return width === 0 ? 0 : Math.floor(((256 * width + Math.floor(128 / mdw)) / 256) * mdw) + 5
} }
/// Excel's built-in default column width when sheetFormatPr carries no
/// defaultColWidth: baseColWidth (default 8) plus cell padding, snapped to
/// the format's 1/256-char granularity (ECMA-376 §18.3.1.81).
export function paddedBaseColumnWidth(base: number | null | undefined): number {
const chars = base ?? 8
const mdw = getWorkbookMdw()
return Math.trunc(((chars * mdw + 5) / mdw) * 256) / 256
}
const CJK_FAMILY_NAME = const CJK_FAMILY_NAME =
/[\u1100-\u11ff\u3000-\u303f\u3040-\u30ff\u3130-\u318f\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uf900-\ufaff\uff00-\uffef]/ /[\u1100-\u11ff\u3000-\u303f\u3040-\u30ff\u3130-\u318f\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uf900-\ufaff\uff00-\uffef]/
@@ -464,7 +479,12 @@ export function resolveNormalMdwFamily(file: WorkbookFile): string {
export function measureNormalFontMdw(file: WorkbookFile): number { export function measureNormalFontMdw(file: WorkbookFile): number {
const size = file.styles?.[0]?.fontSize ?? 11 const size = file.styles?.[0]?.fontSize ?? 11
const family = resolveNormalMdwFamily(file) const family = resolveNormalMdwFamily(file)
if (family === 'Calibri' && size === 11) return 7 // Mac Excel (the fidelity reference) lays Calibri 11 out at MDW 8, not the
// Windows GDI 7: live probes and ref print geometry both fit
// floor((w+16/256)*8) within 1pt across corpora (prod_054 50.86ch→305pt,
// prod_027 32.44ch→195pt, lo/built-in_ranges 13.71ch→82pt) while MDW 7
// misses by 12%+, wrapping borderline text a line early.
if (family === 'Calibri' && size === 11) return 8
const perPt = EXCEL_DIGIT_PER_PT[family] const perPt = EXCEL_DIGIT_PER_PT[family]
if (perPt !== undefined) return clampMdw(Math.round(perPt * size)) if (perPt !== undefined) return clampMdw(Math.round(perPt * size))
// CJK faces without a table entry: canvas would measure a macOS // CJK faces without a table entry: canvas would measure a macOS
@@ -1062,7 +1082,13 @@ export async function activateFormulaClosure(
if (!state || state.formulaMode || state.closure.status !== 'idle') return if (!state || state.formulaMode || state.closure.status !== 'idle') return
state.closure.status = 'pending' state.closure.status = 'pending'
const giveUp = (): void => { const giveUp = (): void => {
if (lazyWorkbookRef.current === state) state.closure.status = 'unavailable' if (lazyWorkbookRef.current !== state) return
state.closure.status = 'unavailable'
// Cache-mode fallback starts NOW, not at the first edit: the file's
// cached values may be stale or poisoned (saved by an earlier broken
// session) and would otherwise display until the user edits something
// (alpha ledger r141 reopen).
queueFormulaRecalc(runtime, lazyWorkbookRef, setMessage)
} }
const inputs: ClosureSheetInput[] = [] const inputs: ClosureSheetInput[] = []
@@ -1674,7 +1700,8 @@ export function queueFormulaRecalc(
): void { ): void {
const state = lazyWorkbookRef.current const state = lazyWorkbookRef.current
if (!state || state.formulaMode || state.closure.status !== 'unavailable') return if (!state || state.formulaMode || state.closure.status !== 'unavailable') return
if (state.recalc.failures >= RECALC_MAX_FAILURES) return // minimal states (tests, partial teardown) may carry no recalc slot
if (!state.recalc || state.recalc.failures >= RECALC_MAX_FAILURES) return
// The engine loads the file from disk; session structural edits would // The engine loads the file from disk; session structural edits would
// desync every coordinate — fail soft to cached values. // desync every coordinate — fail soft to cached values.
if ([...state.editJournal.structuralOps.values()].some((ops) => ops.length > 0)) return if ([...state.editJournal.structuralOps.values()].some((ops) => ops.length > 0)) return
@@ -1757,12 +1784,24 @@ async function runFormulaRecalc(
} }
} }
const generation = ++state.recalc.generation const generation = ++state.recalc.generation
state.recalc.running = true
state.recalc.lastRunAt = Date.now()
try { try {
const keys = await recalcFormulaCellKeys(state, sheetId) const keys = await recalcFormulaCellKeys(state, sheetId)
if (lazyWorkbookRef.current !== state || !keys || keys.size === 0) return if (lazyWorkbookRef.current !== state) return
if (!keys || keys.size === 0) {
// nothing to recalculate on this sheet: mark it followed so the
// finished-run chain below doesn't loop on it forever
if (keys) state.recalc.follow.set(sheetId, { anchorRow: 0, complete: true })
return
}
const viewportStartRow = state.loadedRanges.get(sheetId)?.startRow ?? 0 const viewportStartRow = state.loadedRanges.get(sheetId)?.startRow ?? 0
const reads = recalcReadRanges(keys, viewportStartRow, RECALC_READ_BUDGET) const reads = recalcReadRanges(keys, viewportStartRow, RECALC_READ_BUDGET)
if (reads.length === 0) return if (reads.length === 0) {
state.recalc.follow.set(sheetId, { anchorRow: viewportStartRow, complete: true })
return
}
const windowComplete = reads.length === closureFetchRanges(keys).length
const result = await window.desktopApi.recalcWorkbook({ const result = await window.desktopApi.recalcWorkbook({
sessionId: state.file.sessionId, sessionId: state.file.sessionId,
edits, edits,
@@ -1786,6 +1825,7 @@ async function runFormulaRecalc(
overlay.set(`${cell.row}:${cell.column}`, { v: cell.number ?? cell.formatted }) overlay.set(`${cell.row}:${cell.column}`, { v: cell.number ?? cell.formatted })
} }
state.recalc.overlay.set(sheetId, overlay) state.recalc.overlay.set(sheetId, overlay)
state.recalc.follow.set(sheetId, { anchorRow: viewportStartRow, complete: windowComplete })
const loaded = state.loadedRanges.get(sheetId) const loaded = state.loadedRanges.get(sheetId)
if (loaded && overlay.size > 0) { if (loaded && overlay.size > 0) {
journalSuppression.active = true journalSuppression.active = true
@@ -1813,6 +1853,31 @@ async function runFormulaRecalc(
// failures toward the kill switch. // failures toward the kill switch.
if (lazyWorkbookRef.current !== state || state.recalc.generation !== generation) return if (lazyWorkbookRef.current !== state || state.recalc.generation !== generation) return
state.recalc.failures += 1 state.recalc.failures += 1
} finally {
if (state.recalc.generation === generation) {
state.recalc.running = false
// A sheet switched to while this run was in flight got its first-follow
// queue attempt swallowed by the running/cooldown guards, and nothing
// rechecks a fully loaded viewport — chain one run for it. STRICTLY a
// different sheet: chaining on the run's own sheet would turn failures
// and incomplete indexes into an immediate retry loop that burns the
// RECALC_MAX_FAILURES budget before any edit (bugbot).
try {
const activeId = runtime.univerAPI.getActiveWorkbook()?.getActiveSheet()?.getSheetId()
if (
activeId &&
activeId !== sheetId &&
lazyWorkbookRef.current === state &&
state.closure.status === 'unavailable' &&
state.recalc.failures < RECALC_MAX_FAILURES &&
!state.recalc.follow.has(activeId)
) {
queueFormulaRecalc(runtime, lazyWorkbookRef, setMessage)
}
} catch {
/* workbook mid-teardown */
}
}
} }
} }
@@ -1885,6 +1950,7 @@ async function loadFrozenColumnStrip(
mapped.screen.rows, mapped.screen.rows,
sheet.columnWidths, sheet.columnWidths,
sheet.defaultRowHeightFixed, sheet.defaultRowHeightFixed,
sheet.defaultRowHeight,
stripPatchRange, stripPatchRange,
), ),
) )
@@ -2013,13 +2079,36 @@ async function loadRange(
) )
state.loadedRanges.set(sheetId, availableRange) state.loadedRanges.set(sheetId, availableRange)
patchedRange = availableRange patchedRange = availableRange
// Partial recalc windows follow the user: far outside the anchored
// window the grid would show raw (possibly poisoned) file cache —
// re-run the sidecar recalc around the new viewport (r141 reopen).
const recalc = state.recalc
const follow = recalc.follow.get(sheetId)
if (
!state.formulaMode &&
state.closure.status === 'unavailable' &&
!recalc.running &&
// a pending debounce counts as in flight: re-queuing would RESET
// the timer and starve the open-time recalc while streaming keeps
// patching every ~250ms (bugbot)
recalc.timer === null &&
Date.now() - recalc.lastRunAt > 3000 &&
(!follow ||
(!follow.complete && Math.abs(availableRange.startRow - follow.anchorRow) > 200))
) {
queueFormulaRecalc(runtime, lazyWorkbookRef, setMessage)
}
} }
} }
const result = mapped.raw const result = mapped.raw
const hasStructuralOps = (state.editJournal.structuralOps.get(sheetId)?.length ?? 0) > 0
// formulaMode skips the closure/recalc paths that normally fill // formulaMode skips the closure/recalc paths that normally fill
// formulaText; cache-only (defined-name) cells still need it for the // formulaText; cache-only (defined-name) cells still need it for the
// formula bar and Show Formulas view. // formula bar and Show Formulas view. Harvest from screen.cells — raw
if (state.formulaMode) storeFormulaText(state, sheetId, result.cells) // holds only the last batch of an over-cap read — except under
// structural ops, where the store must stay in file coordinates.
if (state.formulaMode)
storeFormulaText(state, sheetId, hasStructuralOps ? result.cells : mapped.screen.cells)
recordHyperlinks(state, sheetId, mapped.screen.hyperlinks) recordHyperlinks(state, sheetId, mapped.screen.hyperlinks)
keepActiveSheet(worksheet, () => { keepActiveSheet(worksheet, () => {
applyRowProperties(worksheet, state, sheetId, mapped.screen.rows) applyRowProperties(worksheet, state, sheetId, mapped.screen.rows)
@@ -2035,6 +2124,7 @@ async function loadRange(
mapped.screen.rows, mapped.screen.rows,
sheetMeta.columnWidths, sheetMeta.columnWidths,
sheetMeta.defaultRowHeightFixed, sheetMeta.defaultRowHeightFixed,
sheetMeta.defaultRowHeight,
patchedRange, patchedRange,
), ),
) )
@@ -2043,7 +2133,6 @@ async function loadRange(
// file-space ranges; Univer shifts the installed models itself on later // file-space ranges; Univer shifts the installed models itself on later
// structural edits, but a fresh install after a shift would be stale — // structural edits, but a fresh install after a shift would be stale —
// skip it (rare: the sheet was being edited before it first rendered). // skip it (rare: the sheet was being edited before it first rendered).
const hasStructuralOps = (state.editJournal.structuralOps.get(sheetId)?.length ?? 0) > 0
if (!hasStructuralOps) { if (!hasStructuralOps) {
await applyConditionalRules(worksheet, state, sheetId, result.conditionalRules) await applyConditionalRules(worksheet, state, sheetId, result.conditionalRules)
if (result.indexingComplete) { if (result.indexingComplete) {
@@ -2380,8 +2469,9 @@ export function applyRowProperties(
} }
if (row.height !== undefined) { if (row.height !== undefined) {
const px = Math.round((row.height * 96) / 72) const px = Math.round((row.height * 96) / 72)
// Excel renders the stored ht verbatim on open — it never re-measures // Paint the stored ht first; the open-time wrap measure
// wrapped content when loading a file, so neither do we. // (wrapAutoFitRows) re-fits auto-mode wrap rows afterwards, matching
// Excel's own open-time re-measure of cached heights.
worksheet.setRowHeightsForced(row.row, 1, px) worksheet.setRowHeightsForced(row.row, 1, px)
if (!row.customHeight && px >= defaultRowHeightPx(state, sheetId)) { if (!row.customHeight && px >= defaultRowHeightPx(state, sheetId)) {
// Without customHeight the row is still in Excel's auto mode: a // Without customHeight the row is still in Excel's auto mode: a
@@ -2749,11 +2839,15 @@ const EXCEL_ERROR_LITERALS = new Set([
]) ])
const keepsCacheMemo = new Map<string, boolean>() const keepsCacheMemo = new Map<string, boolean>()
function formulaKeepsCache(formula: string): boolean { export function formulaKeepsCache(formula: string): boolean {
let cached = keepsCacheMemo.get(formula) let cached = keepsCacheMemo.get(formula)
if (cached === undefined) { if (cached === undefined) {
if (keepsCacheMemo.size > 20_000) keepsCacheMemo.clear() if (keepsCacheMemo.size > 20_000) keepsCacheMemo.clear()
cached = containsUnresolvedNames(formula) // Google Sheets exports unevaluable functions as
// IFERROR(__xludf.DUMMYFUNCTION("..."), <literal>); recalculating turns
// the float-repr literal (46235.0) into a string that numfmt skips.
// The cached <v> IS the computed value — keep it, like Excel does.
cached = formula.includes('__xludf.') || containsUnresolvedNames(formula)
keepsCacheMemo.set(formula, cached) keepsCacheMemo.set(formula, cached)
} }
return cached return cached
@@ -2812,30 +2906,37 @@ export function inheritedWrapLookup(
} }
} }
/// Rows Excel DOES auto-fit when opening a file: the row is in auto mode (no /// Rows Excel DOES auto-fit when opening a file: the row is in auto mode
/// stored ht of its own), the sheet default is not user-fixed (sheetFormatPr /// (no customHeight — a cached ht alone does not opt out: Excel live-probes
/// customHeight), and at least one loaded cell wraps real text. Everything /// re-fit ht="30" rows to 16pt on open, prod_054/prod_027), the sheet
/// else keeps its stored/default height verbatim (#884); numeric wrap cells /// default is not user-fixed (sheetFormatPr customHeight), the cached ht is
/// and no-wrap manual breaks never change the line count, so neither counts. /// not a sub-default spacer, and at least one loaded cell wraps real text.
/// User-fixed heights keep their stored value verbatim (#884); numeric wrap
/// cells and no-wrap manual breaks never change the line count, so neither
/// counts.
export function wrapAutoFitRows( export function wrapAutoFitRows(
cells: WorkbookRangeResult['cells'], cells: WorkbookRangeResult['cells'],
styles: readonly WorkbookCellStyle[], styles: readonly WorkbookCellStyle[],
rows: WorkbookRangeResult['rows'], rows: WorkbookRangeResult['rows'],
columnWidths: WorkbookFile['sheets'][number]['columnWidths'], columnWidths: WorkbookFile['sheets'][number]['columnWidths'],
defaultRowHeightFixed: boolean | undefined, defaultRowHeightFixed: boolean | undefined,
defaultRowHeight: number | null | undefined,
range: IRange, range: IRange,
): number[] { ): number[] {
if (defaultRowHeightFixed) return [] if (defaultRowHeightFixed) return []
const inheritedWrap = inheritedWrapLookup(styles, rows, columnWidths) const inheritedWrap = inheritedWrapLookup(styles, rows, columnWidths)
const storedHeights = new Set<number>() const lockedHeights = new Set<number>()
const defaultPt = defaultRowHeight ?? 15
for (const row of rows) { for (const row of rows) {
if (row.height !== undefined) storedHeights.add(row.row) if (row.customHeight || (row.height !== undefined && row.height < defaultPt)) {
lockedHeights.add(row.row)
}
} }
const qualifying = new Set<number>() const qualifying = new Set<number>()
for (const cell of cells) { for (const cell of cells) {
if (cell.row < range.startRow || cell.row > range.endRow) continue if (cell.row < range.startRow || cell.row > range.endRow) continue
if (cell.column < range.startColumn || cell.column > range.endColumn) continue if (cell.column < range.startColumn || cell.column > range.endColumn) continue
if (qualifying.has(cell.row) || storedHeights.has(cell.row)) continue if (qualifying.has(cell.row) || lockedHeights.has(cell.row)) continue
const style = cell.styleIndex === undefined ? undefined : styles[cell.styleIndex] const style = cell.styleIndex === undefined ? undefined : styles[cell.styleIndex]
const wraps = style ? style.wrapText === true : inheritedWrap(cell.row, cell.column) const wraps = style ? style.wrapText === true : inheritedWrap(cell.row, cell.column)
if (!wraps) continue if (!wraps) continue
@@ -2972,9 +3073,12 @@ function patchWorksheetRangeInner(
// rewriting the formula would re-dirty its dependency web (r141). // rewriting the formula would re-dirty its dependency web (r141).
if (pinnedKeys?.has(`${cell.row}:${cell.column}`)) continue if (pinnedKeys?.has(`${cell.row}:${cell.column}`)) continue
const keepsCache = useFormulas && cell.formula ? formulaKeepsCache(cell.formula) : false const keepsCache = useFormulas && cell.formula ? formulaKeepsCache(cell.formula) : false
// A kept (cache-only) formula with no cached value must show blank — // A formula cell with no cached value must show blank — falling back to
// falling back to the formula string would print it as literal text. // the formula string would print it as literal text (r141 reopen: cache
const displayValue = cell.value ?? (keepsCache ? '' : cell.formula) ?? '' // mode painted "=A750+1" walls). The formula-string fallback survives
// only for engine-installed cells, where displayValue is never painted.
const displayValue =
cell.value ?? (cell.formula ? (useFormulas && !keepsCache ? cell.formula : '') : '') ?? ''
const row = matrix[cell.row - range.startRow] const row = matrix[cell.row - range.startRow]
const style = cell.styleIndex === undefined ? undefined : styles[cell.styleIndex] const style = cell.styleIndex === undefined ? undefined : styles[cell.styleIndex]
// CSE array follower: its dead cached value would block the master's // CSE array follower: its dead cached value would block the master's
@@ -3301,15 +3405,16 @@ function applyTableBanding(
} }
/// Excel keeps pivot styling out of cell xfs entirely; approximate the /// Excel keeps pivot styling out of cell xfs entirely; approximate the
/// Light-family bands (header rows + grand-total row) with the fill resolved /// style bands (header rows, grand-total row, alternating row stripes) with
/// sidecar-side from pivotTableStyleInfo. /// the fills resolved sidecar-side from pivotTableStyleInfo.
export function applyPivotStyling( export function applyPivotStyling(
matrix: ICellData[][], matrix: ICellData[][],
range: IRange, range: IRange,
pivotTables: WorkbookFile['sheets'][number]['pivotTables'], pivotTables: WorkbookFile['sheets'][number]['pivotTables'],
): void { ): void {
for (const pivot of pivotTables) { for (const pivot of pivotTables) {
if (!pivot.headerFill && !pivot.wholeTableFill) continue // Fills imply a named style; the extra checks keep stale sidecars working.
if (!pivot.styled && !pivot.headerFill && !pivot.wholeTableFill && !pivot.stripeFill) continue
let bounds: ReturnType<typeof parseRange> let bounds: ReturnType<typeof parseRange>
try { try {
bounds = parseRange(pivot.outputRef) bounds = parseRange(pivot.outputRef)
@@ -3322,27 +3427,36 @@ export function applyPivotStyling(
const rowEnd = Math.min(range.endRow, bounds.endRow) const rowEnd = Math.min(range.endRow, bounds.endRow)
const columnStart = Math.max(range.startColumn, bounds.startColumn) const columnStart = Math.max(range.startColumn, bounds.startColumn)
const columnEnd = Math.min(range.endColumn, bounds.endColumn) const columnEnd = Math.min(range.endColumn, bounds.endColumn)
// Solid-header families (headerFontColor, no body fill: Medium) keep the
// header treatment off the grand-total row; tinted Light headers and the
// filled Dark1 body extend it (refs: aspose_sample1 vs POI 54436/Dark1).
const totalTakesHeaderFill = Boolean(pivot.wholeTableFill) || !pivot.headerFontColor
for (let row = rowStart; row <= rowEnd; row += 1) { for (let row = rowStart; row <= rowEnd; row += 1) {
const isBand = row <= headerEndRow || row === totalRow const isHeader = row <= headerEndRow
const isBand = isHeader || row === totalRow
const headerTreated = isHeader || (row === totalRow && totalTakesHeaderFill)
// Excel's pivot stripe covers the first data row, then alternates. // Excel's pivot stripe covers the first data row, then alternates.
const isStripe = const isStripe =
!isBand && pivot.stripeFill !== undefined && (row - headerEndRow - 1) % 2 === 0 !isBand && pivot.stripeFill !== undefined && (row - headerEndRow - 1) % 2 === 0
const fill = isBand ? pivot.headerFill : isStripe ? pivot.stripeFill : pivot.wholeTableFill const fill = headerTreated
if (!fill) continue ? pivot.headerFill
: isStripe
? pivot.stripeFill
: isBand
? undefined
: pivot.wholeTableFill
// Fill-less bands (Light 1-7, Medium grand total) still bold their rows.
if (!fill && !isBand) continue
for (let column = columnStart; column <= columnEnd; column += 1) { for (let column = columnStart; column <= columnEnd; column += 1) {
const cell = matrix[row - range.startRow]?.[column - range.startColumn] const cell = matrix[row - range.startRow]?.[column - range.startColumn]
if (!cell) continue if (!cell) continue
const style = (cell.s ?? {}) as IStyleData const style = (cell.s ?? {}) as IStyleData
if (styleHasFill(style)) continue if (fill && styleHasFill(style)) continue
cell.s = { cell.s = {
...style, ...style,
bg: { rgb: fill }, ...(fill ? { bg: { rgb: fill } } : {}),
...(isBand ...(isBand ? { bl: BooleanNumber.TRUE } : {}),
? { ...(headerTreated && pivot.headerFontColor ? { cl: { rgb: pivot.headerFontColor } } : {}),
bl: BooleanNumber.TRUE,
...(pivot.headerFontColor ? { cl: { rgb: pivot.headerFontColor } } : {}),
}
: {}),
} }
} }
} }
@@ -3644,6 +3758,7 @@ export async function preloadEntireWorkbook(
screen.rows, screen.rows,
sheet.columnWidths, sheet.columnWidths,
sheet.defaultRowHeightFixed, sheet.defaultRowHeightFixed,
sheet.defaultRowHeight,
screenRange, screenRange,
), ),
) )
@@ -3710,6 +3825,9 @@ function captureSheetFileState(
colBreaks: [...result.colBreaks], colBreaks: [...result.colBreaks],
}) })
} }
if (!state.sheetFilePageSetups.has(sheetId) && result.pageSetup != null) {
state.sheetFilePageSetups.set(sheetId, result.pageSetup)
}
if (!state.sheetProtectedRanges.has(sheetId)) { if (!state.sheetProtectedRanges.has(sheetId)) {
// File coordinates → this session's screen space; later structural ops // File coordinates → this session's screen space; later structural ops
// remap the stored set incrementally (see the App structural listener). // remap the stored set incrementally (see the App structural listener).
@@ -4652,7 +4770,7 @@ type CfHighlightBuilder = ReturnType<
ReturnType<UniverWorksheet['newConditionalFormattingRule']>['whenCellNotEmpty'] ReturnType<UniverWorksheet['newConditionalFormattingRule']>['whenCellNotEmpty']
> >
function buildConditionalRule( export function buildConditionalRule(
worksheet: UniverWorksheet, worksheet: UniverWorksheet,
dxfStyles: readonly WorkbookCellStyle[], dxfStyles: readonly WorkbookCellStyle[],
rule: WorkbookRangeResult['conditionalRules'][number], rule: WorkbookRangeResult['conditionalRules'][number],
@@ -4739,17 +4857,54 @@ function buildConditionalRule(
const highlight = buildHighlightCondition(builder, rule, anchor, coveredCells) const highlight = buildHighlightCondition(builder, rule, anchor, coveredCells)
if (!highlight) return null if (!highlight) return null
const built = applyDxfFormat(highlight, dxfStyles, rule.dxfIndex).setRanges(ranges).build() const built = applyDxfFormat(highlight, dxfStyles, rule.dxfIndex).setRanges(ranges).build()
// The facade builder has no number-format setter, but IHighlightCell.style patchBuiltHighlightRule(
// is an IStyleBase which carries n — a dxf numFmt goes onto the built rule built.rule as BuiltHighlightRule,
// (a numFmt-only dxf builds with no style object at all). rule.ruleType,
const pattern = rule.dxfIndex === undefined ? undefined : dxfStyles[rule.dxfIndex]?.numberFormat rule.dxfIndex === undefined ? undefined : dxfStyles[rule.dxfIndex],
if (pattern) { )
const target = built.rule as { style?: { n?: { pattern: string } } }
target.style = { ...target.style, n: { pattern } }
}
return built return built
} }
export type BuiltHighlightRule = {
operator?: string
value?: string
/// The builder's IStyleBase plus the patched-on keys.
style?: {
n?: { pattern: string }
bd?: Partial<Record<'t' | 'b' | 'l' | 'r', ReturnType<typeof toUniverBorder>>>
[key: string]: unknown
}
}
/// IHighlightCell supports more than the facade builder exposes: style is an
/// IStyleBase (the paint path merges its n and bd verbatim), and the
/// error-presence text operators have no setter at all. Patch the built rule
/// for a dxf number format, dxf borders, and containsErrors /
/// notContainsErrors (built as a placeholder text condition in
/// buildHighlightCondition).
export function patchBuiltHighlightRule(
target: BuiltHighlightRule,
ruleType: string,
dxf: WorkbookCellStyle | undefined,
): void {
if (ruleType === 'containsErrors' || ruleType === 'notContainsErrors') {
target.operator = ruleType
delete target.value
}
if (!dxf) return
// A numFmt-only dxf builds with no style object at all.
if (dxf.numberFormat) {
target.style = { ...target.style, n: { pattern: dxf.numberFormat } }
}
const bd = {
...(dxf.borderTop ? { t: toUniverBorder(dxf.borderTop) } : {}),
...(dxf.borderBottom ? { b: toUniverBorder(dxf.borderBottom) } : {}),
...(dxf.borderLeft ? { l: toUniverBorder(dxf.borderLeft) } : {}),
...(dxf.borderRight ? { r: toUniverBorder(dxf.borderRight) } : {}),
}
if (Object.keys(bd).length > 0) target.style = { ...target.style, bd }
}
function toCfValue(cfvo: { kind: string; value?: string | undefined }): IValueConfig { function toCfValue(cfvo: { kind: string; value?: string | undefined }): IValueConfig {
switch (cfvo.kind) { switch (cfvo.kind) {
case 'min': case 'min':
@@ -4919,6 +5074,12 @@ function buildHighlightCondition(
return builder.whenCellEmpty() return builder.whenCellEmpty()
case 'notContainsBlanks': case 'notContainsBlanks':
return builder.whenCellNotEmpty() return builder.whenCellNotEmpty()
case 'containsErrors':
case 'notContainsErrors':
// Univer's calculate unit evaluates these operators but the facade
// builder has no setter; build a placeholder text condition and
// re-target the operator on the built rule (patchBuiltHighlightRule).
return builder.whenTextContains('')
case 'duplicateValues': case 'duplicateValues':
return builder.setDuplicateValues() return builder.setDuplicateValues()
case 'uniqueValues': case 'uniqueValues':
@@ -5334,8 +5495,14 @@ export function queueSparklineInstall(
cells: entry.cells, cells: entry.cells,
})), })),
] ]
sparklineDisposablesRef.current = // In-cell rich-value pictures share the per-cell float DOM lifecycle.
sparklines.length === 0 ? [] : installSparklines(runtime, sparklines, sheetId) const cellImages = sheetMeta?.cellImages ?? []
sparklineDisposablesRef.current = [
...(sparklines.length === 0 ? [] : installSparklines(runtime, sparklines, sheetId)),
...(cellImages.length === 0
? []
: installCellImages(runtime, state.file.sessionId, cellImages, sheetId)),
]
}, 100) }, 100)
} }
+46 -3
View File
@@ -5,6 +5,8 @@
* helpers applied against the live Univer runtime. Extracted from App.tsx; * helpers applied against the live Univer runtime. Extracted from App.tsx;
* every function receives its runtime and state explicitly. * every function receives its runtime and state explicitly.
*/ */
import { isDefaultFormat, numfmt } from '@univerjs/core'
import { DATE_1904_OFFSET, isCalendarDatePattern } from './numfmt-fix'
import type { import type {
AddPivotOperation, AddPivotOperation,
AddTableColumnOperation, AddTableColumnOperation,
@@ -221,6 +223,46 @@ export function applyAiTableColumnAdd(
}) })
} }
/// Width-independent pivot source read. getValues() goes through the view
/// interceptors, which clip numbers to the column width (#### fill,
/// budget-limited General) — lies that must not become pivot labels,
/// aggregates, saved sharedItems, or recompute keys (a date column displayed
/// as #### broke timeline binding and slicer recompute). Re-format raw
/// values through each cell's own pattern instead; General numbers stay
/// numeric.
export function readPivotSourceGrid(
range: {
getRawValues(): unknown[][]
getNumberFormats(): string[][]
getFormulas(): string[][]
},
date1904: boolean,
): (string | number | boolean | null)[][] {
const patterns = range.getNumberFormats()
// 1904 workbooks: file-loaded static serials count from 1904-01-01, but
// formula results come from the 1900-based engine — same rule as the
// display interceptor's calendar-date shift.
const formulas = date1904 ? range.getFormulas() : null
return (range.getRawValues() as (string | number | boolean | null)[][]).map((row, rowOffset) =>
row.map((value, columnOffset) => {
if (typeof value !== 'number') return value
const pattern = patterns[rowOffset]?.[columnOffset] ?? ''
if (pattern === '' || isDefaultFormat(pattern)) return value
const shift =
formulas !== null &&
isCalendarDatePattern(pattern) &&
(formulas[rowOffset]?.[columnOffset] ?? '') === ''
? DATE_1904_OFFSET
: 0
try {
return numfmt.format(pattern, value + shift, { nbsp: true, throws: false })
} catch {
return value
}
}),
)
}
export function applyAiPivotAdd( export function applyAiPivotAdd(
runtime: UniverRuntime, runtime: UniverRuntime,
state: LazyWorkbookState, state: LazyWorkbookState,
@@ -257,9 +299,10 @@ export function applyAiPivotAdd(
// Univer's Nullable<CellValue> narrows to the scalar union we aggregate // Univer's Nullable<CellValue> narrows to the scalar union we aggregate
// over; undefined behaves like an empty cell throughout. // over; undefined behaves like an empty cell throughout.
const grid = sourceSheet const grid = readPivotSourceGrid(
.getRange(source.startRow, source.startColumn, sourceRows, sourceColumns) sourceSheet.getRange(source.startRow, source.startColumn, sourceRows, sourceColumns),
.getValues() as (string | number | boolean | null)[][] state.file.date1904 === true,
)
const fieldNames = (grid[0] ?? []).map((value) => String(value ?? '').trim()) const fieldNames = (grid[0] ?? []).map((value) => String(value ?? '').trim())
if (fieldNames.some((name) => name.length === 0)) { if (fieldNames.some((name) => name.length === 0)) {
throw new Error(t('appPivotHeaderBlank')) throw new Error(t('appPivotHeaderBlank'))
+155 -4
View File
@@ -1,6 +1,11 @@
import { z } from 'zod' import { z } from 'zod'
import { MAX_SAVE_EDITS, MAX_SAVE_EDITS_TOTAL, SAVE_EDITS_CHUNK_MAX } from './ipc-channels' import {
MAX_CSV_EXPORT_CHARS,
MAX_SAVE_EDITS,
MAX_SAVE_EDITS_TOTAL,
SAVE_EDITS_CHUNK_MAX,
} from './ipc-channels'
import { ADDABLE_SHAPE_TYPES } from './shape-types' import { ADDABLE_SHAPE_TYPES } from './shape-types'
import type { import type {
AiChatRequest, AiChatRequest,
@@ -52,6 +57,10 @@ const worksheetMetadataSchema = z
/// compatibility with an older sidecar binary. /// compatibility with an older sidecar binary.
defaultRowHeightFixed: z.boolean().optional(), defaultRowHeightFixed: z.boolean().optional(),
defaultColumnWidth: z.number().nonnegative().nullable(), defaultColumnWidth: z.number().nonnegative().nullable(),
/// sheetFormatPr/@baseColWidth — the built-in default column width is
/// derived from this (default 8) when defaultColWidth is absent.
/// Optional for compatibility with an older sidecar binary.
baseColumnWidth: z.number().nonnegative().nullable().optional(),
freeze: z freeze: z
.object({ .object({
frozenColumns: z.number().int().nonnegative(), frozenColumns: z.number().int().nonnegative(),
@@ -140,6 +149,8 @@ const worksheetMetadataSchema = z
/// Body band fill for solid families (Dark); stripe overlays it. /// Body band fill for solid families (Dark); stripe overlays it.
wholeTableFill: z.string().optional(), wholeTableFill: z.string().optional(),
stripeFill: z.string().optional(), stripeFill: z.string().optional(),
/// A named pivotTableStyleInfo: band rows bold even with no fills.
styled: z.boolean().optional(),
firstDataRow: z.number().int().nonnegative().optional(), firstDataRow: z.number().int().nonnegative().optional(),
rowGrandTotals: z.boolean().optional(), rowGrandTotals: z.boolean().optional(),
}) })
@@ -173,6 +184,25 @@ const worksheetMetadataSchema = z
) )
.max(100) .max(100)
.default([]), .default([]),
/// Saved `_xlnm.Print_Area` / `_xlnm.Print_Titles` formulas for this
/// sheet, verbatim from workbook.xml.
printArea: z.string().min(1).max(2_000).optional(),
printTitles: z.string().min(1).max(2_000).optional(),
/// In-cell rich-value pictures (Excel "place picture in cell"): the id is
/// a media lookup key for readWorkbookMedia, like a visual id.
/// Defaulted for stale sidecar binaries, like sparklines.
cellImages: z
.array(
z
.object({
id: z.string().min(1),
row: z.number().int().nonnegative(),
column: z.number().int().nonnegative(),
})
.strict(),
)
.max(500)
.default([]),
}) })
.strict() .strict()
const richRunSchema = z const richRunSchema = z
@@ -274,6 +304,11 @@ const drawingAnchorSchema = z
toColumn: z.number().int().nonnegative(), toColumn: z.number().int().nonnegative(),
toRowOffset: z.number().int(), toRowOffset: z.number().int(),
toColumnOffset: z.number().int(), toColumnOffset: z.number().int(),
/// True when the file carried a real `<xdr:to>` marker: its offset
/// clamps at the cell edge (Excel behavior for broken writers) instead
/// of walking past it like synthesized oneCellAnchor/absoluteAnchor
/// encodings.
explicitTo: z.boolean().optional(),
}) })
.strict() .strict()
const chartAxisInfoSchema = z const chartAxisInfoSchema = z
@@ -286,6 +321,8 @@ const chartAxisInfoSchema = z
majorGridlines: z.boolean(), majorGridlines: z.boolean(),
/// c:delete — the axis scales series but is not drawn. /// c:delete — the axis scales series but is not drawn.
hidden: z.boolean().default(false), hidden: z.boolean().default(false),
/// c:scaling/c:orientation val="maxMin".
reversed: z.boolean().default(false),
}) })
.strict() .strict()
@@ -342,9 +379,24 @@ const visualObjectSchema = z
.optional(), .optional(),
/// spPr/a:ln color; "none" for an explicit noFill line. /// spPr/a:ln color; "none" for an explicit noFill line.
lineColor: z.string().optional(), lineColor: z.string().optional(),
/// spPr/a:ln/@w in CSS px (EMU / 12700 pt · 96/72).
lineWidth: z.number().finite().optional(),
smooth: z.boolean().optional(), smooth: z.boolean().optional(),
/// c:marker symbol — "none" hides scatter/line markers. /// c:marker symbol — "none" hides scatter/line markers.
marker: z.string().optional(), marker: z.string().optional(),
/// First outer multiLvlStrCache level; start/end index the
/// compacted `categories` (end exclusive).
categoryGroups: z
.array(
z
.object({
label: z.string(),
start: z.number().int().nonnegative(),
end: z.number().int().nonnegative(),
})
.strict(),
)
.optional(),
}) })
.strict(), .strict(),
), ),
@@ -390,6 +442,8 @@ const visualObjectSchema = z
secondaryYAxis: chartAxisInfoSchema.optional(), secondaryYAxis: chartAxisInfoSchema.optional(),
/// c:scatterStyle — whether scatter points connect with lines. /// c:scatterStyle — whether scatter points connect with lines.
scatterStyle: z.string().optional(), scatterStyle: z.string().optional(),
/// Plot-level c:lineChart/c:marker flag; per-series symbols refine it.
lineMarkers: z.boolean().optional(),
/// c:title/c:txPr//a:defRPr shorthand. /// c:title/c:txPr//a:defRPr shorthand.
titleStyle: z titleStyle: z
.object({ .object({
@@ -405,6 +459,12 @@ const visualObjectSchema = z
chartPath: z.string().optional(), chartPath: z.string().optional(),
mediaPath: z.string().optional(), mediaPath: z.string().optional(),
mediaType: z.string().optional(), mediaType: z.string().optional(),
/// a:blip/a:alphaModFix amt as 0..1 picture opacity.
opacity: z.number().min(0).max(1).optional(),
/// spPr/a:blipFill on a shape — the image painted clipped to the
/// preset geometry.
fillMediaPath: z.string().optional(),
fillMediaType: z.string().optional(),
/// Renderer-only: preview bytes for images added this session (not yet in /// Renderer-only: preview bytes for images added this session (not yet in
/// the package); the sidecar never emits this. /// the package); the sidecar never emits this.
mediaDataUrl: z.string().optional(), mediaDataUrl: z.string().optional(),
@@ -526,9 +586,14 @@ export const workbookFileSchema = z
.strict(), .strict(),
), ),
readOnly: z.boolean(), readOnly: z.boolean(),
/// Converted import (.xls/.csv): the first save opens a Save As dialog, /// Converted .xls import: the first save opens a Save As dialog,
/// so background flows (AutoSave) must not trigger mode 'save'. /// so background flows (AutoSave) must not trigger mode 'save'.
needsSaveAs: z.boolean().optional(), needsSaveAs: z.boolean().optional(),
/// CSV session: the original .csv on disk. Save keeps the CSV identity —
/// the renderer sends csvContent with the save and the main process
/// writes it back here. Background flows (AutoSave, crash recovery)
/// stand down: silently flattening the file would lose data.
csvPath: z.string().min(1).optional(),
/// Session opened from a restored crash-recovery copy: Save silently /// Session opened from a restored crash-recovery copy: Save silently
/// writes back to the original file, and the 30s recovery writer stands /// writes back to the original file, and the 30s recovery writer stands
/// down (it would overwrite the copy the sidecar is streaming from). /// down (it would overwrite the copy the sidecar is streaming from).
@@ -673,6 +738,38 @@ export const workbookRangeResultSchema = z
/// sheet-wide, complete-only. /// sheet-wide, complete-only.
rowBreaks: z.array(z.number().int().nonnegative()).max(1_024), rowBreaks: z.array(z.number().int().nonnegative()).max(1_024),
colBreaks: z.array(z.number().int().nonnegative()).max(1_024), colBreaks: z.array(z.number().int().nonnegative()).max(1_024),
/// Saved print settings (pageSetup / pageMargins / printOptions /
/// headerFooter); sheet-wide, complete-only. Absent/null when the sheet
/// declares none (also for stale sidecar binaries).
pageSetup: z
.object({
orientation: z.enum(['portrait', 'landscape']).optional(),
paperSize: z.number().int().min(1).max(256).optional(),
scale: z.number().int().min(10).max(400).optional(),
fitToWidth: z.number().int().min(0).max(32_767).optional(),
fitToHeight: z.number().int().min(0).max(32_767).optional(),
fitToPage: z.boolean().optional(),
/// Inches.
margins: z
.object({
left: z.number().min(0).max(10),
right: z.number().min(0).max(10),
top: z.number().min(0).max(10),
bottom: z.number().min(0).max(10),
header: z.number().min(0).max(10),
footer: z.number().min(0).max(10),
})
.strict()
.optional(),
printGridlines: z.boolean().optional(),
printHeadings: z.boolean().optional(),
/// Excel-encoded odd header/footer (&L/&C/&R sections, field codes).
oddHeader: z.string().min(1).max(500).optional(),
oddFooter: z.string().min(1).max(500).optional(),
})
.strict()
.nullish()
.default(null),
/// Allow-edit ranges (<protectedRanges>); sheet-wide, complete-only. /// Allow-edit ranges (<protectedRanges>); sheet-wide, complete-only.
protectedRanges: z protectedRanges: z
.array( .array(
@@ -1651,6 +1748,9 @@ export const workbookSaveRequestSchema = z
/// change is the workbook bytes themselves, so the request is valid with /// change is the workbook bytes themselves, so the request is valid with
/// an otherwise empty payload (like an explicit Save As). /// an otherwise empty payload (like an explicit Save As).
restoreWriteBack: z.boolean().optional(), restoreWriteBack: z.boolean().optional(),
/// CSV session in-place save: the active sheet serialized as CSV text.
/// Written back to the session's original .csv after the xlsx save.
csvContent: z.string().max(MAX_CSV_EXPORT_CHARS).optional(),
edits: z.array(workbookCellEditSchema).max(MAX_SAVE_EDITS), edits: z.array(workbookCellEditSchema).max(MAX_SAVE_EDITS),
/// Edit sets above MAX_SAVE_EDITS arrive through the chunked transfer /// Edit sets above MAX_SAVE_EDITS arrive through the chunked transfer
/// (saveEditsBegin/saveEditsChunk) instead of inline: the request then /// (saveEditsBegin/saveEditsChunk) instead of inline: the request then
@@ -1854,7 +1954,15 @@ export const workbookSaveRequestSchema = z
}) })
export const workbookSaveResultSchema = z.union([ export const workbookSaveResultSchema = z.union([
z.object({ canceled: z.literal(true) }).strict(), z
.object({
canceled: z.literal(true),
/// The user picked the CSV format in the Save As dialog: no xlsx was
/// written; the renderer serializes the active sheet to this path via
/// the CSV export channel instead.
csvSaveAsPath: z.string().min(1).optional(),
})
.strict(),
z z
.object({ .object({
canceled: z.literal(false), canceled: z.literal(false),
@@ -2089,6 +2197,8 @@ export type WorkbookRangeRequest = z.infer<typeof workbookRangeRequestSchema>
export type WorkbookFormulaCellsRequest = z.infer<typeof workbookFormulaCellsRequestSchema> export type WorkbookFormulaCellsRequest = z.infer<typeof workbookFormulaCellsRequestSchema>
export type WorkbookFormulaCellsResult = z.infer<typeof workbookFormulaCellsResultSchema> export type WorkbookFormulaCellsResult = z.infer<typeof workbookFormulaCellsResultSchema>
export type WorkbookRangeResult = z.infer<typeof workbookRangeResultSchema> export type WorkbookRangeResult = z.infer<typeof workbookRangeResultSchema>
/// The sheet's saved print settings as parsed from the file.
export type WorkbookPagePrintSettings = NonNullable<WorkbookRangeResult['pageSetup']>
export type WorkbookRecalcRequest = z.infer<typeof workbookRecalcRequestSchema> export type WorkbookRecalcRequest = z.infer<typeof workbookRecalcRequestSchema>
export type WorkbookRecalcResult = z.infer<typeof workbookRecalcResultSchema> export type WorkbookRecalcResult = z.infer<typeof workbookRecalcResultSchema>
export type WorkbookMediaRequest = z.infer<typeof workbookMediaRequestSchema> export type WorkbookMediaRequest = z.infer<typeof workbookMediaRequestSchema>
@@ -2168,6 +2278,8 @@ const agentMessageSchema = z.union([
role: z.literal('assistant'), role: z.literal('assistant'),
text: z.string(), text: z.string(),
toolCalls: z.array(agentToolCallSchema).optional(), toolCalls: z.array(agentToolCallSchema).optional(),
// captured model thinking, echoed back for interleaved-thinking models
reasoning: z.string().optional(),
}) })
.strict(), .strict(),
z.object({ role: z.literal('tool'), results: z.array(agentToolResultSchema) }).strict(), z.object({ role: z.literal('tool'), results: z.array(agentToolResultSchema) }).strict(),
@@ -2234,6 +2346,10 @@ export const workbookExportPdfRequestSchema = z
}) })
.strict(), .strict(),
scale: z.number().min(0.1).max(2), scale: z.number().min(0.1).max(2),
/// Chromium print header/footer templates (rendered in the margin
/// boxes; `pageNumber`/`totalPages` spans resolve per page).
headerTemplate: z.string().min(1).max(50_000).optional(),
footerTemplate: z.string().min(1).max(50_000).optional(),
}) })
.strict() .strict()
@@ -2245,6 +2361,38 @@ export const workbookExportPdfResultSchema = z.union([
export type WorkbookExportPdfRequest = z.infer<typeof workbookExportPdfRequestSchema> export type WorkbookExportPdfRequest = z.infer<typeof workbookExportPdfRequestSchema>
export type WorkbookExportPdfResult = z.infer<typeof workbookExportPdfResultSchema> export type WorkbookExportPdfResult = z.infer<typeof workbookExportPdfResultSchema>
/// CSV export of the active sheet: the renderer serializes display values,
/// the main process runs the loss warning + save dialog and writes the bytes.
export const workbookExportCsvRequestSchema = z
.object({
fileName: z.string().min(1).max(255),
content: z.string().max(MAX_CSV_EXPORT_CHARS),
/// The exported sheet carries formulas — CSV keeps their values only, so
/// the main process offers Save As .xlsx first (Excel's warning flow).
hasFormulas: z.boolean(),
/// Set when the workbook has more sheets than the exported one.
activeSheetName: z.string().max(255).optional(),
/// Write straight to this path (from the Save As dialog's CSV pick)
/// instead of opening another save dialog.
targetPath: z.string().min(1).optional(),
})
.strict()
export const workbookExportCsvResultSchema = z.union([
z
.object({
canceled: z.literal(true),
/// The user chose "Save as .xlsx" in the formula-loss warning; the
/// renderer routes into the regular Save As flow instead.
saveAsXlsxInstead: z.boolean().optional(),
})
.strict(),
z.object({ canceled: z.literal(false), path: z.string().min(1) }).strict(),
])
export type WorkbookExportCsvRequest = z.infer<typeof workbookExportCsvRequestSchema>
export type WorkbookExportCsvResult = z.infer<typeof workbookExportCsvResultSchema>
// ---- Chat attachments (local files fed to the agent via tools; same structure // ---- Chat attachments (local files fed to the agent via tools; same structure
// as apps/docs and apps/slides) ---- // as apps/docs and apps/slides) ----
@@ -2349,6 +2497,9 @@ export interface DesktopApi {
baseName: string, baseName: string,
): Promise<{ renamed: boolean; name?: string }> ): Promise<{ renamed: boolean; name?: string }>
exportPdf(request: WorkbookExportPdfRequest): Promise<WorkbookExportPdfResult> exportPdf(request: WorkbookExportPdfRequest): Promise<WorkbookExportPdfResult>
exportCsv(request: WorkbookExportCsvRequest): Promise<WorkbookExportCsvResult>
/// First Save of a CSV session: native "keep this format?" dialog.
confirmCsvSave(): Promise<'csv' | 'xlsx' | 'cancel'>
closeWorkbook(sessionId: string): Promise<void> closeWorkbook(sessionId: string): Promise<void>
openExternal(url: string): Promise<void> openExternal(url: string): Promise<void>
/// Application-menu File commands (Open/Save/Save As); returns unsubscribe. /// Application-menu File commands (Open/Save/Save As); returns unsubscribe.
@@ -2408,7 +2559,7 @@ export interface DesktopApi {
getPathForFile(file: File): string getPathForFile(file: File): string
} }
export type MenuAction = 'open' | 'save' | 'save-as' | 'export-pdf' | 'undo' | 'redo' export type MenuAction = 'open' | 'save' | 'save-as' | 'export-pdf' | 'export-csv' | 'undo' | 'redo'
export interface WebSearchResult { export interface WebSearchResult {
results: Array<{ title: string; url: string; snippet: string }> results: Array<{ title: string; url: string; snippet: string }>
+6
View File
@@ -15,6 +15,10 @@ export const MAX_SAVE_EDITS = 1_000_000
export const SAVE_EDITS_CHUNK_MAX = 100_000 export const SAVE_EDITS_CHUNK_MAX = 100_000
export const MAX_SAVE_EDITS_TOTAL = 10_000_000 export const MAX_SAVE_EDITS_TOTAL = 10_000_000
/// Upper bound on one CSV export's serialized text (shared by the zod schema
/// and the preload validator, like MAX_SAVE_EDITS above).
export const MAX_CSV_EXPORT_CHARS = 64_000_000
export const IPC_CHANNELS = { export const IPC_CHANNELS = {
selectWorkbook: 'workbook:select', selectWorkbook: 'workbook:select',
readWorkbookRange: 'workbook:read-range', readWorkbookRange: 'workbook:read-range',
@@ -40,6 +44,8 @@ export const IPC_CHANNELS = {
closeSaveRequest: 'workbook:close-save-request', closeSaveRequest: 'workbook:close-save-request',
closeSaveResult: 'workbook:close-save-result', closeSaveResult: 'workbook:close-save-result',
exportPdf: 'workbook:export-pdf', exportPdf: 'workbook:export-pdf',
exportCsv: 'workbook:export-csv',
csvSaveConfirm: 'workbook:csv-save-confirm',
openExternal: 'shell:open-external', openExternal: 'shell:open-external',
menuAction: 'menu:action', menuAction: 'menu:action',
aiGetSettings: 'ai:get-settings', aiGetSettings: 'ai:get-settings',
@@ -0,0 +1,41 @@
import { describe, expect, it } from 'vitest'
import {
clampExplicitTo,
EMU_PER_PIXEL,
markerFrom,
walkMarker,
} from '../src/renderer/WorkbookVisuals'
const columnWidth = (): number => 64
describe('clampExplicitTo', () => {
it('clamps a real <xdr:to> offset at the cell edge like Excel', () => {
// closedxml_picture-webp.xlsx: to = col 0 + 3524250 EMU (~370px) while
// col 0 is ~64px wide — Excel shows a col-sized sliver, not 370px.
const to = markerFrom(0, 3524250)
expect(to.offset).toBeCloseTo(3524250 / EMU_PER_PIXEL)
expect(clampExplicitTo(to, true, columnWidth)).toEqual({ index: 0, offset: 64 })
})
it('keeps in-cell offsets untouched', () => {
const to = markerFrom(3, 10 * EMU_PER_PIXEL)
expect(clampExplicitTo(to, true, columnWidth)).toBe(to)
})
it('never clamps synthesized markers (oneCellAnchor ext, absoluteAnchor)', () => {
const to = markerFrom(0, 3524250)
expect(clampExplicitTo(to, false, columnWidth)).toBe(to)
})
it('drag commits walk from the clamped edge, not the raw overflow', () => {
// commitDrag seeds its to marker this way: without the clamp, walkMarker
// normalizes the ~370px overflow into real columns and the committed
// anchor re-expands the visual to its walked size.
const to = clampExplicitTo(markerFrom(0, 3524250), true, columnWidth)
expect(walkMarker(to, 10, columnWidth, 100)).toEqual({ index: 1, offset: 10 })
// Normal in-cell anchors take the identical path (clamp is a no-op).
const normal = clampExplicitTo(markerFrom(2, 10 * EMU_PER_PIXEL), true, columnWidth)
expect(walkMarker(normal, 10, columnWidth, 100)).toEqual({ index: 2, offset: 20 })
})
})
+101
View File
@@ -0,0 +1,101 @@
import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
import { rename, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { atomicWriteFile } from '../src/main/atomic-write'
vi.mock('node:fs/promises', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs/promises')>()
return { ...actual, rename: vi.fn(actual.rename), writeFile: vi.fn(actual.writeFile) }
})
let dir = ''
afterEach(() => {
if (dir) rmSync(dir, { recursive: true, force: true })
dir = ''
vi.mocked(rename).mockClear()
vi.mocked(writeFile).mockClear()
})
const epermError = () =>
Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' })
describe('atomicWriteFile', () => {
it('replaces the target and leaves no temp file behind', async () => {
dir = mkdtempSync(join(tmpdir(), 'sheets-aw-'))
const target = join(dir, 'data.csv')
writeFileSync(target, 'old')
await atomicWriteFile(target, Buffer.from('new'))
expect(readFileSync(target, 'utf8')).toBe('new')
expect(readdirSync(dir)).toEqual(['data.csv'])
})
it('retries transient Windows rename locks', async () => {
dir = mkdtempSync(join(tmpdir(), 'sheets-aw-'))
const target = join(dir, 'data.csv')
writeFileSync(target, 'old')
vi.mocked(rename).mockRejectedValueOnce(epermError()).mockRejectedValueOnce(epermError())
await atomicWriteFile(target, Buffer.from('new'))
expect(vi.mocked(rename)).toHaveBeenCalledTimes(3)
expect(readFileSync(target, 'utf8')).toBe('new')
expect(readdirSync(dir)).toEqual(['data.csv'])
})
it('falls back to an in-place write when the rename stays locked', async () => {
dir = mkdtempSync(join(tmpdir(), 'sheets-aw-'))
const target = join(dir, 'data.csv')
writeFileSync(target, 'old')
for (let attempt = 0; attempt < 5; attempt += 1) {
vi.mocked(rename).mockRejectedValueOnce(epermError())
}
await atomicWriteFile(target, Buffer.from('new'))
expect(readFileSync(target, 'utf8')).toBe('new')
expect(readdirSync(dir)).toEqual(['data.csv'])
})
it('preserves the completed temp file when the fallback write fails', async () => {
dir = mkdtempSync(join(tmpdir(), 'sheets-aw-'))
const target = join(dir, 'data.csv')
writeFileSync(target, 'old')
for (let attempt = 0; attempt < 5; attempt += 1) {
vi.mocked(rename).mockRejectedValueOnce(epermError())
}
const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
const fallbackError = Object.assign(new Error('EIO: fallback write failed'), { code: 'EIO' })
vi.mocked(writeFile)
.mockImplementationOnce(actual.writeFile)
.mockRejectedValueOnce(fallbackError)
await expect(atomicWriteFile(target, Buffer.from('new'))).rejects.toThrow(
'fallback write failed',
)
const files = readdirSync(dir)
expect(files).toContain('data.csv')
const temp = files.find((file) => file !== 'data.csv')
expect(temp).toBeDefined()
expect(readFileSync(join(dir, temp!), 'utf8')).toBe('new')
})
it('uses distinct temp files for concurrent writes to one target', async () => {
dir = mkdtempSync(join(tmpdir(), 'sheets-aw-'))
const target = join(dir, 'data.csv')
await Promise.all([
atomicWriteFile(target, Buffer.from('first')),
atomicWriteFile(target, Buffer.from('second')),
])
expect(['first', 'second']).toContain(readFileSync(target, 'utf8'))
expect(readdirSync(dir)).toEqual(['data.csv'])
})
})
+1 -1
View File
@@ -6,7 +6,7 @@ import {
withSansSerifFallback, withSansSerifFallback,
} from '../src/renderer/cell-font-fallback' } from '../src/renderer/cell-font-fallback'
const EMOJI = '"Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji"' const EMOJI = '"Cell Text Dingbats", "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji"'
describe('withSansSerifFallback', () => { describe('withSansSerifFallback', () => {
it('appends sans-serif to a bare family string', () => { it('appends sans-serif to a bare family string', () => {
+147
View File
@@ -0,0 +1,147 @@
import { describe, expect, it } from 'vitest'
import { BorderStyleTypes } from '@univerjs/core'
import { FConditionalFormattingBuilder } from '@univerjs/sheets-conditional-formatting/facade'
import {
buildConditionalRule,
patchBuiltHighlightRule,
type BuiltHighlightRule,
} from '../src/renderer/univer-sync'
import type { WorkbookCellStyle } from '../src/shared/desktop-api'
type CfRule = Parameters<typeof buildConditionalRule>[2]
const worksheet = {
newConditionalFormattingRule: () => new FConditionalFormattingBuilder(),
} as unknown as Parameters<typeof buildConditionalRule>[0]
function cfRule(overrides: Partial<CfRule>): CfRule {
return {
ranges: [{ startRow: 0, startColumn: 0, endRow: 3, endColumn: 0 }],
ruleType: 'cellIs',
formulas: [],
priority: 1,
percent: false,
bottom: false,
cfvos: [],
colors: [],
iconReverse: false,
showValue: true,
...overrides,
}
}
function dxf(overrides: Partial<WorkbookCellStyle>): WorkbookCellStyle {
return {
bold: false,
italic: false,
underline: false,
strikethrough: false,
wrapText: false,
diagonalUp: false,
diagonalDown: false,
...overrides,
}
}
describe('patchBuiltHighlightRule', () => {
it('re-targets the placeholder text condition to containsErrors', () => {
const target: BuiltHighlightRule = {
operator: 'containsText',
value: '',
style: { bg: { rgb: '#FF0000' } },
}
patchBuiltHighlightRule(target, 'containsErrors', dxf({ fillColor: '#FF0000' }))
expect(target.operator).toBe('containsErrors')
expect('value' in target).toBe(false)
expect(target.style).toMatchObject({ bg: { rgb: '#FF0000' } })
})
it('re-targets to notContainsErrors', () => {
const target: BuiltHighlightRule = { operator: 'containsText', value: '' }
patchBuiltHighlightRule(target, 'notContainsErrors', undefined)
expect(target.operator).toBe('notContainsErrors')
expect('value' in target).toBe(false)
})
it('leaves other rule types untouched', () => {
const target: BuiltHighlightRule = { operator: 'containsText', value: 'apple' }
patchBuiltHighlightRule(target, 'containsText', undefined)
expect(target).toEqual({ operator: 'containsText', value: 'apple' })
})
it('injects dxf borders onto the built style', () => {
const target: BuiltHighlightRule = {}
patchBuiltHighlightRule(
target,
'cellIs',
dxf({
fontColor: '#008000',
borderTop: { style: 'thin', color: '#008000' },
borderBottom: { style: 'medium' },
}),
)
expect(target.style?.bd).toEqual({
t: { s: BorderStyleTypes.THIN, cl: { rgb: '#008000' } },
b: { s: BorderStyleTypes.MEDIUM, cl: { rgb: '#000000' } },
})
})
it('merges borders and number format without dropping builder style keys', () => {
const target: BuiltHighlightRule = { style: { bg: { rgb: '#FFFF00' } } }
patchBuiltHighlightRule(
target,
'expression',
dxf({ numberFormat: '0.00%', borderLeft: { style: 'dashed', color: '#0000FF' } }),
)
expect(target.style).toMatchObject({
bg: { rgb: '#FFFF00' },
n: { pattern: '0.00%' },
bd: { l: { s: BorderStyleTypes.DASHED, cl: { rgb: '#0000FF' } } },
})
})
it('does not create a style for a border-free dxf', () => {
const target: BuiltHighlightRule = {}
patchBuiltHighlightRule(target, 'cellIs', dxf({ fillColor: '#FF0000' }))
expect(target.style).toBeUndefined()
})
})
describe('buildConditionalRule', () => {
it('builds notContainsErrors as a text rule with the error operator and dxf fill', () => {
const built = buildConditionalRule(
worksheet,
[dxf({ fillColor: '#FF0000' })],
cfRule({ ruleType: 'notContainsErrors', dxfIndex: 0, formulas: ['NOT(ISERROR(A1))'] }),
)
expect(built?.rule).toMatchObject({
type: 'highlightCell',
subType: 'text',
operator: 'notContainsErrors',
})
expect((built?.rule as { value?: string }).value).toBeUndefined()
expect((built?.rule as BuiltHighlightRule).style?.bg).toBeTruthy()
expect(built?.ranges).toEqual([{ startRow: 0, startColumn: 0, endRow: 3, endColumn: 0 }])
})
it('builds containsErrors', () => {
const built = buildConditionalRule(
worksheet,
[],
cfRule({ ruleType: 'containsErrors', formulas: ['ISERROR(A1)'] }),
)
expect(built?.rule).toMatchObject({ subType: 'text', operator: 'containsErrors' })
})
it('carries a dxf border onto the built cellIs rule style', () => {
const built = buildConditionalRule(
worksheet,
[dxf({ bold: true, borderTop: { style: 'thin', color: '#92D050' } })],
cfRule({ ruleType: 'cellIs', operator: 'equal', dxfIndex: 0, formulas: ['1'] }),
)
expect(built?.rule).toMatchObject({ subType: 'number', operator: 'equal' })
const style = (built?.rule as BuiltHighlightRule).style
expect(style?.bd).toEqual({ t: { s: BorderStyleTypes.THIN, cl: { rgb: '#92D050' } } })
expect(style?.bl).toBe(1)
})
})
@@ -0,0 +1,51 @@
import { describe, expect, it } from 'vitest'
import {
legendSwatchColor,
legendUsesLineSwatches,
lineStroke,
} from '../src/renderer/WorkbookVisuals'
describe('lineStroke', () => {
it('prefers the explicit series line color over the fill/accent default', () => {
expect(lineStroke({ color: '#9BBB59', lineColor: '#10253F' }, 0)).toBe('#10253F')
expect(lineStroke({ color: '#9BBB59' }, 0)).toBe('#9BBB59')
})
it('returns null for an explicit noFill line and falls back to the palette', () => {
expect(lineStroke({ color: '#9BBB59', lineColor: 'none' }, 0)).toBeNull()
expect(lineStroke({}, 0)).toBe('#4472c4')
})
})
describe('legendSwatchColor', () => {
const series = { color: '#9BBB59', lineColor: '#10253F' }
it('mirrors the drawn stroke on line-family charts', () => {
expect(legendSwatchColor(series, 0, true)).toBe('#10253F')
// noFill line: the swatch keeps the series color instead of vanishing.
expect(legendSwatchColor({ color: '#9BBB59', lineColor: 'none' }, 0, true)).toBe('#9BBB59')
expect(legendSwatchColor({}, 1, true)).toBe('#ed7d31')
})
it('keeps the fill resolution for non-line charts', () => {
expect(legendSwatchColor(series, 0, false)).toBe('#9BBB59')
expect(legendSwatchColor({}, 1, false)).toBe('#ed7d31')
})
})
describe('legendUsesLineSwatches', () => {
it('follows the render dispatch: only a winning line/radar plot strokes', () => {
expect(legendUsesLineSwatches(['lineChart'])).toBe(true)
expect(legendUsesLineSwatches(['radarChart'])).toBe(true)
// Area wins the cascade over line: the drawn series are fills, so the
// swatches must keep the fill resolution.
expect(legendUsesLineSwatches(['lineChart', 'areaChart'])).toBe(false)
expect(legendUsesLineSwatches(['lineChart', 'scatterChart'])).toBe(false)
// Bar combos render BarChart; pie keeps its own legend.
expect(legendUsesLineSwatches(['barChart', 'lineChart'])).toBe(false)
expect(legendUsesLineSwatches(['radarChart', 'barChart'])).toBe(false)
expect(legendUsesLineSwatches(['pieChart', 'lineChart'])).toBe(false)
expect(legendUsesLineSwatches(['barChart'])).toBe(false)
})
})
@@ -66,6 +66,18 @@ describe('applyChartStateEdit', () => {
expect(next.series[0]?.categories).toEqual(['a', 'b']) expect(next.series[0]?.categories).toEqual(['a', 'b'])
}) })
it('drops the parsed outer-level groups when an edit replaces the categories', () => {
const chart = base()
const first = chart.series[0]
if (first) first.categoryGroups = [{ label: '2008', start: 0, end: 2 }]
const kept = applyChartStateEdit(chart, { series: [{ index: 0, values: [5, 6] }] })
expect(kept.series[0]?.categoryGroups).toEqual([{ label: '2008', start: 0, end: 2 }])
const replaced = applyChartStateEdit(chart, {
series: [{ index: 0, categories: ['x', 'y'] }],
})
expect(replaced.series[0]?.categoryGroups).toBeUndefined()
})
it('merges slice explosions per point over the series default', () => { it('merges slice explosions per point over the series default', () => {
const pie = applyChartStateEdit(base(), { chartType: 'pie', explosionPct: 10 }) const pie = applyChartStateEdit(base(), { chartType: 'pie', explosionPct: 10 })
expect(pie.chartTypes).toEqual(['pieChart']) expect(pie.chartTypes).toEqual(['pieChart'])
@@ -248,6 +260,7 @@ describe('transposeChartSeries', () => {
describe('formatCategoryLabel', () => { describe('formatCategoryLabel', () => {
it('formats numeric category text through its number format', () => { it('formats numeric category text through its number format', () => {
expect(formatCategoryLabel('44562', 'mmm\\-yy')).toBe('Jan-22') expect(formatCategoryLabel('44562', 'mmm\\-yy')).toBe('Jan-22')
expect(formatCategoryLabel('41387', 'mmm\\ yyyy')).toBe('Apr 2013')
expect(formatCategoryLabel('0.152', '0.0%')).toBe('15.2%') expect(formatCategoryLabel('0.152', '0.0%')).toBe('15.2%')
}) })
@@ -368,6 +381,32 @@ describe('valueAxisScale', () => {
expect(valueAxisScale(3750).ticks).toHaveLength(9) expect(valueAxisScale(3750).ticks).toHaveLength(9)
// 57362: 13 → 0..14 step 2 // 57362: 13 → 0..14 step 2
expect(valueAxisScale(13)).toEqual({ min: 0, max: 14, ticks: [0, 2, 4, 6, 8, 10, 12, 14] }) expect(valueAxisScale(13)).toEqual({ min: 0, max: 14, ticks: [0, 2, 4, 6, 8, 10, 12, 14] })
// prod_055: 877 → 0..1000 step 100 (the earlier 900 reading came from a
// page-clipped ref; the plot area runs past the 900 gridline).
expect(valueAxisScale(877).max).toBe(1000)
expect(valueAxisScale(877).ticks).toHaveLength(11)
})
it('leaves Excel 5% auto-max headroom, calibrated on the real-run1 refs', () => {
// aspose_sample1 pivot chart: 18 → 0..20 step 2
expect(valueAxisScale(18)).toEqual({
min: 0,
max: 20,
ticks: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
})
// aspose_sampleModifyLineChart: 148 → 0..160 step 20
expect(valueAxisScale(148).max).toBe(160)
expect(valueAxisScale(148).ticks[1]).toBe(20)
// aspose_sampleGetFonts stacked: 289753.76 → 0..350000 step 50000
expect(valueAxisScale(289753.76).max).toBe(350000)
expect(valueAxisScale(289753.76).ticks[1]).toBe(50000)
// aspose_sampleDisableTextWrappingForDataLabels: 1000 → 0..1200 step
// 200 (the 5% bump makes 11 intervals of 100, pushing the unit to 200)
expect(valueAxisScale(1000).max).toBe(1200)
expect(valueAxisScale(1000).ticks[1]).toBe(200)
// phpss_32readwriteLineChartNoPointMarkers1: 3490 → 0..4000 step 500
expect(valueAxisScale(3490).max).toBe(4000)
expect(valueAxisScale(3490).ticks[1]).toBe(500)
}) })
it('honours explicit bounds and unit', () => { it('honours explicit bounds and unit', () => {
+22 -1
View File
@@ -10,6 +10,7 @@ import { generalCharBudget } from '../src/renderer/numfmt-fix'
import { import {
characterWidthToPixels, characterWidthToPixels,
measureNormalFontMdw, measureNormalFontMdw,
paddedBaseColumnWidth,
resolveNormalMdwFamily, resolveNormalMdwFamily,
toUniverStyle, toUniverStyle,
} from '../src/renderer/univer-sync' } from '../src/renderer/univer-sync'
@@ -65,6 +66,19 @@ describe('workbook MDW', () => {
setWorkbookMdw(Number.NaN) setWorkbookMdw(Number.NaN)
expect(getWorkbookMdw()).toBe(7) expect(getWorkbookMdw()).toBe(7)
}) })
it('derives the built-in default width from baseColWidth (prod_039)', () => {
// MDW 7 reproduces the classic 8.7109375 chars Excel writes into files;
// MDW 8 gives 8.625 chars = 74px, matching live Excel's 8.0-char default
// column — narrow enough that 10-digit General numbers go scientific.
setWorkbookMdw(7)
expect(paddedBaseColumnWidth(null)).toBe(8.7109375)
setWorkbookMdw(8)
expect(paddedBaseColumnWidth(null)).toBe(8.625)
expect(characterWidthToPixels(paddedBaseColumnWidth(null))).toBe(74)
expect(generalCharBudget(74)).toBe(8)
expect(paddedBaseColumnWidth(10)).toBe(10.625)
})
}) })
describe('measureNormalFontMdw', () => { describe('measureNormalFontMdw', () => {
@@ -130,7 +144,14 @@ describe('measureNormalFontMdw', () => {
normalFontName: 'Nonexistent Face', normalFontName: 'Nonexistent Face',
}) })
expect(resolveNormalMdwFamily(file)).toBe('Calibri') expect(resolveNormalMdwFamily(file)).toBe('Calibri')
expect(measureNormalFontMdw(file)).toBe(7) expect(measureNormalFontMdw(file)).toBe(8)
})
it('lays Calibri 11 out at the Mac Excel MDW 8, not the GDI 7', () => {
// Live probes + ref print geometry: prod_054 50.86ch → 305pt and
// prod_027 32.44ch → 195pt both fit floor((w+16/256)*8); MDW 7 wraps
// wide wrap columns a line early and re-fits their rows too tall.
expect(measureNormalFontMdw(workbook({ fontFamily: 'Calibri', fontSize: 11 }))).toBe(8)
}) })
it('quotes the family for canvas measurement so odd names still measure', () => { it('quotes the family for canvas measurement so odd names still measure', () => {
+205
View File
@@ -0,0 +1,205 @@
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import { parseCsv } from '../src/gateway/csv-import'
import {
csvField,
csvFromDisplayRows,
serializeActiveSheetCsv,
withoutFormulaView,
} from '../src/renderer/csv-export'
import {
workbookExportCsvRequestSchema,
workbookExportCsvResultSchema,
workbookSaveResultSchema,
} from '../src/shared/desktop-api'
const here = dirname(fileURLToPath(import.meta.url))
const read = (rel: string) => readFileSync(join(here, '..', rel), 'utf8')
describe('csvField', () => {
it('passes plain text through unquoted', () => {
expect(csvField('hello')).toBe('hello')
expect(csvField('12.5')).toBe('12.5')
expect(csvField('')).toBe('')
})
it('quotes fields carrying commas, quotes, or newlines', () => {
expect(csvField('a,b')).toBe('"a,b"')
expect(csvField('say "hi"')).toBe('"say ""hi"""')
expect(csvField('line1\nline2')).toBe('"line1\nline2"')
})
it('normalizes CR/CRLF line breaks before quoting', () => {
expect(csvField('a\r\nb')).toBe('"a\nb"')
expect(csvField('a\rb')).toBe('"a\nb"')
})
it('leaves tabs unquoted (CSV only cares about its own delimiter)', () => {
expect(csvField('a\tb')).toBe('a\tb')
})
})
describe('csvFromDisplayRows', () => {
it('joins rows with CRLF and ends the file with one', () => {
expect(
csvFromDisplayRows([
['a', 'b'],
['c', ''],
]),
).toBe('a,b\r\nc,\r\n')
})
it('serializes an empty grid to an empty string', () => {
expect(csvFromDisplayRows([])).toBe('')
})
it('round-trips through the CSV importer', () => {
const rows = [
['name', 'note', 'amount'],
['Ada, Bob', 'says "ok"', '1,234.50'],
['multi\nline', '', '-3'],
]
expect(parseCsv(csvFromDisplayRows(rows), ',')).toEqual(rows)
})
})
function fakeCsvSheet(rows: string[][]) {
const columns = Math.max(1, ...rows.map((row) => row.length))
return {
getLastRow: () => rows.length - 1,
getLastColumn: () => columns - 1,
getSheetId: () => 's1',
getSheetName: () => 'Sheet1',
getRange: (row: number, column: number, numRows: number, numColumns: number) => ({
getDisplayValues: () =>
rows
.slice(row, row + numRows)
.map((cells) =>
Array.from({ length: numColumns }, (_, offset) => cells[column + offset] ?? ''),
),
}),
getSheet: () => ({ getCellMatrix: () => ({ forValue: () => undefined }) }),
}
}
describe('serializeActiveSheetCsv', () => {
it('serializes the display grid with quoting and rectangular padding', () => {
const sheet = fakeCsvSheet([['name', 'note'], ['a,b', 'say "hi"', 'extra'], ['solo']])
expect(serializeActiveSheetCsv(sheet as never, null)).toBe(
'name,note,\r\n"a,b","say ""hi""",extra\r\nsolo,,\r\n',
)
})
})
describe('withoutFormulaView', () => {
it('reads with the flag suspended and restores it afterwards', () => {
const sheets = new Set(['s1', 's2'])
const during = withoutFormulaView(sheets, 's1', () => sheets.has('s1'))
expect(during).toBe(false)
expect(sheets.has('s1')).toBe(true)
})
it('restores the flag when the read throws', () => {
const sheets = new Set(['s1'])
expect(() =>
withoutFormulaView(sheets, 's1', () => {
throw new Error('boom')
}),
).toThrow('boom')
expect(sheets.has('s1')).toBe(true)
})
it('never adds the flag to a sheet that did not have it', () => {
const sheets = new Set<string>()
withoutFormulaView(sheets, 's1', () => undefined)
expect(sheets.size).toBe(0)
})
})
describe('workbookExportCsv schemas', () => {
it('accepts a minimal request and one with the active-sheet name', () => {
expect(
workbookExportCsvRequestSchema.parse({
fileName: 'data.csv',
content: 'a,b\r\n',
hasFormulas: false,
}),
).toBeTruthy()
expect(
workbookExportCsvRequestSchema.parse({
fileName: 'data.csv',
content: '',
hasFormulas: true,
activeSheetName: 'Sheet2',
}),
).toBeTruthy()
})
it('rejects unknown keys and oversized names', () => {
expect(() =>
workbookExportCsvRequestSchema.parse({
fileName: 'data.csv',
content: '',
hasFormulas: false,
html: 'nope',
}),
).toThrow()
expect(() =>
workbookExportCsvRequestSchema.parse({
fileName: 'x'.repeat(256),
content: '',
hasFormulas: false,
}),
).toThrow()
})
it('accepts a direct targetPath for the Save As CSV reroute', () => {
expect(
workbookExportCsvRequestSchema.parse({
fileName: 'data.csv',
content: 'a\r\n',
hasFormulas: false,
targetPath: '/tmp/data.csv',
}),
).toBeTruthy()
})
it('lets a canceled save carry the picked CSV path', () => {
expect(
workbookSaveResultSchema.parse({ canceled: true, csvSaveAsPath: '/tmp/data.csv' }),
).toEqual({ canceled: true, csvSaveAsPath: '/tmp/data.csv' })
expect(workbookSaveResultSchema.parse({ canceled: true })).toEqual({ canceled: true })
})
it('parses both result variants including the Save-As-xlsx reroute', () => {
expect(workbookExportCsvResultSchema.parse({ canceled: true })).toEqual({ canceled: true })
expect(
workbookExportCsvResultSchema.parse({ canceled: true, saveAsXlsxInstead: true }),
).toEqual({ canceled: true, saveAsXlsxInstead: true })
expect(workbookExportCsvResultSchema.parse({ canceled: false, path: '/tmp/a.csv' })).toEqual({
canceled: false,
path: '/tmp/a.csv',
})
})
})
describe('Export CSV wiring', () => {
it('has the File-menu item forwarding export-csv to the renderer', () => {
const mainSrc = read('src/main/sheets-main.ts')
expect(mainSrc).toMatch(/menuExportCsv[\s\S]{0,80}sendMenuAction\('export-csv'\)/)
expect(mainSrc).toContain("action === 'export-csv'")
})
it('dispatches the menu action into handleExportCsv', () => {
const appSrc = read('src/renderer/App.tsx')
expect(appSrc).toMatch(/action === 'export-csv'[\s\S]{0,80}handleExportCsvImpl/)
})
it('allows export-csv through the preload menu-action allowlist', () => {
const preloadSrc = read('src/preload/index.ts')
expect(preloadSrc).toContain("action === 'export-csv'")
})
})
+71
View File
@@ -6,6 +6,7 @@ import {
scanStreamedWorkbookErrors, scanStreamedWorkbookErrors,
type SheetError, type SheetError,
} from '../src/renderer/error-checking' } from '../src/renderer/error-checking'
import { FILE_READ_BATCH_CELLS, MAX_SCAN_CELLS } from '../src/renderer/ai/workbook-search'
import { ensureLazyRangeLoaded, readSheetRangeMapped } from '../src/renderer/univer-sync' import { ensureLazyRangeLoaded, readSheetRangeMapped } from '../src/renderer/univer-sync'
import type { LazyWorkbookState } from '../src/renderer/univer-state' import type { LazyWorkbookState } from '../src/renderer/univer-state'
@@ -154,6 +155,55 @@ describe('scanStreamedWorkbookErrors', () => {
expect(scan.errors).toHaveLength(0) expect(scan.errors).toHaveLength(0)
expect(scan.truncated).toBe(true) expect(scan.truncated).toBe(true)
}) })
it('reads back journal formula results and reports their errors', async () => {
const lazyState = state()
lazyState.editJournal.cells.set(
's1',
new Map([['0', { row: 3, column: 1, value: null, formula: '=1/0', hasValue: true }]]),
)
mockRead.mockImplementation(async () => mapped([]))
const scan = await scanStreamedWorkbookErrors(lazyState, {
resolveFormulaValue: () => '#DIV/0!',
})
expect(scan.errors).toEqual([{ sheetId: 's1', row: 3, column: 1, value: '#DIV/0!' }])
})
it('does not let style-only journal entries hide file errors', async () => {
const lazyState = state()
lazyState.editJournal.cells.set(
's1',
new Map([['0', { row: 20, column: 2, value: null, hasValue: false }]]),
)
mockRead.mockImplementation(async (_state, sheetId) =>
sheetId === 's1' ? mapped([{ row: 20, column: 2, value: '#VALUE!' }]) : mapped([]),
)
const scan = await scanStreamedWorkbookErrors(lazyState)
expect(scan.errors).toEqual([{ sheetId: 's1', row: 20, column: 2, value: '#VALUE!' }])
})
it('follows live membership: session-added sheets scanned, deleted ones skipped', async () => {
const lazyState = state()
lazyState.editJournal.cells.set(
's3',
new Map([['0', { row: 1, column: 0, value: '#REF!', hasValue: true }]]),
)
mockRead.mockImplementation(async () => mapped([]))
const scan = await scanStreamedWorkbookErrors(lazyState, { liveSheetIds: ['s2', 's3'] })
expect(scan.errors).toEqual([{ sheetId: 's3', row: 1, column: 0, value: '#REF!' }])
// s1 was deleted this session: its file pages are never read.
expect(mockRead.mock.calls.every(([, sheetId]) => sheetId === 's2')).toBe(true)
})
it('stops at the scan-cell budget instead of paging the whole file', async () => {
const lazyState = state()
;(lazyState.file.sheets as { rowCount: number }[])[0]!.rowCount = 300_000
mockRead.mockImplementation(async () => mapped([]))
const scan = await scanStreamedWorkbookErrors(lazyState)
expect(scan.truncated).toBe(true)
const cellsPerBatch = Math.floor(FILE_READ_BATCH_CELLS / 4) * 4
expect(mockRead).toHaveBeenCalledTimes(Math.ceil(MAX_SCAN_CELLS / cellsPerBatch))
})
}) })
describe('runStreamedErrorCheck', () => { describe('runStreamedErrorCheck', () => {
@@ -246,4 +296,25 @@ describe('runStreamedErrorCheck', () => {
harnessData.setMessage.mock.calls.filter(([text]) => text === 'appCheckingErrors'), harnessData.setMessage.mock.calls.filter(([text]) => text === 'appCheckingErrors'),
).toHaveLength(1) ).toHaveLength(1)
}) })
it('bails out when the workbook is swapped mid-scan', async () => {
const harnessData = harness(state(), [])
mockRead.mockImplementation(async () => {
harnessData.lazyWorkbookRef.current = state() // file switch during the paged read
return mapped([{ row: 300, column: 0, value: '#DIV/0!' }])
})
await runStreamedErrorCheck(harnessData)
expect(mockEnsure).not.toHaveBeenCalled()
expect(harnessData.workbook.setActiveSheet).not.toHaveBeenCalled()
// Only the initial scanning status — no stale found/not-found result.
expect(harnessData.setMessage).toHaveBeenCalledTimes(1)
// The in-flight guard is released: the new workbook scans normally.
mockRead.mockImplementation(async () => mapped([]))
await runStreamedErrorCheck(harnessData)
expect(harnessData.setMessage.mock.calls.map(([text]) => text)).toEqual([
'appCheckingErrors',
'appCheckingErrors',
'appNoErrorsFound',
])
})
}) })
+16
View File
@@ -10,6 +10,7 @@ import {
shiftPinnedCells, shiftPinnedCells,
type ClosureSheetInput, type ClosureSheetInput,
} from '../src/renderer/formula-closure' } from '../src/renderer/formula-closure'
import { formulaKeepsCache } from '../src/renderer/univer-sync'
const sheet = ( const sheet = (
id: string, id: string,
@@ -72,6 +73,21 @@ describe('containsUnresolvedNames', () => {
}) })
}) })
describe('formulaKeepsCache', () => {
it('keeps the cached value for Google Sheets __xludf exports (prod_016)', () => {
// Recalculating turns the float-repr fallback literal (46235.0) into a
// string the numfmt layer skips; the cached <v> is the computed value.
expect(formulaKeepsCache('IFERROR(__xludf.DUMMYFUNCTION("""COMPUTED_VALUE"""),46235.0)')).toBe(
true,
)
expect(formulaKeepsCache('IFERROR(__xludf.DUMMYFUNCTION("X"),"✖")')).toBe(true)
})
it('recalculates ordinary formulas', () => {
expect(formulaKeepsCache('SUM(A1:A5)')).toBe(false)
})
})
describe('computeFormulaClosure', () => { describe('computeFormulaClosure', () => {
it('collects formulas plus referenced precedents across sheets', () => { it('collects formulas plus referenced precedents across sheets', () => {
const result = computeFormulaClosure( const result = computeFormulaClosure(
+2
View File
@@ -179,6 +179,8 @@ describe('formatGeneral', () => {
it('switches to scientific when the integer part cannot fit', () => { it('switches to scientific when the integer part cannot fit', () => {
expect(formatGeneral(123456789012, 8)).toBe('1.23E+11') expect(formatGeneral(123456789012, 8)).toBe('1.23E+11')
expect(formatGeneral(1234567890123456, 20)).toBe('1.23457E+15') expect(formatGeneral(1234567890123456, 20)).toBe('1.23457E+15')
// prod_039: 10-digit phone numbers in a built-in-width column.
expect(formatGeneral(7028015141, 8)).toBe('7.03E+09')
}) })
it('uses scientific for tiny fractions instead of rounding to 0', () => { it('uses scientific for tiny fractions instead of rounding to 0', () => {
+121 -4
View File
@@ -7,12 +7,18 @@ import { applyPivotStyling } from '../src/renderer/univer-sync'
/// firstHeaderRow="1" firstDataRow="1"/> where A8 = "Row Labels" (header), /// firstHeaderRow="1" firstDataRow="1"/> where A8 = "Row Labels" (header),
/// A9/A10 = data, A11 = Grand Total. firstDataRow is the offset of the FIRST /// A9/A10 = data, A11 = Grand Total. firstDataRow is the offset of the FIRST
/// DATA row inside the ref, so header rows are offsets 0..firstDataRow-1. /// DATA row inside the ref, so header rows are offsets 0..firstDataRow-1.
function paint(pivot: { interface PivotSpec {
outputRef: string outputRef: string
headerFill?: string headerFill?: string
headerFontColor?: string
wholeTableFill?: string
stripeFill?: string
styled?: boolean
firstDataRow?: number firstDataRow?: number
rowGrandTotals?: boolean rowGrandTotals?: boolean
}): boolean[] { }
function paintCells(pivot: PivotSpec): ICellData[][] {
const range = { startRow: 0, startColumn: 0, endRow: 19, endColumn: 4 } const range = { startRow: 0, startColumn: 0, endRow: 19, endColumn: 4 }
const matrix: ICellData[][] = Array.from({ length: 20 }, () => const matrix: ICellData[][] = Array.from({ length: 20 }, () =>
Array.from({ length: 5 }, () => ({})), Array.from({ length: 5 }, () => ({})),
@@ -20,7 +26,15 @@ function paint(pivot: {
applyPivotStyling(matrix, range, [ applyPivotStyling(matrix, range, [
{ path: 'xl/pivotTables/pivotTable1.xml', cachePath: null, ...pivot }, { path: 'xl/pivotTables/pivotTable1.xml', cachePath: null, ...pivot },
]) ])
return matrix.map((row) => Boolean(row[0]?.s)) return matrix
}
function paint(pivot: PivotSpec): boolean[] {
return paintCells(pivot).map((row) => Boolean(row[0]?.s))
}
function fills(pivot: PivotSpec): (string | undefined)[] {
return paintCells(pivot).map((row) => ((row[0]?.s ?? {}) as { bg?: { rgb?: string } }).bg?.rgb)
} }
describe('applyPivotStyling', () => { describe('applyPivotStyling', () => {
@@ -62,8 +76,111 @@ describe('applyPivotStyling', () => {
expect(painted[10]).toBe(false) expect(painted[10]).toBe(false)
}) })
it('paints nothing without a style fill', () => { it('paints nothing without a pivot style', () => {
const painted = paint({ outputRef: 'A8:B11', firstDataRow: 1, rowGrandTotals: true }) const painted = paint({ outputRef: 'A8:B11', firstDataRow: 1, rowGrandTotals: true })
expect(painted.every((row) => !row)).toBe(true) expect(painted.every((row) => !row)).toBe(true)
}) })
// Light 1-7 with stripes off: no fills survive, but a named style still
// bolds the header and grand-total bands.
it('bolds band rows of a styled pivot even when every fill is absent', () => {
const cells = paintCells({
outputRef: 'A8:B11',
styled: true,
firstDataRow: 1,
rowGrandTotals: true,
})
const bold = (row: number) => ((cells[row]?.[0]?.s ?? {}) as { bl?: number }).bl
expect(bold(7)).toBe(1) // A8 header
expect(cells[8]?.[0]?.s).toBeUndefined() // data rows untouched
expect(cells[9]?.[0]?.s).toBeUndefined()
expect(bold(10)).toBe(1) // A11 grand total
const rowFills = fills({
outputRef: 'A8:B11',
styled: true,
firstDataRow: 1,
rowGrandTotals: true,
})
expect(rowFills.every((fill) => fill === undefined)).toBe(true)
})
// Ground truth from oxmlsdk_RelationalPivotB6 (PivotStyleLight2,
// showRowStripes): unfilled header, stripes from the first data row.
it('stripes alternate data rows and leave a fill-less header unfilled but bold', () => {
const cells = paintCells({
outputRef: 'A8:B14',
stripeFill: '#DCE6F1',
firstDataRow: 1,
rowGrandTotals: true,
})
const rowFills = fills({
outputRef: 'A8:B14',
stripeFill: '#DCE6F1',
firstDataRow: 1,
rowGrandTotals: true,
})
expect(rowFills[7]).toBeUndefined() // A8 header: no fill for Light 1-7
expect((cells[7]?.[0]?.s as { bl?: number }).bl).toBe(1) // ...but bold
expect(rowFills[8]).toBe('#DCE6F1') // A9 first data row starts the stripe
expect(rowFills[9]).toBeUndefined()
expect(rowFills[10]).toBe('#DCE6F1')
expect(rowFills[11]).toBeUndefined()
expect(rowFills[12]).toBe('#DCE6F1')
expect(rowFills[13]).toBeUndefined() // A14 grand total: band, not stripe
})
// Ground truth from aspose_sample1 (PivotStyleMedium9): solid accent header
// with white bold text.
it('paints the header font color with the header fill', () => {
const cells = paintCells({
outputRef: 'A8:B11',
headerFill: '#4F81BD',
headerFontColor: '#FFFFFF',
firstDataRow: 1,
rowGrandTotals: false,
})
const header = cells[7]?.[0]?.s as { bg?: { rgb?: string }; cl?: { rgb?: string }; bl?: number }
expect(header.bg?.rgb).toBe('#4F81BD')
expect(header.cl?.rgb).toBe('#FFFFFF')
expect(header.bl).toBe(1)
})
// Ground truth from aspose_sample1 (Medium9, G6:H7 with grand totals): the
// solid header does not bleed onto the grand-total row, which Excel leaves
// plain black-on-white bold.
it('keeps the solid header treatment off the grand-total row', () => {
const cells = paintCells({
outputRef: 'A8:B11',
headerFill: '#4F81BD',
headerFontColor: '#FFFFFF',
firstDataRow: 1,
rowGrandTotals: true,
})
type CellStyle = { bg?: { rgb?: string }; cl?: { rgb?: string }; bl?: number }
const header = cells[7]?.[0]?.s as CellStyle
expect(header.bg?.rgb).toBe('#4F81BD')
expect(header.cl?.rgb).toBe('#FFFFFF')
const total = cells[10]?.[0]?.s as CellStyle
expect(total.bg).toBeUndefined()
expect(total.cl).toBeUndefined()
expect(total.bl).toBe(1)
})
// Dark1 fills its body, so its calibrated grand-total band keeps the
// header fill and white text.
it('extends the header treatment to the grand total when the body is filled', () => {
const cells = paintCells({
outputRef: 'A8:B11',
headerFill: '#808080',
headerFontColor: '#FFFFFF',
wholeTableFill: '#A6A6A6',
stripeFill: '#BFBFBF',
firstDataRow: 1,
rowGrandTotals: true,
})
const total = cells[10]?.[0]?.s as { bg?: { rgb?: string }; cl?: { rgb?: string }; bl?: number }
expect(total.bg?.rgb).toBe('#808080')
expect(total.cl?.rgb).toBe('#FFFFFF')
expect(total.bl).toBe(1)
})
}) })
+355
View File
@@ -0,0 +1,355 @@
import { describe, expect, it } from 'vitest'
import { buildSheetPrintPayload, renderHeaderFooterHtml } from '../src/renderer/print-html'
import {
decodeHeaderFooter,
printAreasFromFormula,
printTitleRowsFromFormula,
resolveEffectivePageSetup,
type EffectivePageSetup,
} from '../src/renderer/print-settings'
import type { PrintWorksheet } from '../src/renderer/print-html'
describe('decodeHeaderFooter', () => {
it('splits left/center/right sections and keeps resolvable field codes', () => {
expect(decodeHeaderFooter('&L&A&CSeite &P von &N')).toEqual({
left: '&A',
center: 'Seite &P von &N',
})
})
it('defaults unmarked text to the center section', () => {
expect(decodeHeaderFooter('Quarterly Report')).toEqual({ center: 'Quarterly Report' })
})
it('strips font, size, color and unsupported codes', () => {
expect(decodeHeaderFooter('&C&"Broadway,Bold Italic"&12&KFF0000Big &BRed&B Title&G')).toEqual({
center: 'Big Red Title',
})
})
it('drops the picture/path codes but keeps the file code', () => {
expect(decodeHeaderFooter('&C&P / &N&R&Z&F')).toEqual({
center: '&P / &N',
right: '&F',
})
})
it('keeps escaped ampersands verbatim', () => {
expect(decodeHeaderFooter('&LProfit && Loss')).toEqual({ left: 'Profit && Loss' })
})
it('returns null when everything strips away', () => {
expect(decodeHeaderFooter('&L&G')).toBeNull()
expect(decodeHeaderFooter('')).toBeNull()
})
it('accepts lowercase section markers', () => {
expect(decodeHeaderFooter('&lLeft&rRight')).toEqual({ left: 'Left', right: 'Right' })
})
})
describe('printAreasFromFormula', () => {
it('parses a quoted sheet-qualified absolute range', () => {
expect(printAreasFromFormula("'W PS Mustermann Hans'!$A$1:$K$84")).toEqual(['A1:K84'])
})
it('parses multiple areas and quoted commas', () => {
expect(printAreasFromFormula("'a,b'!$A$1:$B$2,'a,b'!$D$3:$E$4")).toEqual(['A1:B2', 'D3:E4'])
})
it('expands a single-cell area', () => {
expect(printAreasFromFormula('Sheet1!$B$2')).toEqual(['B2:B2'])
})
it('falls back to the used range for refs it cannot crop to', () => {
expect(printAreasFromFormula("'S'!$A:$C")).toEqual([])
expect(printAreasFromFormula("'S'!#REF!")).toEqual([])
expect(printAreasFromFormula("'S'!$A$1:$B$2,'S'!$C:$D")).toEqual([])
})
it('returns [] when absent', () => {
expect(printAreasFromFormula(undefined)).toEqual([])
})
})
describe('printTitleRowsFromFormula', () => {
it('extracts the repeated row span', () => {
expect(printTitleRowsFromFormula("'S'!$17:$17")).toBe('17:17')
})
it('skips a column-repeat part and finds the rows', () => {
expect(printTitleRowsFromFormula("'S'!$A:$B,'S'!$1:$3")).toBe('1:3')
})
it('drops spans beyond the layout title cap', () => {
expect(printTitleRowsFromFormula("'S'!$1:$40")).toBeNull()
})
it('returns null when absent or column-only', () => {
expect(printTitleRowsFromFormula(undefined)).toBeNull()
expect(printTitleRowsFromFormula("'S'!$A:$B")).toBeNull()
})
})
describe('resolveEffectivePageSetup', () => {
it('defaults to A4 portrait at 100% with normal margins', () => {
const setup = resolveEffectivePageSetup({}, null, null)
expect(setup.orientation).toBe('portrait')
expect(setup.paperSize).toBe(9)
expect(setup.scale).toBe(100)
expect(setup.fitToPage).toBe(false)
expect(setup.margins).toEqual({
left: 0.7,
right: 0.7,
top: 0.75,
bottom: 0.75,
header: 0.3,
footer: 0.3,
})
expect(setup.printAreas).toEqual([])
expect(setup.header).toBeNull()
expect(setup.footer).toBeNull()
})
it('applies the saved file settings when the session touched nothing', () => {
const setup = resolveEffectivePageSetup(
{},
{
orientation: 'landscape',
paperSize: 1,
scale: 65,
margins: { left: 0.98, right: 0.98, top: 5, bottom: 0.79, header: 0, footer: 0.51 },
printGridlines: true,
oddFooter: '&CSeite &P von &N',
},
{ printArea: "'S'!$A$1:$K$84", printTitles: "'S'!$17:$17" },
)
expect(setup.orientation).toBe('landscape')
expect(setup.paperSize).toBe(1)
expect(setup.scale).toBe(65)
// margins clamp to the export wire's 3in cap
expect(setup.margins.top).toBe(3)
expect(setup.margins.left).toBe(0.98)
expect(setup.printGridlines).toBe(true)
expect(setup.printAreas).toEqual(['A1:K84'])
expect(setup.printTitles).toBe('17:17')
expect(setup.footer).toEqual({ center: 'Seite &P von &N' })
expect(setup.header).toBeNull()
})
it('lets the session journal win over the file', () => {
const setup = resolveEffectivePageSetup(
{
orientation: 'portrait',
printArea: 'B2:C3',
printTitles: null,
header: null,
margins: 'narrow',
},
{
orientation: 'landscape',
margins: { left: 1, right: 1, top: 1, bottom: 1, header: 0.5, footer: 0.5 },
oddHeader: '&CFile Header',
},
{ printArea: "'S'!$A$1:$K$84", printTitles: "'S'!$1:$2" },
)
expect(setup.orientation).toBe('portrait')
expect(setup.printAreas).toEqual(['B2:C3'])
expect(setup.printTitles).toBeNull()
expect(setup.header).toBeNull()
expect(setup.margins.left).toBe(0.25)
})
it('clears the file print area when the session cleared it', () => {
const setup = resolveEffectivePageSetup({ printArea: null }, null, {
printArea: "'S'!$A$1:$K$84",
})
expect(setup.printAreas).toEqual([])
})
it('defaults fitToWidth to one page when the file only sets fitToPage', () => {
const setup = resolveEffectivePageSetup({}, { fitToPage: true }, null)
expect(setup.fitToPage).toBe(true)
expect(setup.fitToWidth).toBe(1)
})
it('shifts the file print area through rows inserted above', () => {
const setup = resolveEffectivePageSetup({}, null, { printArea: "'S'!$A$1:$K$84" }, [
{ kind: 'insert-rows', index: 0, count: 2 },
])
expect(setup.printAreas).toEqual(['A3:K86'])
})
it('shrinks the file print area when a column inside it is deleted', () => {
const setup = resolveEffectivePageSetup({}, null, { printArea: "'S'!$A$1:$K$84" }, [
{ kind: 'remove-cols', index: 2, count: 1 },
])
expect(setup.printAreas).toEqual(['A1:J84'])
})
it('falls back to the used range when the edits delete the whole area', () => {
const setup = resolveEffectivePageSetup({}, null, { printArea: "'S'!$B$2:$C$3" }, [
{ kind: 'remove-rows', index: 1, count: 2 },
])
expect(setup.printAreas).toEqual([])
})
it('shifts the file title rows through structural edits', () => {
const setup = resolveEffectivePageSetup({}, null, { printTitles: "'S'!$17:$17" }, [
{ kind: 'insert-rows', index: 0, count: 3 },
])
expect(setup.printTitles).toBe('20:20')
})
it('keeps title rows through column edits and drops them when deleted', () => {
const columnEdit = resolveEffectivePageSetup({}, null, { printTitles: "'S'!$1:$2" }, [
{ kind: 'remove-cols', index: 0, count: 3 },
])
expect(columnEdit.printTitles).toBe('1:2')
const deleted = resolveEffectivePageSetup({}, null, { printTitles: "'S'!$1:$2" }, [
{ kind: 'remove-rows', index: 0, count: 2 },
])
expect(deleted.printTitles).toBeNull()
})
it('does not remap session-set print areas (already screen space)', () => {
const setup = resolveEffectivePageSetup({ printArea: 'B2:C3' }, null, null, [
{ kind: 'insert-rows', index: 0, count: 5 },
])
expect(setup.printAreas).toEqual(['B2:C3'])
})
it('drops title rows stretched past the cap by inserts between them', () => {
const setup = resolveEffectivePageSetup({}, null, { printTitles: "'S'!$1:$2" }, [
{ kind: 'insert-rows', index: 1, count: 25 },
])
expect(setup.printTitles).toBeNull()
// the export payload still builds instead of throwing on the span
const payload = buildSheetPrintPayload(fakeWorksheet(), setup, 'Book.pdf', 'S1')
expect(payload.html).toContain('<table>')
})
})
describe('renderHeaderFooterHtml', () => {
const now = new Date(2026, 0, 2, 3, 4, 5)
it('turns &P/&N into live Chromium spans', () => {
expect(renderHeaderFooterHtml('Seite &P von &N', 'Book', 'S1', now)).toBe(
'Seite <span class="pageNumber"></span> von <span class="totalPages"></span>',
)
})
it('resolves static codes and escapes markup', () => {
const html = renderHeaderFooterHtml('&A <&F> && more', 'Bud<get', 'Sh&eet', now)
expect(html).toBe('Sh&amp;eet &lt;Bud&lt;get&gt; &amp; more')
})
})
const usedGrid = [
['A1', 'B1'],
['A2', 'B2'],
['A3', 'B3'],
]
function fakeWorksheet(): PrintWorksheet {
return {
getLastRow: () => 2,
getLastColumn: () => 1,
getRowHeight: () => 20,
getColumnWidth: () => 100,
getMergedRanges: () => [],
getRange: ((row: number, column: number, numRows?: number, numColumns?: number) => ({
getDisplayValues: () =>
usedGrid
.slice(row, row + (numRows ?? 1))
.map((cells) => cells.slice(column, column + (numColumns ?? 1))),
getValues: () =>
usedGrid
.slice(row, row + (numRows ?? 1))
.map((cells) => cells.slice(column, column + (numColumns ?? 1))),
getCellStyleData: () => null,
})) as PrintWorksheet['getRange'],
}
}
function payloadSetup(overrides: Partial<EffectivePageSetup>): EffectivePageSetup {
return {
orientation: 'portrait',
paperSize: 9,
scale: 100,
fitToWidth: 0,
fitToPage: false,
margins: { left: 0.7, right: 0.7, top: 0.75, bottom: 0.75, header: 0.3, footer: 0.3 },
printGridlines: false,
printHeadings: false,
printAreas: [],
printTitles: null,
header: null,
footer: null,
...overrides,
}
}
describe('buildSheetPrintPayload', () => {
it('crops the layout to the print area', () => {
const payload = buildSheetPrintPayload(
fakeWorksheet(),
payloadSetup({ printAreas: ['A1:A2'] }),
'Book.pdf',
'S1',
)
expect(payload.html).toContain('A1')
expect(payload.html).toContain('A2')
expect(payload.html).not.toContain('B1')
expect(payload.html).not.toContain('A3')
})
it('emits one page-broken table per print area', () => {
const payload = buildSheetPrintPayload(
fakeWorksheet(),
payloadSetup({ printAreas: ['A1:A1', 'B2:B2'] }),
'Book.pdf',
'S1',
)
expect(payload.html.match(/<table>/g)).toHaveLength(2)
expect(payload.html).toContain('table + table { break-before: page; }')
})
it('carries the page geometry and header/footer templates', () => {
const payload = buildSheetPrintPayload(
fakeWorksheet(),
payloadSetup({
orientation: 'landscape',
paperSize: 1,
scale: 65,
margins: { left: 0.98, right: 0.98, top: 0.98, bottom: 0.79, header: 0, footer: 0.51 },
footer: { center: 'Seite &P von &N' },
}),
'Book.pdf',
'S1',
)
expect(payload.landscape).toBe(true)
expect(payload.pageSize).toBe('Letter')
expect(payload.scale).toBeCloseTo(0.65, 5)
expect(payload.margins).toEqual({ top: 0.98, bottom: 0.79, left: 0.98, right: 0.98 })
expect(payload.headerTemplate).toBeUndefined()
expect(payload.footerTemplate).toContain('<span class="pageNumber"></span>')
expect(payload.footerTemplate).toContain('<span class="totalPages"></span>')
expect(payload.footerTemplate).toContain('padding-bottom:0.51in')
// the template document is content-box: without an inline border-box the
// padded 100%-wide row overflows the page and shifts/clips the sections
expect(payload.footerTemplate).toContain('box-sizing:border-box')
})
it('shrinks to fit the width when fit-to-page is on', () => {
// content 150pt wide (two 100px columns at 0.75), A4 printable ~493pt
const payload = buildSheetPrintPayload(
fakeWorksheet(),
payloadSetup({ fitToPage: true, fitToWidth: 1 }),
'Book.pdf',
'S1',
)
expect(payload.scale).toBe(1)
})
})
+15 -5
View File
@@ -155,29 +155,34 @@ describe('wrapAutoFitRows', () => {
[], [],
[], [],
false, false,
null,
range, range,
) )
expect(rows).toEqual([0, 1]) expect(rows).toEqual([0, 1])
}) })
it('keeps rows with a stored ht verbatim — Excel renders them as-is (#884)', () => { it('re-fits cached-ht auto rows but keeps user-fixed and spacer rows (prod_054)', () => {
const rows = wrapAutoFitRows( const rows = wrapAutoFitRows(
[ [
{ row: 0, column: 0, value: 'wrapping text', styleIndex: 0 }, { row: 0, column: 0, value: 'wrapping text', styleIndex: 0 },
{ row: 1, column: 0, value: 'wrapping text', styleIndex: 0 }, { row: 1, column: 0, value: 'wrapping text', styleIndex: 0 },
{ row: 2, column: 0, value: 'wrapping text', styleIndex: 0 },
] as never, ] as never,
styles, styles,
// Both an auto-fit cache (no customHeight) and a user-fixed height // A cached ht without customHeight stays in auto mode — Excel re-fits
// count: Excel never re-measures a stored ht on open. // it on open (live probe: ht="30" rows reopen at 16pt). customHeight
// and sub-default spacer heights stay verbatim.
[ [
{ row: 0, height: 38.25, hidden: false }, { row: 0, height: 30, hidden: false },
{ row: 1, height: 56, customHeight: true, hidden: false }, { row: 1, height: 56, customHeight: true, hidden: false },
{ row: 2, height: 6, hidden: false },
] as never, ] as never,
[], [],
false, false,
15,
range, range,
) )
expect(rows).toEqual([]) expect(rows).toEqual([0])
}) })
it('selects nothing when sheetFormatPr customHeight fixes the default (prod_012)', () => { it('selects nothing when sheetFormatPr customHeight fixes the default (prod_012)', () => {
@@ -187,6 +192,7 @@ describe('wrapAutoFitRows', () => {
[], [],
[], [],
true, true,
null,
range, range,
) )
expect(rows).toEqual([]) expect(rows).toEqual([])
@@ -203,6 +209,7 @@ describe('wrapAutoFitRows', () => {
[], [],
[], [],
false, false,
null,
range, range,
) )
expect(rows).toEqual([]) expect(rows).toEqual([])
@@ -218,6 +225,7 @@ describe('wrapAutoFitRows', () => {
[], [],
[], [],
false, false,
null,
range, range,
) )
expect(rows).toEqual([]) expect(rows).toEqual([])
@@ -238,6 +246,7 @@ describe('wrapAutoFitRows', () => {
] as never, ] as never,
[{ startColumn: 2, endColumn: 5, hidden: false, styleIndex: 0 }] as never, [{ startColumn: 2, endColumn: 5, hidden: false, styleIndex: 0 }] as never,
false, false,
null,
range, range,
) )
expect(rows).toEqual([0, 1]) expect(rows).toEqual([0, 1])
@@ -253,6 +262,7 @@ describe('wrapAutoFitRows', () => {
{ startColumn: 3, endColumn: 4, hidden: false, styleIndex: 1 }, { startColumn: 3, endColumn: 4, hidden: false, styleIndex: 1 },
] as never, ] as never,
false, false,
null,
range, range,
) )
expect(rows).toEqual([]) expect(rows).toEqual([])
+294 -29
View File
@@ -1,7 +1,13 @@
import { DataValidationRenderMode } from '@univerjs/core' import { DataValidationRenderMode } from '@univerjs/core'
import { describe, expect, it, vi } from 'vitest' import { describe, expect, it, vi } from 'vitest'
import { installPopulatedDataValidationArrow } from '../src/renderer/data-validation-arrow' import {
dataValidationInputMessageHeight,
getDataValidationInputMessage,
installActiveCellDataValidationChrome,
openActiveDataValidationDropdown,
shouldShowDataValidationDropdown,
} from '../src/renderer/data-validation-dropdown'
import { toUniverDvRule } from '../src/renderer/univer-sync' import { toUniverDvRule } from '../src/renderer/univer-sync'
const listRule = { const listRule = {
@@ -24,6 +30,16 @@ describe('toUniverDvRule', () => {
}) })
}) })
it('preserves an OOXML request to suppress the dropdown', () => {
expect(
toUniverDvRule({ ...listRule, suppressDropdown: true }, 'file-dv-sheet-1-0'),
).toMatchObject({
type: 'list',
showDropDown: false,
renderMode: DataValidationRenderMode.TEXT,
})
})
it('drops a list rule formula2 — Univer reads it as per-item chip colors', () => { it('drops a list rule formula2 — Univer reads it as per-item chip colors', () => {
// LibreOffice writes junk formula2 ("0") on list validations; passing it // LibreOffice writes junk formula2 ("0") on list validations; passing it
// through painted validated cells black. // through painted validated cells black.
@@ -45,38 +61,287 @@ describe('toUniverDvRule', () => {
}) })
}) })
describe('installPopulatedDataValidationArrow', () => { function createDropdownHarness() {
it('overlays an arrow only for populated cells without repainting their value', () => { const active = { unitId: 'book-1', sheetId: 'sheet-1', row: 17, col: 4 }
const drawWith = vi.fn((..._args: unknown[]) => undefined) const validation = {
const isHit = vi.fn((..._args: unknown[]) => true) present: true,
const rule = { renderMode: DataValidationRenderMode.TEXT } criteria: 'list',
const validator = { showDropDown: true,
canvasRender: { showInputMessage: false,
drawWith, promptTitle: 'Type',
isHit, prompt: 'Return or Exchange',
_dataValidationModel: { getRuleByLocation: () => rule }, merged: false,
}
const handlers = new Map<string, (event?: { id: string }) => void>()
const eventDisposes = new Map<string, ReturnType<typeof vi.fn>>()
const floatingDisposes: Array<ReturnType<typeof vi.fn>> = []
const range = {
getRow: () => active.row,
getLastRow: () => active.row + (validation.merged ? 1 : 0),
getDataValidation: () =>
validation.present
? {
rule: {
showDropDown: validation.showDropDown,
showInputMessage: validation.showInputMessage,
promptTitle: validation.promptTitle,
prompt: validation.prompt,
},
getCriteriaType: () => validation.criteria,
}
: null,
}
const addFloatDomToRange = vi.fn(
(_range: unknown, _layer: unknown, _layout: unknown, _id: string) => {
const dispose = vi.fn()
floatingDisposes.push(dispose)
return { dispose }
},
)
const worksheet = {
getSheetId: () => active.sheetId,
getRange: () => range,
getCellMergeData: () => (validation.merged ? range : null),
getRowHeight: () => 20,
addFloatDomToRange,
}
const executeCommand = vi.fn()
const componentDisposes: Array<ReturnType<typeof vi.fn>> = []
const runtime = {
univerAPI: {
Event: {
SelectionChanged: 'selection-changed',
ActiveSheetChanged: 'active-sheet-changed',
CommandExecuted: 'command-executed',
}, },
} getActiveWorkbook: () => ({
const runtime = { getId: () => active.unitId,
univer: { getActiveSheet: () => worksheet,
__getInjector: () => ({ getActiveCell: () => ({
get: () => ({ getValidatorItem: () => validator }), getRow: () => active.row,
getColumn: () => active.col,
}), }),
}, }),
} addEvent: vi.fn((event: string, handler: (event?: { id: string }) => void) => {
const location = { unitId: 'book-1', subUnitId: 'sheet-1', row: 17, col: 4 } const dispose = vi.fn()
const populated = { ...location, data: { v: 'Return' } } handlers.set(event, handler)
const empty = { ...location, data: { v: null } } eventDisposes.set(event, dispose)
return { dispose }
}),
registerComponent: vi.fn(() => {
const dispose = vi.fn()
componentDisposes.push(dispose)
return { dispose }
}),
executeCommand,
},
}
return {
active,
validation,
handlers,
eventDisposes,
floatingDisposes,
range,
addFloatDomToRange,
executeCommand,
componentDisposes,
runtime,
}
}
const disposable = installPopulatedDataValidationArrow(runtime as never) describe('active-cell data-validation chrome', () => {
validator.canvasRender.drawWith({}, populated) it('shows only list rules whose dropdown is not suppressed', () => {
validator.canvasRender.drawWith({}, empty) expect(
expect(drawWith).toHaveBeenCalledTimes(1) shouldShowDataValidationDropdown({
expect(drawWith.mock.calls[0]?.[1]).toMatchObject({ data: { v: '' } }) rule: { showDropDown: true },
expect(validator.canvasRender.isHit({}, populated)).toBe(true) getCriteriaType: () => 'list',
expect(validator.canvasRender.isHit({}, empty)).toBe(false) }),
expect(rule.renderMode).toBe(DataValidationRenderMode.TEXT) ).toBe(true)
expect(
shouldShowDataValidationDropdown({
rule: { showDropDown: false },
getCriteriaType: () => 'list',
}),
).toBe(false)
expect(
shouldShowDataValidationDropdown({
rule: { showDropDown: true },
getCriteriaType: () => 'whole',
}),
).toBe(false)
expect(shouldShowDataValidationDropdown(null)).toBe(false)
})
it('shows and sizes only enabled non-empty input messages', () => {
const message = getDataValidationInputMessage({
rule: {
showInputMessage: true,
promptTitle: 'Type',
prompt: 'Return or Exchange',
},
getCriteriaType: () => 'list',
})
expect(message).toEqual({ title: 'Type', prompt: 'Return or Exchange' })
expect(dataValidationInputMessageHeight(message!)).toBe(40)
expect(
dataValidationInputMessageHeight({
title: 'Type',
prompt: 'A long validation message that wraps across several display lines',
}),
).toBeGreaterThan(40)
expect(
getDataValidationInputMessage({
rule: { showInputMessage: false, prompt: 'Hidden' },
getCriteriaType: () => 'list',
}),
).toBeNull()
expect(
getDataValidationInputMessage({
rule: { showInputMessage: true },
getCriteriaType: () => 'list',
}),
).toBeNull()
})
it('anchors one button outside the active validation cell', () => {
const harness = createDropdownHarness()
const disposable = installActiveCellDataValidationChrome(harness.runtime as never)
expect(harness.addFloatDomToRange).toHaveBeenCalledTimes(1)
expect(harness.addFloatDomToRange.mock.calls[0]?.[2]).toEqual({
width: 14,
height: 14,
marginX: '100%',
marginY: 0,
verticalOffsetAlign: 'bottom',
})
harness.handlers.get('selection-changed')?.()
expect(harness.addFloatDomToRange).toHaveBeenCalledTimes(1)
disposable.dispose() disposable.dispose()
}) })
it('anchors the input message from the cell midpoint below the cell', () => {
const harness = createDropdownHarness()
harness.validation.showInputMessage = true
const disposable = installActiveCellDataValidationChrome(harness.runtime as never)
expect(harness.addFloatDomToRange).toHaveBeenCalledTimes(2)
expect(harness.addFloatDomToRange.mock.calls[1]?.[2]).toEqual({
width: 108,
height: 40,
marginX: '50%',
marginY: '100%',
})
disposable.dispose()
})
it('shows an input message for non-list validation without a dropdown', () => {
const harness = createDropdownHarness()
harness.validation.criteria = 'whole'
harness.validation.showInputMessage = true
const disposable = installActiveCellDataValidationChrome(harness.runtime as never)
expect(harness.addFloatDomToRange).toHaveBeenCalledTimes(1)
expect(harness.addFloatDomToRange.mock.calls[0]?.[2]).toMatchObject({
marginX: '50%',
marginY: '100%',
})
disposable.dispose()
})
it('anchors the button to the edge of a merged validation cell', () => {
const harness = createDropdownHarness()
harness.validation.merged = true
const disposable = installActiveCellDataValidationChrome(harness.runtime as never)
expect(harness.addFloatDomToRange.mock.calls[0]?.[2]).toEqual({
width: 14,
height: 14,
marginX: '100%',
marginY: 0,
verticalOffsetAlign: 'bottom',
})
disposable.dispose()
})
it('moves with selection and disappears outside the validation range', () => {
const harness = createDropdownHarness()
const disposable = installActiveCellDataValidationChrome(harness.runtime as never)
harness.active.row = 18
harness.handlers.get('selection-changed')?.()
expect(harness.floatingDisposes[0]).toHaveBeenCalledTimes(1)
expect(harness.addFloatDomToRange).toHaveBeenCalledTimes(2)
harness.validation.present = false
harness.handlers.get('selection-changed')?.()
expect(harness.floatingDisposes[1]).toHaveBeenCalledTimes(1)
expect(harness.addFloatDomToRange).toHaveBeenCalledTimes(2)
disposable.dispose()
})
it('reacts when a validation rule arrives after workbook streaming', () => {
const harness = createDropdownHarness()
harness.validation.present = false
const disposable = installActiveCellDataValidationChrome(harness.runtime as never)
expect(harness.addFloatDomToRange).not.toHaveBeenCalled()
harness.validation.present = true
harness.handlers.get('command-executed')?.({ id: 'other.command' })
expect(harness.addFloatDomToRange).not.toHaveBeenCalled()
harness.handlers.get('command-executed')?.({ id: 'data-validation.mutation.addRule' })
expect(harness.addFloatDomToRange).toHaveBeenCalledTimes(1)
disposable.dispose()
})
it('opens the dropdown for the current active cell', () => {
const harness = createDropdownHarness()
const preventDefault = vi.fn()
const stopPropagation = vi.fn()
openActiveDataValidationDropdown(
harness.runtime as never,
{
preventDefault,
stopPropagation,
} as never,
)
expect(preventDefault).toHaveBeenCalledTimes(1)
expect(stopPropagation).toHaveBeenCalledTimes(1)
expect(harness.executeCommand).toHaveBeenCalledWith(
'sheet.operation.show-data-validation-dropdown',
{
unitId: 'book-1',
subUnitId: 'sheet-1',
row: 17,
column: 4,
},
)
harness.validation.showDropDown = false
openActiveDataValidationDropdown(harness.runtime as never)
expect(harness.executeCommand).toHaveBeenCalledTimes(1)
})
it('disposes the floating control, events, and component', () => {
const harness = createDropdownHarness()
const disposable = installActiveCellDataValidationChrome(harness.runtime as never)
disposable.dispose()
expect(harness.floatingDisposes[0]).toHaveBeenCalledTimes(1)
expect(harness.componentDisposes).toHaveLength(2)
expect(harness.componentDisposes[0]).toHaveBeenCalledTimes(1)
expect(harness.componentDisposes[1]).toHaveBeenCalledTimes(1)
expect(harness.eventDisposes.get('selection-changed')).toHaveBeenCalledTimes(1)
expect(harness.eventDisposes.get('active-sheet-changed')).toHaveBeenCalledTimes(1)
expect(harness.eventDisposes.get('command-executed')).toHaveBeenCalledTimes(1)
})
}) })
+1
View File
@@ -120,6 +120,7 @@ describe('mapRangeResultToScreen', () => {
rowBreaks: [], rowBreaks: [],
colBreaks: [], colBreaks: [],
protectedRanges: [], protectedRanges: [],
pageSetup: null,
indexedThroughRow: null, indexedThroughRow: null,
indexingComplete: true, indexingComplete: true,
}) })
@@ -0,0 +1,101 @@
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import {
applyCellEditsToXlsx,
assertOnlyTouchedEntriesChanged,
type CellEdit,
} from '../src/gateway/xlsx-gateway'
const contentTypes = `<?xml version="1.0" encoding="UTF-8"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="png" ContentType="image/png"/>
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>
<Override PartName="/xl/metadata.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml"/>
<Override PartName="/xl/richData/richValueRel.xml" ContentType="application/vnd.ms-excel.richvaluerel+xml"/>
<Override PartName="/xl/richData/rdrichvalue.xml" ContentType="application/vnd.ms-excel.rdrichvalue+xml"/>
<Override PartName="/xl/richData/rdrichvaluestructure.xml" ContentType="application/vnd.ms-excel.rdrichvaluestructure+xml"/>
</Types>`
const worksheet = `<?xml version="1.0" encoding="UTF-8"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData><row r="2"><c r="B2" t="e" vm="1"><v>#VALUE!</v></c></row></sheetData>
</worksheet>`
/// Minimal modern-Excel "picture in cell" package: the cell carries vm= and a
/// cached #VALUE!, the picture lives behind xl/metadata.xml → xl/richData.
async function buildRichDataFixture(): Promise<Buffer> {
const zip = new JSZip()
zip.file('[Content_Types].xml', contentTypes)
zip.file(
'_rels/.rels',
`<?xml version="1.0" encoding="UTF-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>`,
)
zip.file(
'xl/workbook.xml',
`<?xml version="1.0" encoding="UTF-8"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets></workbook>`,
)
zip.file(
'xl/_rels/workbook.xml.rels',
`<?xml version="1.0" encoding="UTF-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata" Target="metadata.xml"/><Relationship Id="rId5" Type="http://schemas.microsoft.com/office/2022/10/relationships/richValueRel" Target="richData/richValueRel.xml"/><Relationship Id="rId6" Type="http://schemas.microsoft.com/office/2017/06/relationships/rdRichValue" Target="richData/rdrichvalue.xml"/><Relationship Id="rId7" Type="http://schemas.microsoft.com/office/2017/06/relationships/rdRichValueStructure" Target="richData/rdrichvaluestructure.xml"/></Relationships>`,
)
zip.file('xl/worksheets/sheet1.xml', worksheet)
zip.file(
'xl/metadata.xml',
`<metadata xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:xlrd="http://schemas.microsoft.com/office/spreadsheetml/2017/richdata"><metadataTypes count="1"><metadataType name="XLRICHVALUE" minSupportedVersion="120000"/></metadataTypes><futureMetadata name="XLRICHVALUE" count="1"><bk><extLst><ext uri="{3e2802c4-a4d2-4d8b-9148-e3be6c30e623}"><xlrd:rvb i="0"/></ext></extLst></bk></futureMetadata><valueMetadata count="1"><bk><rc t="1" v="0"/></bk></valueMetadata></metadata>`,
)
zip.file(
'xl/richData/richValueRel.xml',
`<richValueRels xmlns="http://schemas.microsoft.com/office/spreadsheetml/2022/richvaluerel" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><rel r:id="rId1"/></richValueRels>`,
)
zip.file(
'xl/richData/_rels/richValueRel.xml.rels',
`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="../media/image1.png"/></Relationships>`,
)
zip.file(
'xl/richData/rdrichvalue.xml',
`<rvData xmlns="http://schemas.microsoft.com/office/spreadsheetml/2017/richdata" count="1"><rv s="0"><v>0</v><v>5</v></rv></rvData>`,
)
zip.file(
'xl/richData/rdrichvaluestructure.xml',
`<rvStructures xmlns="http://schemas.microsoft.com/office/spreadsheetml/2017/richdata" count="1"><s t="_localImage"><k n="_rvRel:LocalImageIdentifier" t="i"/><k n="CalcOrigin" t="i"/></s></rvStructures>`,
)
zip.file('xl/media/image1.png', Buffer.from('fake-png-bytes'))
return zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' })
}
describe('richData passthrough on save', () => {
it('keeps the metadata, richData, and media parts byte-identical', async () => {
const edit: CellEdit = {
sheetName: 'Sheet1',
row: 0,
column: 0,
writeValue: true,
cell: { value: 'hello' },
}
const mutation = await applyCellEditsToXlsx(await buildRichDataFixture(), [edit])
expect(() => assertOnlyTouchedEntriesChanged(mutation)).not.toThrow()
const before = new Map(mutation.beforeEntries.map((entry) => [entry.path, entry.sha256]))
const after = new Map(mutation.afterEntries.map((entry) => [entry.path, entry.sha256]))
for (const part of [
'xl/metadata.xml',
'xl/richData/richValueRel.xml',
'xl/richData/_rels/richValueRel.xml.rels',
'xl/richData/rdrichvalue.xml',
'xl/richData/rdrichvaluestructure.xml',
'xl/media/image1.png',
]) {
expect(after.get(part), part).toBe(before.get(part))
}
// The untouched picture cell keeps its vm= marker and cached error.
const saved = await JSZip.loadAsync(mutation.buffer)
const sheet = await saved.file('xl/worksheets/sheet1.xml')?.async('string')
expect(sheet).toContain('<c r="B2" t="e" vm="1"><v>#VALUE!</v></c>')
})
})
+30 -7
View File
@@ -19,15 +19,37 @@
* into the packaged app's package.json via extraMetadata and read back by * into the packaged app's package.json via extraMetadata and read back by
* src/main/analytics.ts. When either is unset — every source/fork build — * src/main/analytics.ts. When either is unset — every source/fork build —
* nothing is injected and the app runs with analytics fully disabled. * nothing is injected and the app runs with analytics fully disabled.
*
* GENOFFICE_FONT_CDN_URL — base URL for the curated downloadable-font catalog.
* Official release jobs inject it through extraMetadata so the endpoint stays
* out of source. Without it, font download prompts/catalog entries are hidden;
* users can still install local font files.
*/ */
const { execFileSync } = require('node:child_process') const { execFileSync } = require('node:child_process')
const { existsSync, rmSync } = require('node:fs') const { existsSync, rmSync } = require('node:fs')
const { join } = require('node:path') const { join } = require('node:path')
function normalizeHttpsBaseUrl(name, value) {
if (!value || !value.trim()) return null
try {
const url = new URL(value.trim())
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) {
throw new Error('invalid')
}
return `${url.origin}${url.pathname.replace(/\/+$/, '')}`
} catch {
throw new Error(`${name} must be an HTTPS base URL without credentials, query, or fragment`)
}
}
const updateUrl = process.env.GENOFFICE_UPDATE_URL const updateUrl = process.env.GENOFFICE_UPDATE_URL
const ga4MeasurementId = process.env.GENOFFICE_GA4_MEASUREMENT_ID const ga4MeasurementId = process.env.GENOFFICE_GA4_MEASUREMENT_ID
const ga4ApiSecret = process.env.GENOFFICE_GA4_API_SECRET const ga4ApiSecret = process.env.GENOFFICE_GA4_API_SECRET
const fontCdnUrl = normalizeHttpsBaseUrl(
'GENOFFICE_FONT_CDN_URL',
process.env.GENOFFICE_FONT_CDN_URL,
)
// GENOFFICE_MAC_X64=1 — opt into packaging the Intel (x64) dmg/zip alongside // GENOFFICE_MAC_X64=1 — opt into packaging the Intel (x64) dmg/zip alongside
// arm64. Off by default: Intel packages must only ever ship signed with the // arm64. Off by default: Intel packages must only ever ship signed with the
@@ -469,15 +491,16 @@ if (updateUrl) {
] ]
} }
// CI's "-c.extraMetadata.version=..." CLI override deep-merges with this // CI's "-c.extraMetadata.version=..." CLI override deep-merges with this block,
// block, so both survive together in the packaged package.json. // so the version and all injected feature settings survive together.
const extraMetadata = {}
if (ga4MeasurementId && ga4ApiSecret) { if (ga4MeasurementId && ga4ApiSecret) {
config.extraMetadata = { extraMetadata.genofficeAnalytics = {
genofficeAnalytics: { measurementId: ga4MeasurementId,
measurementId: ga4MeasurementId, apiSecret: ga4ApiSecret,
apiSecret: ga4ApiSecret,
},
} }
} }
if (fontCdnUrl) extraMetadata.genofficeFontCdn = { baseUrl: fontCdnUrl }
if (Object.keys(extraMetadata).length) config.extraMetadata = extraMetadata
module.exports = config module.exports = config
+81 -11
View File
@@ -1,5 +1,5 @@
import { randomUUID } from 'node:crypto' import { randomUUID } from 'node:crypto'
import { readAppSettings, writeAppSetting } from './app-settings' import { readAppSettings, writeAppSetting, writeAppSettings } from './app-settings'
/** /**
* Anonymous usage analytics via the GA4 Measurement Protocol. * Anonymous usage analytics via the GA4 Measurement Protocol.
@@ -23,6 +23,15 @@ import { readAppSettings, writeAppSetting } from './app-settings'
export const ANALYTICS_ENABLED_KEY = 'analyticsEnabled' export const ANALYTICS_ENABLED_KEY = 'analyticsEnabled'
/** app-settings.json key: random UUID identifying this install anonymously */ /** app-settings.json key: random UUID identifying this install anonymously */
export const ANALYTICS_CLIENT_ID_KEY = 'analyticsClientId' export const ANALYTICS_CLIENT_ID_KEY = 'analyticsClientId'
/** true while a newly identified install still needs its cohort-start event */
export const ANALYTICS_FIRST_LAUNCH_PENDING_KEY = 'analyticsFirstLaunchPending'
/** Custom event used as the inclusion criterion for install-retention cohorts. */
export const INSTALL_FIRST_LAUNCH_EVENT = 'install_first_launch'
export interface AnalyticsClientState {
clientId: string
firstLaunchPending: boolean
}
export interface AnalyticsKeys { export interface AnalyticsKeys {
measurementId: string measurementId: string
@@ -68,16 +77,36 @@ export function analyticsEnabledFrom(settings: Record<string, unknown>): boolean
* Read the persistent anonymous install id, creating and saving one on first * Read the persistent anonymous install id, creating and saving one on first
* use. Storage failures fall back to a per-session id rather than blocking. * use. Storage failures fall back to a per-session id rather than blocking.
*/ */
export function ensureAnalyticsClientId(settingsPath: string): string { export function ensureAnalyticsClientState(settingsPath: string): AnalyticsClientState {
const existing = readAppSettings(settingsPath)[ANALYTICS_CLIENT_ID_KEY] const settings = readAppSettings(settingsPath)
if (typeof existing === 'string' && existing.trim()) return existing const existing = settings[ANALYTICS_CLIENT_ID_KEY]
if (typeof existing === 'string' && existing.trim()) {
return {
clientId: existing,
// Missing means this id predates retention tracking; do not misclassify
// every existing install as newly acquired when the feature ships.
firstLaunchPending: settings[ANALYTICS_FIRST_LAUNCH_PENDING_KEY] === true,
}
}
const created = randomUUID() const created = randomUUID()
try { try {
writeAppSetting(settingsPath, ANALYTICS_CLIENT_ID_KEY, created) writeAppSettings(settingsPath, {
[ANALYTICS_CLIENT_ID_KEY]: created,
[ANALYTICS_FIRST_LAUNCH_PENDING_KEY]: true,
})
} catch { } catch {
// unwritable settings file: report under a session-scoped id instead // unwritable settings file: report under a session-scoped id instead
} }
return created return { clientId: created, firstLaunchPending: true }
}
export function ensureAnalyticsClientId(settingsPath: string): string {
return ensureAnalyticsClientState(settingsPath).clientId
}
export function markAnalyticsFirstLaunchSent(settingsPath: string): void {
writeAppSetting(settingsPath, ANALYTICS_FIRST_LAUNCH_PENDING_KEY, false)
} }
/** GA4 event name rules: letters/digits/underscore, must start with a letter */ /** GA4 event name rules: letters/digits/underscore, must start with a letter */
@@ -103,6 +132,10 @@ export interface AnalyticsOptions {
getClientId: () => string getClientId: () => string
/** re-checked per event so the Settings toggle applies immediately */ /** re-checked per event so the Settings toggle applies immediately */
isEnabled: () => boolean isEnabled: () => boolean
/** true only for a newly created anonymous install id */
shouldTrackFirstLaunch?: () => boolean
/** persists successful delivery so failed sends can retry on a later launch */
onFirstLaunchSent?: () => void
/** attached to every event; evaluated per event so live-changeable values /** attached to every event; evaluated per event so live-changeable values
* (UI language) stay fresh */ * (UI language) stay fresh */
baseParams?: () => Record<string, string | number> baseParams?: () => Record<string, string | number>
@@ -129,6 +162,8 @@ export function createAnalytics(options: AnalyticsOptions): Analytics {
keys, keys,
getClientId, getClientId,
isEnabled, isEnabled,
shouldTrackFirstLaunch = () => false,
onFirstLaunchSent = () => {},
baseParams = () => ({}), baseParams = () => ({}),
getCountryCode = () => null, getCountryCode = () => null,
fetchFn = fetch, fetchFn = fetch,
@@ -142,6 +177,8 @@ export function createAnalytics(options: AnalyticsOptions): Analytics {
// one session per process run; GA4 uses it to group events and count // one session per process run; GA4 uses it to group events and count
// engaged sessions (together with engagement_time_msec) // engaged sessions (together with engagement_time_msec)
const sessionId = Date.now().toString() const sessionId = Date.now().toString()
let firstLaunchPending: boolean | null = null
let firstLaunchInFlight = false
return { return {
active: true, active: true,
@@ -150,27 +187,60 @@ export function createAnalytics(options: AnalyticsOptions): Analytics {
try { try {
if (!isEnabled()) return if (!isEnabled()) return
const countryCode = readCountryCode(getCountryCode) const countryCode = readCountryCode(getCountryCode)
const commonParams = {
session_id: sessionId,
engagement_time_msec: 100,
...clampParams(baseParams()),
}
const includeFirstLaunch =
!firstLaunchInFlight && (firstLaunchPending ??= shouldTrackFirstLaunch())
const body = JSON.stringify({ const body = JSON.stringify({
client_id: getClientId(), client_id: getClientId(),
...(countryCode ? { user_location: { country_id: countryCode } } : {}), ...(countryCode ? { user_location: { country_id: countryCode } } : {}),
events: [ events: [
...(includeFirstLaunch
? [
{
name: INSTALL_FIRST_LAUNCH_EVENT,
params: commonParams,
},
]
: []),
{ {
name, name,
params: { params: {
session_id: sessionId, ...commonParams,
engagement_time_msec: 100,
...clampParams(baseParams()),
...clampParams(params), ...clampParams(params),
}, },
}, },
], ],
}) })
void fetchFn(endpoint, { const request = fetchFn(endpoint, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body, body,
signal: AbortSignal.timeout(SEND_TIMEOUT_MS), signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
}).catch(() => {}) })
if (includeFirstLaunch) {
firstLaunchInFlight = true
void request.then(
(response) => {
firstLaunchInFlight = false
if (!response.ok) return
firstLaunchPending = false
try {
onFirstLaunchSent()
} catch {
// A later process retries if persisting the receipt fails.
}
},
() => {
firstLaunchInFlight = false
},
)
} else {
void request.catch(() => {})
}
} catch { } catch {
// analytics must never surface an error into the app // analytics must never surface an error into the app
} }
+7 -2
View File
@@ -53,8 +53,9 @@ import {
ANALYTICS_ENABLED_KEY, ANALYTICS_ENABLED_KEY,
analyticsEnabledFrom, analyticsEnabledFrom,
createAnalytics, createAnalytics,
ensureAnalyticsClientId, ensureAnalyticsClientState,
extractPackagedAnalyticsKeys, extractPackagedAnalyticsKeys,
markAnalyticsFirstLaunchSent,
} from './analytics' } from './analytics'
import type { Analytics, AnalyticsKeys } from './analytics' import type { Analytics, AnalyticsKeys } from './analytics'
import { import {
@@ -362,10 +363,14 @@ function persistAnalyticsPreference(enabled: boolean): boolean {
function initAnalytics(): void { function initAnalytics(): void {
try { try {
let clientState: ReturnType<typeof ensureAnalyticsClientState> | null = null
const getClientState = () => (clientState ??= ensureAnalyticsClientState(APP_SETTINGS_PATH()))
analytics = createAnalytics({ analytics = createAnalytics({
keys: resolveAnalyticsKeys(), keys: resolveAnalyticsKeys(),
getClientId: () => ensureAnalyticsClientId(APP_SETTINGS_PATH()), getClientId: () => getClientState().clientId,
isEnabled: analyticsEnabled, isEnabled: analyticsEnabled,
shouldTrackFirstLaunch: () => getClientState().firstLaunchPending,
onFirstLaunchSent: () => markAnalyticsFirstLaunchSent(APP_SETTINGS_PATH()),
// Country-only approximation from OS regional settings. This avoids an // Country-only approximation from OS regional settings. This avoids an
// IP lookup while populating GA4's built-in Country dimension. // IP lookup while populating GA4's built-in Country dimension.
getCountryCode: () => app.getLocaleCountryCode(), getCountryCode: () => app.getLocaleCountryCode(),
+16 -4
View File
@@ -1440,7 +1440,12 @@ export function Home() {
const moveFileTo = async (filePath: string, targetProjectId: string) => { const moveFileTo = async (filePath: string, targetProjectId: string) => {
setMoveFileMenu(null) setMoveFileMenu(null)
setRowMenu(null) setRowMenu(null)
await window.aiOfficeProject?.moveFile(filePath, targetProjectId) try {
await window.aiOfficeProject?.moveFile(filePath, targetProjectId)
} catch (error) {
window.alert(error instanceof Error ? error.message : String(error))
return
}
refresh() refresh()
if (selectedProjectId) { if (selectedProjectId) {
setProjectFileEntries((prev) => prev.filter((e) => e.path !== filePath)) setProjectFileEntries((prev) => prev.filter((e) => e.path !== filePath))
@@ -1454,10 +1459,17 @@ export function Home() {
// re-selected or re-moved while the sequential IPC loop is in flight // re-selected or re-moved while the sequential IPC loop is in flight
const moved = new Set(paths) const moved = new Set(paths)
setProjectFileEntries((prev) => prev.filter((e) => !moved.has(e.path))) setProjectFileEntries((prev) => prev.filter((e) => !moved.has(e.path)))
for (const path of paths) { try {
await window.aiOfficeProject?.moveFile(path, targetProjectId) for (const path of paths) {
await window.aiOfficeProject?.moveFile(path, targetProjectId)
}
} catch (error) {
window.alert(error instanceof Error ? error.message : String(error))
} finally {
// A bulk move can fail after earlier paths succeeded; reload to restore
// unmoved rows while keeping successfully moved rows out of this project.
refresh()
} }
refresh()
} }
// ── New file (passes projectId when a project is selected) ── // ── New file (passes projectId when a project is selected) ──
+100
View File
@@ -5,12 +5,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { import {
ANALYTICS_CLIENT_ID_KEY, ANALYTICS_CLIENT_ID_KEY,
ANALYTICS_ENABLED_KEY, ANALYTICS_ENABLED_KEY,
ANALYTICS_FIRST_LAUNCH_PENDING_KEY,
INSTALL_FIRST_LAUNCH_EVENT,
analyticsEnabledFrom, analyticsEnabledFrom,
createAnalytics, createAnalytics,
ensureAnalyticsClientId, ensureAnalyticsClientId,
ensureAnalyticsClientState,
extractAnalyticsKeys, extractAnalyticsKeys,
extractPackagedAnalyticsKeys, extractPackagedAnalyticsKeys,
isValidEventName, isValidEventName,
markAnalyticsFirstLaunchSent,
} from '../src/main/analytics' } from '../src/main/analytics'
/** /**
@@ -115,6 +119,30 @@ describe('ensureAnalyticsClientId', () => {
const saved = JSON.parse(readFileSync(settingsPath, 'utf8')) as Record<string, unknown> const saved = JSON.parse(readFileSync(settingsPath, 'utf8')) as Record<string, unknown>
expect(saved.language).toBe('ja') expect(saved.language).toBe('ja')
}) })
it('keeps a new install pending until its cohort-start event is delivered', () => {
const created = ensureAnalyticsClientState(settingsPath)
expect(created.clientId).toMatch(/^[0-9a-f-]{36}$/)
expect(created.firstLaunchPending).toBe(true)
expect(JSON.parse(readFileSync(settingsPath, 'utf8'))[ANALYTICS_FIRST_LAUNCH_PENDING_KEY]).toBe(
true,
)
expect(ensureAnalyticsClientState(settingsPath)).toEqual(created)
markAnalyticsFirstLaunchSent(settingsPath)
expect(ensureAnalyticsClientState(settingsPath)).toEqual({
clientId: created.clientId,
firstLaunchPending: false,
})
})
it('does not classify an id created before retention tracking as new', () => {
writeFileSync(settingsPath, JSON.stringify({ [ANALYTICS_CLIENT_ID_KEY]: 'legacy-install-id' }))
expect(ensureAnalyticsClientState(settingsPath)).toEqual({
clientId: 'legacy-install-id',
firstLaunchPending: false,
})
})
}) })
describe('isValidEventName', () => { describe('isValidEventName', () => {
@@ -136,16 +164,19 @@ describe('createAnalytics', () => {
it('is a strict no-op without keys', () => { it('is a strict no-op without keys', () => {
const fetchFn = okFetch() const fetchFn = okFetch()
const getClientId = vi.fn(() => 'c') const getClientId = vi.fn(() => 'c')
const shouldTrackFirstLaunch = vi.fn(() => true)
const analytics = createAnalytics({ const analytics = createAnalytics({
keys: null, keys: null,
getClientId, getClientId,
isEnabled: () => true, isEnabled: () => true,
shouldTrackFirstLaunch,
fetchFn, fetchFn,
}) })
expect(analytics.active).toBe(false) expect(analytics.active).toBe(false)
analytics.track('app_launch') analytics.track('app_launch')
expect(fetchFn).not.toHaveBeenCalled() expect(fetchFn).not.toHaveBeenCalled()
expect(getClientId).not.toHaveBeenCalled() expect(getClientId).not.toHaveBeenCalled()
expect(shouldTrackFirstLaunch).not.toHaveBeenCalled()
}) })
it('sends a Measurement Protocol payload with keys present', () => { it('sends a Measurement Protocol payload with keys present', () => {
@@ -201,34 +232,103 @@ describe('createAnalytics', () => {
expect(payload.events).toHaveLength(1) expect(payload.events).toHaveLength(1)
}) })
it('prepends one cohort-start event for a newly identified install', async () => {
const fetchFn = okFetch()
const shouldTrackFirstLaunch = vi.fn(() => true)
const onFirstLaunchSent = vi.fn()
const analytics = createAnalytics({
keys: KEYS,
getClientId: () => 'new-install-id',
isEnabled: () => true,
shouldTrackFirstLaunch,
onFirstLaunchSent,
baseParams: () => ({ app_version: '1.0.0' }),
fetchFn,
})
analytics.track('app_launch')
const firstPayload = JSON.parse((fetchFn.mock.calls[0][1] as RequestInit).body as string) as {
events: Array<{ name: string; params: Record<string, unknown> }>
}
expect(firstPayload.events.map((event) => event.name)).toEqual([
INSTALL_FIRST_LAUNCH_EVENT,
'app_launch',
])
expect(firstPayload.events[0].params.app_version).toBe('1.0.0')
expect(firstPayload.events[0].params.session_id).toMatch(/^\d+$/)
await vi.waitFor(() => expect(onFirstLaunchSent).toHaveBeenCalledTimes(1))
analytics.track('file_open', { ext: 'docx' })
const laterPayload = JSON.parse((fetchFn.mock.calls[1][1] as RequestInit).body as string) as {
events: Array<{ name: string }>
}
expect(laterPayload.events.map((event) => event.name)).toEqual(['file_open'])
expect(shouldTrackFirstLaunch).toHaveBeenCalledTimes(1)
})
it('retries the cohort-start event after a failed delivery', async () => {
const fetchFn = vi
.fn()
.mockRejectedValueOnce(new Error('offline'))
.mockResolvedValue(new Response(null, { status: 204 }))
const onFirstLaunchSent = vi.fn()
const analytics = createAnalytics({
keys: KEYS,
getClientId: () => 'new-install-id',
isEnabled: () => true,
shouldTrackFirstLaunch: () => true,
onFirstLaunchSent,
fetchFn,
})
analytics.track('app_launch')
await vi.waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(1))
await Promise.resolve()
analytics.track('file_open')
const retryPayload = JSON.parse((fetchFn.mock.calls[1][1] as RequestInit).body as string) as {
events: Array<{ name: string }>
}
expect(retryPayload.events.map((event) => event.name)).toEqual([
INSTALL_FIRST_LAUNCH_EVENT,
'file_open',
])
await vi.waitFor(() => expect(onFirstLaunchSent).toHaveBeenCalledTimes(1))
})
it('honors the runtime gate and stops immediately after opt-out', () => { it('honors the runtime gate and stops immediately after opt-out', () => {
const fetchFn = okFetch() const fetchFn = okFetch()
const getClientId = vi.fn(() => 'c') const getClientId = vi.fn(() => 'c')
const getCountryCode = vi.fn(() => 'US') const getCountryCode = vi.fn(() => 'US')
const shouldTrackFirstLaunch = vi.fn(() => false)
let enabled = false let enabled = false
const analytics = createAnalytics({ const analytics = createAnalytics({
keys: KEYS, keys: KEYS,
getClientId, getClientId,
isEnabled: () => enabled, isEnabled: () => enabled,
getCountryCode, getCountryCode,
shouldTrackFirstLaunch,
fetchFn, fetchFn,
}) })
analytics.track('pre_consent') analytics.track('pre_consent')
expect(fetchFn).not.toHaveBeenCalled() expect(fetchFn).not.toHaveBeenCalled()
expect(getClientId).not.toHaveBeenCalled() expect(getClientId).not.toHaveBeenCalled()
expect(getCountryCode).not.toHaveBeenCalled() expect(getCountryCode).not.toHaveBeenCalled()
expect(shouldTrackFirstLaunch).not.toHaveBeenCalled()
enabled = true enabled = true
analytics.track('post_consent') analytics.track('post_consent')
expect(fetchFn).toHaveBeenCalledTimes(1) expect(fetchFn).toHaveBeenCalledTimes(1)
expect(getClientId).toHaveBeenCalledTimes(1) expect(getClientId).toHaveBeenCalledTimes(1)
expect(getCountryCode).toHaveBeenCalledTimes(1) expect(getCountryCode).toHaveBeenCalledTimes(1)
expect(shouldTrackFirstLaunch).toHaveBeenCalledTimes(1)
enabled = false enabled = false
analytics.track('after_opt_out') analytics.track('after_opt_out')
expect(fetchFn).toHaveBeenCalledTimes(1) expect(fetchFn).toHaveBeenCalledTimes(1)
expect(getClientId).toHaveBeenCalledTimes(1) expect(getClientId).toHaveBeenCalledTimes(1)
expect(getCountryCode).toHaveBeenCalledTimes(1) expect(getCountryCode).toHaveBeenCalledTimes(1)
expect(shouldTrackFirstLaunch).toHaveBeenCalledTimes(1)
}) })
it('creates and persists the client id only when an eligible consented event needs it', () => { it('creates and persists the client id only when an eligible consented event needs it', () => {
+5 -3
View File
@@ -1,16 +1,18 @@
import { readFileSync } from 'node:fs' import { readFileSync } from 'node:fs'
import { join } from 'node:path' import { join } from 'node:path'
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest'
import { INSTALL_FIRST_LAUNCH_EVENT } from '../src/main/analytics'
describe('PRIVACY.md analytics disclosure', () => { describe('PRIVACY.md analytics disclosure', () => {
it('lists every event emitted by the shell main process', () => { it('lists every event emitted by the shell main process', () => {
const source = readFileSync(join(__dirname, '../src/main/index.ts'), 'utf8') const source = readFileSync(join(__dirname, '../src/main/index.ts'), 'utf8')
const privacy = readFileSync(join(__dirname, '../../../PRIVACY.md'), 'utf8') const privacy = readFileSync(join(__dirname, '../../../PRIVACY.md'), 'utf8')
const emitted = new Set( const emitted = new Set([
[...source.matchAll(/\banalytics\.track\(\s*['"]([a-z][a-z0-9_]*)['"]/g)].map( ...[...source.matchAll(/\banalytics\.track\(\s*['"]([a-z][a-z0-9_]*)['"]/g)].map(
(match) => match[1], (match) => match[1],
), ),
) INSTALL_FIRST_LAUNCH_EVENT,
])
const documented = new Set( const documented = new Set(
[...privacy.matchAll(/^- `([a-z][a-z0-9_]*)` —/gm)].map((match) => match[1]), [...privacy.matchAll(/^- `([a-z][a-z0-9_]*)` —/gm)].map((match) => match[1]),
) )
+1
View File
@@ -177,6 +177,7 @@ export function registerAiIpc(): void {
await streamForProvider(provider, config, system, messages, tools, maxTokens, { await streamForProvider(provider, config, system, messages, tools, maxTokens, {
signal: controller.signal, signal: controller.signal,
onDelta: (text) => send({ requestId, type: 'delta', text }), onDelta: (text) => send({ requestId, type: 'delta', text }),
onReasoningDelta: (text) => send({ requestId, type: 'reasoning', text }),
onToolCall: (toolCall) => send({ requestId, type: 'tool-call', toolCall }), onToolCall: (toolCall) => send({ requestId, type: 'tool-call', toolCall }),
onActivity: ping, onActivity: ping,
}) })
+514
View File
@@ -0,0 +1,514 @@
/** OFL font catalog for the build-injected mirror. Generated by the mirror script — do not hand-edit files/hashes. */
export interface CatalogFile {
style: 'regular' | 'bold' | 'italic' | 'boldItalic'
file: string
sha256: string
bytes: number
}
export interface CatalogFamily {
family: string
/** Primary script, for grouping in the picker */
script: 'latin' | 'ja' | 'ko' | 'sc' | 'tc'
files: CatalogFile[]
}
export const FONT_CATALOG: CatalogFamily[] = [
{
family: 'Open Sans',
script: 'latin',
files: [
{
style: 'italic',
file: 'OpenSans-italic.ttf',
sha256: '1bc0594a83762b2c25d38915a34464b7fec6088298ca22d151757bf98d6700ec',
bytes: 127392,
},
{
style: 'boldItalic',
file: 'OpenSans-boldItalic.ttf',
sha256: '6d3884d0d57c1b67e9c50c54eca7b69c535c114e76bd7a9cfda0258588185553',
bytes: 127156,
},
{
style: 'regular',
file: 'OpenSans-regular.ttf',
sha256: '47ed1cfaa7ffca04a04ab850b2938fd52c09d1b44cfa3e2980878e166b0cbd87',
bytes: 122116,
},
{
style: 'bold',
file: 'OpenSans-bold.ttf',
sha256: '75367e6da7d914eaed87883ba51b2a2b5816b5cdbb39f96ec5c81a5b032bfd5a',
bytes: 122132,
},
],
},
{
family: 'Roboto',
script: 'latin',
files: [
{
style: 'italic',
file: 'Roboto-italic.ttf',
sha256: '4d3035883c531846bd1ce2dc89f36d932e72dc114f56062c7e3a9cdd74f3d3ea',
bytes: 127988,
},
{
style: 'boldItalic',
file: 'Roboto-boldItalic.ttf',
sha256: 'be7639306a4fc4a02ce2ae2ff59eb1335e4db4a7379dd0a384ed7cc053817789',
bytes: 128772,
},
{
style: 'regular',
file: 'Roboto-regular.ttf',
sha256: 'dece7c71bbe61710787f0839c722c65e87355dd2eb4a823e6b5488121ff81e4b',
bytes: 123720,
},
{
style: 'bold',
file: 'Roboto-bold.ttf',
sha256: '35757eaa996b3359022f47f164a67ee9eac04971af24c5b8fbd4b89e844ff190',
bytes: 124292,
},
],
},
{
family: 'Lato',
script: 'latin',
files: [
{
style: 'italic',
file: 'Lato-italic.ttf',
sha256: 'ae2f4abf0bf802b3710c474f05d1a34f086ef57001f5751d03e428e113f5a684',
bytes: 72936,
},
{
style: 'boldItalic',
file: 'Lato-boldItalic.ttf',
sha256: '0c55b8d34d395c056230c7c5741244de73d0d3cf5fe01b5a0f54cb025fb942fd',
bytes: 74836,
},
{
style: 'regular',
file: 'Lato-regular.ttf',
sha256: 'f43f1c7780d69792278f04b136c934a0298fc66f2e974bac13dd2e53adc52bde',
bytes: 72312,
},
{
style: 'bold',
file: 'Lato-bold.ttf',
sha256: '02e8f4be57ddc47cb7882c41b60216b6085b1ceaf717514be2b88fa15396238d',
bytes: 70576,
},
],
},
{
family: 'Montserrat',
script: 'latin',
files: [
{
style: 'italic',
file: 'Montserrat-italic.ttf',
sha256: 'afb8986a68a0d5189122bd11ed236bd4087abb2b4415b5df1e2bc2579f5d1241',
bytes: 181552,
},
{
style: 'boldItalic',
file: 'Montserrat-boldItalic.ttf',
sha256: '24ffadc3cd172e73f8205c11b3136baf8daec40b97855eb710c8c5074747eb1b',
bytes: 182608,
},
{
style: 'regular',
file: 'Montserrat-regular.ttf',
sha256: '84f3d3275dfb159dd311c61828fd754a82ec31c377120518e2cd3e7d34394e96',
bytes: 180068,
},
{
style: 'bold',
file: 'Montserrat-bold.ttf',
sha256: '247f052d2f5b84a5bbe7831c3b08a71ca391ff54f1dfb9be88a3d3da569e3a38',
bytes: 181028,
},
],
},
{
family: 'Poppins',
script: 'latin',
files: [
{
style: 'italic',
file: 'Poppins-italic.ttf',
sha256: 'd455310e3d1e4393723dbe5836cb27c351751123b89a74c7034ec60c861d5556',
bytes: 178112,
},
{
style: 'boldItalic',
file: 'Poppins-boldItalic.ttf',
sha256: '733b74494c0b5856045e34eea8b899f02458ca8e0b7ebd2a887a86b64d99b0d0',
bytes: 172720,
},
{
style: 'regular',
file: 'Poppins-regular.ttf',
sha256: 'cdedb1729acac414ed01744a11da7badb86adf13108e7bd3fa161b9323f7fe54',
bytes: 154628,
},
{
style: 'bold',
file: 'Poppins-bold.ttf',
sha256: '1984efdda0fbe207d7ac20feac2ba7c2768c92a90094b02a206c9d58cc30ff2e',
bytes: 150292,
},
],
},
{
family: 'Inter',
script: 'latin',
files: [
{
style: 'italic',
file: 'Inter-italic.ttf',
sha256: 'ef8f755d933b9310804cc9152f1f18cb2ac460d6b05054ec913d889c9f11f79e',
bytes: 328252,
},
{
style: 'boldItalic',
file: 'Inter-boldItalic.ttf',
sha256: 'c1811d32ac0f6eed1bbf57529f2ecdfc6c717d48a969dd864942436315a1b198',
bytes: 330132,
},
{
style: 'regular',
file: 'Inter-regular.ttf',
sha256: '1b08e7fc267a5c7e1d614100f604b83e7e8a0be241f0f288faa2b3ac93a683ba',
bytes: 324820,
},
{
style: 'bold',
file: 'Inter-bold.ttf',
sha256: 'b37284b5701b6b168dfc770aa1a4ac492106422fd3ba76bc7641e37434e8019c',
bytes: 326468,
},
],
},
{
family: 'Source Sans 3',
script: 'latin',
files: [
{
style: 'italic',
file: 'SourceSans3-italic.ttf',
sha256: '4c51c2a49d1bd7046376443c1577b76f251944a6366f5f7918a8377e20e50c1f',
bytes: 209376,
},
{
style: 'boldItalic',
file: 'SourceSans3-boldItalic.ttf',
sha256: '3d685c1b7bc3660ab9d92a6e0c04cdf8605065f09c46617fe078b8f1c260d5f3',
bytes: 209356,
},
{
style: 'regular',
file: 'SourceSans3-regular.ttf',
sha256: 'b6f2cc8d9905e97b5cd7a294367bb529814385f299fb23057060394cbd6bbffb',
bytes: 234708,
},
{
style: 'bold',
file: 'SourceSans3-bold.ttf',
sha256: 'e53acf3eb590b2ff183288401da9f3b829703e9716bc88e0da821e3a2ce9c175',
bytes: 234640,
},
],
},
{
family: 'Oswald',
script: 'latin',
files: [
{
style: 'regular',
file: 'Oswald-regular.ttf',
sha256: 'bd6ff5a83bcdc92d7aac6dbb16e4dd2b0b0320bec6402bb81f5dd9735b500e46',
bytes: 86068,
},
{
style: 'bold',
file: 'Oswald-bold.ttf',
sha256: 'a6ee8b91ec269a6f48631ba4ba1a3ab7e5039e5482dda8dc9672ee4620d7bd68',
bytes: 86416,
},
],
},
{
family: 'Raleway',
script: 'latin',
files: [
{
style: 'italic',
file: 'Raleway-italic.ttf',
sha256: '947194506dcf722728b84075659c60350c6a730d1ef8bbfe03acb4980e0b165a',
bytes: 136572,
},
{
style: 'boldItalic',
file: 'Raleway-boldItalic.ttf',
sha256: '4f8f9bad6e888d63aea502d11b85db15ac6b751bacb1198fb4ca5b722b1fbc68',
bytes: 136680,
},
{
style: 'regular',
file: 'Raleway-regular.ttf',
sha256: '943300b002516feaf028c27aceaa2f473f2e1c0229ed913652a406d43277d9ba',
bytes: 138808,
},
{
style: 'bold',
file: 'Raleway-bold.ttf',
sha256: '6cd34aa42be80b5ae85cc8c816f241d46a6d77a3a3277a6a20962b134b567cea',
bytes: 138748,
},
],
},
{
family: 'Nunito',
script: 'latin',
files: [
{
style: 'italic',
file: 'Nunito-italic.ttf',
sha256: '49a2a2cbe1e0b58a4313217cc74fc122c8a4e5ba1539e67f2a87e0832d881281',
bytes: 128400,
},
{
style: 'boldItalic',
file: 'Nunito-boldItalic.ttf',
sha256: '4d6c0d42a74b753d33fba2c33f117264ca8c0e3f40df7a4313419ad5e6c95eae',
bytes: 128268,
},
{
style: 'regular',
file: 'Nunito-regular.ttf',
sha256: '9ecbdba35fa74f10a1a916c31649b802a12deb9e66c7b1fe4650afcfd4d16971',
bytes: 125528,
},
{
style: 'bold',
file: 'Nunito-bold.ttf',
sha256: '1a025dfce6e6e03bbe31ba82277ec5ed96df8b8dd58b3df6267269490b90b1dc',
bytes: 125464,
},
],
},
{
family: 'Merriweather',
script: 'latin',
files: [
{
style: 'italic',
file: 'Merriweather-italic.ttf',
sha256: 'afff81272b7653417bb6f8bef57add055b1f9fda36f27eba5f32b40752bd08da',
bytes: 595652,
},
{
style: 'boldItalic',
file: 'Merriweather-boldItalic.ttf',
sha256: 'e9864a6790bf712a04e20f3662b206a1535186ed3e877fd859dd5fb9682335df',
bytes: 599500,
},
{
style: 'regular',
file: 'Merriweather-regular.ttf',
sha256: 'e029d3b71e5bae3877c73f4f2b15af28db16593d49b0aed2a328d37ff7075846',
bytes: 585976,
},
{
style: 'bold',
file: 'Merriweather-bold.ttf',
sha256: '90b7db4460fcd1a5ca49575c2668a793f3cd6447664d312a068d690e1c01e6bc',
bytes: 586052,
},
],
},
{
family: 'Playfair Display',
script: 'latin',
files: [
{
style: 'italic',
file: 'PlayfairDisplay-italic.ttf',
sha256: '6021680663c58b344d8404c289c755aadc662a02189ffe4f5ca79378f9e97840',
bytes: 110816,
},
{
style: 'boldItalic',
file: 'PlayfairDisplay-boldItalic.ttf',
sha256: '954e20ee10ae685d0a5a6e6ee380165ea9c8eb329c0e22a58739496714f66991',
bytes: 111128,
},
{
style: 'regular',
file: 'PlayfairDisplay-regular.ttf',
sha256: '1609a54fa3ad1abc8d0037132f73700333241ea0b65672079998e352f151dea7',
bytes: 123240,
},
{
style: 'bold',
file: 'PlayfairDisplay-bold.ttf',
sha256: 'adefc53e7b3d483f1fa5e85edd82b7689ca79db25a1f6786bd7949cdcfeec601',
bytes: 123536,
},
],
},
{
family: 'Work Sans',
script: 'latin',
files: [
{
style: 'italic',
file: 'WorkSans-italic.ttf',
sha256: 'd38632ddd219dea11541e99bcbcf9b0569ca6aa3fcdb942fbddbaf79cc3a6a99',
bytes: 109088,
},
{
style: 'boldItalic',
file: 'WorkSans-boldItalic.ttf',
sha256: '2907c2e697650caf6cd7dde599e3a7471d3e8713ce5c694f838a0296f464d6d6',
bytes: 110364,
},
{
style: 'regular',
file: 'WorkSans-regular.ttf',
sha256: 'a131e7022b34ef1950a9d6bdda16f5d4509cc1fe1af5991a4552febd2a4027e5',
bytes: 114144,
},
{
style: 'bold',
file: 'WorkSans-bold.ttf',
sha256: 'e8398b22225a1f971df9bb12fa8fb9dd4c76e80aa4d67d45bde60ebbc6c5ad81',
bytes: 115632,
},
],
},
{
family: 'Rubik',
script: 'latin',
files: [
{
style: 'italic',
file: 'Rubik-italic.ttf',
sha256: '16fc8b9b98fdf8c100a2266321c23da5b686aac084645053ad169f0a5b9fadee',
bytes: 173148,
},
{
style: 'boldItalic',
file: 'Rubik-boldItalic.ttf',
sha256: '5df975955c4daa64e3872facb84017eca844b82dccaf295ec5462ac66640ba7e',
bytes: 173968,
},
{
style: 'regular',
file: 'Rubik-regular.ttf',
sha256: 'cc6a4222027f8e57ff86a50c5ba88f12326d7223bde9bf6531538633ebad3343',
bytes: 174992,
},
{
style: 'bold',
file: 'Rubik-bold.ttf',
sha256: '2d6393d64232ea3e0eeff79165d80df61c0859213abdd638b0ec1e81d21098dc',
bytes: 175628,
},
],
},
{
family: 'Noto Sans JP',
script: 'ja',
files: [
{
style: 'regular',
file: 'NotoSansJP-regular.ttf',
sha256: '4593dfcdc70ee68852606c90d75dfc6e022feda12780a55615239c53c54ef086',
bytes: 5324144,
},
{
style: 'bold',
file: 'NotoSansJP-bold.ttf',
sha256: 'a3910e15eea0451ffbea62e894e951ea9f7c812c8b4b5e947593b6ecc2d4b057',
bytes: 5319680,
},
],
},
{
family: 'Noto Sans KR',
script: 'ko',
files: [
{
style: 'regular',
file: 'NotoSansKR-regular.ttf',
sha256: 'c733940a7dc687142848b30a491e97138ed58dc58c4cae33c44e3ee52da411cb',
bytes: 6163256,
},
{
style: 'bold',
file: 'NotoSansKR-bold.ttf',
sha256: '5ebb0def0fe9e7c853253eca8ec9c1066adc479f2e248533b412ed0c6a663abc',
bytes: 6159248,
},
],
},
{
family: 'Noto Sans SC',
script: 'sc',
files: [
{
style: 'regular',
file: 'NotoSansSC-regular.ttf',
sha256: '450625c8d46ab3df97b7904ded955ec2746d17ec76740cb1e91d1ba63a0f89af',
bytes: 10540644,
},
{
style: 'bold',
file: 'NotoSansSC-bold.ttf',
sha256: '0066a522a1ac007c1d72bc4fccb114f80ff7294641c78cead9715bd14d43b9ea',
bytes: 10530408,
},
],
},
{
family: 'Noto Sans TC',
script: 'tc',
files: [
{
style: 'regular',
file: 'NotoSansTC-regular.ttf',
sha256: '619662a0583f38311e92666927e5edbfd30f2a1fbe8593685660bd11bdd46a10',
bytes: 7090820,
},
{
style: 'bold',
file: 'NotoSansTC-bold.ttf',
sha256: '33e8464f3432fd9eba5fa6ff74f5fb9ee612cad703877bd71c36e6f167c0a7e3',
bytes: 7085600,
},
],
},
{
family: 'Nanum Gothic',
script: 'ko',
files: [
{
style: 'regular',
file: 'NanumGothic-regular.ttf',
sha256: '370dbd31aa8abd8f8c057f7d41a71d38f2e71f070fa50a8cc20fecef88a9baab',
bytes: 2052640,
},
{
style: 'bold',
file: 'NanumGothic-bold.ttf',
sha256: 'd81d6344e36f05ff1fe42b18cc9d18feece8283ae1132e1ef890b5f421eefb4a',
bytes: 2071704,
},
],
},
]
+186
View File
@@ -0,0 +1,186 @@
/**
* Downloadable/installable font store (main process).
*
* A curated catalog of OFL-licensed families is mirrored on the GenOffice CDN
* (versioned paths, sha256-pinned). Downloads and user-installed font files both
* land in <userData>/fonts, which the FontRegistry scans as a private dir — the
* same measure-and-register pipeline as Office DFonts, so a newly installed font
* immediately drives both layout metrics and canvas drawing.
*/
import { createHash } from 'node:crypto'
import { mkdirSync, readFileSync, writeFileSync, existsSync, copyFileSync } from 'node:fs'
import { basename, join } from 'node:path'
import { app, net } from 'electron'
import type { OpenedPptx } from '@genoffice/pptx-engine'
import { familyAvailable, fontFileFamilies, setUserFontDir } from './fonts'
import { FONT_CATALOG, type CatalogFamily } from './font-catalog'
function normalizeFontCdnBaseUrl(value: unknown): string | null {
if (typeof value !== 'string' || !value.trim()) return null
try {
const url = new URL(value.trim())
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) {
return null
}
const path = url.pathname.replace(/\/+$/, '')
return `${url.origin}${path}`
} catch {
return null
}
}
/** Read the build-injected font CDN URL from packaged app metadata. */
export function extractFontCdnBaseUrl(pkg: unknown): string | null {
if (!pkg || typeof pkg !== 'object') return null
const raw = (pkg as Record<string, unknown>).genofficeFontCdn
if (!raw || typeof raw !== 'object') return null
return normalizeFontCdnBaseUrl((raw as Record<string, unknown>).baseUrl)
}
/**
* Official packages receive the URL through electron-builder extraMetadata.
* Source/dev builds may opt in with an environment variable; without either,
* all downloadable-font UI stays disabled while local font installation works.
*/
export function fontCdnBaseUrl(): string | null {
if (!app.isPackaged) return normalizeFontCdnBaseUrl(process.env.GENOFFICE_FONT_CDN_URL)
try {
const pkg = JSON.parse(readFileSync(join(app.getAppPath(), 'package.json'), 'utf8')) as unknown
return extractFontCdnBaseUrl(pkg)
} catch {
return null
}
}
export function fontStoreDir(): string {
return join(app.getPath('userData'), 'fonts')
}
/** Wire the store dir into the font registry; call once at startup. */
export function initFontStore(): void {
setUserFontDir(fontStoreDir())
}
const downloading = new Map<string, Promise<void>>()
export interface FontCatalogEntry {
family: string
script: CatalogFamily['script']
installed: boolean
downloading: boolean
}
export function listFontCatalog(): FontCatalogEntry[] {
if (!fontCdnBaseUrl()) return []
return FONT_CATALOG.map((f) => ({
family: f.family,
script: f.script,
installed: familyAvailable(f.family),
downloading: downloading.has(f.family),
}))
}
async function fetchVerified(url: string, sha256: string): Promise<Buffer> {
const res = await net.fetch(url)
if (!res.ok) throw new Error(`download failed: HTTP ${res.status}`)
const buf = Buffer.from(await res.arrayBuffer())
const got = createHash('sha256').update(buf).digest('hex')
if (got !== sha256) throw new Error('download failed: checksum mismatch')
return buf
}
/** Download every style file of a catalog family into the store. Throws on any failure;
* a concurrent call for the same family joins the in-flight download. */
export function downloadFontFamily(family: string): Promise<void> {
const entry = FONT_CATALOG.find((f) => f.family === family)
if (!entry) return Promise.reject(new Error(`not in catalog: ${family}`))
const baseUrl = fontCdnBaseUrl()
if (!baseUrl) return Promise.reject(new Error('font downloads are unavailable'))
const inFlight = downloading.get(family)
if (inFlight) return inFlight
const run = (async () => {
const dir = fontStoreDir()
mkdirSync(dir, { recursive: true })
for (const file of entry.files) {
const dest = join(dir, file.file)
if (existsSync(dest)) continue
const url = new URL(encodeURIComponent(file.file), `${baseUrl}/`).toString()
const buf = await fetchVerified(url, file.sha256)
writeFileSync(dest, buf)
}
})().finally(() => downloading.delete(family))
downloading.set(family, run)
return run
}
const SFNT_MAGIC = new Set(['00010000', '4f54544f', '74746366', '74727565']) // sfnt / OTTO / ttcf / true
/**
* Copy user-picked font files into the store, renamed to their primary family
* name so the filename-keyed registry index can find them. Returns the family
* names that were installed.
*/
export function installLocalFontFiles(paths: string[]): string[] {
const dir = fontStoreDir()
mkdirSync(dir, { recursive: true })
const installed: string[] = []
for (const p of paths) {
let head: string
try {
head = readFileSync(p).subarray(0, 4).toString('hex')
} catch {
continue
}
if (!SFNT_MAGIC.has(head)) continue
const families = fontFileFamilies(p)
const primary = families[0]
if (!primary) continue
const ext =
basename(p)
.match(/\.(ttc|otc|otf)$/i)?.[1]
?.toLowerCase() ?? 'ttf'
// Family-derived name = registry index key; suffix keeps distinct style files apart
const styleTag = /bold\s*italic/i.test(basename(p))
? '-BoldItalic'
: /bold/i.test(basename(p))
? '-Bold'
: /italic|oblique/i.test(basename(p))
? '-Italic'
: ''
const dest = join(dir, `${primary.replace(/[\\/:]/g, '')}${styleTag}.${ext}`)
try {
copyFileSync(p, dest)
installed.push(...families)
} catch {
/* unreadable/locked source: skip */
}
}
return [...new Set(installed)]
}
/** Deck-referenced families that are missing locally but present in the catalog. */
export function missingCatalogFonts(opened: OpenedPptx): string[] {
if (!fontCdnBaseUrl()) return []
const wanted = new Set<string>()
type TextLike = { paragraphs?: Array<{ runs?: Array<{ fontFamily?: string }> }> }
const collectText = (text: TextLike | undefined): void => {
for (const p of text?.paragraphs ?? [])
for (const r of p.runs ?? []) if (r.fontFamily) wanted.add(r.fontFamily)
}
const walk = (els: unknown[]): void => {
for (const el of els as Array<{
type?: string
children?: unknown[]
text?: TextLike
rows?: Array<Array<{ text?: TextLike }>>
}>) {
if (!el || typeof el !== 'object') continue
if (el.children) walk(el.children)
collectText(el.text)
for (const row of el.rows ?? []) for (const cell of row) collectText(cell.text)
}
}
for (const s of opened.deck.slides) walk(s.elements as unknown[])
const inCatalog = new Set(FONT_CATALOG.map((f) => f.family))
return [...wanted].filter((f) => inCatalog.has(f) && !familyAvailable(f)).sort()
}
+52 -1
View File
@@ -40,6 +40,20 @@ const BUNDLED_FONTS: Record<string, string> = {
'Carlito-BoldItalic': carlitoBoldItalic, 'Carlito-BoldItalic': carlitoBoldItalic,
} }
/**
* User font store (downloaded catalog fonts + fonts installed via the in-app entry).
* Injected by slides-main at startup (fonts.ts stays free of electron imports); invisible
* to Chromium, so faces resolved from here get the same private FontFace treatment as
* Office DFonts.
*/
let userFontDir: string | null = null
export function setUserFontDir(dir: string): void {
userFontDir = dir
}
export function getUserFontDir(): string | null {
return userFontDir
}
function fontDirs(): string[] { function fontDirs(): string[] {
switch (process.platform) { switch (process.platform) {
case 'darwin': case 'darwin':
@@ -150,6 +164,9 @@ const ALIASES: Record<string, string[]> = {
'lucida sans': ['Lucida Grande', 'Arial'], 'lucida sans': ['Lucida Grande', 'Arial'],
// —— Japanese —— // —— Japanese ——
'yu gothic': [...YU_GOTHIC, ...HIRAGINO_SANS], 'yu gothic': [...YU_GOTHIC, ...HIRAGINO_SANS],
// Yu Gothic UI faces live inside YuGothM/YuGothB.ttc (like Meiryo UI in meiryo.ttc);
// the origKey bonus in rankFaces picks them out of the alias target's collection
'yu gothic ui': [...YU_GOTHIC, ...HIRAGINO_SANS],
游ゴシック: [...YU_GOTHIC, ...HIRAGINO_SANS], 游ゴシック: [...YU_GOTHIC, ...HIRAGINO_SANS],
游ゴシック体: [...YU_GOTHIC, ...HIRAGINO_SANS], 游ゴシック体: [...YU_GOTHIC, ...HIRAGINO_SANS],
'yu mincho': [...YU_MINCHO, ...HIRAGINO_MINCHO], 'yu mincho': [...YU_MINCHO, ...HIRAGINO_MINCHO],
@@ -483,6 +500,10 @@ class FontRegistry {
} }
// System dirs first so same-named Office copies (arial.ttf…) resolve non-private // System dirs first so same-named Office copies (arial.ttf…) resolve non-private
for (const dir of fontDirs()) this.scanFlatDir(dir) for (const dir of fontDirs()) this.scanFlatDir(dir)
if (userFontDir) {
this.privateDirs.push(userFontDir)
this.scanFlatDir(userFontDir)
}
for (const dir of officeFontDirs()) { for (const dir of officeFontDirs()) {
this.privateDirs.push(dir) this.privateDirs.push(dir)
this.scanFlatDir(dir) this.scanFlatDir(dir)
@@ -842,10 +863,40 @@ export function getPrivateFontData(id: string): ArrayBuffer | null {
} }
} }
/** Process-wide registry; reset after the user font store changes so new files get indexed. */
let sharedRegistry: FontRegistry | null = null
function getRegistry(): FontRegistry {
return (sharedRegistry ??= new FontRegistry())
}
export function resetFontRegistry(): void {
sharedRegistry = null
}
/** True when the family resolves without same-script/class substitution (alias hits count as available). */
export function familyAvailable(family: string): boolean {
const hit = getRegistry().resolve({
fontFamily: family,
fontSizePx: 100,
bold: false,
italic: false,
})
return !!hit && !hit.substituted
}
/** Family names (name 1/16) declared by a local font file; [] when unreadable. */
export function fontFileFamilies(path: string): string[] {
try {
const faces = readFaceDir(readFileSync(path))
return [...new Set(faces.map((f) => f.display).filter(Boolean))]
} catch {
return []
}
}
/** Create a metrics provider injected with system fonts (falls back to heuristics per run when no font is found). */ /** Create a metrics provider injected with system fonts (falls back to heuristics per run when no font is found). */
export function createSystemFontMetrics(): FontMetricsProvider { export function createSystemFontMetrics(): FontMetricsProvider {
initShapedMetrics() initShapedMetrics()
const registry = new FontRegistry() const registry = getRegistry()
const cache = new Map< const cache = new Map<
string, string,
{ font: OpentypeFontLike; family: string; substituted?: boolean } | undefined { font: OpentypeFontLike; family: string; substituted?: boolean } | undefined
+46 -1
View File
@@ -19,8 +19,10 @@ import {
promoteSlideBackground, promoteSlideBackground,
savePptx, savePptx,
type Paragraph, type Paragraph,
type TextElement,
type TextRun, type TextRun,
} from '@genoffice/pptx-engine' } from '@genoffice/pptx-engine'
import { buildRenderSlide, EMU_PER_PX_96, type FontMetricsProvider } from '@genoffice/pptx-render'
import { coverCropFractions } from '../shared/cover-crop' import { coverCropFractions } from '../shared/cover-crop'
export const SPEC_CANVAS_W = 1280 export const SPEC_CANVAS_W = 1280
@@ -317,6 +319,47 @@ export interface BuildPageDeps {
fetchImage: (url: string) => Promise<{ bytes: Uint8Array; ext: string } | null> fetchImage: (url: string) => Promise<{ bytes: Uint8Array; ext: string } | null>
/** Decodes natural pixel size for cover-cropping; null skips the crop */ /** Decodes natural pixel size for cover-cropping; null skips the crop */
imageDims?: (bytes: Uint8Array) => { width: number; height: number } | null imageDims?: (bytes: Uint8Array) => { width: number; height: number } | null
/** Font metrics for the post-build text measurement; absent skips the box-height fix */
fontMetrics?: FontMetricsProvider
}
/**
* The LLM sizes text boxes from a rough chars-per-line heuristic, which routinely
* undersizes big CJK titles; the box has no autofit, so the canvas draws the overflow
* past the selection frame (and PowerPoint past the shape). Re-measure every text box
* with the real layout engine — on the reopened (parsed) model, the exact input the
* landed page will render from — and grow too-short boxes to their content height.
* Grow-only, plain text boxes only (shape label boxes are design intent); middle/bottom
* anchored boxes shift up so the rendered glyphs stay exactly where they were.
* Returns the re-saved bytes, or null when every box already fits.
*/
async function growTextBoxesToContent(
bytes: Uint8Array,
metrics: FontMetricsProvider,
): Promise<Uint8Array | null> {
const opened = await openPptx(bytes)
const slide = opened.deck.slides[0]
if (!slide) return null
const baseWidthPx = opened.deck.size.cx / EMU_PER_PX_96 // native px → vp.scale = 1
const rendered = buildRenderSlide(slide, opened.deck.size, { fitWidthPx: baseWidthPx, metrics })
let changed = false
for (const node of rendered.nodes) {
if (node.type !== 'text' || !node.text) continue
const el = slide.elements.find((e) => e.id === node.sourceId)
if (el?.type !== 'text') continue
const t = node.text
const needH = Math.max(t.contentHeight, t.inkBottom ?? 0) + t.insets.t + t.insets.b
const growPx = needH - node.box.h
if (growPx < 0.5) continue
const tel = el as TextElement
const offset = { ...tel.transform.offset, cy: Math.max(1, Math.round(needH * EMU_PER_PX_96)) }
if (t.anchor === 'middle') offset.y -= Math.round((growPx / 2) * EMU_PER_PX_96)
else if (t.anchor === 'bottom') offset.y -= Math.round(growPx * EMU_PER_PX_96)
tel.transform = { ...tel.transform, offset }
tel.dirtyTransform = true
changed = true
}
return changed ? savePptx(opened) : null
} }
function toEngineParagraphs(paragraphs: SpecParagraph[]): Paragraph[] { function toEngineParagraphs(paragraphs: SpecParagraph[]): Paragraph[] {
@@ -440,5 +483,7 @@ export async function buildPagePptx(
} }
promoteSlideBackground(slide, opened.deck.size) promoteSlideBackground(slide, opened.deck.size)
return { bytes: await savePptx(opened), imageFailures } let bytes = await savePptx(opened)
if (deps.fontMetrics) bytes = (await growTextBoxesToContent(bytes, deps.fontMetrics)) ?? bytes
return { bytes, imageFailures }
} }

Some files were not shown because too many files have changed in this diff Show More