feat: lines and arrows, which both importers used to drop
Two endpoints rather than a box: no text, no fill, and the diagonal of the frame with `flipV` picking which one. The three kinds share their preset names, since the heads a file declares are what tell them apart. ODF gives a line its own element and its heads a named marker, which needs the draw: prefix declared in styles.xml — undeclared, the file does not parse at all. Word keeps the frame and flips it.
This commit is contained in:
1 parent
03384c3da4
commit
3b24b14470
15 files changed
+367
-30
No files matched your search
+2
-1
@@ -66,6 +66,7 @@
|
||||
- Formulas in a cell (LibreOffice's Table ▸ Formula, Word's Layout ▸ Formula): `=SUM(ABOVE)`, `=AVERAGE(A1:A3)`, `=A1*2` — SUM, PRODUCT, AVERAGE, MIN, MAX, COUNT, ABS, INT, SIGN, MOD and ROUND over cell references, ranges and Word's directions, with arithmetic and parentheses. A formula cell shows its result on the field shade both word processors use and recomputes as the cells it reads change, a formula reading another formula included. It rides the cell as ODF's `table:formula` in LibreOffice's own language (`ooow:sum <A1:A3>`, a direction resolved to the range it stands for) with the result cached as `office:value`, and as Word's `=` field inside the cell — both re-read
|
||||
- Number recognition (LibreOffice's Table ▸ Number Recognition): with it on, a cell whose text reads as a number is rewritten in the document language's number format when the cursor leaves it — `007,50` becomes `7,5`. **Off** by default, as it is in LibreOffice, and the parsing a formula does is independent of it, exactly as there
|
||||
- Table border control (Word/LibreOffice-style): per-side cell borders with presets (all / outside / inside / single edges / none), line width and color; buttons show active states matching the current pen and toggle borders off; round-trips to ODF `fo:border-*` and DOCX `w:tcBorders`
|
||||
- Lines and arrows (shape gallery: line, arrow, double arrow), which both importers used to drop: two endpoints rather than a box, so they hold no text, run across the frame's diagonal and take an arrow head that scales with the pen. The three kinds share their preset names on purpose — the heads a file declares are what tell them apart, so a Word `straightConnector1` with no heads opens as a plain line. ODF gets its own `<draw:line>` plus the one named `Arrow` marker LibreOffice itself writes; Word gets the `line` preset with `flipV` and `a:headEnd`/`a:tailEnd`. Verified against LibreOffice: the same three lines render identically from the .odt, the .docx and the editor
|
||||
- Images: inline or floating with text wrap (left / right / top-bottom), resize handles, rotation, live size badge; insert via toolbar, drag-and-drop, or paste. A floating frame is placed by the file's own offsets, and two top-and-bottom frames set against opposite ends of the text share one band, side by side
|
||||
- A CMYK JPEG's embedded ICC profile is dropped on import: Chromium colour-manages through it where LibreOffice and Word convert naively, which turned a contract's logo from vivid blue to dull teal and its black to grey. It also removes what is often most of the file (a 757 KB logo → 102 KB, easing the localStorage ceiling below)
|
||||
- EMF metafiles are drawn (`import/emf.ts`): the picture is rebuilt as SVG from the metafile's own records — paths, filled shapes, text with its font and colour, embedded bitmaps — so a plot pasted out of MATLAB or Excel arrives as a picture instead of a placeholder
|
||||
@@ -143,7 +144,7 @@ The gap against Word/LibreOffice, most valuable first. Reviewed 2026-08-14.
|
||||
|
||||
**Content an imported document loses**
|
||||
- Charts are **drawn** from the file (`import/chart.ts`: DrawingML `chartN.xml` and ODF `chart:chart`), but as a picture, not a chart object — a re-export carries the drawing and the numbers behind it are no longer editable. The same holds for an **EMF** metafile (`import/emf.ts`): it is drawn, but as the SVG picture it was rebuilt into, and only from the record set a plot consists of — a hatched brush, a clipping region or a rotated bitmap is skipped. **WMF/SVM** metafiles and OLE objects still keep their box and a placeholder label, and export writes that back out: WMF is a different (16-bit) record format, SVM is StarOffice-proprietary, and an OLE object cannot be rendered without its application
|
||||
- Shapes with no text area of their own: lines, arrows as a *line* rather than a block arrow, connectors and freeform curves — they are two endpoints, not a box, and ODF gives each its own element (`draw:line`, `draw:polyline`) rather than a `draw:custom-shape` preset. Rotated shape text (`w:bodyPr vert`) too. All dropped on import with a warning
|
||||
- Connectors that attach to other shapes, and freeform curves — a connector is an anchoring model rather than a shape, and a freeform needs a drawing tool. Rotated shape text (`w:bodyPr vert`) too. All still dropped on import with a warning
|
||||
|
||||
**Missing while writing**
|
||||
- One colour for every tracked change, where both word processors give each author their own — and no reviewing pane listing the revisions the way the comments pane lists comments
|
||||
|
||||
@@ -28,3 +28,28 @@ Adding a shape is one entry in `SHAPES` — no icon, no export branch, no import
|
||||
- An importer maps the file's `draw:type`/`prst` back through the same table;
|
||||
`shapeFromOdfType`/`shapeFromPrst` return **null** for a preset we can't draw, which is
|
||||
what makes the warning possible instead of flattening it to a rectangle.
|
||||
|
||||
## Lines and arrows
|
||||
|
||||
`line`, `lineArrow` and `lineDoubleArrow` are **two endpoints, not a box**: they hold no
|
||||
text (the paragraph the schema requires is hidden and never exported), take no fill, and
|
||||
run across the frame's diagonal — `flipV` picking which one, the single flag Word's
|
||||
`flipV` and ODF's own endpoint order both come down to. They are drawn in the frame's
|
||||
**real pixels** (`linePaths`), not the stretched 0…100 box a polygon uses: an arrow head
|
||||
has to keep its shape however flat the frame is, and the head scales with the pen
|
||||
(`arrowHeadPx`, floored so a hairline still shows one).
|
||||
|
||||
The three share their `odf`/`prst` names, because **the heads are what tell them apart**:
|
||||
both importers read the heads a file declares and `lineKindFor` names the kind, so a
|
||||
`straightConnector1` with no heads is a plain line and a `line` preset with both is a
|
||||
double arrow.
|
||||
|
||||
- **ODF** gives a line its own element — `<draw:line svg:x1/y1/x2/y2>`, no width or
|
||||
height — and its heads are a **named marker**, so `applyTextBoxes` also writes the one
|
||||
`<draw:marker draw:name="Arrow">` definition into `styles.xml`, LibreOffice's own name
|
||||
and path. It goes in only when a line asks for it, and needs `ensureDrawNamespaces`:
|
||||
an undeclared `draw:` prefix there makes the whole file unreadable.
|
||||
- **DOCX** keeps the frame and flips it (`<a:xfrm flipV="1">`), the heads riding the
|
||||
shape's `<a:ln>` as `a:headEnd`/`a:tailEnd`, and writes no `wps:txbx` at all.
|
||||
- **Not covered**: connectors that attach to other shapes, and freeform curves. Both are
|
||||
still dropped with a warning — a connector is an anchoring model, not a shape.
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { SHAPES, shapePath, type ShapeKind } from '../utils/shapes';
|
||||
import { SHAPES, shapePath, linePaths, isLineKind, type ShapeKind } from '../utils/shapes';
|
||||
import { t } from '../i18n/i18n.svelte';
|
||||
|
||||
// The shape gallery, shared by the floating box toolbar and the ribbon's Shape tab.
|
||||
@@ -59,7 +59,14 @@
|
||||
|
||||
{#snippet tile(k: ShapeKind)}
|
||||
<svg viewBox="0 0 100 100" fill="none" aria-hidden="true">
|
||||
{#if k === 'ellipse'}
|
||||
{#if isLineKind(k)}
|
||||
<!-- The tile's box is square, so the heads keep their shape as drawn. -->
|
||||
{@const p = linePaths(k, 76, 76, true, 26)}
|
||||
<path d={p?.line} stroke="currentColor" stroke-width="7" transform="translate(12,12)" />
|
||||
{#each p?.heads ?? [] as d}
|
||||
<path {d} fill="currentColor" transform="translate(12,12)" />
|
||||
{/each}
|
||||
{:else if k === 'ellipse'}
|
||||
<ellipse cx="50" cy="50" rx="45" ry="35" stroke="currentColor" stroke-width="7" />
|
||||
{:else if k === 'roundRect'}
|
||||
<rect x="5" y="15" width="90" height="70" rx="18" stroke="currentColor" stroke-width="7" />
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { EditorState } from '@tiptap/pm/state';
|
||||
import { Decoration, DecorationSet } from '@tiptap/pm/view';
|
||||
import type { EditorView } from '@tiptap/pm/view';
|
||||
import { HANDLES, MIN_SIZE_PX, clamp, parsePx, frameMargins, pageContentHeightPx, type WrapMode } from './image';
|
||||
import { SHAPES, shapePath, isShapeKind, type ShapeKind } from '../../utils/shapes';
|
||||
import { SHAPES, shapePath, linePaths, arrowHeadPx, isShapeKind, isLineKind, type ShapeKind } from '../../utils/shapes';
|
||||
|
||||
// cm attribute value → number, for the frame offsets (px ones use parsePx).
|
||||
const parseCmAttr = (v: string | null): number | null => {
|
||||
@@ -30,6 +30,9 @@ const ELLIPSE_INSET_RATIO = (1 - 1 / Math.SQRT2) / 2;
|
||||
|
||||
const DEFAULT_WIDTH_PX = 280;
|
||||
const DEFAULT_HEIGHT_PX = 96;
|
||||
// A fresh line is flat: both word processors drop one across the text, not down it.
|
||||
const DEFAULT_LINE_HEIGHT_PX = 0;
|
||||
const SVG_NS = 'http://www.w3.org/2000/svg';
|
||||
const PX_PER_PT = 96 / 72;
|
||||
|
||||
export interface TextBoxAttrs {
|
||||
@@ -43,6 +46,7 @@ export interface TextBoxAttrs {
|
||||
wrapAlign: string | null; // 'center'/'right' = set against the middle/far end
|
||||
paddingCm: number; // inset ring around the text (ODF fo:padding)
|
||||
shapeKind: ShapeKind;
|
||||
flipV: boolean; // a line runs bottom-left → top-right instead
|
||||
fillColor: string | null;
|
||||
strokeColor: string | null;
|
||||
strokeWidthPt: number;
|
||||
@@ -149,6 +153,13 @@ export const TextBox = Node.create({
|
||||
},
|
||||
renderHTML: () => ({}),
|
||||
},
|
||||
// Which diagonal of the frame a line runs along — the one flag Word's `flipV`
|
||||
// and ODF's own endpoints both come down to.
|
||||
flipV: {
|
||||
default: false,
|
||||
parseHTML: el => (el as HTMLElement).getAttribute('data-flip-v') === 'true',
|
||||
renderHTML: () => ({}),
|
||||
},
|
||||
fillColor: {
|
||||
default: '#FFFFFF',
|
||||
parseHTML: el => (el as HTMLElement).getAttribute('data-fill') || null,
|
||||
@@ -179,9 +190,10 @@ export const TextBox = Node.create({
|
||||
const style = [
|
||||
a.width ? `width:${a.width}px` : '',
|
||||
a.height ? `min-height:${a.height}px` : '',
|
||||
// A polygon shape paints itself, so the box behind it stays bare.
|
||||
a.fillColor && !SHAPES[a.shapeKind]?.points ? `background:${a.fillColor}` : '',
|
||||
a.strokeColor && !SHAPES[a.shapeKind]?.points
|
||||
// A polygon paints itself and a line is only its stroke, so the box behind
|
||||
// either of them stays bare.
|
||||
a.fillColor && !SHAPES[a.shapeKind]?.points && !isLineKind(a.shapeKind) ? `background:${a.fillColor}` : '',
|
||||
a.strokeColor && !SHAPES[a.shapeKind]?.points && !isLineKind(a.shapeKind)
|
||||
? `border:${a.strokeWidthPt * PX_PER_PT}px solid ${a.strokeColor}` : '',
|
||||
a.shapeKind !== 'textbox' ? `border-radius:${shapeRadius(a.shapeKind)}` : '',
|
||||
a.rotation ? `transform:rotate(${a.rotation}deg)` : '',
|
||||
@@ -193,6 +205,7 @@ export const TextBox = Node.create({
|
||||
...(a.rotation ? { 'data-rotation': String(a.rotation) } : {}),
|
||||
...(a.wrap !== 'inline' ? { 'data-wrap': a.wrap } : {}),
|
||||
...(a.shapeKind !== 'textbox' ? { 'data-shape': a.shapeKind } : {}),
|
||||
...(a.flipV ? { 'data-flip-v': 'true' } : {}),
|
||||
...(a.fillColor ? { 'data-fill': a.fillColor } : {}),
|
||||
...(a.strokeColor ? { 'data-stroke': a.strokeColor } : {}),
|
||||
...(a.strokeWidthPt !== 1 ? { 'data-stroke-width': String(a.strokeWidthPt) } : {}),
|
||||
@@ -277,6 +290,8 @@ class TextBoxView {
|
||||
private resizing = false;
|
||||
// The polygon outline, for a shape CSS cannot draw; null for the three it can.
|
||||
private outline: SVGPathElement | null = null;
|
||||
// The line and its arrow heads, for the kinds that are two endpoints, not a box.
|
||||
private lineSvg: SVGSVGElement | null = null;
|
||||
// Last text-area inset applied; guards the ResizeObserver feedback loop.
|
||||
private lastInset = '';
|
||||
|
||||
@@ -339,23 +354,56 @@ class TextBoxView {
|
||||
const a = this.attrs();
|
||||
this.rotor.style.width = a.width ? `${a.width}px` : `${DEFAULT_WIDTH_PX}px`;
|
||||
this.rotor.style.minHeight = a.height ? `${a.height}px` : '';
|
||||
// A polygon shape paints its own fill and stroke, so the box behind it stays bare.
|
||||
// A polygon shape paints its own fill and stroke, so the box behind it stays bare;
|
||||
// a line has no box at all, only the two endpoints it is drawn between.
|
||||
const poly = !!SHAPES[a.shapeKind]?.points;
|
||||
const line = isLineKind(a.shapeKind);
|
||||
// The outline covers the padding box, so the frame's own ring moves to the text
|
||||
// where a polygon draws it — applyShapeInset adds it back in.
|
||||
this.rotor.style.padding = poly ? '0' : `${paddingPx(a.paddingCm).toFixed(2)}px`;
|
||||
this.rotor.style.background = !poly && a.fillColor ? a.fillColor : 'transparent';
|
||||
this.rotor.style.border = !poly && a.strokeColor
|
||||
this.rotor.style.padding = poly || line ? '0' : `${paddingPx(a.paddingCm).toFixed(2)}px`;
|
||||
this.rotor.style.background = !poly && !line && a.fillColor ? a.fillColor : 'transparent';
|
||||
this.rotor.style.border = !poly && !line && a.strokeColor
|
||||
? `${a.strokeWidthPt * PX_PER_PT}px solid ${a.strokeColor}`
|
||||
: 'none';
|
||||
this.rotor.style.borderRadius = shapeRadius(a.shapeKind);
|
||||
this.rotor.style.transform = `translate(-50%, -50%) rotate(${a.rotation}deg)`;
|
||||
// A line holds no text: the paragraph the schema requires stays in the document
|
||||
// (and in both exports' anchor), it just takes no room.
|
||||
this.contentDOM.style.display = line ? 'none' : '';
|
||||
this.applyOutline();
|
||||
this.applyLine();
|
||||
this.applyWrap();
|
||||
this.applyShapeInset();
|
||||
this.fitWrapper();
|
||||
}
|
||||
|
||||
// A line is drawn in real pixels, not the 0…100 box a polygon is stretched into: an
|
||||
// arrow head has to keep its shape however flat the frame is drawn.
|
||||
private applyLine(): void {
|
||||
const a = this.attrs();
|
||||
const w = a.width ?? DEFAULT_WIDTH_PX;
|
||||
const h = a.height ?? DEFAULT_LINE_HEIGHT_PX;
|
||||
const stroke = a.strokeWidthPt * PX_PER_PT;
|
||||
const paths = linePaths(a.shapeKind, w, h, a.flipV, arrowHeadPx(a.strokeWidthPt));
|
||||
if (!paths) {
|
||||
this.lineSvg?.remove();
|
||||
this.lineSvg = null;
|
||||
return;
|
||||
}
|
||||
if (!this.lineSvg) {
|
||||
this.lineSvg = document.createElementNS(SVG_NS, 'svg');
|
||||
this.lineSvg.setAttribute('class', 'textbox-line');
|
||||
this.rotor.insertBefore(this.lineSvg, this.rotor.firstChild);
|
||||
}
|
||||
const color = a.strokeColor ?? '#000000';
|
||||
this.lineSvg.setAttribute('viewBox', `0 0 ${w} ${h}`);
|
||||
this.lineSvg.setAttribute('width', `${w}`);
|
||||
this.lineSvg.setAttribute('height', `${h}`);
|
||||
this.lineSvg.innerHTML =
|
||||
`<path d="${paths.line}" fill="none" stroke="${color}" stroke-width="${stroke}"/>` +
|
||||
paths.heads.map((d) => `<path d="${d}" fill="${color}"/>`).join('');
|
||||
}
|
||||
|
||||
// The outline of a shape CSS can't draw, behind the text. preserveAspectRatio="none"
|
||||
// stretches the 0…100 box to the frame, and non-scaling-stroke keeps the line even
|
||||
// width under that distortion.
|
||||
|
||||
+16
-4
@@ -650,6 +650,7 @@ type TextBoxDocx = {
|
||||
offsetYCm: number | null;
|
||||
distCm: number | null;
|
||||
shapeKind: ShapeKind;
|
||||
flipV: boolean;
|
||||
fill: string | null;
|
||||
stroke: string | null;
|
||||
strokeWidthPt: number;
|
||||
@@ -668,6 +669,7 @@ function textBoxDocxDescriptor(node: TiptapNode): TextBoxDocx {
|
||||
offsetYCm: typeof a.wrapOffsetY === 'number' ? a.wrapOffsetY : null,
|
||||
distCm: typeof a.wrapDist === 'number' ? a.wrapDist : null,
|
||||
shapeKind: isShapeKind(a.shapeKind) ? a.shapeKind : 'textbox',
|
||||
flipV: a.flipV === true,
|
||||
fill: typeof a.fillColor === 'string' && a.fillColor ? a.fillColor : null,
|
||||
stroke: typeof a.strokeColor === 'string' && a.strokeColor ? a.strokeColor : null,
|
||||
strokeWidthPt: typeof a.strokeWidthPt === 'number' && a.strokeWidthPt > 0 ? a.strokeWidthPt : 1,
|
||||
@@ -872,18 +874,28 @@ function textBoxDrawingXml(box: TextBoxDocx, index: number, parts: TxbxParts): s
|
||||
const fill = box.fill
|
||||
? `<a:solidFill><a:srgbClr val="${hexColor(box.fill) ?? 'FFFFFF'}"/></a:solidFill>`
|
||||
: '<a:noFill/>';
|
||||
// A line is only its stroke, and its heads ride the same <a:ln>.
|
||||
const line = SHAPES[box.shapeKind].line;
|
||||
const ends = line === 'end' ? '<a:tailEnd type="triangle"/>'
|
||||
: line === 'both' ? '<a:headEnd type="triangle"/><a:tailEnd type="triangle"/>' : '';
|
||||
const ln = box.stroke
|
||||
? `<a:ln w="${Math.round(box.strokeWidthPt * EMU_PER_PT)}"><a:solidFill><a:srgbClr val="${hexColor(box.stroke) ?? '000000'}"/></a:solidFill></a:ln>`
|
||||
? `<a:ln w="${Math.round(box.strokeWidthPt * EMU_PER_PT)}"><a:solidFill><a:srgbClr val="${hexColor(box.stroke) ?? '000000'}"/></a:solidFill>${ends}</a:ln>`
|
||||
: '<a:ln><a:noFill/></a:ln>';
|
||||
const inset = Math.round(TEXTBOX_PADDING_CM * EMU_PER_CM);
|
||||
// Auto-grow only for plain text boxes, matching the ODT export.
|
||||
const autofit = box.shapeKind === 'textbox' ? '<a:spAutoFit/>' : '';
|
||||
// Word draws the `line` preset down the frame's diagonal and flips it to reach the
|
||||
// other one; a line carries no fill and no text body.
|
||||
const flip = line && box.flipV ? ' flipV="1"' : '';
|
||||
const body = line
|
||||
? ''
|
||||
: `<wps:txbx><w:txbxContent>${txbxContentXml(box.content, parts)}</w:txbxContent></wps:txbx>`;
|
||||
const wsp =
|
||||
`<wps:wsp xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">` +
|
||||
`<wps:cNvSpPr txBox="1"/>` +
|
||||
`<wps:spPr><a:xfrm${rot}><a:off x="0" y="0"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm>` +
|
||||
`<a:prstGeom prst="${SHAPES[box.shapeKind].prst}"><a:avLst/></a:prstGeom>${fill}${ln}</wps:spPr>` +
|
||||
`<wps:txbx><w:txbxContent>${txbxContentXml(box.content, parts)}</w:txbxContent></wps:txbx>` +
|
||||
`<wps:spPr><a:xfrm${rot}${flip}><a:off x="0" y="0"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm>` +
|
||||
`<a:prstGeom prst="${SHAPES[box.shapeKind].prst}"><a:avLst/></a:prstGeom>${line ? '<a:noFill/>' : fill}${ln}</wps:spPr>` +
|
||||
body +
|
||||
`<wps:bodyPr rot="0" vert="horz" wrap="square" lIns="${inset}" tIns="${inset}" rIns="${inset}" bIns="${inset}" anchor="t">${autofit}</wps:bodyPr>` +
|
||||
`</wps:wsp>`;
|
||||
const graphic =
|
||||
|
||||
+34
-2
@@ -24,7 +24,7 @@ import { BORDER_SIDES, parseBorderAttr } from '../editor/extensions/tableCellBor
|
||||
import { parseCellPadding, DEFAULT_CELL_PADDING, type CellPadding } from '../editor/extensions/tableCellPadding';
|
||||
import { TEXTBOX_PADDING_CM } from '../editor/extensions/textBox';
|
||||
import { numberLocale, parseCellNumber, toWriterFormula, type CellRef, type NumberLocale } from '../utils/tableFormula';
|
||||
import { isShapeKind, odfEnhancedGeometry, type ShapeKind } from '../utils/shapes';
|
||||
import { SHAPES, arrowHeadCm, isShapeKind, isLineKind, odfEnhancedGeometry, type ShapeKind } from '../utils/shapes';
|
||||
import { normalizeLeader, parseTabStops } from '../editor/extensions/tabStops';
|
||||
import { charStyleProps, listMarkerFormat, type MarkerFormat } from '../editor/extensions/listMarker';
|
||||
import { orderedTypeDef, effectiveOrderedDef, effectiveOrderedDefAt, childCycle, formatOrdinal, ROOT_ORDERED_CYCLE, type OrderedCycle } from '../utils/orderedListTypes';
|
||||
@@ -886,6 +886,7 @@ type TextBoxExport = {
|
||||
wrapAlign: string | null;
|
||||
paddingCm: number;
|
||||
shapeKind: ShapeKind;
|
||||
flipV: boolean;
|
||||
fill: string | null;
|
||||
stroke: string | null;
|
||||
strokeWidthPt: number;
|
||||
@@ -910,6 +911,7 @@ function textBoxDescriptor(node: TiptapNode): TextBoxExport {
|
||||
wrapAlign: a.wrapAlign === 'center' || a.wrapAlign === 'right' ? a.wrapAlign : null,
|
||||
paddingCm: typeof a.paddingCm === 'number' ? round3(a.paddingCm) : TEXTBOX_PADDING_CM,
|
||||
shapeKind: isShapeKind(a.shapeKind) ? a.shapeKind : 'textbox',
|
||||
flipV: a.flipV === true,
|
||||
fill: typeof a.fillColor === 'string' && a.fillColor ? a.fillColor : null,
|
||||
stroke: typeof a.strokeColor === 'string' && a.strokeColor ? a.strokeColor : null,
|
||||
strokeWidthPt: typeof a.strokeWidthPt === 'number' && a.strokeWidthPt > 0 ? a.strokeWidthPt : 1,
|
||||
@@ -3747,9 +3749,15 @@ function textBoxGraphicStyle(box: TextBoxExport, index: number): string {
|
||||
const grow = box.shapeKind === 'textbox'
|
||||
? ' draw:auto-grow-height="true"'
|
||||
: ' draw:auto-grow-height="false" draw:auto-grow-width="false"';
|
||||
// An arrow head is a named marker in ODF, defined once in styles.xml.
|
||||
const heads = SHAPES[box.shapeKind].line;
|
||||
const marker = (side: 'start' | 'end') =>
|
||||
` draw:marker-${side}="${ODF_ARROW}" draw:marker-${side}-width="${arrowHeadCm(box.strokeWidthPt)}cm"`;
|
||||
const arrows = heads === 'end' ? marker('end')
|
||||
: heads === 'both' ? marker('end') + marker('start') : '';
|
||||
return (
|
||||
`<style:style style:name="TbxFr${index + 1}" style:family="graphic">` +
|
||||
`<style:graphic-properties ${fill} ${stroke} fo:padding="${box.paddingCm}cm"` +
|
||||
`<style:graphic-properties ${fill} ${stroke}${arrows} fo:padding="${box.paddingCm}cm"` +
|
||||
`${grow} draw:textarea-vertical-align="top"${wrap}/>` +
|
||||
`</style:style>`
|
||||
);
|
||||
@@ -3779,6 +3787,16 @@ function textBoxXml(box: TextBoxExport, inner: string, index: number): string {
|
||||
const common =
|
||||
` draw:style-name="TbxFr${n}" text:anchor-type="${anchor}" draw:z-index="${index}"` +
|
||||
` svg:width="${box.widthCm}cm"${at}`;
|
||||
// A line is its two endpoints, so ODF gives it its own element rather than a frame
|
||||
// with a width and a height. The blocks the schema keeps on the node are dropped:
|
||||
// <draw:line> holds no text, and the editor draws none.
|
||||
if (isLineKind(box.shapeKind)) {
|
||||
const [y1, y2] = box.flipV ? [box.heightCm, 0] : [0, box.heightCm];
|
||||
return (
|
||||
`<draw:line draw:name="Line${n}"${common.replace(/ svg:width="[^"]*"/, '')}` +
|
||||
` svg:x1="0cm" svg:y1="${y1}cm" svg:x2="${box.widthCm}cm" svg:y2="${y2}cm"/>`
|
||||
);
|
||||
}
|
||||
if (box.shapeKind === 'textbox') {
|
||||
// svg:height for consumers without auto-grow; fo:min-height is the real semantic
|
||||
// (height = minimum, content grows the box) and wins on our own re-import.
|
||||
@@ -3793,6 +3811,11 @@ function textBoxXml(box: TextBoxExport, inner: string, index: number): string {
|
||||
);
|
||||
}
|
||||
|
||||
// LibreOffice's own standard arrow head, name and path alike, so a file we write and
|
||||
// one it writes carry the same marker rather than two that look the same.
|
||||
const ODF_ARROW = 'Arrow';
|
||||
const ODF_ARROW_MARKER = `<draw:marker draw:name="${ODF_ARROW}" svg:viewBox="0 0 20 30" svg:d="m10 0-10 30h20z"/>`;
|
||||
|
||||
// Resolve the text-box marker paragraphs: wrap each S{i}…E{i} region (the box's
|
||||
// hoisted, fully serialized blocks) into its drawing element inside a fresh anchor
|
||||
// paragraph, and inject the minted graphic styles.
|
||||
@@ -3818,6 +3841,15 @@ function applyTextBoxes(odtBytes: Uint8Array, boxes: TextBoxExport[]): Uint8Arra
|
||||
boxes.map((b, i) => textBoxGraphicStyle(b, i) + textBoxAnchorStyle(b, i)).join(''),
|
||||
);
|
||||
files['content.xml'] = strToU8(content);
|
||||
// An arrow head is referenced by name, so its one definition goes where LibreOffice
|
||||
// keeps its own — office:styles in styles.xml — and only when a line asks for it.
|
||||
const stylesBytes = files['styles.xml'];
|
||||
if (stylesBytes && boxes.some((b) => SHAPES[b.shapeKind].line && SHAPES[b.shapeKind].line !== 'none')) {
|
||||
const styles = ensureDrawNamespaces(strFromU8(stylesBytes));
|
||||
if (!styles.includes(`draw:name="${ODF_ARROW}"`)) {
|
||||
files['styles.xml'] = strToU8(styles.replace(/<office:styles(\s[^>]*)?>/, (m) => `${m}${ODF_ARROW_MARKER}`));
|
||||
}
|
||||
}
|
||||
return rezipOdt(files);
|
||||
}
|
||||
|
||||
|
||||
@@ -298,6 +298,9 @@ const de: Messages = {
|
||||
leftArrow: 'Pfeil nach links',
|
||||
upArrow: 'Pfeil nach oben',
|
||||
downArrow: 'Pfeil nach unten',
|
||||
line: 'Linie',
|
||||
lineArrow: 'Pfeil',
|
||||
lineDoubleArrow: 'Doppelpfeil',
|
||||
},
|
||||
fillColor: 'Füllfarbe',
|
||||
chooseFillColor: 'Füllfarbe wählen',
|
||||
|
||||
@@ -302,6 +302,9 @@ const en = {
|
||||
leftArrow: 'Left arrow',
|
||||
upArrow: 'Up arrow',
|
||||
downArrow: 'Down arrow',
|
||||
line: 'Line',
|
||||
lineArrow: 'Arrow',
|
||||
lineDoubleArrow: 'Double arrow',
|
||||
},
|
||||
fillColor: 'Fill color',
|
||||
chooseFillColor: 'Choose fill color',
|
||||
|
||||
@@ -11,7 +11,7 @@ import { tableLookAttr } from '../styles/tableStyles';
|
||||
import { formatOrdinal, orderedTypeFromFormat, orderedTypeAttrAt, childCycle, ROOT_ORDERED_CYCLE, type OrderedCycle } from '../utils/orderedListTypes';
|
||||
import { bulletCharAttr, bulletCharFromDocx } from '../utils/bulletListTypes';
|
||||
import { DATE_FORMATS, TIME_FORMATS, docxPicture, toDateValue } from '../utils/dateTime';
|
||||
import { shapeFromPrst } from '../utils/shapes';
|
||||
import { shapeFromPrst, isLineKind, lineKindFor } from '../utils/shapes';
|
||||
import { imageDataUrl, placeholderImage, type ConvertedImages } from './imageFormats';
|
||||
import { PX_PER_CM, cmToPx, type PageMargins } from '../storage/pageMargins';
|
||||
import type { Orientation } from '../storage/pageOrientation';
|
||||
@@ -1863,6 +1863,13 @@ function convertWpsShape(wsp: Element, root: Element, isAnchor: boolean, ctx: Ct
|
||||
const stroke = ln && !nsChild(ln, A, 'noFill') ? hexColor(lnClr ?? '000000') ?? '#000000' : null;
|
||||
const lnW = intAttr(ln, '', 'w');
|
||||
setShapeStyleAttrs(attrs, fill, stroke, lnW != null ? lnW / 12700 : null);
|
||||
// A line's heads live on its <a:ln>, and they are what tells the three kinds apart;
|
||||
// Word reaches the frame's other diagonal by flipping it.
|
||||
if (isLineKind(kind)) {
|
||||
const head = (name: string) => (nsChild(ln, A, name)?.getAttribute('type') ?? 'none') !== 'none';
|
||||
attrs.shapeKind = lineKindFor(head('headEnd'), head('tailEnd'));
|
||||
if (nsChild(spPr, A, 'xfrm')?.getAttribute('flipV') === '1') attrs.flipV = true;
|
||||
}
|
||||
|
||||
const txbxContent = nsChild(nsChild(wsp, WPS, 'txbx'), W, 'txbxContent');
|
||||
const blocks = txbxContent ? convertBlocks(Array.from(txbxContent.children), ctx, 'cell') : [];
|
||||
|
||||
+25
-1
@@ -11,7 +11,7 @@ import { TABLE_REGIONS, tableLookAttr, type TableLook, type TableRegion } from '
|
||||
import { orderedTypeFromFormat, orderedTypeAttrAt, childCycle, ROOT_ORDERED_CYCLE, type OrderedCycle } from '../utils/orderedListTypes';
|
||||
import { bulletCharAttr, bulletCharFromOdf } from '../utils/bulletListTypes';
|
||||
import { matchFormat, toDateValue, type Token } from '../utils/dateTime';
|
||||
import { shapeFromOdfType, type ShapeKind } from '../utils/shapes';
|
||||
import { shapeFromOdfType, lineKindFor, type ShapeKind } from '../utils/shapes';
|
||||
import { imageDataUrl, placeholderImage, type ConvertedImages } from './imageFormats';
|
||||
import { astToLatex } from '../math/latex';
|
||||
import { parseMathml } from '../math/mathml';
|
||||
@@ -514,6 +514,26 @@ function convertShape(el: Element, ctx: Ctx): Node | null {
|
||||
return { type: 'textBox', attrs, content: textBoxContent(Array.from(el.children), ctx) };
|
||||
}
|
||||
|
||||
// draw:line → a textBox of the matching line kind: the two endpoints become the frame
|
||||
// they span, and which diagonal they run along. Which heads the graphic style declares
|
||||
// is what decides plain line / arrow / double arrow.
|
||||
function convertLine(el: Element, ctx: Ctx): Node | null {
|
||||
const at = (name: string) => lengthToCm(el.getAttributeNS(NS.svg, name)) ?? 0;
|
||||
const [x1, y1, x2, y2] = [at('x1'), at('y1'), at('x2'), at('y2')];
|
||||
const gp = ctx.resolver.graphicProps(el.getAttributeNS(NS.draw, 'style-name'));
|
||||
const kind = lineKindFor(!!gp['draw:marker-start'], !!gp['draw:marker-end']);
|
||||
const attrs: Record<string, unknown> = {
|
||||
shapeKind: kind,
|
||||
width: framePx(cmToPx(Math.abs(x2 - x1))),
|
||||
height: framePx(cmToPx(Math.abs(y2 - y1))),
|
||||
};
|
||||
// The editor draws a line across its frame, so only the direction is left to keep.
|
||||
if ((y2 - y1) * (x2 - x1) < 0) attrs.flipV = true;
|
||||
applyFrameRotationAndWrap(el, attrs, gp);
|
||||
shapeStyleAttrs(gp, attrs, true);
|
||||
return { type: 'textBox', attrs, content: [{ type: 'paragraph' }] };
|
||||
}
|
||||
|
||||
// Dispatch any draw:* element: an image stays inline; a text box / shape is a block
|
||||
// node routed through ctx.pendingBlocks; everything else is dropped with a warning.
|
||||
function convertDrawElement(e: Element, ctx: Ctx): { inline?: Node; block?: Node } | null {
|
||||
@@ -537,6 +557,10 @@ function convertDrawElement(e: Element, ctx: Ctx): { inline?: Node; block?: Node
|
||||
if (!hasImage) ctx.warnings.add('Drawings were removed');
|
||||
return null;
|
||||
}
|
||||
if (e.localName === 'line') {
|
||||
const line = convertLine(e, ctx);
|
||||
return line ? { block: line } : null;
|
||||
}
|
||||
if (e.localName === 'rect' || e.localName === 'ellipse' || e.localName === 'custom-shape') {
|
||||
const shape = convertShape(e, ctx);
|
||||
return shape ? { block: shape } : null;
|
||||
|
||||
+80
-3
@@ -7,7 +7,11 @@ export type ShapeKind =
|
||||
| 'textbox' | 'roundRect' | 'ellipse'
|
||||
| 'triangle' | 'rightTriangle' | 'diamond' | 'pentagon' | 'hexagon' | 'star5'
|
||||
| 'trapezoid' | 'parallelogram'
|
||||
| 'rightArrow' | 'leftArrow' | 'upArrow' | 'downArrow';
|
||||
| 'rightArrow' | 'leftArrow' | 'upArrow' | 'downArrow'
|
||||
| 'line' | 'lineArrow' | 'lineDoubleArrow';
|
||||
|
||||
/** Which ends of a line carry an arrow head. */
|
||||
export type LineHeads = 'none' | 'end' | 'both';
|
||||
|
||||
type Point = readonly [number, number];
|
||||
|
||||
@@ -20,6 +24,11 @@ export type ShapePreset = {
|
||||
points?: readonly Point[];
|
||||
/** Where text goes inside the outline: x0 y0 x1 y1, same 0…100 box. */
|
||||
textArea?: readonly [number, number, number, number];
|
||||
/**
|
||||
* Two endpoints rather than a box, so it holds no text and is stroked, not filled.
|
||||
* The value is which ends carry an arrow head.
|
||||
*/
|
||||
line?: LineHeads;
|
||||
};
|
||||
|
||||
// A regular n-gon's corners on the circle around the box, first one straight up.
|
||||
@@ -107,8 +116,41 @@ export const SHAPES: Record<ShapeKind, ShapePreset> = {
|
||||
points: [[25, 0], [25, 50], [0, 50], [50, 100], [100, 50], [75, 50], [75, 0]],
|
||||
textArea: [30, 5, 70, 50],
|
||||
},
|
||||
// ODF gives a line its own element (draw:line, two endpoints), where Word draws
|
||||
// the `line` preset across the frame and flips it to reach the other diagonal.
|
||||
line: { odf: 'line', prst: 'line', line: 'none' },
|
||||
lineArrow: { odf: 'line', prst: 'straightConnector1', line: 'end' },
|
||||
lineDoubleArrow: { odf: 'line', prst: 'straightConnector1', line: 'both' },
|
||||
};
|
||||
|
||||
export function isLineKind(kind: ShapeKind): boolean {
|
||||
return !!SHAPES[kind].line;
|
||||
}
|
||||
|
||||
/**
|
||||
* How long an arrow head is, in px, for a pen of `strokeWidthPt`. Word scales the head
|
||||
* with the line; the floor keeps a hairline's head visible, near the fixed 0.3 cm
|
||||
* LibreOffice's own dialog offers.
|
||||
*/
|
||||
export function arrowHeadPx(strokeWidthPt: number): number {
|
||||
return Math.max(8, strokeWidthPt * (96 / 72) * 5);
|
||||
}
|
||||
|
||||
/** The same head as an ODF `draw:marker-*-width`, which is measured across it. */
|
||||
export function arrowHeadCm(strokeWidthPt: number): number {
|
||||
return Math.round((arrowHeadPx(strokeWidthPt) * 0.7 * 2.54) / 96 * 1000) / 1000;
|
||||
}
|
||||
|
||||
/** The line kinds, in the order the shape picker offers them. */
|
||||
export const LINE_KINDS = (Object.keys(SHAPES) as ShapeKind[]).filter(isLineKind);
|
||||
|
||||
// A line's heads decide which kind it is, so a file's own arrow settings land on the
|
||||
// right one whatever preset it used.
|
||||
export function lineKindFor(start: boolean, end: boolean): ShapeKind {
|
||||
if (start && end) return 'lineDoubleArrow';
|
||||
return start || end ? 'lineArrow' : 'line';
|
||||
}
|
||||
|
||||
/** The kinds drawn as a polygon — everything past the three CSS ones. */
|
||||
export const POLYGON_KINDS = (Object.keys(SHAPES) as ShapeKind[]).filter((k) => SHAPES[k].points);
|
||||
|
||||
@@ -118,6 +160,38 @@ export function isShapeKind(v: unknown): v is ShapeKind {
|
||||
|
||||
const r2 = (n: number) => Math.round(n * 100) / 100;
|
||||
|
||||
// An arrow head as a filled triangle: the tip at (x,y), pointing along the unit
|
||||
// vector (dx,dy). 0.35 of the length to each side is the proportion both word
|
||||
// processors draw a plain arrow at.
|
||||
function headPath(x: number, y: number, dx: number, dy: number, len: number): string {
|
||||
const bx = x - dx * len;
|
||||
const by = y - dy * len;
|
||||
const px = -dy * len * 0.35;
|
||||
const py = dx * len * 0.35;
|
||||
return `M ${r2(x)},${r2(y)} L ${r2(bx + px)},${r2(by + py)} L ${r2(bx - px)},${r2(by - py)} Z`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A line kind drawn across a `w`×`h` box: the stroked segment and its filled heads,
|
||||
* in real pixels rather than the distorted 0…100 box a polygon uses — an arrow head
|
||||
* has to stay proportional to the pen however flat the frame is.
|
||||
*/
|
||||
export function linePaths(kind: ShapeKind, w: number, h: number, flip: boolean, headLen: number): { line: string; heads: string[] } | null {
|
||||
const heads = SHAPES[kind].line;
|
||||
if (!heads) return null;
|
||||
const [x1, y1, x2, y2] = flip ? [0, h, w, 0] : [0, 0, w, h];
|
||||
const len = Math.hypot(x2 - x1, y2 - y1) || 1;
|
||||
const dx = (x2 - x1) / len;
|
||||
const dy = (y2 - y1) / len;
|
||||
const cap = Math.min(headLen, len / 2);
|
||||
return {
|
||||
line: `M ${r2(x1)},${r2(y1)} L ${r2(x2)},${r2(y2)}`,
|
||||
heads: heads === 'none' ? []
|
||||
: heads === 'end' ? [headPath(x2, y2, dx, dy, cap)]
|
||||
: [headPath(x2, y2, dx, dy, cap), headPath(x1, y1, -dx, -dy, cap)],
|
||||
};
|
||||
}
|
||||
|
||||
/** The outline as an SVG `d`, in the 0…100 box the node view's viewBox uses. */
|
||||
export function shapePath(kind: ShapeKind): string | null {
|
||||
const pts = SHAPES[kind].points;
|
||||
@@ -154,8 +228,11 @@ export function odfEnhancedGeometry(kind: ShapeKind): string | null {
|
||||
return body === null ? null : `<draw:enhanced-geometry svg:viewBox="0 0 ${VB} ${VB}"${body}/>`;
|
||||
}
|
||||
|
||||
const BY_ODF = new Map((Object.keys(SHAPES) as ShapeKind[]).map((k) => [SHAPES[k].odf, k]));
|
||||
const BY_PRST = new Map((Object.keys(SHAPES) as ShapeKind[]).map((k) => [SHAPES[k].prst, k]));
|
||||
// The three line kinds share their names, and the heads a file declares are what
|
||||
// tells them apart (lineKindFor), so only the bare one is reachable by name.
|
||||
const NAMED = (Object.keys(SHAPES) as ShapeKind[]).filter((k) => SHAPES[k].line !== 'end' && SHAPES[k].line !== 'both');
|
||||
const BY_ODF = new Map(NAMED.map((k) => [SHAPES[k].odf, k]));
|
||||
const BY_PRST = new Map([...NAMED.map((k) => [SHAPES[k].prst, k] as const), ['straightConnector1', 'line' as ShapeKind]]);
|
||||
|
||||
// null = a preset we don't draw, which the importers report rather than flatten to a
|
||||
// rectangle. LibreOffice writes `circle` for an ellipse constrained to one.
|
||||
|
||||
@@ -478,6 +478,14 @@
|
||||
overflow: visible;
|
||||
pointer-events: none;
|
||||
}
|
||||
/* A line is drawn in the frame's own pixels, so the SVG carries no stretching; it
|
||||
still overflows, since half the stroke sits outside a frame of no height. */
|
||||
.paper .tiptap .textbox-line {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
overflow: visible;
|
||||
pointer-events: none;
|
||||
}
|
||||
.paper .tiptap .textbox-content {
|
||||
cursor: text;
|
||||
min-height: 1em;
|
||||
|
||||
+45
-3
@@ -1303,9 +1303,9 @@ describe('Leg 7: foreign shapes/text boxes → importOdt', () => {
|
||||
const f = importOdt(foreign);
|
||||
const c = f.content.content!;
|
||||
const boxes = c.filter((n: N) => n.type === 'textBox');
|
||||
check('4 supported shapes imported', boxes.length === 4, c.map((n: N) => n.type));
|
||||
check('5 supported shapes imported', boxes.length === 5, c.map((n: N) => n.type));
|
||||
|
||||
const [floatBox, rect, ellipse, star] = boxes;
|
||||
const [floatBox, rect, ellipse, star, line] = boxes;
|
||||
check('frame: free x/y collapses to wrap side (right)', floatBox?.attrs?.wrap === 'right', floatBox?.attrs);
|
||||
check('frame: 2in → 192px, min-height 1in → 96px', floatBox?.attrs?.width === 192 && floatBox?.attrs?.height === 96, floatBox?.attrs);
|
||||
check('frame: fill + stroke from graphic style', floatBox?.attrs?.fillColor === '#CCFFCC' && floatBox?.attrs?.strokeColor === '#003300', floatBox?.attrs);
|
||||
@@ -1317,7 +1317,9 @@ describe('Leg 7: foreign shapes/text boxes → importOdt', () => {
|
||||
check('custom-shape ellipse: shapeKind + geometry', ellipse?.attrs?.shapeKind === 'ellipse' && ellipse?.attrs?.width === 192 && ellipse?.attrs?.height === 96, ellipse?.attrs);
|
||||
check('star5: preset kept', star?.attrs?.shapeKind === 'star5', star?.attrs);
|
||||
check('a preset we can\'t draw is dropped with a warning', f.warnings.includes('Unsupported shapes were removed'), f.warnings);
|
||||
check('draw:line dropped with warning', f.warnings.includes('Drawings were removed'), f.warnings);
|
||||
// A 5cm horizontal draw:line: two endpoints, so it arrives as a flat frame.
|
||||
check('draw:line: a plain line, no heads declared', line?.attrs?.shapeKind === 'line', line?.attrs);
|
||||
check('draw:line: 5cm wide and flat', line?.attrs?.width === 189 && line?.attrs?.height === 0, line?.attrs);
|
||||
|
||||
const table = c.find((n: N) => n.type === 'table');
|
||||
const cellBlocks = table?.content?.[0]?.content?.[0]?.content ?? [];
|
||||
@@ -2413,6 +2415,46 @@ describe('Leg 27: per-section page size and orientation (ODT + DOCX)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Leg 29: lines and arrows (ODT + DOCX)', () => {
|
||||
const line = (kind: string, flipV = false): N => ({
|
||||
type: 'textBox',
|
||||
// strokeColor as the schema defaults it: a line with no pen is invisible, and
|
||||
// both exports then write it as one.
|
||||
attrs: { width: 200, height: 60, shapeKind: kind, strokeColor: '#000000', ...(flipV ? { flipV: true } : {}) },
|
||||
content: [P(null)],
|
||||
});
|
||||
const doc: N = { type: 'doc', content: [P(null, T('above')), line('lineArrow', true), P(null, T('below'))] };
|
||||
const boxOf = (res: N): N => (res.content.content ?? []).find((n: N) => n.type === 'textBox');
|
||||
|
||||
it('ODT: a line is two endpoints, not a frame', async () => {
|
||||
const bytes = await buildOdt(doc, margins);
|
||||
const xml = strFromU8(unzipSync(bytes)['content.xml']);
|
||||
const el = /<draw:line\b[^>]*\/>/.exec(xml)?.[0] ?? '';
|
||||
check('the flipped line runs bottom-left to top-right', /svg:y1="[^0][^"]*cm" svg:x2="[^"]*" svg:y2="0cm"/.test(el), el);
|
||||
const style = /<style:style style:name="TbxFr1"[\s\S]*?\/><\/style:style>/.exec(xml)?.[0] ?? '';
|
||||
check('and carries the arrow head at its end', /draw:marker-end="Arrow"/.test(style), style);
|
||||
check('but not at its start', !/draw:marker-start=/.test(style), style);
|
||||
check('the marker itself is defined once', /<draw:marker draw:name="Arrow"/.test(strFromU8(unzipSync(bytes)['styles.xml'])), 'styles.xml');
|
||||
|
||||
const res = importOdt(bytes);
|
||||
check('no warnings — the line is not dropped', res.warnings.length === 0, res.warnings);
|
||||
check('it comes back as an arrow', boxOf(res)?.attrs?.shapeKind === 'lineArrow', boxOf(res)?.attrs);
|
||||
check('on the same diagonal', boxOf(res)?.attrs?.flipV === true, boxOf(res)?.attrs);
|
||||
});
|
||||
|
||||
it('DOCX: a line is the preset Word flips across the frame', async () => {
|
||||
const bytes = await buildDocx(doc, margins);
|
||||
const xml = strFromU8(unzipSync(bytes)['word/document.xml']);
|
||||
check('the frame is flipped, not the geometry', /<a:xfrm flipV="1">/.test(xml), xml.slice(xml.indexOf('<a:xfrm'), xml.indexOf('<a:xfrm') + 80));
|
||||
check('one head, at the tail', /<a:tailEnd type="triangle"\/>/.test(xml) && !/<a:headEnd/.test(xml), 'a:ln');
|
||||
check('and no text body on it', !/<wps:txbx>/.test(xml), 'wps:txbx');
|
||||
|
||||
const res = importDocx(bytes);
|
||||
check('it comes back as an arrow', boxOf(res)?.attrs?.shapeKind === 'lineArrow', boxOf(res)?.attrs);
|
||||
check('on the same diagonal', boxOf(res)?.attrs?.flipV === true, boxOf(res)?.attrs);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Leg 28: a cell formula (ODT + DOCX)', () => {
|
||||
// A1..A3 hold the numbers, A4 sums them the way Word names the range.
|
||||
const num = (text: string): N => ({ type: 'tableCell', attrs: { colspan: 1, rowspan: 1, colwidth: [100] }, content: [P(null, T(text))] });
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// The line kinds: geometry across the frame, and which kind a file's arrow heads make.
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { linePaths, lineKindFor, isLineKind, arrowHeadPx, arrowHeadCm, LINE_KINDS, shapeFromPrst, shapeFromOdfType } from '../../src/lib/utils/shapes';
|
||||
|
||||
describe('line shapes', () => {
|
||||
it('runs across the frame, and flips to the other diagonal', () => {
|
||||
expect(linePaths('line', 200, 60, false, 10)?.line).toBe('M 0,0 L 200,60');
|
||||
expect(linePaths('line', 200, 60, true, 10)?.line).toBe('M 0,60 L 200,0');
|
||||
expect(linePaths('textbox', 200, 60, false, 10)).toBeNull();
|
||||
});
|
||||
|
||||
it('gives a head to the ends the kind names', () => {
|
||||
expect(linePaths('line', 100, 0, false, 10)?.heads).toHaveLength(0);
|
||||
expect(linePaths('lineArrow', 100, 0, false, 10)?.heads).toHaveLength(1);
|
||||
expect(linePaths('lineDoubleArrow', 100, 0, false, 10)?.heads).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('keeps the head inside a line shorter than it', () => {
|
||||
const short = linePaths('lineArrow', 10, 0, false, 40)?.heads[0] ?? '';
|
||||
// Capped at half the line, so the head never reaches past the far end.
|
||||
expect(short).toContain('M 10,0');
|
||||
expect(short).toContain('5,');
|
||||
});
|
||||
|
||||
it('reads a file\'s heads back as the kind they make', () => {
|
||||
expect(lineKindFor(false, false)).toBe('line');
|
||||
expect(lineKindFor(false, true)).toBe('lineArrow');
|
||||
expect(lineKindFor(true, false)).toBe('lineArrow');
|
||||
expect(lineKindFor(true, true)).toBe('lineDoubleArrow');
|
||||
expect(LINE_KINDS.every(isLineKind)).toBe(true);
|
||||
});
|
||||
|
||||
it('resolves both formats\' names to the bare line, the heads deciding the rest', () => {
|
||||
expect(shapeFromPrst('line')).toBe('line');
|
||||
expect(shapeFromPrst('straightConnector1')).toBe('line');
|
||||
expect(shapeFromOdfType('line')).toBe('line');
|
||||
});
|
||||
|
||||
it('scales the head with the pen, with a floor', () => {
|
||||
expect(arrowHeadPx(0.25)).toBe(8);
|
||||
expect(arrowHeadPx(3)).toBeCloseTo(20, 5);
|
||||
expect(arrowHeadCm(3)).toBeCloseTo(0.37, 2);
|
||||
});
|
||||
});
|
||||
@@ -1,20 +1,24 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
SHAPES, POLYGON_KINDS, shapePath, odfEnhancedGeometry, shapeFromOdfType, shapeFromPrst,
|
||||
SHAPES, POLYGON_KINDS, shapePath, odfEnhancedGeometry, shapeFromOdfType, shapeFromPrst, isLineKind,
|
||||
type ShapeKind,
|
||||
} from '../../src/lib/utils/shapes';
|
||||
|
||||
describe('shape presets', () => {
|
||||
it('names every kind once per format', () => {
|
||||
const kinds = Object.keys(SHAPES) as ShapeKind[];
|
||||
// The three line kinds share their names on purpose — the arrow heads a file
|
||||
// declares are what tells them apart (lineKindFor) — so the box shapes are the
|
||||
// ones a name has to identify on its own.
|
||||
it('names every box kind once per format', () => {
|
||||
const kinds = (Object.keys(SHAPES) as ShapeKind[]).filter((k) => !isLineKind(k));
|
||||
expect(new Set(kinds.map((k) => SHAPES[k].odf)).size).toBe(kinds.length);
|
||||
expect(new Set(kinds.map((k) => SHAPES[k].prst)).size).toBe(kinds.length);
|
||||
});
|
||||
|
||||
it('round-trips a kind through both formats', () => {
|
||||
for (const k of Object.keys(SHAPES) as ShapeKind[]) {
|
||||
expect(shapeFromOdfType(SHAPES[k].odf)).toBe(k);
|
||||
expect(shapeFromPrst(SHAPES[k].prst)).toBe(k);
|
||||
const same = isLineKind(k) ? 'line' : k;
|
||||
expect(shapeFromOdfType(SHAPES[k].odf)).toBe(same);
|
||||
expect(shapeFromPrst(SHAPES[k].prst)).toBe(same);
|
||||
}
|
||||
// A preset we can't draw stays unknown rather than flattening to a rectangle.
|
||||
expect(shapeFromOdfType('bent-connector')).toBeNull();
|
||||
|
||||
Reference in new issue
Block a user