Generated
Vendored
+274
@@ -0,0 +1,274 @@
|
||||
# Presentation Quick Start (TypeScript)
|
||||
|
||||
## API Docs
|
||||
|
||||
API docs: `api/API_DOCS.md`
|
||||
|
||||
`Presentation` is the in-memory API object. A deck is the exported presentation
|
||||
file. A slide is one page in the deck.
|
||||
|
||||
## Imports
|
||||
|
||||
```ts
|
||||
import fs from "node:fs/promises";
|
||||
import { FileBlob, Presentation, PresentationFile } from "@oai/artifact-tool";
|
||||
```
|
||||
|
||||
## Create, Render, Export
|
||||
|
||||
This script creates an editable deck, renders each slide PNG, and exports PPTX.
|
||||
|
||||
```ts
|
||||
import fs from "node:fs/promises";
|
||||
import { Presentation, PresentationFile } from "@oai/artifact-tool";
|
||||
|
||||
async function writeBlob(path: string, blob: Blob): Promise<void> {
|
||||
await fs.writeFile(path, new Uint8Array(await blob.arrayBuffer()));
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
await fs.mkdir("output", { recursive: true });
|
||||
|
||||
const presentation = Presentation.create({
|
||||
slideSize: { width: 1280, height: 720 },
|
||||
});
|
||||
|
||||
const slide = presentation.slides.add();
|
||||
slide.background.fill = "slate-50";
|
||||
|
||||
const page = { left: 72, top: 64, width: 1136, height: 592 };
|
||||
const gutter = 28;
|
||||
const leftCol = 430;
|
||||
const rightCol = page.width - leftCol - gutter;
|
||||
|
||||
const eyebrow = slide.shapes.add({
|
||||
geometry: "textbox",
|
||||
position: { left: page.left, top: page.top, width: 280, height: 28 },
|
||||
fill: "none",
|
||||
line: { style: "solid", fill: "none", width: 0 },
|
||||
});
|
||||
eyebrow.text = "EDITABLE PRESENTATION";
|
||||
eyebrow.text.style = { fontSize: 12, bold: true, color: "slate-500" };
|
||||
|
||||
const title = slide.shapes.add({
|
||||
geometry: "textbox",
|
||||
position: {
|
||||
left: page.left,
|
||||
top: page.top + 92,
|
||||
width: leftCol,
|
||||
height: 184,
|
||||
},
|
||||
fill: "none",
|
||||
line: { style: "solid", fill: "none", width: 0 },
|
||||
});
|
||||
title.text = "Build decks with editable objects";
|
||||
title.text.style = { fontSize: 42, bold: true, color: "slate-950" };
|
||||
|
||||
const subtitle = slide.shapes.add({
|
||||
geometry: "textbox",
|
||||
position: {
|
||||
left: page.left,
|
||||
top: page.top + 292,
|
||||
width: leftCol,
|
||||
height: 96,
|
||||
},
|
||||
fill: "none",
|
||||
line: { style: "solid", fill: "none", width: 0 },
|
||||
});
|
||||
subtitle.text =
|
||||
"Rows, columns, grids, charts, tables, images, and text remain editable.";
|
||||
subtitle.text.style = { fontSize: 20, color: "slate-600" };
|
||||
|
||||
const chartFrame = slide.shapes.add({
|
||||
geometry: "roundRect",
|
||||
name: "chart-frame",
|
||||
position: {
|
||||
left: page.left + leftCol + gutter,
|
||||
top: page.top + 92,
|
||||
width: rightCol,
|
||||
height: 388,
|
||||
},
|
||||
fill: "white",
|
||||
line: { style: "solid", fill: "slate-200", width: 1 },
|
||||
borderRadius: "rounded-2xl",
|
||||
shadow: "shadow-sm",
|
||||
});
|
||||
|
||||
slide.charts.add("bar", {
|
||||
position: {
|
||||
left: chartFrame.position.left + 36,
|
||||
top: chartFrame.position.top + 52,
|
||||
width: chartFrame.position.width - 72,
|
||||
height: 280,
|
||||
},
|
||||
categories: ["Rows", "Grid", "Tokens"],
|
||||
series: [{ name: "Coverage", values: [3, 4, 5], fill: "accent1" }],
|
||||
hasLegend: false,
|
||||
dataLabels: { showValue: true, position: "outEnd" },
|
||||
yAxis: {
|
||||
majorGridlines: { style: "solid", fill: "slate-200", width: 1 },
|
||||
},
|
||||
});
|
||||
|
||||
for (const [index, slide] of presentation.slides.items.entries()) {
|
||||
const stem = `slide-${String(index + 1).padStart(2, "0")}`;
|
||||
const png = await presentation.export({ slide, format: "png", scale: 1 });
|
||||
await writeBlob(`output/${stem}.png`, png);
|
||||
}
|
||||
|
||||
const pptx = await PresentationFile.exportPptx(presentation);
|
||||
await pptx.save("output/deck.pptx");
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
```
|
||||
|
||||
Inspect every final slide at full size before delivery. After repairs, refresh
|
||||
the affected slide previews, including slides affected by inherited changes.
|
||||
Add the [optional inspection exports](#optional-inspection-exports) when needed.
|
||||
|
||||
## JSX Compose Equivalent
|
||||
|
||||
Use JSX when the slide is naturally rows, columns, grids, or overlays.
|
||||
|
||||
```tsx
|
||||
/** @jsxRuntime automatic */
|
||||
/** @jsxImportSource @oai/artifact-tool/presentation-jsx */
|
||||
|
||||
const frame = { left: 72, top: 64, width: 1136, height: 592 };
|
||||
|
||||
slide.compose(
|
||||
<column name="content-frame" width="fill" height="fill" gap={28}>
|
||||
<row width="fill" height={72} align="center" justify="between">
|
||||
<paragraph name="eyebrow" className="text-slate-500 text-sm font-bold">
|
||||
EDITABLE PRESENTATION
|
||||
</paragraph>
|
||||
<paragraph className="text-slate-400 text-sm">Q2 planning</paragraph>
|
||||
</row>
|
||||
<row width="fill" height="fill" gap={28} align="stretch">
|
||||
<column width={430} height="fill" gap={18}>
|
||||
<paragraph
|
||||
name="primary-heading"
|
||||
className="text-slate-950 text-5xl font-bold leading-tight"
|
||||
>
|
||||
Build decks with editable objects
|
||||
</paragraph>
|
||||
<paragraph className="text-slate-600 text-xl leading-relaxed">
|
||||
Rows, columns, grids, charts, tables, images, and text remain
|
||||
editable.
|
||||
</paragraph>
|
||||
</column>
|
||||
<box
|
||||
name="chart-frame"
|
||||
width="fill"
|
||||
height="fill"
|
||||
className="bg-white rounded-2xl shadow-sm"
|
||||
line={{ style: "solid", fill: "slate-200", width: 1 }}
|
||||
>
|
||||
<chart
|
||||
name="coverage-chart"
|
||||
chartType="bar"
|
||||
categories={["Rows", "Grid", "Tokens"]}
|
||||
series={[{ name: "Coverage", values: [3, 4, 5], fill: "accent1" }]}
|
||||
hasLegend={false}
|
||||
width="fill"
|
||||
height="fill"
|
||||
/>
|
||||
</box>
|
||||
</row>
|
||||
</column>,
|
||||
{ frame, baseUnit: 8 },
|
||||
);
|
||||
```
|
||||
|
||||
## Import And Edit PPTX
|
||||
|
||||
Load a PPTX, inspect for stable ids, render the affected slide before and after
|
||||
a focused edit, re-inspect, and export the edited PPTX.
|
||||
|
||||
```ts
|
||||
const presentation = await PresentationFile.importPptx(
|
||||
await FileBlob.load("input.pptx"),
|
||||
);
|
||||
|
||||
const before = await presentation.inspect({
|
||||
kind: "slide,textbox,shape,image,table,chart,notes,thread,layout",
|
||||
search: "Revenue",
|
||||
maxChars: 8000,
|
||||
});
|
||||
console.log(before.ndjson);
|
||||
|
||||
const slide = presentation.resolve(slideIdFromInspect);
|
||||
await writeBlob(
|
||||
"output/before-slide.png",
|
||||
await presentation.export({ slide, format: "png", scale: 1 }),
|
||||
);
|
||||
|
||||
const target = presentation.resolve(anchorIdFromInspect);
|
||||
target.text.replace("Revenue", "Updated revenue outlook");
|
||||
|
||||
await writeBlob(
|
||||
"output/after-slide.png",
|
||||
await presentation.export({ slide, format: "png", scale: 1 }),
|
||||
);
|
||||
|
||||
const after = await presentation.inspect({
|
||||
target: { id: anchorIdFromInspect, beforeLines: 2, afterLines: 2 },
|
||||
kind: "textbox,shape,image,table,chart",
|
||||
maxChars: 3000,
|
||||
});
|
||||
console.log(after.ndjson);
|
||||
|
||||
const pptx = await PresentationFile.exportPptx(presentation);
|
||||
await pptx.save("output/edited-deck.pptx");
|
||||
```
|
||||
|
||||
## Optional Inspection Exports
|
||||
|
||||
When investigating placement, export layout evidence for the affected slide
|
||||
in the authoring process. Capture it before and after a change when comparison
|
||||
is useful.
|
||||
|
||||
```ts
|
||||
const layout = await slide.export({ format: "layout" });
|
||||
await fs.writeFile("output/slide.layout.json", await layout.text());
|
||||
```
|
||||
|
||||
For deck flow or changes affecting multiple slides, add an overview montage.
|
||||
Continue to inspect individual slide PNGs at full size.
|
||||
|
||||
```ts
|
||||
const montage = await presentation.export({
|
||||
format: "webp",
|
||||
montage: true,
|
||||
});
|
||||
await writeBlob("output/deck-montage.webp", montage);
|
||||
```
|
||||
|
||||
## Local Image Bytes
|
||||
|
||||
Use byte-backed images for embedded PPTX assets.
|
||||
|
||||
```ts
|
||||
async function readImageBlob(imagePath: string): Promise<ArrayBuffer> {
|
||||
const bytes = await fs.readFile(imagePath);
|
||||
return bytes.buffer.slice(
|
||||
bytes.byteOffset,
|
||||
bytes.byteOffset + bytes.byteLength,
|
||||
);
|
||||
}
|
||||
|
||||
const imageBytes = await readImageBlob("assets/product.png");
|
||||
slide.images.add({
|
||||
blob: imageBytes,
|
||||
contentType: "image/png",
|
||||
alt: "Product screenshot",
|
||||
fit: "cover",
|
||||
position: { left: 720, top: 96, width: 420, height: 280 },
|
||||
geometry: "roundRect",
|
||||
borderRadius: "rounded-xl",
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+270
@@ -0,0 +1,270 @@
|
||||
# Presentation API Docs
|
||||
|
||||
Use the presentation facades to create PowerPoint-style decks in TypeScript.
|
||||
|
||||
## Conventions (units + presets)
|
||||
|
||||
- **Pixels everywhere**: all slide geometry uses CSS pixels (`px`) at 96 DPI: `position.{left,top,width,height}`, line widths, and text `fontSize`.
|
||||
- **Default canvas for examples**: use `1280 x 720` unless the task or source deck says otherwise. A useful full-slide content frame is `{ left: 72, top: 64, width: 1136, height: 592 }`.
|
||||
- **Angles**: rotations use degrees.
|
||||
- **Preset geometry**: `geometry` uses preset shape-name strings. Use standard shape presets and `geometry: "custom"` for bespoke paths.
|
||||
- **Gradients**: stop `offset` ranges from `0` to `100000`.
|
||||
- **Config-first authoring**: pass config objects into create/add APIs and grouped setters when the API provides them.
|
||||
- **String values**: options such as geometry, fit, alignment, chart type, line style, and connector kind are strings; reference pages list exact small unions and grep targets for huge catalogs.
|
||||
- **Inline docs types**: reference pages include illustrative `type ... = { ... }` blocks. Treat them as schema-shaped authoring guidance, not imports.
|
||||
- **Authoring surfaces**: `slide.compose(...)` covers rows, columns, grids, layers, and token strings. Config-first facade APIs cover exact positions, fixed chrome, native charts/tables/images, and imported deck edits.
|
||||
|
||||
## Common Routes
|
||||
|
||||
- Rows, columns, grids, overlays, and 12-column spans: [`references/cookbook/layout.md`](./references/cookbook/layout.md).
|
||||
- JSX node props and sizing mechanics: [`references/jsx.md`](./references/jsx.md).
|
||||
- Tailwind-like visual strings: [`references/tokens.md`](./references/tokens.md).
|
||||
- Inspect, resolve, edit, preview, and re-inspect loops: [`references/cookbook/imported-deck.md`](./references/cookbook/imported-deck.md).
|
||||
|
||||
## Quick start
|
||||
|
||||
```ts
|
||||
const presentation = Presentation.create({
|
||||
slideSize: { width: 1280, height: 720 },
|
||||
});
|
||||
|
||||
const slide = presentation.slides.add();
|
||||
slide.background.fill = "slate-50";
|
||||
|
||||
const headline = slide.shapes.add({
|
||||
geometry: "textbox",
|
||||
name: "headline",
|
||||
position: { left: 72, top: 64, width: 720, height: 96 },
|
||||
fill: "none",
|
||||
line: { style: "solid", fill: "none", width: 0 },
|
||||
});
|
||||
headline.text = "Editable headline";
|
||||
headline.text.style = { fontSize: 44, bold: true, color: "slate-950" };
|
||||
|
||||
const shape = slide.shapes.add({
|
||||
geometry: "roundRect",
|
||||
name: "summary-surface",
|
||||
position: { left: 72, top: 188, width: 520, height: 300 },
|
||||
fill: "white",
|
||||
line: { style: "solid", fill: "slate-200", width: 1 },
|
||||
borderRadius: "rounded-2xl",
|
||||
});
|
||||
|
||||
const previewBlob = await presentation.export({
|
||||
slide,
|
||||
format: "png",
|
||||
scale: 2,
|
||||
});
|
||||
const deckPdfBlob = await presentation.export({ format: "pdf" });
|
||||
const slidePdfBlob = await presentation.export({ slide, format: "pdf" });
|
||||
const snapshot = await presentation.inspect({
|
||||
kind: "slide,textbox,shape",
|
||||
maxChars: 4000,
|
||||
});
|
||||
const help = presentation.help("*", {
|
||||
search: "chart axis labels",
|
||||
include: ["index", "notes"],
|
||||
maxChars: 4000,
|
||||
});
|
||||
const proto = presentation.toProto();
|
||||
```
|
||||
|
||||
Inspect every final slide PNG at full size. After repairs, refresh previews for
|
||||
the affected slides, including those affected by inherited changes.
|
||||
|
||||
## Optional Inspection Exports
|
||||
|
||||
When investigating placement, export layout evidence for the affected slide:
|
||||
|
||||
```ts
|
||||
const layoutBlob = await slide.export({ format: "layout" });
|
||||
```
|
||||
|
||||
For deck flow or changes affecting multiple slides, export an overview montage:
|
||||
|
||||
```ts
|
||||
const montageBlob = await presentation.export({
|
||||
format: "webp",
|
||||
montage: true,
|
||||
});
|
||||
```
|
||||
|
||||
Capture these before and after edits when comparison is useful. A montage
|
||||
supports deck-level review; use individual PNGs for full-size slide inspection.
|
||||
|
||||
## Load Existing Presentation Data
|
||||
|
||||
Load a PPTX from a local path:
|
||||
|
||||
```ts
|
||||
const presentation = await Presentation.load("input.pptx");
|
||||
```
|
||||
|
||||
Load serialized presentation data with `Presentation.load(proto)`:
|
||||
|
||||
```ts
|
||||
const presentation = Presentation.load(proto);
|
||||
|
||||
const before = await presentation.inspect({
|
||||
kind: "slide,textbox,shape,image,table,chart,notes,thread,layout",
|
||||
search: "Revenue",
|
||||
maxChars: 8000,
|
||||
});
|
||||
|
||||
const slide = presentation.resolve(slideAnchorIdFromInspect);
|
||||
const previewBefore = await presentation.export({
|
||||
slide,
|
||||
format: "png",
|
||||
scale: 1,
|
||||
});
|
||||
|
||||
const target = presentation.resolve(anchorIdFromInspect);
|
||||
target.text.replace("Revenue", "Revenue outlook");
|
||||
target.text.style = { fontSize: 24, color: "slate-950", bold: true };
|
||||
|
||||
const previewAfter = await presentation.export({
|
||||
slide,
|
||||
format: "png",
|
||||
scale: 1,
|
||||
});
|
||||
const after = await presentation.inspect({
|
||||
target: { id: anchorIdFromInspect, beforeLines: 2, afterLines: 2 },
|
||||
kind: "textbox,shape,image,table,chart",
|
||||
maxChars: 3000,
|
||||
});
|
||||
const nextProto = presentation.toProto();
|
||||
```
|
||||
|
||||
## Compose-first layout
|
||||
|
||||
```tsx
|
||||
/** @jsxRuntime automatic */
|
||||
|
||||
const presentation = Presentation.create();
|
||||
const slide = presentation.slides.add();
|
||||
|
||||
slide.compose(
|
||||
<column width="fill" height="fill" gap={16}>
|
||||
<paragraph
|
||||
name="headline"
|
||||
className="text-slate-950 text-3xl leading-tight"
|
||||
>
|
||||
<run textStyle={{ bold: true }}>Quarterly</run>
|
||||
<run> readiness</run>
|
||||
</paragraph>
|
||||
<rule stroke="#0f172a" width={160} weight={2} />
|
||||
</column>,
|
||||
{
|
||||
frame: { left: 48, top: 40, width: 864, height: 460 },
|
||||
baseUnit: 8,
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
Use `name` for stable inspect and layout-export targeting. JSX materializing
|
||||
tags default `width` to `"fill"` when you omit it.
|
||||
|
||||
## Core API Sequence
|
||||
|
||||
- Create presentations with `Presentation.create({ slideSize })` to control default slide dimensions.
|
||||
- Add slides with `presentation.slides.add({ layout, layoutId })` or `presentation.slides.insert({ after, ... })`.
|
||||
- Use `slide.compose(nodeOrJsx, { frame, baseUnit })` for compose-first layouts. JSX lowers into the same compose runtime as the helper-based API.
|
||||
- Author content with config-first calls: `slide.shapes.add({ geometry, position, fill, line })`, `slide.images.add({ ... })`, `slide.tables.add({ ... })`, and `slide.charts.add(chartType, { ... })`.
|
||||
- Format whole-shape text with grouped configs such as `shape.text.style = { fontSize, bold, color, alignment }`.
|
||||
- Edit imported decks with `presentation.inspect({ kind, search, maxChars })`, `presentation.resolve(anchorId)`, and focused facade edits.
|
||||
- Export previews with `presentation.export({ slide, format, scale })`.
|
||||
- Export all slides as one PDF with `presentation.export({ format: "pdf" })`.
|
||||
- Export deck montages for overview review with `presentation.export({ format: "webp", montage: true })`.
|
||||
- Export layout JSON for placement investigations with `slide.export({ format: "layout" })`.
|
||||
- Control editor gridlines and imported guides with `presentation.view`.
|
||||
- Search API help with `presentation.help(query, { search, include, maxChars })`.
|
||||
- Run high-level edits with `presentation.scripts.run(kind, options)`; see [`references/presentation.spec.md`](./references/presentation.spec.md) for the script surface.
|
||||
|
||||
## Output Map
|
||||
|
||||
| Output | API | Result |
|
||||
| ------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------ |
|
||||
| All slide previews | `presentation.render()` | PNG blobs in deck order, named `slide-1.png`, `slide-2.png`, and so on |
|
||||
| Selected previews | `presentation.render({ slide: [0, 2] })` | PNG blobs for zero-based indexes, in requested order |
|
||||
| Raster preview | `presentation.render({ slide, format: "png", scale })` | One raster blob for a `Slide` or a single zero-based index |
|
||||
| Slide PNG | `presentation.export({ slide, format: "png", scale })` | One preview image for one slide |
|
||||
| Deck PDF | `presentation.export({ format: "pdf" })` | One PDF `Blob` with one page per slide |
|
||||
| Slide PDF | `presentation.export({ slide, format: "pdf" })` | One PDF `Blob` for one slide |
|
||||
| Editable PPTX | `presentation.export({ format: "pptx" })` | Editable presentation `Blob` |
|
||||
| Deck montage | `presentation.export({ format: "webp", montage: true, scale })` | One overview image containing the deck slides |
|
||||
| Layout JSON | `slide.export({ format: "layout" })` | Structural JSON with bounds, ids, text, names, and object metadata |
|
||||
| Searchable snapshot | `presentation.inspect({ kind, search, maxChars })` | NDJSON records for locating and resolving objects |
|
||||
| Runtime handoff | `presentation.toProto()` | Serializable presentation data for host adapters |
|
||||
|
||||
## Minimal Patterns
|
||||
|
||||
Use these as the first API patterns to reach for:
|
||||
|
||||
```ts
|
||||
// Create, preview, inspect, then serialize.
|
||||
const presentation = Presentation.create({
|
||||
slideSize: { width: 1280, height: 720 },
|
||||
});
|
||||
const slide = presentation.slides.add();
|
||||
const preview = await presentation.export({ slide, format: "png", scale: 1 });
|
||||
const snapshot = await presentation.inspect({
|
||||
kind: "slide,textbox,shape,image,chart,table",
|
||||
maxChars: 4000,
|
||||
});
|
||||
const proto = presentation.toProto();
|
||||
```
|
||||
|
||||
```tsx
|
||||
// Compose structure with first-principles rows/columns.
|
||||
slide.compose(
|
||||
<row width="fill" height="fill" gap={28}>
|
||||
<column width={420} height="fill" gap={16}>
|
||||
<paragraph className="text-slate-950 text-5xl font-bold leading-tight">
|
||||
Title
|
||||
</paragraph>
|
||||
<paragraph className="text-slate-600 text-xl leading-relaxed">
|
||||
Editable copy in a fixed text column.
|
||||
</paragraph>
|
||||
</column>
|
||||
<box
|
||||
width="fill"
|
||||
height="fill"
|
||||
className="bg-slate-50 rounded-2xl shadow-sm"
|
||||
/>
|
||||
</row>,
|
||||
{ frame: { left: 56, top: 56, width: 1168, height: 608 }, baseUnit: 8 },
|
||||
);
|
||||
```
|
||||
|
||||
For 3-column and 12-column layouts, use [`references/cookbook/layout.md`](./references/cookbook/layout.md); keep spans local with `{ mode: "fr", value: 1 }` track objects.
|
||||
|
||||
Use `className` only for visual/text tokens such as `bg-*`, `rounded-*`,
|
||||
`shadow-*`, `text-*`, `font-*`, and `leading-*`. Use layout props for
|
||||
`width`, `height`, `gap`, `padding`, `align`, and `justify`.
|
||||
|
||||
## Reference Map
|
||||
|
||||
Open these references as needed:
|
||||
|
||||
- [`references/jsx.md`](./references/jsx.md) — compact JSX node surface and layout mechanics.
|
||||
- [`references/tokens.md`](./references/tokens.md) — Tailwind-like token reference for colors, text, radius, shadows, and `className`.
|
||||
- [`references/cookbook/layout.md`](./references/cookbook/layout.md) — first-principles layout recipes for rows, columns, 12-column grids, alignment, masks, and overlays.
|
||||
- [`references/cookbook/imported-deck.md`](./references/cookbook/imported-deck.md) — safe inspect, resolve, edit, preview, and re-inspect loops for existing decks.
|
||||
- [`references/presentation.spec.md`](./references/presentation.spec.md) — `Presentation` facade, slide collection, view controls, export/toProto, scripts.
|
||||
- [`references/slide.spec.md`](./references/slide.spec.md) — `Slide` API, backgrounds, placeholders, notes, export, auto-layout.
|
||||
- [`references/inspect.md`](./references/inspect.md) — grep-first snapshot (`inspect → rg → resolve/edit → re-inspect`) for loaded presentation data and templates.
|
||||
- [`references/help.md`](./references/help.md) — grep-first API and template lookup (`help → build/edit → inspect`) for presentation JS workflows.
|
||||
- [`references/layout.spec.md`](./references/layout.spec.md) — layouts, placeholders, and slide layout assignment.
|
||||
- [`references/master.spec.md`](./references/master.spec.md) — masters, layout linking, background refs, color maps.
|
||||
- [`references/theme.spec.md`](./references/theme.spec.md) — theme color schemes and hex maps.
|
||||
- [`references/styles.spec.md`](./references/styles.spec.md) — named text styles and flow through text.
|
||||
- [`references/rich-text.spec.md`](./references/rich-text.spec.md) — text blocks, ranges, links, list presets.
|
||||
- [`references/shapes.spec.md`](./references/shapes.spec.md) — shape geometry, custom Bézier curves, fills, strokes, rounded corners, shadows, and z-ordering.
|
||||
- [`references/connectors.md`](./references/connectors.md) — connected lines, arrows, side anchors, direct connection sites, and rerouting behavior.
|
||||
- [`references/fill.spec.md`](./references/fill.spec.md) — fill/stroke config shapes and color shorthands, solid, gradient, pattern.
|
||||
- [`references/images.spec.md`](./references/images.spec.md) — images, cropping, contain/cover framing, prompt placeholders.
|
||||
- [`references/tables.spec.md`](./references/tables.spec.md) — tables, merges, and cell text.
|
||||
- [`references/charts.spec.md`](./references/charts.spec.md) — charts, series, axes, legends, mini-chart YAML.
|
||||
- [`references/comments.md`](./references/comments.md) — comment authors, threads, replies, reactions, and resolving imported review threads.
|
||||
- [`references/auto-layout.spec.md`](./references/auto-layout.spec.md) — deterministic layout helpers for arranging shapes within frames.
|
||||
- [`references/speaker-notes.spec.md`](./references/speaker-notes.spec.md) — speaker notes surface and visibility toggles.
|
||||
Generated
Vendored
+100
@@ -0,0 +1,100 @@
|
||||
# Auto Layout
|
||||
|
||||
`slide.autoLayout(...)` places shapes within a frame using deterministic spacing.
|
||||
Use `slide.compose(<row>/<column>/<grid>)` for new structured JSX layouts. Use
|
||||
`slide.autoLayout(...)` when repositioning existing facade shapes, especially
|
||||
imported or generated shapes.
|
||||
|
||||
## Pattern
|
||||
|
||||
```ts
|
||||
slide.autoLayout(shapes, {
|
||||
direction,
|
||||
frame,
|
||||
align,
|
||||
horizontalGap,
|
||||
verticalGap,
|
||||
horizontalPadding,
|
||||
verticalPadding,
|
||||
});
|
||||
```
|
||||
|
||||
## Inputs
|
||||
|
||||
- `direction`: horizontal or vertical flow.
|
||||
- `frame`: `"slide"`, container `Shape`, or explicit `{ left, top, width, height }`.
|
||||
- `align`: 3x3 group alignment within the frame.
|
||||
- Gap and padding values use pixels.
|
||||
|
||||
## Inline Types
|
||||
|
||||
```ts
|
||||
type AutoLayoutOptions = {
|
||||
direction?: "horizontal" | "vertical";
|
||||
frame?:
|
||||
| "slide"
|
||||
| Shape
|
||||
| { left: number; top: number; width: number; height: number };
|
||||
align?:
|
||||
| "center"
|
||||
| "topLeft"
|
||||
| "topCenter"
|
||||
| "topRight"
|
||||
| "left"
|
||||
| "right"
|
||||
| "bottomLeft"
|
||||
| "bottomCenter"
|
||||
| "bottomRight";
|
||||
horizontalGap?: number | "auto";
|
||||
verticalGap?: number | "auto";
|
||||
horizontalPadding?: number;
|
||||
verticalPadding?: number;
|
||||
};
|
||||
```
|
||||
|
||||
## Shape Prep
|
||||
|
||||
```ts
|
||||
for (const shape of shapes) {
|
||||
shape.position = {
|
||||
width: shapeWidthPx,
|
||||
height: shapeHeightPx,
|
||||
};
|
||||
}
|
||||
|
||||
slide.autoLayout(shapes, layoutConfig);
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Equal KPI row.
|
||||
const kpiShapes = metrics.map((metric) =>
|
||||
slide.shapes.add({
|
||||
geometry: "roundRect",
|
||||
position: { width: 240, height: 132 },
|
||||
fill: "white",
|
||||
line: { style: "solid", fill: "slate-200", width: 1 },
|
||||
borderRadius: "rounded-xl",
|
||||
}),
|
||||
);
|
||||
|
||||
slide.autoLayout(kpiShapes, {
|
||||
direction: "horizontal",
|
||||
frame: { left: 80, top: 160, width: 1120, height: 160 },
|
||||
horizontalGap: "auto",
|
||||
align: "center",
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Vertical callout stack inside an existing shape frame.
|
||||
slide.autoLayout(callouts, {
|
||||
direction: "vertical",
|
||||
frame: frameShape,
|
||||
verticalGap: 14,
|
||||
horizontalPadding: 24,
|
||||
verticalPadding: 24,
|
||||
align: "topLeft",
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+330
@@ -0,0 +1,330 @@
|
||||
# Charts
|
||||
|
||||
`slide.charts` creates chart elements with slide placement and chart configuration.
|
||||
|
||||
## Resolved From Inspect
|
||||
|
||||
```ts
|
||||
const chart = presentation.resolve("ch/b2c3d4e5");
|
||||
chart.title = "Updated chart title";
|
||||
chart.yAxis = { numberFormatCode: "$#,##0M" };
|
||||
chart.series.getItemAt(0).values = [3.1, 3.7, 4.2, 4.8];
|
||||
```
|
||||
|
||||
Use `presentation.inspect({ kind: "chart", search })` to find the `ch/...`
|
||||
anchor id. If an imported chart resolves as an image, preserve it as an image or
|
||||
rebuild it as a native chart intentionally.
|
||||
|
||||
## Add Chart
|
||||
|
||||
```ts
|
||||
const chart = slide.charts.add(chartType, {
|
||||
position,
|
||||
title,
|
||||
titleTextStyle,
|
||||
categories,
|
||||
series,
|
||||
hasLegend,
|
||||
legend,
|
||||
barOptions,
|
||||
lineOptions,
|
||||
areaOptions,
|
||||
pieOptions,
|
||||
doughnutOptions,
|
||||
treemapOptions,
|
||||
mapOptions,
|
||||
funnelOptions,
|
||||
boxWhiskerOptions,
|
||||
histogramOptions,
|
||||
view3d,
|
||||
scatterOptions,
|
||||
radarOptions,
|
||||
bubbleOptions,
|
||||
xAxis,
|
||||
yAxis,
|
||||
dataLabels,
|
||||
dataTable,
|
||||
chartFill,
|
||||
chartLine,
|
||||
plotAreaFill,
|
||||
plotAreaLine,
|
||||
});
|
||||
```
|
||||
|
||||
Small chart option enums are listed below.
|
||||
|
||||
## Chart Inline Types
|
||||
|
||||
```ts
|
||||
type ChartTypeName =
|
||||
| "line" | "pie" | "bar" | "doughnut" | "scatter" | "bubble" | "radar"
|
||||
| "treemap" | "sunburst" | "map" | "waterfall" | "line3D" | "pie3D"
|
||||
| "area3D" | "bar3D" | "funnel" | "histogram" | "boxWhisker" | "stock"
|
||||
| "surface3D" | "ofPie" | "surface" | "pareto" | "combo" | "area";
|
||||
|
||||
type ChartConfig = {
|
||||
position?: { left?: number; top?: number; width?: number; height?: number };
|
||||
title?: string;
|
||||
roundedCorners?: boolean | null;
|
||||
titlePlacement?: "none" | "aboveChart" | "centeredOverlay";
|
||||
titleTextStyle?: ChartTextStyleConfig;
|
||||
categories?: string[];
|
||||
series?: ChartSeriesConfig[];
|
||||
hasLegend?: boolean;
|
||||
legend?: ChartLegendConfig;
|
||||
barOptions?: { direction?: "bar" | "column"; grouping?: "clustered" | "stacked" | "percentStacked"; varyColors?: boolean; gapWidth?: number; gapDepth?: number; overlap?: number; bar3dShape?: number };
|
||||
lineOptions?: { grouping?: "standard" | "stacked" | "percentStacked"; smooth?: boolean; varyColors?: boolean };
|
||||
areaOptions?: { grouping?: "standard" | "stacked" | "percentStacked"; varyColors?: boolean };
|
||||
pieOptions?: { firstSliceAngle?: number };
|
||||
doughnutOptions?: { holeSize?: number; firstSliceAngle?: number };
|
||||
treemapOptions?: { parentLabelLayout?: "none" | "overlapping" | "banner" };
|
||||
mapOptions?: { mapArea?: "world" | "auto" | "dataOnly" | "region"; projection?: "mercator" | "auto" | "miller" | "albers"; labelLayout?: "none" | "bestFit" | "showAll"; dataLevel?: "auto" | "county" | "postalCode" | "countryOrRegion" | "stateOrProvince" | "stateCode" | "countyCode" | "countryOrRegionCode"; showUnknown?: boolean; onlyRegionsWithData?: boolean };
|
||||
funnelOptions?: { gapWidth?: number };
|
||||
boxWhiskerOptions?: { showMeanLine?: boolean; showMeanMarker?: boolean; showNonOutliers?: boolean; showOutliers?: boolean; quartileMethod?: "inclusive" | "exclusive" };
|
||||
histogramOptions?: { binWidth?: number | null; binCount?: number | null; underflow?: number | null; overflow?: number | null; intervalClosed?: number; aggregated?: boolean };
|
||||
view3d?: { rotX?: number; rotY?: number; perspective?: number; rightAngleAxes?: boolean };
|
||||
scatterOptions?: { style?: "line" | "lineWithMarkers" | "marker" | "smooth" | "smoothWithMarkers"; varyColors?: boolean };
|
||||
radarOptions?: { style?: "standard" | "marker" | "filled"; varyColors?: boolean };
|
||||
bubbleOptions?: { scale?: number | null; sizeRepresents?: "area" | "width" | null; showNegative?: boolean | null };
|
||||
xAxis?: ChartAxisConfig;
|
||||
yAxis?: ChartAxisConfig;
|
||||
dataLabels?: ChartDataLabelsConfig;
|
||||
dataTable?: ChartDataTableConfig;
|
||||
chartFill?: FillConfig;
|
||||
chartLine?: LineConfig;
|
||||
plotAreaFill?: FillConfig;
|
||||
plotAreaLine?: LineConfig;
|
||||
displayBlanksAs?: "zero" | "gap" | "span" | null;
|
||||
styleIndex?: number;
|
||||
};
|
||||
```
|
||||
|
||||
## Chart Family Options
|
||||
|
||||
```ts
|
||||
histogram.histogramOptions = { binWidth: 5 };
|
||||
histogram.histogramOptions = { binCount: 8, underflow: 0, overflow: 30 };
|
||||
histogram.histogramOptions = { binWidth: null, binCount: null };
|
||||
histogram.histogramOptions = { underflow: null, overflow: null };
|
||||
bubble.bubbleOptions = { scale: 150, sizeRepresents: "area" };
|
||||
bubble.bubbleOptions = { scale: null, sizeRepresents: null };
|
||||
bubble.bubbleOptions = { showNegative: true };
|
||||
```
|
||||
|
||||
## Grouped Edits
|
||||
|
||||
```ts
|
||||
chart.xAxis = axisConfig;
|
||||
chart.yAxis = axisConfig;
|
||||
chart.legend = legendConfig;
|
||||
chart.dataLabels = dataLabelsConfig;
|
||||
chart.dataTable = dataTableConfig;
|
||||
```
|
||||
|
||||
### Data Labels
|
||||
|
||||
```ts
|
||||
chart.dataLabels = { showValue: true, position: "outEnd" };
|
||||
chart.dataLabels = { textStyle: { fontSize: 14 } };
|
||||
chart.dataLabels.showCategoryName = true;
|
||||
|
||||
const series = chart.series.getItemAt(seriesIndex);
|
||||
series.dataLabels = { showValue: false, showSeriesName: true };
|
||||
series.dataLabels.showSeriesName = false;
|
||||
```
|
||||
|
||||
Config assignments update supplied fields and preserve omitted values. New label
|
||||
collections initialize all seven `show*` flags to `false`. A series without its
|
||||
own label collection inherits chart labels; omitted point flags inherit series
|
||||
or chart labels.
|
||||
|
||||
### Axis Placement
|
||||
|
||||
```ts
|
||||
chart.xAxis = { crossesAt: 2 }; // The value axis crosses at category 2.
|
||||
chart.yAxis = { crossesAt: 25 }; // The category axis crosses at value 25.
|
||||
chart.yAxis = { tickLabelPosition: "high" };
|
||||
```
|
||||
|
||||
## Series
|
||||
|
||||
```ts
|
||||
const chart = slide.charts.add(chartType, {
|
||||
categories,
|
||||
series: [
|
||||
{
|
||||
name: seriesName,
|
||||
categories,
|
||||
values,
|
||||
xValues,
|
||||
categoryPaths,
|
||||
fill: fillConfig,
|
||||
line: lineConfig,
|
||||
marker: markerConfig,
|
||||
points,
|
||||
dataLabels: dataLabelsConfig,
|
||||
dataLabelOverrides,
|
||||
trendlines,
|
||||
errorBars,
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Series Inline Type
|
||||
|
||||
```ts
|
||||
type ChartSeriesConfig = {
|
||||
name: string;
|
||||
categories?: string[];
|
||||
values?: Array<number | null>;
|
||||
xValues?: Array<number | null>;
|
||||
categoryPaths?: string[][];
|
||||
bubbleSizes?: Array<number | null>;
|
||||
bubbleSizeFormula?: string;
|
||||
bubbleSizesFormatCode?: string;
|
||||
explosion?: number;
|
||||
smooth?: boolean;
|
||||
fill?: FillConfig;
|
||||
line?: LineConfig;
|
||||
stroke?: LineConfig;
|
||||
// Scatter outline color defaults to the marker's solid fill; explicit stroke fills take precedence.
|
||||
marker?: { symbol?: "circle" | "diamond" | "dot" | "none" | "plus" | "square" | "star" | "triangle" | "x"; size?: number; fill?: FillConfig };
|
||||
points?: Array<{ idx: number; fill?: FillConfig; line?: LineConfig; stroke?: LineConfig }>;
|
||||
dataLabels?: ChartDataLabelsConfig;
|
||||
dataLabelOverrides?: Array<{ idx: number; text?: string; separator?: string; position?: string; fill?: FillConfig; line?: LineConfig; stroke?: LineConfig; showValue?: boolean; showSeriesName?: boolean; showCategoryName?: boolean; showPercent?: boolean; textStyle?: ChartTextStyleConfig }>;
|
||||
trendlines?: Array<{
|
||||
type?: "linear" | "exponential" | "logarithmic" | "polynomial" | "power" | "movingAverage";
|
||||
name?: string;
|
||||
polynomialOrder?: number;
|
||||
movingAveragePeriod?: number;
|
||||
forecastForward?: number;
|
||||
forecastBackward?: number;
|
||||
intercept?: number;
|
||||
displayEquation?: boolean;
|
||||
displayRSquared?: boolean;
|
||||
line?: LineConfig;
|
||||
label?: { text?: string; textStyle?: ChartTextStyleConfig; fill?: FillConfig; line?: LineConfig };
|
||||
}>;
|
||||
errorBars?: { type?: "standardError" | "percentage" | "standardDeviation" | "none"; value?: number; endStyle?: "cap" | "noCap"; line?: LineConfig };
|
||||
valuesFormatCode?: string;
|
||||
xValuesFormatCode?: string;
|
||||
};
|
||||
```
|
||||
|
||||
## Data Label Overrides
|
||||
|
||||
```ts
|
||||
const override = chart.series
|
||||
.getItemAt(seriesIndex)
|
||||
.dataLabelOverrides.add(dataPointIdx);
|
||||
override.text = labelText;
|
||||
override.position = labelPosition;
|
||||
override.textStyle.fontSize = fontSizePx;
|
||||
override.textStyle.fill = textFill;
|
||||
override.fill = fillConfig;
|
||||
override.stroke = lineConfig;
|
||||
```
|
||||
|
||||
## Chart Areas
|
||||
|
||||
```ts
|
||||
const chart = slide.charts.add(chartType, {
|
||||
chartFill,
|
||||
plotAreaFill,
|
||||
});
|
||||
```
|
||||
|
||||
## Axis, Legend, Label Inline Types
|
||||
|
||||
```ts
|
||||
type ChartTextStyleConfig = {
|
||||
fontSize?: number;
|
||||
fill?: FillConfig;
|
||||
bold?: boolean;
|
||||
italic?: boolean;
|
||||
underline?: string;
|
||||
alignment?: "left" | "center" | "right" | "justify";
|
||||
};
|
||||
|
||||
type ChartLegendConfig = {
|
||||
position?: "left" | "top" | "topRight" | "right" | "bottom";
|
||||
overlay?: boolean;
|
||||
fill?: FillConfig;
|
||||
line?: LineConfig;
|
||||
textStyle?: ChartTextStyleConfig;
|
||||
};
|
||||
|
||||
type ChartDataLabelsConfig = {
|
||||
visible?: boolean;
|
||||
deleted?: boolean;
|
||||
position?: "center" | "inEnd" | "outEnd" | "left" | "right" | "top" | "bottom" | "insideBase" | "bestFit" | "dataCallout";
|
||||
showValue?: boolean;
|
||||
showSeriesName?: boolean;
|
||||
showCategoryName?: boolean;
|
||||
showLegendKey?: boolean;
|
||||
showPercent?: boolean;
|
||||
showBubbleSize?: boolean;
|
||||
showLeaderLines?: boolean;
|
||||
numberFormatCode?: string;
|
||||
numberFormatSourceLinked?: boolean;
|
||||
separator?: string;
|
||||
textStyle?: ChartTextStyleConfig;
|
||||
fill?: FillConfig;
|
||||
line?: LineConfig;
|
||||
};
|
||||
|
||||
type ChartAxisConfig = {
|
||||
visible?: boolean;
|
||||
title?: string | { text?: string; textStyle?: ChartTextStyleConfig };
|
||||
numberFormatCode?: string;
|
||||
min?: number;
|
||||
max?: number;
|
||||
majorUnit?: number;
|
||||
minorUnit?: number;
|
||||
position?: "bottom" | "left" | "right" | "top";
|
||||
tickLabelPosition?: "nextTo" | "high" | "low" | "none" | string;
|
||||
labelOffsetPercent?: number; // Category-axis font-size percentage; 0–1000, default 100.
|
||||
textStyle?: ChartTextStyleConfig;
|
||||
line?: LineConfig;
|
||||
majorGridlines?: LineConfig | null;
|
||||
minorGridlines?: LineConfig | null;
|
||||
};
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Executive horizontal bar chart.
|
||||
slide.charts.add("bar", {
|
||||
position: { left: 96, top: 160, width: 720, height: 360 },
|
||||
categories: ["Enterprise", "Mid-market", "SMB"],
|
||||
series: [{ name: "ARR", values: [42, 28, 17], fill: "#2563eb" }],
|
||||
barOptions: { direction: "bar", grouping: "clustered", gapWidth: 44 },
|
||||
hasLegend: false,
|
||||
xAxis: { visible: false, majorGridlines: null },
|
||||
yAxis: { textStyle: { fill: "#475569", fontSize: 13 }, line: { style: "solid", fill: "#e2e8f0", width: 1 } },
|
||||
dataLabels: { showValue: true, position: "outEnd", textStyle: { fill: "#0f172a", fontSize: 13, bold: true } },
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Compact trend line with muted grid.
|
||||
slide.charts.add("line", {
|
||||
position: { left: 96, top: 150, width: 880, height: 280 },
|
||||
categories: ["Jan", "Feb", "Mar", "Apr"],
|
||||
series: [{ name: "Conversion", values: [31, 34, 37, 43], line: { style: "solid", fill: "#0f766e", width: 3 } }],
|
||||
legend: { position: "bottom", overlay: false },
|
||||
yAxis: { numberFormatCode: "0%", majorGridlines: { style: "solid", fill: "#e2e8f0", width: 1 } },
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Doughnut chart with labels outside.
|
||||
slide.charts.add("doughnut", {
|
||||
categories: ["Product", "Sales", "Support"],
|
||||
series: [{ name: "Share", values: [52, 31, 17] }],
|
||||
dataLabels: { showPercent: true, showCategoryName: true, position: "outEnd" },
|
||||
legend: { position: "right" },
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+103
@@ -0,0 +1,103 @@
|
||||
# Comments
|
||||
|
||||
Presentation comments use people, threads, replies, reactions, and thread state.
|
||||
|
||||
## Current Author
|
||||
|
||||
```ts
|
||||
presentation.comments.setSelf({
|
||||
displayName,
|
||||
initials,
|
||||
email,
|
||||
});
|
||||
```
|
||||
|
||||
## Person Inline Type
|
||||
|
||||
```ts
|
||||
type PersonConfig = {
|
||||
id?: string;
|
||||
displayName: string;
|
||||
initials?: string;
|
||||
email?: string;
|
||||
avatarUrl?: string;
|
||||
userId?: string;
|
||||
providerId?: string;
|
||||
};
|
||||
```
|
||||
|
||||
## Element Thread
|
||||
|
||||
```ts
|
||||
const thread = presentation.comments.addThread({ element }, bodyText, {
|
||||
position,
|
||||
});
|
||||
|
||||
const reply = thread.addReply(replyText);
|
||||
reply.toggleReaction(reactionText);
|
||||
thread.resolve();
|
||||
thread.reopen();
|
||||
```
|
||||
|
||||
## Thread Inline Types
|
||||
|
||||
```ts
|
||||
type CommentTarget =
|
||||
| { slide: Slide }
|
||||
| { element: Shape | ImageElement | Table | ChartElement }
|
||||
| { textRange: TextRange }
|
||||
| { textMatch: { element: Shape; query: string; occurrence?: number } };
|
||||
|
||||
type ThreadAddOptions = {
|
||||
author?: Person | PersonConfig | { id: string };
|
||||
createdAt?: string;
|
||||
position?: { x: number; y: number; unit?: "px" | "emu" };
|
||||
};
|
||||
```
|
||||
|
||||
## Slide And Text Threads
|
||||
|
||||
```ts
|
||||
presentation.comments.addThread({ slide }, bodyText, { position });
|
||||
|
||||
presentation.comments.addThread(
|
||||
{ textMatch: { element, query, occurrence } },
|
||||
bodyText,
|
||||
);
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Add a review comment to exact text.
|
||||
presentation.comments.setSelf({
|
||||
displayName: "Presentation Reviewer",
|
||||
initials: "PR",
|
||||
email: "reviewer@example.com",
|
||||
});
|
||||
|
||||
const thread = presentation.comments.addThread(
|
||||
{ textMatch: { element: titleShape, query: "Q4", occurrence: 0 } },
|
||||
"Check whether this should be FY2026 Q1.",
|
||||
);
|
||||
thread.addReply("Leaving this unresolved for owner review.");
|
||||
```
|
||||
|
||||
```ts
|
||||
// Resolve an imported thread after an edit.
|
||||
const self = presentation.comments.setSelf({
|
||||
displayName: "Presentation Editor",
|
||||
initials: "PE",
|
||||
email: "editor@example.com",
|
||||
});
|
||||
|
||||
const thread = presentation.resolve(threadAnchorId);
|
||||
thread.addReply("Updated the chart title and source note.", { author: self });
|
||||
thread.resolve(self);
|
||||
|
||||
const verified = await presentation.inspect({
|
||||
kind: "thread",
|
||||
target: { id: threadAnchorId, beforeLines: 0, afterLines: 2 },
|
||||
maxChars: 2000,
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+225
@@ -0,0 +1,225 @@
|
||||
# Connectors
|
||||
|
||||
`slide.shapes.connect` creates connector lines that stay attached to slide
|
||||
shapes. Use it for arrows, flow links, callouts, dependency lines, and other
|
||||
relationships between positioned shapes.
|
||||
|
||||
Use direct `geometry: "connector"` creation only when you need exact connection
|
||||
site indexes.
|
||||
|
||||
## Connect Shapes
|
||||
|
||||
```ts
|
||||
const connector = slide.shapes.connect(sourceShape, targetShape, {
|
||||
kind: "elbow",
|
||||
fromSide: "right",
|
||||
toSide: "left",
|
||||
line: { style: "solid", fill: "slate-500", width: 2 },
|
||||
head: { type: "arrow", width: "med", length: "med" },
|
||||
});
|
||||
```
|
||||
|
||||
Endpoints accept shape facades or shape ids. `fromSide` and `toSide` accept
|
||||
`"top"`, `"left"`, `"bottom"`, or `"right"` and resolve to the nearest
|
||||
connection site for that shape geometry. When you omit side and index options,
|
||||
the API chooses a connection pair from the relative shape positions.
|
||||
|
||||
`kind` defaults to `"elbow"` for `slide.shapes.connect(...)`.
|
||||
|
||||
## Connect Inline Types
|
||||
|
||||
```ts
|
||||
type ConnectorSide = "top" | "left" | "bottom" | "right";
|
||||
|
||||
type ShapeConnectOptions = {
|
||||
kind?:
|
||||
| "straight"
|
||||
| "elbow"
|
||||
| "elbow2"
|
||||
| "elbow3"
|
||||
| "elbow4"
|
||||
| "elbow5"
|
||||
| "curved";
|
||||
fromSide?: ConnectorSide;
|
||||
toSide?: ConnectorSide;
|
||||
fromIdx?: number;
|
||||
toIdx?: number;
|
||||
line?: LineConfig;
|
||||
head?: LineEndConfig;
|
||||
tail?: LineEndConfig;
|
||||
cap?: "flat" | "round" | "square";
|
||||
join?: "round" | "bevel" | "miter";
|
||||
};
|
||||
|
||||
type LineEndConfig = {
|
||||
type?: "none" | "triangle" | "stealth" | "diamond" | "oval" | "arrow";
|
||||
width?: "sm" | "med" | "lg";
|
||||
length?: "sm" | "med" | "lg";
|
||||
};
|
||||
```
|
||||
|
||||
## Anchor Choice
|
||||
|
||||
Use side anchors for readable authoring:
|
||||
|
||||
```ts
|
||||
slide.shapes.connect(sourceShape, targetShape, {
|
||||
fromSide: "bottom",
|
||||
toSide: "top",
|
||||
kind: "elbow",
|
||||
line: { style: "dashed", fill: "accent1", width: 2 },
|
||||
});
|
||||
```
|
||||
|
||||
Use explicit connection site indexes when you need an exact preset-geometry site:
|
||||
|
||||
```ts
|
||||
const fromIdx = slide.shapes.getConnectionSiteIndex(sourceShape, "right");
|
||||
const toIdx = slide.shapes.getConnectionSiteIndex(targetShape, "left");
|
||||
|
||||
slide.shapes.connect(sourceShape.id, targetShape.id, {
|
||||
fromIdx,
|
||||
toIdx,
|
||||
kind: "straight",
|
||||
line: { style: "solid", fill: "slate-700", width: 2 },
|
||||
});
|
||||
```
|
||||
|
||||
Connection site indexes are PowerPoint preset geometry connection points. Side
|
||||
anchors map to the closest useful preset site for rectangles, ellipses, and
|
||||
other shapes.
|
||||
|
||||
## Direct Connector Shape
|
||||
|
||||
```ts
|
||||
const connector = slide.shapes.add({
|
||||
geometry: "connector",
|
||||
kind: "curved",
|
||||
from: sourceShape,
|
||||
fromIdx: 3,
|
||||
to: targetShape,
|
||||
toIdx: 1,
|
||||
line: { style: "solid", fill: "accent1", width: 2 },
|
||||
tail: { type: "triangle", width: "med", length: "med" },
|
||||
});
|
||||
```
|
||||
|
||||
## Unattached Connector
|
||||
|
||||
```ts
|
||||
const arrow = slide.shapes.add({
|
||||
geometry: "connector",
|
||||
kind: "straight",
|
||||
position: { left: 40, top: 160, width: 240, height: 0 },
|
||||
line: { fill: "accent1", width: 2 },
|
||||
tail: { type: "arrow" },
|
||||
});
|
||||
```
|
||||
|
||||
## One Attached Endpoint
|
||||
|
||||
```ts
|
||||
const connector = slide.shapes.add({
|
||||
geometry: "connector",
|
||||
kind: "straight",
|
||||
from: sourceShape,
|
||||
fromIdx: slide.shapes.getConnectionSiteIndex(sourceShape, "right"),
|
||||
position: { left: 40, top: 160, width: 240, height: 0 },
|
||||
line: { fill: "accent1", width: 2 },
|
||||
tail: { type: "arrow" },
|
||||
});
|
||||
```
|
||||
|
||||
## Direct Connector Inline Type
|
||||
|
||||
```ts
|
||||
type ConnectorConfig = {
|
||||
geometry: "connector";
|
||||
from?: Shape | string;
|
||||
fromIdx?: number;
|
||||
to?: Shape | string;
|
||||
toIdx?: number;
|
||||
position?: PositionConfig;
|
||||
kind?:
|
||||
| "straight"
|
||||
| "elbow"
|
||||
| "elbow2"
|
||||
| "elbow3"
|
||||
| "elbow4"
|
||||
| "elbow5"
|
||||
| "curved";
|
||||
line?: LineConfig;
|
||||
head?: LineEndConfig;
|
||||
tail?: LineEndConfig;
|
||||
cap?: "flat" | "round" | "square";
|
||||
join?: "round" | "bevel" | "miter";
|
||||
};
|
||||
```
|
||||
|
||||
Connectors support line styling and line ends, but not `borderRadius` or
|
||||
`shadow`.
|
||||
|
||||
## Edit Existing Connectors
|
||||
|
||||
```ts
|
||||
const connector = presentation.resolve(connectorAnchorId);
|
||||
const nextFromIdx = slide.shapes.getConnectionSiteIndex(
|
||||
nextSourceShape,
|
||||
"right",
|
||||
);
|
||||
const nextToIdx = slide.shapes.getConnectionSiteIndex(nextTargetShape, "left");
|
||||
|
||||
connector.setConnectorFrom(nextSourceShape, nextFromIdx);
|
||||
connector.setConnectorTo(nextTargetShape.id, nextToIdx);
|
||||
connector.line = { style: "solid", fill: "slate-800", width: 2 };
|
||||
connector.bringToFront();
|
||||
```
|
||||
|
||||
Use `presentation.inspect({ kind: "shape", search })` to find connector anchor
|
||||
ids. Connector facades expose `connector`, `connectorLineStyle`,
|
||||
`connectorHead`, and `connectorTail` for readback.
|
||||
|
||||
## Routing And Ordering
|
||||
|
||||
New connectors are sent behind shapes by default so boxes and labels remain
|
||||
readable. Call `connector.bringToFront()` when the connector should sit above
|
||||
other elements.
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Arrow from one card to another.
|
||||
slide.shapes.connect(sourceCard, targetCard, {
|
||||
kind: "elbow",
|
||||
fromSide: "right",
|
||||
toSide: "left",
|
||||
line: { style: "solid", fill: "slate-500", width: 2 },
|
||||
head: { type: "arrow", width: "med", length: "med" },
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Bidirectional relationship line.
|
||||
slide.shapes.connect(leftShape, rightShape, {
|
||||
kind: "straight",
|
||||
fromSide: "right",
|
||||
toSide: "left",
|
||||
line: { style: "dashed", fill: "accent2", width: 2 },
|
||||
head: { type: "arrow", width: "sm", length: "sm" },
|
||||
tail: { type: "arrow", width: "sm", length: "sm" },
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Curved connector with explicit preset connection sites.
|
||||
slide.shapes.add({
|
||||
geometry: "connector",
|
||||
kind: "curved",
|
||||
from: sourceShape,
|
||||
fromIdx: slide.shapes.getConnectionSiteIndex(sourceShape, "bottom"),
|
||||
to: targetShape,
|
||||
toIdx: slide.shapes.getConnectionSiteIndex(targetShape, "top"),
|
||||
line: { style: "solid", fill: "accent1", width: 2 },
|
||||
tail: { type: "triangle", width: "med", length: "med" },
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+187
@@ -0,0 +1,187 @@
|
||||
# Imported Deck Cookbook
|
||||
|
||||
Use these recipes when editing an existing presentation. The goal is targeted,
|
||||
type-aware edits with a preview and a small verification snapshot.
|
||||
|
||||
For imported decks, render the affected slide before and after focused edits,
|
||||
export layout JSON before and after when object placement matters, and use a
|
||||
deck montage before/after when a change may affect multiple slides.
|
||||
|
||||
## Load A PPTX
|
||||
|
||||
```ts
|
||||
const presentation = await Presentation.load("input.pptx");
|
||||
```
|
||||
|
||||
## Edit Loop
|
||||
|
||||
```ts
|
||||
const before = await presentation.inspect({
|
||||
kind: "slide,textbox,shape,image,table,chart,notes,thread,layout",
|
||||
search: "Revenue",
|
||||
maxChars: 8000,
|
||||
});
|
||||
|
||||
// Pick an exact anchor id from `before`; use inspect ids instead of slide indexes.
|
||||
const target = presentation.resolve(anchorId);
|
||||
|
||||
// slideAnchorId is the `sl/...` id from inspect for the affected slide.
|
||||
const slide = presentation.resolve(slideAnchorId);
|
||||
const previewBefore = await slide.export({ format: "png", scale: 2 });
|
||||
const layoutBefore = await slide.export({ format: "layout" });
|
||||
const montageBefore = await presentation.export({
|
||||
format: "webp",
|
||||
montage: true,
|
||||
scale: 1,
|
||||
});
|
||||
|
||||
target.text.replace("Revenue", "Revenue outlook");
|
||||
|
||||
const previewAfter = await slide.export({ format: "png", scale: 2 });
|
||||
const layoutAfter = await slide.export({ format: "layout" });
|
||||
const montageAfter = await presentation.export({
|
||||
format: "webp",
|
||||
montage: true,
|
||||
scale: 1,
|
||||
});
|
||||
|
||||
const after = await presentation.inspect({
|
||||
target: { id: anchorId, beforeLines: 2, afterLines: 2 },
|
||||
kind: "textbox,shape",
|
||||
maxChars: 2000,
|
||||
});
|
||||
```
|
||||
|
||||
## Placeholder Edit
|
||||
|
||||
```ts
|
||||
const layoutSnapshot = await presentation.inspect({
|
||||
kind: "slide,layout,textbox,shape",
|
||||
search: "Click to add title",
|
||||
maxChars: 6000,
|
||||
});
|
||||
|
||||
// slideAnchorId is the `sl/...` id from inspect for this slide.
|
||||
const slide = presentation.resolve(slideAnchorId);
|
||||
const title = slide.placeholders.getItem("title");
|
||||
title.text = "Updated executive summary";
|
||||
```
|
||||
|
||||
Edit a slide placeholder for a local content change. Edit a layout or master
|
||||
only when the intended change is global.
|
||||
Inspect records use 1-based `slide` numbers for display; `slides.getItem(index)`
|
||||
is 0-based. Prefer resolving the `sl/...` anchor from inspect.
|
||||
|
||||
## Master/Layout Blast Radius
|
||||
|
||||
```ts
|
||||
// layoutId comes from inspect/layout export metadata; use it for search and comparison.
|
||||
const affected = await presentation.inspect({
|
||||
kind: "slide,layout",
|
||||
search: layoutId,
|
||||
maxChars: 6000,
|
||||
});
|
||||
```
|
||||
|
||||
Inspect affected layouts and slides before changing a master, layout, theme
|
||||
color, or placeholder geometry. Use layout ids for comparison/search, then
|
||||
resolve affected slides through their `sl/...` ids before editing. These edits
|
||||
can update many slides.
|
||||
|
||||
## Preserve Imported Image Placement
|
||||
|
||||
```ts
|
||||
const image = presentation.resolve(imageAnchorId);
|
||||
const oldFrame = image.frame;
|
||||
const oldCrop = image.crop;
|
||||
const oldFit = image.fit;
|
||||
const oldAlt = image.alt;
|
||||
const oldPrompt = image.prompt;
|
||||
const oldGeometry = image.geometry;
|
||||
const oldBorderRadius = image.borderRadius;
|
||||
const oldRotation = image.rotation;
|
||||
const oldFlipHorizontal = image.flipHorizontal;
|
||||
const oldFlipVertical = image.flipVertical;
|
||||
const oldLockAspectRatio = image.lockAspectRatio;
|
||||
|
||||
image.replace({
|
||||
blob: replacementBytes,
|
||||
contentType: "image/png",
|
||||
alt: oldAlt ?? "Updated product screenshot",
|
||||
...(oldFit ? { fit: oldFit } : {}),
|
||||
...(oldPrompt ? { prompt: oldPrompt } : {}),
|
||||
});
|
||||
image.frame = oldFrame;
|
||||
image.crop = oldCrop;
|
||||
image.geometry = oldGeometry;
|
||||
image.borderRadius = oldBorderRadius;
|
||||
image.rotation = oldRotation;
|
||||
image.flipHorizontal = oldFlipHorizontal;
|
||||
image.flipVertical = oldFlipVertical;
|
||||
image.lockAspectRatio = oldLockAspectRatio;
|
||||
```
|
||||
|
||||
Render the slide after replacement and verify subject crop, aspect ratio,
|
||||
rounded mask, and legibility. Preserve placement-affecting properties unless the
|
||||
edit explicitly changes them. Concrete source replacements produce concrete
|
||||
images; pass `prompt` when it should remain available as regeneration metadata.
|
||||
|
||||
## Existing Table And Chart Edits
|
||||
|
||||
```ts
|
||||
const table = presentation.resolve(tableAnchorId);
|
||||
table.cells.set(1, 2, "$4.2M");
|
||||
table.getCell(1, 2).text.style = "Body Small";
|
||||
|
||||
const chart = presentation.resolve(chartAnchorId);
|
||||
chart.xAxis = { title: "Quarter" };
|
||||
chart.yAxis = { numberFormatCode: "$#,##0M" };
|
||||
chart.series.getItemAt(0).values = [3.1, 3.7, 4.2, 4.8];
|
||||
|
||||
await presentation.inspect({
|
||||
kind: "table,chart",
|
||||
target: { id: chartAnchorId, beforeLines: 3, afterLines: 3 },
|
||||
maxChars: 3000,
|
||||
});
|
||||
```
|
||||
|
||||
If an imported chart or table resolves as an image, preserve it as an image or
|
||||
rebuild it as a native chart/table intentionally.
|
||||
|
||||
## Comments And Speaker Notes
|
||||
|
||||
```ts
|
||||
const review = await presentation.inspect({
|
||||
kind: "thread,notes,slide,textbox",
|
||||
search: "TODO",
|
||||
maxChars: 8000,
|
||||
});
|
||||
|
||||
const self = presentation.comments.setSelf({
|
||||
displayName: "Presentation Editor",
|
||||
initials: "PE",
|
||||
email: "presentation@example.com",
|
||||
});
|
||||
|
||||
const thread = presentation.resolve(commentThreadAnchorId);
|
||||
thread.addReply("Addressed in this revision.", { author: self });
|
||||
thread.resolve(self);
|
||||
|
||||
const notes = presentation.resolve(notesAnchorId);
|
||||
const existing = notes.text.trim();
|
||||
notes.text = [
|
||||
existing,
|
||||
"Opening: summarize the revised revenue outlook.",
|
||||
"Call out risk on enterprise timing.",
|
||||
].filter(Boolean).join("\n");
|
||||
notes.setVisible(true);
|
||||
|
||||
const verified = await presentation.inspect({
|
||||
kind: "thread,notes",
|
||||
target: { id: slideAnchorId, beforeLines: 1, afterLines: 4 },
|
||||
maxChars: 3000,
|
||||
});
|
||||
```
|
||||
|
||||
Keep unrelated threads and speaker notes intact unless the task explicitly asks
|
||||
to clear them.
|
||||
Generated
Vendored
+419
@@ -0,0 +1,419 @@
|
||||
# Presentation Layout Cookbook
|
||||
|
||||
First-principles recipes for arranging editable presentation JSX. These are
|
||||
layout mechanics, not deck archetypes.
|
||||
|
||||
Examples start after `presentation` and `slide` exist. Prefer string sizing
|
||||
(`"fill"`, `"hug"`) and local track values over helper imports.
|
||||
|
||||
Use `1280 x 720` as the default canvas unless the task or source deck requires
|
||||
another size:
|
||||
|
||||
```ts
|
||||
const SLIDE_W = 1280;
|
||||
const SLIDE_H = 720;
|
||||
const PAGE = { left: 72, top: 64, width: 1136, height: 592 };
|
||||
```
|
||||
|
||||
## Choose The Primitive
|
||||
|
||||
| Need | Use |
|
||||
| --- | --- |
|
||||
| Horizontal flow | `row` |
|
||||
| Vertical flow | `column` |
|
||||
| Column/row spans | `grid` |
|
||||
| Overlays or background plates | `layers` |
|
||||
| Surface plus child content | `box` |
|
||||
| Fixed placement on a slide | `slide.compose(node, { frame })` or facade `position` |
|
||||
|
||||
Use `frame` for the outer composed region. Inside the region, use `row`,
|
||||
`column`, `grid`, and `layers` so content stays resizable and inspectable. Use
|
||||
`layers` plus image `geometry`/`borderRadius` for overlays, scrims, and masked
|
||||
image compositions inside a region.
|
||||
|
||||
## Sizing Vocabulary
|
||||
|
||||
```tsx
|
||||
<box width="fill" height="fill" /> // claim available space
|
||||
<box width="hug" height="hug" /> // fit its children
|
||||
<box width={320} height={180} /> // fixed pixels
|
||||
```
|
||||
|
||||
Equal siblings fill equally:
|
||||
|
||||
```tsx
|
||||
<row width="fill" height={160} gap={24} align="stretch">
|
||||
<box width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
</row>
|
||||
```
|
||||
|
||||
One fixed sibling plus one flexible sibling:
|
||||
|
||||
```tsx
|
||||
<row width="fill" height="fill" gap={32} align="stretch">
|
||||
<column width={360} height="fill" gap={16}>
|
||||
<paragraph className="text-slate-950 text-4xl font-bold">Fixed rail</paragraph>
|
||||
<paragraph className="text-slate-600 text-lg">This column stays 360px wide.</paragraph>
|
||||
</column>
|
||||
<box width="fill" height="fill" className="bg-slate-100 rounded-2xl" />
|
||||
</row>
|
||||
```
|
||||
|
||||
## Padding And Gutters
|
||||
|
||||
Use object padding for asymmetric page gutters. Use numeric padding for all
|
||||
sides.
|
||||
|
||||
Use an 8px spacing scale unless matching a source deck: common gaps are `16`,
|
||||
`24`, `28`, and `32`. Common page gutters use `PAGE`; pass `baseUnit: 8` to
|
||||
`slide.compose` when examples rely on this scale.
|
||||
|
||||
```tsx
|
||||
<column
|
||||
width="fill"
|
||||
height="fill"
|
||||
padding={{ top: 64, right: 80, bottom: 56, left: 80 }}
|
||||
gap={28}
|
||||
>
|
||||
<paragraph className="text-slate-950 text-5xl font-bold">Page title</paragraph>
|
||||
<box width="fill" height="fill" className="bg-white rounded-xl" />
|
||||
</column>
|
||||
```
|
||||
|
||||
```tsx
|
||||
<box width="fill" height="hug" padding={{ x: 28, y: 18 }} className="bg-sky-50 rounded-xl">
|
||||
<paragraph className="text-sky-950 text-xl font-bold">Compact padded box</paragraph>
|
||||
</box>
|
||||
```
|
||||
|
||||
## Rows
|
||||
|
||||
`row` lays out children left to right. `justify` distributes along the
|
||||
horizontal axis. `align` controls vertical alignment.
|
||||
|
||||
```tsx
|
||||
<row width="fill" height={72} align="center" justify="between">
|
||||
<paragraph className="text-slate-950 text-2xl font-bold">Left</paragraph>
|
||||
<paragraph className="text-slate-500 text-sm">Right</paragraph>
|
||||
</row>
|
||||
```
|
||||
|
||||
Center a child:
|
||||
|
||||
```tsx
|
||||
<row width="fill" height={220} align="center" justify="center">
|
||||
<box width={360} height={120} className="bg-white rounded-xl shadow-sm" />
|
||||
</row>
|
||||
```
|
||||
|
||||
Stretch all children to the row height:
|
||||
|
||||
```tsx
|
||||
<row width="fill" height={240} gap={20} align="stretch">
|
||||
<box width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
</row>
|
||||
```
|
||||
|
||||
## Columns
|
||||
|
||||
`column` lays out children top to bottom. `justify` distributes along the
|
||||
vertical axis. `align` controls horizontal alignment.
|
||||
|
||||
```tsx
|
||||
<column width="fill" height="fill" justify="between" gap={24}>
|
||||
<paragraph className="text-slate-950 text-4xl font-bold">Top block</paragraph>
|
||||
<paragraph className="text-slate-600 text-lg">Bottom block</paragraph>
|
||||
</column>
|
||||
```
|
||||
|
||||
Metadata row, content region, and closing rule:
|
||||
|
||||
```tsx
|
||||
<column width="fill" height="fill" gap={24}>
|
||||
<row width="fill" height={72} align="center" justify="between">
|
||||
<paragraph className="text-slate-500 text-sm font-bold">HEADER</paragraph>
|
||||
<paragraph className="text-slate-400 text-sm">Source</paragraph>
|
||||
</row>
|
||||
<box width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<rule stroke="slate-200" weight={1} />
|
||||
</column>
|
||||
```
|
||||
|
||||
## Three Columns
|
||||
|
||||
Use a `row` when all columns are equal or only one side is fixed.
|
||||
|
||||
```tsx
|
||||
slide.compose(
|
||||
<row name="three-column-layout" width="fill" height="fill" gap={24} align="stretch">
|
||||
<column name="column-a" width="fill" height="fill" gap={12}>
|
||||
<paragraph className="text-slate-950 text-2xl font-bold">Column A</paragraph>
|
||||
<paragraph className="text-slate-600 text-base">Editable body copy.</paragraph>
|
||||
</column>
|
||||
<column name="column-b" width="fill" height="fill" gap={12}>
|
||||
<paragraph className="text-slate-950 text-2xl font-bold">Column B</paragraph>
|
||||
<paragraph className="text-slate-600 text-base">Editable body copy.</paragraph>
|
||||
</column>
|
||||
<column name="column-c" width="fill" height="fill" gap={12}>
|
||||
<paragraph className="text-slate-950 text-2xl font-bold">Column C</paragraph>
|
||||
<paragraph className="text-slate-600 text-base">Editable body copy.</paragraph>
|
||||
</column>
|
||||
</row>,
|
||||
{ frame: PAGE, baseUnit: 8 },
|
||||
);
|
||||
```
|
||||
|
||||
Use fixed rails when the center should absorb resize:
|
||||
|
||||
```tsx
|
||||
<row width="fill" height="fill" gap={24} align="stretch">
|
||||
<box width={240} height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box width="fill" height="fill" className="bg-white rounded-xl" />
|
||||
<box width={240} height="fill" className="bg-slate-50 rounded-xl" />
|
||||
</row>
|
||||
```
|
||||
|
||||
## Twelve-Column Grid
|
||||
|
||||
Use `grid` when child spans matter. Keep `fr` and fixed track objects local and
|
||||
obvious; use the literal `"auto"` for auto tracks:
|
||||
|
||||
```tsx
|
||||
const GRID_12 = Array.from(
|
||||
{ length: 12 },
|
||||
() => ({ mode: "fr", value: 1 }) as const,
|
||||
);
|
||||
```
|
||||
|
||||
Use a 12-column grid when spans communicate structure. Spans in a row usually
|
||||
add to 12, such as `4/4/4`, `3/6/3`, or `4/8`. Put vertical content inside
|
||||
`column` children and surfaces inside `box` children. Use a simple `row` when
|
||||
every column is equal and no span semantics are needed.
|
||||
|
||||
Full-width heading plus three equal columns:
|
||||
|
||||
```tsx
|
||||
<grid
|
||||
width="fill"
|
||||
height="fill"
|
||||
columns={GRID_12}
|
||||
rows={["auto", { mode: "fr", value: 1 }]}
|
||||
columnGap={24}
|
||||
rowGap={28}
|
||||
>
|
||||
<paragraph columnSpan={12} className="text-slate-950 text-5xl font-bold">
|
||||
Full-width heading
|
||||
</paragraph>
|
||||
<box columnSpan={4} width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box columnSpan={4} width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box columnSpan={4} width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
</grid>
|
||||
```
|
||||
|
||||
Four/eight split:
|
||||
|
||||
```tsx
|
||||
<grid width="fill" height="fill" columns={GRID_12} columnGap={28}>
|
||||
<column columnSpan={4} width="fill" height="fill" gap={16}>
|
||||
<paragraph className="text-slate-950 text-4xl font-bold">Left span</paragraph>
|
||||
<paragraph className="text-slate-600 text-lg">Uses 4 of 12 columns.</paragraph>
|
||||
</column>
|
||||
<box columnSpan={8} width="fill" height="fill" className="bg-sky-50 rounded-2xl" />
|
||||
</grid>
|
||||
```
|
||||
|
||||
Three/six/three split:
|
||||
|
||||
```tsx
|
||||
<grid width="fill" height="fill" columns={GRID_12} columnGap={20}>
|
||||
<box columnSpan={3} width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box columnSpan={6} width="fill" height="fill" className="bg-white rounded-xl shadow-sm" />
|
||||
<box columnSpan={3} width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
</grid>
|
||||
```
|
||||
|
||||
Rows plus row spans:
|
||||
|
||||
```tsx
|
||||
<grid
|
||||
width="fill"
|
||||
height="fill"
|
||||
columns={GRID_12}
|
||||
rows={["auto", { mode: "fr", value: 1 }, { mode: "fr", value: 1 }]}
|
||||
columnGap={24}
|
||||
rowGap={24}
|
||||
>
|
||||
<paragraph columnSpan={12} className="text-slate-950 text-4xl font-bold">
|
||||
Heading
|
||||
</paragraph>
|
||||
<box columnSpan={8} rowSpan={2} width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box columnSpan={4} width="fill" height="fill" className="bg-sky-50 rounded-xl" />
|
||||
<box columnSpan={4} width="fill" height="fill" className="bg-emerald-50 rounded-xl" />
|
||||
</grid>
|
||||
```
|
||||
|
||||
Mixed fixed and flexible tracks:
|
||||
|
||||
```tsx
|
||||
<grid
|
||||
width="fill"
|
||||
height="fill"
|
||||
columns={[
|
||||
{ mode: "fixed", value: 280 },
|
||||
{ mode: "fr", value: 1 },
|
||||
{ mode: "fixed", value: 220 },
|
||||
]}
|
||||
columnGap={24}
|
||||
>
|
||||
<box width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box width="fill" height="fill" className="bg-white rounded-xl shadow-sm" />
|
||||
<box width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
</grid>
|
||||
```
|
||||
|
||||
## Grid Alignment
|
||||
|
||||
Use `alignItems` and `justifyItems` for grid child alignment. If one child
|
||||
needs different alignment, wrap it in a `row`, `column`, or `box`.
|
||||
|
||||
| Node | Main axis | Cross axis | Distribution prop | Cross-axis prop | Defaults |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `row` | horizontal | vertical | `justify`: `start`, `center`, `end`, `between` | `align`: `start`, `center`, `end`, `stretch` | `start` / `start` |
|
||||
| `column` | vertical | horizontal | `justify`: `start`, `center`, `end`, `between` | `align`: `start`, `center`, `end`, `stretch` | `start` / `start` |
|
||||
| `grid` | tracks | cells | `justifyItems`: `start`, `center`, `end`, `stretch` | `alignItems`: `start`, `center`, `end`, `stretch` | `stretch` / `stretch` |
|
||||
| `layers` | shared frame | shared frame | `justifyItems`: `start`, `center`, `end`, `stretch` | `alignItems`: `start`, `center`, `end`, `stretch` | `stretch` / `stretch` |
|
||||
|
||||
```tsx
|
||||
<grid
|
||||
width="fill"
|
||||
height={260}
|
||||
columns={[{ mode: "fr", value: 1 }, { mode: "fr", value: 1 }]}
|
||||
rows={[{ mode: "fr", value: 1 }]}
|
||||
columnGap={24}
|
||||
alignItems="center"
|
||||
justifyItems="stretch"
|
||||
>
|
||||
<box height={120} className="bg-slate-50 rounded-xl" />
|
||||
<box height="fill" className="bg-sky-50 rounded-xl" />
|
||||
</grid>
|
||||
```
|
||||
|
||||
## Layers
|
||||
|
||||
`layers` gives every child the same parent frame. Put visual backgrounds first,
|
||||
then overlays, then editable text.
|
||||
|
||||
```tsx
|
||||
<layers width="fill" height="fill">
|
||||
<image
|
||||
blob={backgroundBytes}
|
||||
contentType="image/jpeg"
|
||||
fit="cover"
|
||||
alt="Background"
|
||||
width="fill"
|
||||
height="fill"
|
||||
/>
|
||||
<shape geometry="rect" width="fill" height="fill" fill="black/45" />
|
||||
<column width={620} height="fill" padding={64} justify="end" gap={18}>
|
||||
<paragraph className="text-white text-5xl font-bold leading-tight">
|
||||
Editable headline
|
||||
</paragraph>
|
||||
<paragraph className="text-white/80 text-xl leading-relaxed">
|
||||
Editable supporting copy.
|
||||
</paragraph>
|
||||
</column>
|
||||
</layers>
|
||||
```
|
||||
|
||||
## Image Masks
|
||||
|
||||
Use image `geometry` for real clipping. Use `crop` plus `fit="cover"` when the
|
||||
subject should fill the mask.
|
||||
|
||||
Quick reference:
|
||||
|
||||
| Need | Use |
|
||||
| --- | --- |
|
||||
| Preserve the full image | `fit="contain"` |
|
||||
| Fill the frame and allow crop | `fit="cover"` |
|
||||
| Clip to a shape | `geometry="ellipse"` or `geometry="roundRect"` |
|
||||
| Rounded rectangle mask | `borderRadius="rounded-2xl"` |
|
||||
| Manual crop | `crop={{ left, top, right, bottom }}` with normalized `0..1` insets |
|
||||
|
||||
`crop` values are fractions removed from each source-image edge and are clamped.
|
||||
Overlays do not clip images; use image `geometry` or `borderRadius` for masks.
|
||||
|
||||
```tsx
|
||||
<image
|
||||
blob={portraitBytes}
|
||||
contentType="image/jpeg"
|
||||
alt="Portrait"
|
||||
geometry="ellipse"
|
||||
fit="cover"
|
||||
crop={{ left: 0.1, top: 0, right: 0.08, bottom: 0 }}
|
||||
width={240}
|
||||
height={240}
|
||||
/>
|
||||
```
|
||||
|
||||
Rounded rectangle image:
|
||||
|
||||
```tsx
|
||||
<image
|
||||
blob={photoBytes}
|
||||
contentType="image/jpeg"
|
||||
alt="Photo"
|
||||
fit="cover"
|
||||
width="fill"
|
||||
height={320}
|
||||
borderRadius="rounded-2xl"
|
||||
/>
|
||||
```
|
||||
|
||||
## Flow Versus Absolute Placement
|
||||
|
||||
Use flow for related content:
|
||||
|
||||
```tsx
|
||||
slide.compose(
|
||||
<column width="fill" height="fill" gap={20}>
|
||||
<paragraph className="text-slate-950 text-4xl font-bold">Title</paragraph>
|
||||
<row width="fill" height="fill" gap={24} align="stretch">
|
||||
<box width="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box width="fill" className="bg-slate-50 rounded-xl" />
|
||||
</row>
|
||||
</column>,
|
||||
{ frame: PAGE, baseUnit: 8 },
|
||||
);
|
||||
```
|
||||
|
||||
Use absolute positions for elements that must land at exact slide coordinates:
|
||||
|
||||
```ts
|
||||
slide.shapes.add({
|
||||
geometry: "rect",
|
||||
name: "fixed-accent-bar",
|
||||
position: { left: 0, top: 0, width: 12, height: 720 },
|
||||
fill: "accent1",
|
||||
line: { style: "solid", fill: "none", width: 0 },
|
||||
});
|
||||
```
|
||||
|
||||
## Verify Layout
|
||||
|
||||
Inspect the layout tree when spans or wrapping matter:
|
||||
|
||||
```ts
|
||||
const layout = await slide.export({ format: "layout" });
|
||||
const png = await slide.export({ format: "png", scale: 1 });
|
||||
const snapshot = await presentation.inspect({
|
||||
kind: "slide,textbox,shape,image,table,chart",
|
||||
maxChars: 8000,
|
||||
});
|
||||
```
|
||||
|
||||
Check the rendered PNG for clipping, overlap, broken image crops, and text
|
||||
that should have stayed editable.
|
||||
Generated
Vendored
+201
@@ -0,0 +1,201 @@
|
||||
# Fill And Line Configs
|
||||
|
||||
Fill configs style shapes, chart regions, table cells, slide backgrounds, lines,
|
||||
and text fills. Text outlines use `LineConfig`, so their `fill`/`color` fields
|
||||
accept the same fill forms.
|
||||
|
||||
## Fill Forms
|
||||
|
||||
```ts
|
||||
shape.fill = fillConfig;
|
||||
shape.line = lineConfig;
|
||||
```
|
||||
|
||||
Supported fill forms:
|
||||
|
||||
- Theme, hex, RGB/RGBA, Tailwind-like color, and transformed color strings.
|
||||
- `"none"` and `"transparent"`.
|
||||
- Gradient strings such as `linear(...)` and `radial(...)`.
|
||||
- `{ type: "none" }`.
|
||||
- `{ type: "solid", color, pattern }`.
|
||||
- `{ type: "gradient", gradientKind, angleDeg, stops }`.
|
||||
- `{ type: "image", imageReference, srcRect, fillRect, stretchFillRect }`.
|
||||
|
||||
## String Fill Shortcuts
|
||||
|
||||
Use string fills for compact JSX and facade setters:
|
||||
|
||||
```tsx
|
||||
<shape geometry="rect" fill="none" line={{ style: "solid", fill: "slate-300", width: 1 }} />
|
||||
<box fill="black/45" />
|
||||
<box fill="transparent" />
|
||||
<box fill="accent1+18/90" />
|
||||
<box fill="linear(135deg, #ffffff 0%, sky-100 58%, #ffffff/0 100%)" />
|
||||
<shape geometry="ellipse" fill="radial(white/80 0%, emerald-200/45 48%, emerald-700/0 100%)" />
|
||||
```
|
||||
|
||||
Use `fill="none"` when the object should have no fill. Use
|
||||
`fill="transparent"` when the object should keep an editable transparent solid
|
||||
fill.
|
||||
|
||||
`+` lightens theme/RGB colors, `-` darkens, and `/` sets opacity. Tailwind-like
|
||||
color tokens, theme aliases, gradients, shadows, and text style strings are
|
||||
summarized in `tokens.md`.
|
||||
|
||||
## Fill Inline Types
|
||||
|
||||
```ts
|
||||
type ThemeColorName =
|
||||
| "accent1" | "accent2" | "accent3" | "accent4" | "accent5" | "accent6"
|
||||
| "bg1" | "bg2" | "tx1" | "tx2" | "dk1" | "lt1" | "dk2" | "lt2"
|
||||
| "hlink" | "folHlink";
|
||||
|
||||
type ColorConfig =
|
||||
| string
|
||||
| { type: "rgb"; value: string; transform?: ColorTransform }
|
||||
| { type: "theme"; value: ThemeColorName; transform?: ColorTransform };
|
||||
|
||||
type ColorTransform = {
|
||||
opacity?: number; // 0..1 or 0..100
|
||||
lighten?: number; // 0..1 or 0..100
|
||||
darken?: number; // 0..1 or 0..100
|
||||
};
|
||||
|
||||
type FillConfig =
|
||||
| string
|
||||
| { type: "none" }
|
||||
| { type: "solid"; color: ColorConfig; pattern?: PatternConfig }
|
||||
| {
|
||||
type: "gradient";
|
||||
stops: Array<{ offset: number; color: ColorConfig }>; // offset 0..100000
|
||||
offsetScale?: 1 | 100000;
|
||||
angleDeg?: number;
|
||||
gradientKind?: "linear" | "path";
|
||||
}
|
||||
| {
|
||||
type: "image";
|
||||
imageReference: { id: string };
|
||||
alphaModFix?: number;
|
||||
stretchFillRect?: { l?: number; t?: number; r?: number; b?: number };
|
||||
fillRect?: { l?: number; t?: number; r?: number; b?: number };
|
||||
srcRect?: { l?: number; t?: number; r?: number; b?: number };
|
||||
};
|
||||
```
|
||||
|
||||
## Gradient
|
||||
|
||||
```ts
|
||||
const fillConfig = {
|
||||
type: "gradient",
|
||||
gradientKind,
|
||||
angleDeg,
|
||||
stops: [
|
||||
{ offset: startOffset, color: startColor },
|
||||
{ offset: endOffset, color: endColor },
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
Gradient offsets use `0` to `100000`.
|
||||
|
||||
## Pattern Fills
|
||||
|
||||
Patterns are available through object fill configs:
|
||||
|
||||
```ts
|
||||
shape.fill = {
|
||||
type: "solid",
|
||||
color: "white",
|
||||
pattern: { type: "diagonalCross", color: "slate-300/70" },
|
||||
};
|
||||
```
|
||||
|
||||
Common compact pattern names:
|
||||
|
||||
```text
|
||||
percent10, percent20, lightHorizontal, lightVertical, smallGrid, dotGrid,
|
||||
diagonalCross, narrowVertical, wave, smallCheck
|
||||
```
|
||||
|
||||
Supported pattern names:
|
||||
|
||||
```text
|
||||
none, solid, mediumGray, darkGray, lightGray, darkHorizontal, darkVertical,
|
||||
darkDown, darkUp, darkGrid, darkTrellis, lightHorizontal, lightVertical,
|
||||
lightDown, lightUp, lightGrid, lightTrellis, gray125, gray0625, percent5,
|
||||
percent10, percent20, percent25, percent30, percent40, percent50, percent60,
|
||||
percent70, percent75, percent80, percent90, horizontal, vertical,
|
||||
narrowHorizontal, narrowVertical, dashedHorizontal, dashedVertical, cross,
|
||||
largeGrid, smallGrid, dotGrid, downwardDiagonal, upwardDiagonal,
|
||||
wideDownwardDiagonal, wideUpwardDiagonal, dashedDownwardDiagonal,
|
||||
dashedUpwardDiagonal, diagonalCross, smallCheck, largeCheck, smallConfetti,
|
||||
largeConfetti, horizontalBrick, diagonalBrick, solidDiamond, openDiamond,
|
||||
dottedDiamond, plaid, sphere, weave, divot, shingle, wave, trellis, zigZag
|
||||
```
|
||||
|
||||
## Line
|
||||
|
||||
```ts
|
||||
const lineConfig = {
|
||||
style: lineStyle,
|
||||
fill: lineFill,
|
||||
width: lineWidthPx,
|
||||
};
|
||||
```
|
||||
|
||||
## Line Inline Type
|
||||
|
||||
```ts
|
||||
type LineConfig = {
|
||||
style: "solid" | "dashed" | "dotted" | "dash-dot" | "dash-dot-dot" | string;
|
||||
fill?: FillConfig;
|
||||
width?: number;
|
||||
color?: FillConfig; // alias for fill
|
||||
weight?: number; // alias for width
|
||||
};
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Linear background wash.
|
||||
slide.background.fill = "linear(0deg, #020617 0%, #2563eb 100%)";
|
||||
```
|
||||
|
||||
```ts
|
||||
// Soft radial spotlight behind a chart.
|
||||
chart.plotAreaFill = "radial(#dbeafe/90 0%, #ffffff/0 100%)";
|
||||
```
|
||||
|
||||
```ts
|
||||
// Exact gradient object.
|
||||
shape.fill = {
|
||||
type: "gradient",
|
||||
gradientKind: "linear",
|
||||
angleDeg: 35,
|
||||
offsetScale: 100000,
|
||||
stops: [
|
||||
{ offset: 0, color: "#ffffff" },
|
||||
{ offset: 100000, color: "sky-100" },
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
// Normalized gradient offsets.
|
||||
shape.fill = {
|
||||
type: "gradient",
|
||||
gradientKind: "linear",
|
||||
offsetScale: 1,
|
||||
stops: [
|
||||
{ offset: 0, color: "#ffffff" },
|
||||
{ offset: 1, color: "sky-100" },
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
// Hairline rule and muted border.
|
||||
shape.line = { style: "solid", fill: "slate-200", width: 1 };
|
||||
ruleShape.line = { style: "dashed", fill: "#94a3b8", width: 1 };
|
||||
```
|
||||
Generated
Vendored
+223
@@ -0,0 +1,223 @@
|
||||
# Help
|
||||
|
||||
Use `presentation.help(...)` to search the presentation JS API and template
|
||||
catalog. Help emits bounded NDJSON records for quick lookup during create, edit,
|
||||
and review workflows.
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const result = presentation.help(query, {
|
||||
search,
|
||||
include,
|
||||
maxChars,
|
||||
});
|
||||
console.log(result.ndjson);
|
||||
```
|
||||
|
||||
Example output for `query = "*"` with `include = ["index", "examples"]`:
|
||||
|
||||
```text
|
||||
{"kind":"api","name":"presentation.help","summary":"Search the presentation JS API and template catalog.","tags":["help","docs","examples","presentation.help"],"examples":[{"summary":"Find shape editing APIs","code":"const result = presentation.help('*', {\n search: 'slide.shapes.delete|shape.delete|slide.shapes.add|deleteAll',\n include: ['index', 'examples', 'notes'],\n maxChars: 12000,\n});\nconsole.log(result.ndjson);"}]}
|
||||
{"kind":"api","name":"slide.shapes.add","summary":"Add a preset/custom/connector shape to a slide.","tags":["shape","shapes.add","rectangle","ellipse","connector","slide.shapes.add"],"examples":[{"summary":"Create a styled rectangle","code":"const shape = slide.shapes.add({\n geometry: 'roundRect',\n position: { left: 72, top: 96, width: 320, height: 120 },\n fill: { type: 'solid', color: 'accent1' },\n line: { style: 'solid', fill: 'accent2', width: 2 },\n});\nshape.text = 'Launch plan';"}]}
|
||||
{"kind":"template","name":"agenda","summary":"Agenda slide with a title and list body.","examples":[{"summary":"Apply the agenda template","code":"presentation.apply(presentation.template('agenda'));"}]}
|
||||
```
|
||||
|
||||
Use API records to find facade names and examples; use template records with
|
||||
`presentation.template(name)`.
|
||||
|
||||
Common queries:
|
||||
|
||||
```text
|
||||
*, shape*, slide.shapes.add, chart xAxis, template*
|
||||
```
|
||||
|
||||
Query behavior:
|
||||
|
||||
```text
|
||||
* lists all matching API and template records
|
||||
shape* uses glob matching
|
||||
slide.shapes.add matches the exact dotted API name
|
||||
chart xAxis matches entries containing either word token
|
||||
template* lists template records only
|
||||
```
|
||||
|
||||
Use `search` as a case-insensitive regular expression over the JSON lines after
|
||||
the primary query has selected records:
|
||||
|
||||
```ts
|
||||
const focused = presentation.help("*", {
|
||||
search:
|
||||
"slide\\.shapes\\.delete|shape\\.delete|slide\\.shapes\\.add|deleteAll",
|
||||
include: ["index", "examples", "notes"],
|
||||
maxChars: 12000,
|
||||
});
|
||||
console.log(focused.ndjson);
|
||||
```
|
||||
|
||||
## Include
|
||||
|
||||
Default output includes index fields such as:
|
||||
|
||||
```text
|
||||
kind, name, summary, tags
|
||||
```
|
||||
|
||||
Useful include tokens:
|
||||
|
||||
```text
|
||||
index, examples, notes
|
||||
```
|
||||
|
||||
`include` accepts either an array or a comma-separated string:
|
||||
|
||||
```ts
|
||||
const shapeExamples = presentation.help("slide.shapes.add", {
|
||||
include: ["examples", "notes"],
|
||||
});
|
||||
|
||||
const templateExamples = presentation.help("template*", {
|
||||
include: "index,examples",
|
||||
});
|
||||
```
|
||||
|
||||
## Inline Type
|
||||
|
||||
```ts
|
||||
type PresentationHelpOptions = {
|
||||
include?: string[] | string;
|
||||
search?: string;
|
||||
maxChars?: number;
|
||||
};
|
||||
|
||||
type PresentationHelpResult = {
|
||||
ndjson: string;
|
||||
truncated: boolean;
|
||||
metadata: {
|
||||
revision: string;
|
||||
query: string;
|
||||
include: {
|
||||
requested?: string[] | string;
|
||||
tokens: string[];
|
||||
};
|
||||
search?: string;
|
||||
notices?: string[];
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
## Record Kinds
|
||||
|
||||
API records describe public JS facades and methods:
|
||||
|
||||
```text
|
||||
{"kind":"api","name":"slide.shapes.add","summary":"Add a preset/custom/connector shape to a slide.","tags":["shape","shapes.add","rectangle","ellipse","connector","slide.shapes.add"]}
|
||||
{"kind":"api","name":"shape.delete","summary":"Delete this shape from its slide.","tags":["shape","delete shape","remove shape","shape.delete"]}
|
||||
```
|
||||
|
||||
When examples are included, records focus on usage snippets:
|
||||
|
||||
```text
|
||||
{"kind":"api","name":"slide.shapes.add","examples":[{"summary":"Create a styled rectangle","code":"const shape = slide.shapes.add({\n geometry: 'roundRect',\n position: { left: 72, top: 96, width: 320, height: 120 },\n fill: { type: 'solid', color: 'accent1' },\n line: { style: 'solid', fill: 'accent2', width: 2 },\n});\nshape.text = 'Launch plan';"}],"notes":["Preset geometry values include rect, roundRect, ellipse, triangle, rightArrow, and many other PowerPoint shape names."]}
|
||||
```
|
||||
|
||||
Template records describe named template patches for
|
||||
`presentation.template(name)`:
|
||||
|
||||
```text
|
||||
{"kind":"template","name":"title-slide","summary":"Title + subtitle slide with centered text boxes."}
|
||||
{"kind":"template","name":"two-up","summary":"Two-column slide with left/right content boxes."}
|
||||
{"kind":"template","name":"agenda","summary":"Agenda slide with a title and list body."}
|
||||
```
|
||||
|
||||
If output exceeds `maxChars`, the final line is a notice record and
|
||||
`result.truncated` is `true`:
|
||||
|
||||
```text
|
||||
{"kind":"notice","message":"Truncated: omitted 93 lines. Increase maxChars or narrow query."}
|
||||
```
|
||||
|
||||
## Create/Edit Loop
|
||||
|
||||
```ts
|
||||
// Find the public API surface for the edit.
|
||||
const shapeHelp = presentation.help("shape*", {
|
||||
include: ["index", "examples", "notes"],
|
||||
maxChars: 8000,
|
||||
});
|
||||
|
||||
// Build with the documented JS facade.
|
||||
const slide = presentation.slides.add();
|
||||
const shape = slide.shapes.add({
|
||||
geometry: "roundRect",
|
||||
position: { left: 72, top: 96, width: 320, height: 120 },
|
||||
fill: { type: "solid", color: "accent1" },
|
||||
});
|
||||
shape.text = "Launch plan";
|
||||
|
||||
// Inspect the live deck after editing.
|
||||
const snapshot = await presentation.inspect({
|
||||
kind: "slide,textbox,shape",
|
||||
maxChars: 4000,
|
||||
});
|
||||
```
|
||||
|
||||
## Imported Templates
|
||||
|
||||
```ts
|
||||
const templates = presentation.help("template*", {
|
||||
include: ["index", "examples"],
|
||||
maxChars: 4000,
|
||||
});
|
||||
|
||||
presentation.apply(presentation.template("agenda"));
|
||||
```
|
||||
|
||||
Use template help to discover the available names before calling
|
||||
`presentation.template(name)`.
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// List the top-level deck APIs.
|
||||
const deckApis = presentation.help("presentation*", {
|
||||
include: "index",
|
||||
maxChars: 6000,
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Search broadly, then filter by regex.
|
||||
const hits = presentation.help("*", {
|
||||
search: "chart|axis|legend",
|
||||
include: ["index", "examples"],
|
||||
maxChars: 8000,
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Pull examples for one exact API.
|
||||
const examples = presentation.help("slide.charts.add", {
|
||||
include: ["examples", "notes"],
|
||||
maxChars: 4000,
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Pair help with inspect for focused edits.
|
||||
const help = presentation.help("shape.text.replace", {
|
||||
include: ["examples", "notes"],
|
||||
});
|
||||
const before = await presentation.inspect({
|
||||
kind: "textbox,shape",
|
||||
search: "Placeholder",
|
||||
maxChars: 4000,
|
||||
});
|
||||
const target = presentation.resolve(anchorId);
|
||||
target.text.replace("Placeholder", "Updated text");
|
||||
const after = await presentation.inspect({
|
||||
target: { id: anchorId, beforeLines: 2, afterLines: 2 },
|
||||
kind: "textbox,shape",
|
||||
maxChars: 2000,
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+286
@@ -0,0 +1,286 @@
|
||||
# Images
|
||||
|
||||
`slide.images` inserts image elements from local paths, bytes, data URLs, SVG, and prompts.
|
||||
|
||||
For embedded image output, use `blob={imageBytes}` with `contentType`. Download remote images
|
||||
first, then pass their local `path` or embedded `blob` bytes to `add` or `replace`.
|
||||
HTTP(S) sources are rejected without fetching them.
|
||||
|
||||
## Add Image
|
||||
|
||||
```ts
|
||||
const image = slide.images.add({
|
||||
blob: imageBytes,
|
||||
contentType: "image/png",
|
||||
alt: "Product screenshot",
|
||||
fit: "cover",
|
||||
position: { left: 72, top: 120, width: 520, height: 320 },
|
||||
crop: { left: 0.02, top: 0, right: 0.04, bottom: 0 },
|
||||
geometry: "roundRect",
|
||||
borderRadius: "rounded-2xl",
|
||||
});
|
||||
```
|
||||
|
||||
## Path Reference And Inline SVG
|
||||
|
||||
```ts
|
||||
const localImage = slide.images.add({
|
||||
path: "/absolute/path/to/product.png",
|
||||
alt: "Product screenshot from disk",
|
||||
fit: "cover",
|
||||
position: { left: 72, top: 120, width: 520, height: 320 },
|
||||
});
|
||||
|
||||
const icon = slide.images.add({
|
||||
svg: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="#2563eb"/></svg>',
|
||||
alt: "Blue status icon",
|
||||
position: { left: 620, top: 120, width: 48, height: 48 },
|
||||
});
|
||||
```
|
||||
|
||||
## Image Inline Types
|
||||
|
||||
```ts
|
||||
type ImageSource =
|
||||
| { path: string; prompt?: string }
|
||||
| { svg: string; prompt?: string }
|
||||
| { blob: ArrayBuffer | Uint8Array; prompt?: string }
|
||||
| { dataUrl: string; prompt?: string }
|
||||
| { prompt: string };
|
||||
|
||||
type ImageAddOptions = ImageSource & {
|
||||
alt?: string;
|
||||
fit?: "contain" | "cover";
|
||||
contentType?: string;
|
||||
position?: { left?: number; top?: number; width?: number; height?: number };
|
||||
frame?: { left?: number; top?: number; width?: number; height?: number };
|
||||
crop?: { left: number | string; top: number | string; right: number | string; bottom: number | string };
|
||||
geometry?: string; // common: "rect", "roundRect", "ellipse"; full list is the shape preset list
|
||||
borderRadius?: number | string; // number = pixels; string = supported rounded-* token
|
||||
};
|
||||
```
|
||||
|
||||
`position` and `frame` use the same pixel shape. Use either spelling; prefer
|
||||
`position` in add calls and `frame` when preserving imported placement.
|
||||
|
||||
## Resolved From Inspect
|
||||
|
||||
```ts
|
||||
const image = presentation.resolve("im/c3d4e5f6");
|
||||
const oldFrame = image.frame;
|
||||
const oldCrop = image.crop;
|
||||
const oldFit = image.fit;
|
||||
const oldAlt = image.alt;
|
||||
const oldPrompt = image.prompt;
|
||||
const oldGeometry = image.geometry;
|
||||
const oldBorderRadius = image.borderRadius;
|
||||
const oldRotation = image.rotation;
|
||||
const oldFlipHorizontal = image.flipHorizontal;
|
||||
const oldFlipVertical = image.flipVertical;
|
||||
const oldLockAspectRatio = image.lockAspectRatio;
|
||||
|
||||
image.replace({
|
||||
blob: nextBytes,
|
||||
contentType: "image/png",
|
||||
alt: oldAlt ?? "Updated screenshot",
|
||||
...(oldFit ? { fit: oldFit } : {}),
|
||||
...(oldPrompt ? { prompt: oldPrompt } : {}),
|
||||
});
|
||||
image.frame = oldFrame;
|
||||
image.crop = oldCrop;
|
||||
image.geometry = oldGeometry;
|
||||
image.borderRadius = oldBorderRadius;
|
||||
image.rotation = oldRotation;
|
||||
image.flipHorizontal = oldFlipHorizontal;
|
||||
image.flipVertical = oldFlipVertical;
|
||||
image.lockAspectRatio = oldLockAspectRatio;
|
||||
```
|
||||
|
||||
Use `presentation.inspect({ kind: "image", search })` to find the `im/...`
|
||||
anchor id. Preserve frame, crop, fit, alt text, mask geometry, and border radius
|
||||
unless the edit explicitly changes them.
|
||||
Concrete source replacements produce concrete images; pass `prompt` when it
|
||||
should remain available as regeneration metadata.
|
||||
|
||||
## Edit Placement And Fit
|
||||
|
||||
```ts
|
||||
image.position = position;
|
||||
image.frame = frame;
|
||||
image.fit = fit;
|
||||
image.crop = crop;
|
||||
image.geometry = "roundRect";
|
||||
image.borderRadius = "rounded-xl";
|
||||
image.rotation = rotationDeg;
|
||||
image.flipHorizontal = flipHorizontal;
|
||||
image.flipVertical = flipVertical;
|
||||
image.lockAspectRatio = true;
|
||||
image.width = 320;
|
||||
image.height = 180;
|
||||
image.alt = altText;
|
||||
```
|
||||
|
||||
`crop` supplies all four edges. Numbers are normalized `0..1` fractions removed
|
||||
from the source image; strings accept percentages such as `"10%"` or pixel
|
||||
insets such as `"24px"` when source dimensions are available. Values are clamped.
|
||||
`fit="cover"` fills the frame and may crop; `fit="contain"`
|
||||
preserves the full image. `geometry="ellipse"` or `geometry="roundRect"` clips
|
||||
the image. `borderRadius` is for rect/roundRect masks; numbers are pixels and
|
||||
strings use supported `rounded-*` tokens.
|
||||
|
||||
## Replace Source
|
||||
|
||||
```ts
|
||||
image.replace({
|
||||
blob,
|
||||
contentType,
|
||||
path,
|
||||
svg,
|
||||
dataUrl,
|
||||
prompt,
|
||||
alt,
|
||||
fit,
|
||||
});
|
||||
```
|
||||
|
||||
`replace` swaps the source and common source metadata. Choose one primary source
|
||||
field as with `add`. Preserve or set placement, crop, mask geometry, and border
|
||||
radius on the image facade itself.
|
||||
|
||||
## Replace And Regenerate Inline Types
|
||||
|
||||
```ts
|
||||
type ImageReplaceOptions = {
|
||||
alt?: string;
|
||||
fit?: "contain" | "cover";
|
||||
contentType?: string;
|
||||
path?: string;
|
||||
svg?: string;
|
||||
blob?: ArrayBuffer | Uint8Array;
|
||||
dataUrl?: string;
|
||||
prompt?: string;
|
||||
};
|
||||
|
||||
type ImageRegenerateOptions = {
|
||||
prompt?: string;
|
||||
kind?: "sticker" | "layout" | "content" | "infographic";
|
||||
fit?: "contain" | "cover";
|
||||
size?: "1024x1024" | "1536x1024" | "1024x1536";
|
||||
quality?: "low" | "medium" | "high";
|
||||
background?: "auto" | "transparent" | "opaque";
|
||||
outputFormat?: "png" | "jpeg" | "webp";
|
||||
};
|
||||
```
|
||||
|
||||
## Prompt Images
|
||||
|
||||
```ts
|
||||
const promptImage = slide.images.add({
|
||||
prompt,
|
||||
alt,
|
||||
position,
|
||||
fit,
|
||||
});
|
||||
|
||||
promptImage.regenerate({ kind });
|
||||
```
|
||||
|
||||
Prompt placeholders are optional. Use concrete sources when asset bytes or
|
||||
references are already available.
|
||||
|
||||
## Concrete Image Sources
|
||||
|
||||
```ts
|
||||
const imageBytes = assetBytes;
|
||||
const imageUri = assetUri;
|
||||
const imageDataUrl = assetDataUrl;
|
||||
```
|
||||
|
||||
## JSX Declarative Image
|
||||
|
||||
```tsx
|
||||
/** @jsxRuntime automatic */
|
||||
|
||||
slide.compose(
|
||||
<row width="fill" height="fill" gap={16}>
|
||||
<image
|
||||
blob={imageBytes}
|
||||
alt="Embedded bytes"
|
||||
fit="cover"
|
||||
width={320}
|
||||
height={180}
|
||||
/>
|
||||
<image
|
||||
path={imagePath}
|
||||
alt="Local image"
|
||||
fit="contain"
|
||||
width={320}
|
||||
height={180}
|
||||
/>
|
||||
</row>,
|
||||
{
|
||||
frame: { left: 48, top: 40, width: 864, height: 240 },
|
||||
baseUnit: 8,
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Full-frame image crop.
|
||||
slide.images.add({
|
||||
blob: imageBytes,
|
||||
contentType: "image/jpeg",
|
||||
alt: "Workspace image",
|
||||
fit: "cover",
|
||||
position: { left: 0, top: 0, width: 1280, height: 720 },
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Rounded image mask.
|
||||
slide.images.add({
|
||||
blob: imageBytes,
|
||||
contentType: "image/jpeg",
|
||||
alt: "Customer interview",
|
||||
fit: "cover",
|
||||
geometry: "roundRect",
|
||||
borderRadius: "rounded-3xl",
|
||||
position: { left: 720, top: 96, width: 448, height: 512 },
|
||||
});
|
||||
```
|
||||
|
||||
```tsx
|
||||
// Circular avatar mask in JSX.
|
||||
<image
|
||||
blob={avatarBytes}
|
||||
contentType="image/png"
|
||||
alt="Speaker"
|
||||
fit="cover"
|
||||
geometry="ellipse"
|
||||
width={96}
|
||||
height={96}
|
||||
/>
|
||||
```
|
||||
|
||||
```tsx
|
||||
// Rounded crop/mask in JSX.
|
||||
<image
|
||||
blob={portraitBytes}
|
||||
contentType="image/jpeg"
|
||||
alt="Customer portrait"
|
||||
fit="cover"
|
||||
geometry="roundRect"
|
||||
borderRadius="rounded-2xl"
|
||||
crop={{ left: 0.08, top: 0.02, right: 0.14, bottom: 0 }}
|
||||
width={320}
|
||||
height={420}
|
||||
/>
|
||||
```
|
||||
|
||||
```ts
|
||||
// Manual crop when the subject is off-center.
|
||||
image.fit = "cover";
|
||||
image.crop = { left: 0.08, top: 0.02, right: 0.18, bottom: 0.06 };
|
||||
```
|
||||
Generated
Vendored
+131
@@ -0,0 +1,131 @@
|
||||
# Inspect
|
||||
|
||||
`presentation.inspect({ select, include, fileName })` queries one public
|
||||
presentation tree with [RFC 9535 JSONPath](https://www.rfc-editor.org/rfc/rfc9535.html).
|
||||
The [JSON Schema](./inspect.schema.json) describes its content and layout fields.
|
||||
`select` finds nodes; `include` chooses exact fields from those nodes.
|
||||
|
||||
## Read content
|
||||
|
||||
```ts
|
||||
await presentation.inspect({
|
||||
select: "$.slides[*]",
|
||||
include: [
|
||||
"id", "index", "layout", "title",
|
||||
"elements.id", "elements.kind", "elements.text", "elements.alt", "elements.title",
|
||||
"notes.text",
|
||||
],
|
||||
fileName: "content.ndjson",
|
||||
});
|
||||
```
|
||||
|
||||
This writes one slide per line, retaining its applied layout and editable
|
||||
element IDs. Text includes paragraph breaks and complete table content. The
|
||||
query omits positions and styles, so those fields are not computed.
|
||||
|
||||
The tree has this shape (selected fields):
|
||||
|
||||
```json
|
||||
{
|
||||
"schema": "openai.presentation.inspection/v1",
|
||||
"unit": "px",
|
||||
"id": "pr/abcdefgh",
|
||||
"kind": "presentation",
|
||||
"slides": [{
|
||||
"id": "sl/12345678", "kind": "slide", "index": 0,
|
||||
"layout": { "id": "ly/abcdefgh", "name": "Title and image" },
|
||||
"elements": [{ "id": "sh/abcdefgh", "kind": "textbox", "text": "Welcome" }],
|
||||
"notes": { "id": "nt/12345678", "kind": "notes", "text": "Opening remarks" }
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
Only canonical prefix/hash IDs are exposed. Pass editable `sl/`, `sh/`, `im/`,
|
||||
`ch/`, `tb/`, `ea/`, and `nt/` IDs to `presentation.resolve(id)`.
|
||||
The read-only `ly/` ID identifies the applied layout. `index` is zero-based;
|
||||
positions and computed font sizes use pixels.
|
||||
|
||||
## Find and edit
|
||||
|
||||
```ts
|
||||
const hits = await presentation.inspect({
|
||||
select: "$.slides[*].elements[?(@.text == 'Confidential')]",
|
||||
include: ["id", "text"],
|
||||
});
|
||||
```
|
||||
|
||||
JSONPath filters inspect source fields before projection. Comparisons therefore
|
||||
match the text itself, rather than its serialized JSON representation. Use
|
||||
`$.slides[0,2].elements[*]` for two slides or a predicate such as
|
||||
`@.kind == 'image'` for one element kind. Selected scalar values are also valid;
|
||||
for example, `$.slides[*].title` returns title strings.
|
||||
|
||||
Use `search(@.text, 'overview|steps')` for a text pattern, or `match()` to match
|
||||
the entire string. Patterns follow [I-Regexp](https://www.rfc-editor.org/rfc/rfc9485.html).
|
||||
`length()` measures a value, `count()` counts selected nodes, and `value()`
|
||||
extracts a value when a query selects exactly one node. Filters use `==` and
|
||||
`!=`; JavaScript expressions and method calls are not part of JSONPath.
|
||||
Repeated selectors retain repeated results: `$.slides[0,0]` selects slide zero
|
||||
twice. Invalid queries report a syntax error with the character offset.
|
||||
|
||||
Use the literal ID from the result for subsequent edits. Read computed styling
|
||||
or mixed-format text for that same ID:
|
||||
|
||||
```ts
|
||||
await presentation.inspect({
|
||||
select: "$.slides[*].elements[?(@.id == 'sh/abcdefgh')]",
|
||||
include: ["id", "text", "position", "style", "paragraphs"],
|
||||
});
|
||||
```
|
||||
|
||||
`style` reflects theme and inherited formatting. `paragraphs` preserves styled
|
||||
runs; `cells` expands a table. These fields are evaluated when accessed without
|
||||
rendering slides or fetching images. Explicit paths keep queries focused;
|
||||
recursive `..` queries can traverse computed fields across the document.
|
||||
|
||||
`include` is an exact array of typed field paths. Nested paths such as
|
||||
`elements.text` preserve arrays and object structure. Including a parent such
|
||||
as `style` includes that complete object. Omitting `include` returns complete
|
||||
selected nodes. Include `id` explicitly when the next step needs an editing ID.
|
||||
|
||||
## Files and results
|
||||
|
||||
An attached Artifact Session writes all selected records to
|
||||
`<outputDirectory>/presentation-inspect.ndjson`. `fileName` chooses another
|
||||
NDJSON basename. Reusing a name replaces that file. The completed session run's
|
||||
`files` contains finalized paths. Unnamed inspection outside a session stays in
|
||||
memory; the Node runtime supports a named standalone output path.
|
||||
|
||||
The returned object prints `recordCount` and output metadata. Access `.records`
|
||||
or `.ndjson` explicitly for the complete values. No pagination or record
|
||||
abbreviation applies to JSONPath queries. Select nodes and fields according to
|
||||
the task before reading the output into model context.
|
||||
|
||||
Rendering separately writes `slide-N.png` and `slide-N.layout.json`. Layout
|
||||
files use these same element fields and canonical IDs in a slide-scoped file
|
||||
envelope. The file's `slide` contains the inspected slide metadata and its
|
||||
`elements` contains the compact layout field selection. The content query does
|
||||
not replace those render outputs. Full layout export also exposes inherited
|
||||
paint layers and paragraph/run formatting.
|
||||
|
||||
## Types
|
||||
|
||||
```ts
|
||||
type PresentationInspectQueryOptions = {
|
||||
select: string;
|
||||
include?: readonly PresentationInspectField[];
|
||||
fileName?: string;
|
||||
};
|
||||
|
||||
type PresentationInspectQueryResult = {
|
||||
readonly records: readonly unknown[];
|
||||
readonly recordCount: number;
|
||||
readonly ndjson: string;
|
||||
readonly path?: string;
|
||||
readonly status?: "pending" | "saved" | "conflict" | "error";
|
||||
readonly message?: string;
|
||||
};
|
||||
```
|
||||
|
||||
The earlier preset and record-filter overloads remain deprecated compatibility
|
||||
entry points. New callers should use the explicit query above.
|
||||
Generated
Vendored
+865
@@ -0,0 +1,865 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "openai.presentation.inspection/v1"
|
||||
},
|
||||
"unit": {
|
||||
"type": "string",
|
||||
"const": "px"
|
||||
},
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^pr\\/[a-z0-9]+$"
|
||||
},
|
||||
"kind": {
|
||||
"type": "string",
|
||||
"const": "presentation"
|
||||
},
|
||||
"slides": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/Slide"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"unit",
|
||||
"id",
|
||||
"kind",
|
||||
"slides"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"$defs": {
|
||||
"Slide": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^sl\\/[a-z0-9]+$"
|
||||
},
|
||||
"kind": {
|
||||
"type": "string",
|
||||
"const": "slide"
|
||||
},
|
||||
"index": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"layout": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^ly\\/[a-z0-9]+$"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"title": {
|
||||
"type": "string"
|
||||
},
|
||||
"position": {
|
||||
"$ref": "#/$defs/Position"
|
||||
},
|
||||
"backgroundColor": {
|
||||
"$ref": "#/$defs/Color"
|
||||
},
|
||||
"elements": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/Element"
|
||||
}
|
||||
},
|
||||
"notes": {
|
||||
"$ref": "#/$defs/Notes"
|
||||
},
|
||||
"inheritedLayers": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/InheritedLayer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"kind",
|
||||
"index",
|
||||
"position",
|
||||
"elements"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"id": "Slide"
|
||||
},
|
||||
"Position": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"left": {
|
||||
"type": "number"
|
||||
},
|
||||
"top": {
|
||||
"type": "number"
|
||||
},
|
||||
"width": {
|
||||
"type": "number"
|
||||
},
|
||||
"height": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"left",
|
||||
"top",
|
||||
"width",
|
||||
"height"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"id": "Position"
|
||||
},
|
||||
"Color": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "rgb"
|
||||
},
|
||||
"value": {
|
||||
"type": "string"
|
||||
},
|
||||
"transform": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"opacity": {
|
||||
"type": "number"
|
||||
},
|
||||
"lighten": {
|
||||
"type": "number"
|
||||
},
|
||||
"darken": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"type",
|
||||
"value"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "theme"
|
||||
},
|
||||
"value": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"accent1",
|
||||
"accent2",
|
||||
"accent3",
|
||||
"accent4",
|
||||
"accent5",
|
||||
"accent6",
|
||||
"bg1",
|
||||
"bg2",
|
||||
"tx1",
|
||||
"tx2",
|
||||
"dk1",
|
||||
"lt1",
|
||||
"dk2",
|
||||
"lt2",
|
||||
"hlink",
|
||||
"folHlink"
|
||||
]
|
||||
},
|
||||
"transform": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"opacity": {
|
||||
"type": "number"
|
||||
},
|
||||
"lighten": {
|
||||
"type": "number"
|
||||
},
|
||||
"darken": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"type",
|
||||
"value"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
],
|
||||
"id": "Color"
|
||||
},
|
||||
"Element": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^(sh|im|ch|tb|ea)\\/[a-z0-9]+$"
|
||||
},
|
||||
"kind": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"shape",
|
||||
"textbox",
|
||||
"image",
|
||||
"chart",
|
||||
"table",
|
||||
"embeddedArtifact"
|
||||
]
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"text": {
|
||||
"type": "string"
|
||||
},
|
||||
"title": {
|
||||
"type": "string"
|
||||
},
|
||||
"position": {
|
||||
"$ref": "#/$defs/Position"
|
||||
},
|
||||
"order": {
|
||||
"type": "integer",
|
||||
"exclusiveMinimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"scope": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"slide",
|
||||
"layout",
|
||||
"master"
|
||||
]
|
||||
},
|
||||
"editable": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"rotation": {
|
||||
"type": "number"
|
||||
},
|
||||
"horizontalFlip": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"verticalFlip": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"hidden": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"geometry": {
|
||||
"type": "string"
|
||||
},
|
||||
"style": {
|
||||
"$ref": "#/$defs/TextStyle"
|
||||
},
|
||||
"paragraphs": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/Paragraph"
|
||||
}
|
||||
},
|
||||
"fillColor": {
|
||||
"$ref": "#/$defs/Color"
|
||||
},
|
||||
"lineColor": {
|
||||
"$ref": "#/$defs/Color"
|
||||
},
|
||||
"lineWidth": {
|
||||
"type": "number"
|
||||
},
|
||||
"alt": {
|
||||
"type": "string"
|
||||
},
|
||||
"chartType": {
|
||||
"type": "string"
|
||||
},
|
||||
"rows": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"cols": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"contentType": {
|
||||
"type": "string"
|
||||
},
|
||||
"crop": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"left": {
|
||||
"type": "number"
|
||||
},
|
||||
"top": {
|
||||
"type": "number"
|
||||
},
|
||||
"right": {
|
||||
"type": "number"
|
||||
},
|
||||
"bottom": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"left",
|
||||
"top",
|
||||
"right",
|
||||
"bottom"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"fit": {
|
||||
"type": "string"
|
||||
},
|
||||
"mask": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"geometry": {
|
||||
"type": "string"
|
||||
},
|
||||
"adjustmentList": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"formula": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"geometry"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"prompt": {
|
||||
"type": "string"
|
||||
},
|
||||
"isPlaceholder": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"asset": {
|
||||
"$ref": "#/$defs/Asset"
|
||||
},
|
||||
"fillImage": {
|
||||
"$ref": "#/$defs/Asset"
|
||||
},
|
||||
"tableCell": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"tableId": {
|
||||
"type": "string",
|
||||
"pattern": "^(sh|im|ch|tb|ea)\\/[a-z0-9]+$"
|
||||
},
|
||||
"cellIndex": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"row": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"column": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"overlap": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"tableId",
|
||||
"cellIndex",
|
||||
"row",
|
||||
"column",
|
||||
"overlap"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"cells": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/TableCell"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"kind"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"id": "Element"
|
||||
},
|
||||
"TextStyle": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"anchor": {
|
||||
"type": "number"
|
||||
},
|
||||
"vertical": {
|
||||
"type": "number"
|
||||
},
|
||||
"rotation": {
|
||||
"type": "number"
|
||||
},
|
||||
"fontSize": {
|
||||
"type": "number"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"family": {
|
||||
"type": "number"
|
||||
},
|
||||
"scheme": {
|
||||
"type": "string"
|
||||
},
|
||||
"typeface": {
|
||||
"type": "string"
|
||||
},
|
||||
"color": {
|
||||
"$ref": "#/$defs/Color"
|
||||
},
|
||||
"bold": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"italic": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"alignment": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"left",
|
||||
"center",
|
||||
"right",
|
||||
"justify"
|
||||
]
|
||||
},
|
||||
"verticalAlignment": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"top",
|
||||
"middle",
|
||||
"bottom"
|
||||
]
|
||||
},
|
||||
"lineSpacing": {
|
||||
"type": "number"
|
||||
},
|
||||
"textTransform": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"none",
|
||||
"uppercase",
|
||||
"smallCaps"
|
||||
]
|
||||
},
|
||||
"wrap": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"square",
|
||||
"none"
|
||||
]
|
||||
},
|
||||
"autoFit": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"none",
|
||||
"shrinkText",
|
||||
"resizeShapeToFitText"
|
||||
]
|
||||
},
|
||||
"autoFitScale": {
|
||||
"type": "number"
|
||||
},
|
||||
"autoFitLineSpaceReduction": {
|
||||
"type": "number"
|
||||
},
|
||||
"insets": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"top": {
|
||||
"type": "number"
|
||||
},
|
||||
"right": {
|
||||
"type": "number"
|
||||
},
|
||||
"bottom": {
|
||||
"type": "number"
|
||||
},
|
||||
"left": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"useParagraphSpacing": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"id": "TextStyle"
|
||||
},
|
||||
"Paragraph": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"index": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"text": {
|
||||
"type": "string"
|
||||
},
|
||||
"bulletCharacter": {
|
||||
"type": "string"
|
||||
},
|
||||
"marginLeft": {
|
||||
"type": "number"
|
||||
},
|
||||
"indent": {
|
||||
"type": "number"
|
||||
},
|
||||
"lineSpacingPercent": {
|
||||
"type": "number"
|
||||
},
|
||||
"spaceBefore": {
|
||||
"type": "number"
|
||||
},
|
||||
"spaceAfter": {
|
||||
"type": "number"
|
||||
},
|
||||
"style": {
|
||||
"$ref": "#/$defs/TextStyle"
|
||||
},
|
||||
"runs": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/TextRun"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"index",
|
||||
"runs"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"id": "Paragraph"
|
||||
},
|
||||
"TextRun": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"anchor": {
|
||||
"type": "number"
|
||||
},
|
||||
"vertical": {
|
||||
"type": "number"
|
||||
},
|
||||
"rotation": {
|
||||
"type": "number"
|
||||
},
|
||||
"fontSize": {
|
||||
"type": "number"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"family": {
|
||||
"type": "number"
|
||||
},
|
||||
"scheme": {
|
||||
"type": "string"
|
||||
},
|
||||
"typeface": {
|
||||
"type": "string"
|
||||
},
|
||||
"color": {
|
||||
"$ref": "#/$defs/Color"
|
||||
},
|
||||
"bold": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"italic": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"alignment": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"left",
|
||||
"center",
|
||||
"right",
|
||||
"justify"
|
||||
]
|
||||
},
|
||||
"verticalAlignment": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"top",
|
||||
"middle",
|
||||
"bottom"
|
||||
]
|
||||
},
|
||||
"lineSpacing": {
|
||||
"type": "number"
|
||||
},
|
||||
"textTransform": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"none",
|
||||
"uppercase",
|
||||
"smallCaps"
|
||||
]
|
||||
},
|
||||
"wrap": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"square",
|
||||
"none"
|
||||
]
|
||||
},
|
||||
"autoFit": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"none",
|
||||
"shrinkText",
|
||||
"resizeShapeToFitText"
|
||||
]
|
||||
},
|
||||
"autoFitScale": {
|
||||
"type": "number"
|
||||
},
|
||||
"autoFitLineSpaceReduction": {
|
||||
"type": "number"
|
||||
},
|
||||
"insets": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"top": {
|
||||
"type": "number"
|
||||
},
|
||||
"right": {
|
||||
"type": "number"
|
||||
},
|
||||
"bottom": {
|
||||
"type": "number"
|
||||
},
|
||||
"left": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"useParagraphSpacing": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"index": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"text": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"index",
|
||||
"text"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"id": "TextRun"
|
||||
},
|
||||
"Asset": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"contentType": {
|
||||
"type": "string"
|
||||
},
|
||||
"uri": {
|
||||
"type": "string"
|
||||
},
|
||||
"prompt": {
|
||||
"type": "string"
|
||||
},
|
||||
"byteLength": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"id": "Asset"
|
||||
},
|
||||
"TableCell": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"index": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"row": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"column": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"rowSpan": {
|
||||
"type": "integer",
|
||||
"exclusiveMinimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"colSpan": {
|
||||
"type": "integer",
|
||||
"exclusiveMinimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"position": {
|
||||
"$ref": "#/$defs/Position"
|
||||
},
|
||||
"text": {
|
||||
"type": "string"
|
||||
},
|
||||
"textDirection": {
|
||||
"type": "string"
|
||||
},
|
||||
"fillColor": {
|
||||
"$ref": "#/$defs/Color"
|
||||
},
|
||||
"style": {
|
||||
"$ref": "#/$defs/TextStyle"
|
||||
},
|
||||
"paragraphs": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/Paragraph"
|
||||
}
|
||||
},
|
||||
"ownedElementIds": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"pattern": "^(sh|im|ch|tb|ea)\\/[a-z0-9]+$"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"index",
|
||||
"row",
|
||||
"column"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"id": "TableCell"
|
||||
},
|
||||
"Notes": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^nt\\/[a-z0-9]+$"
|
||||
},
|
||||
"kind": {
|
||||
"type": "string",
|
||||
"const": "notes"
|
||||
},
|
||||
"text": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"kind",
|
||||
"text"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"id": "Notes"
|
||||
},
|
||||
"InheritedLayer": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^ly\\/[a-z0-9]+$"
|
||||
},
|
||||
"scope": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"layout",
|
||||
"master"
|
||||
]
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": {
|
||||
"type": "string"
|
||||
},
|
||||
"parentLayoutId": {
|
||||
"type": "string",
|
||||
"pattern": "^ly\\/[a-z0-9]+$"
|
||||
},
|
||||
"backgroundColor": {
|
||||
"$ref": "#/$defs/Color"
|
||||
},
|
||||
"backgroundImage": {
|
||||
"$ref": "#/$defs/Asset"
|
||||
},
|
||||
"elements": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/Element"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"scope",
|
||||
"elements"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"id": "InheritedLayer"
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+227
@@ -0,0 +1,227 @@
|
||||
# Presentation JSX Reference
|
||||
|
||||
This is the compact API reference for authoring editable presentations with
|
||||
presentation JSX. It describes the node vocabulary and layout mechanics. For
|
||||
first-principles row, column, grid, alignment, mask, and overlay recipes, read
|
||||
`cookbook/layout.md`.
|
||||
|
||||
Examples start after `presentation` and `slide` exist.
|
||||
|
||||
## Authoring Defaults
|
||||
|
||||
- Use JSX for structured slide layout: `slide.compose(<row ... />, { frame })`.
|
||||
- Use string sizing where supported: `width="fill"`, `height="hug"`,
|
||||
`height="fill"`.
|
||||
- Use raw pixel numbers for fixed sizes: `width={420}`, `gap={24}`,
|
||||
`padding={{ x: 48, y: 40 }}`.
|
||||
- Use Tailwind-like tokens for common styling: `fill="slate-950"`,
|
||||
`borderRadius="rounded-xl"`, `shadow="shadow-md"`,
|
||||
`className="bg-white rounded-xl shadow-sm"`.
|
||||
- Use `row`, `column`, `grid`, `layers`, and `box` for layout. Use absolute
|
||||
slide frames only for the outer composed region, fixed chrome, and
|
||||
imported-template details. For overlays, scrims, and masked image
|
||||
compositions inside a region, use `layers` and image `geometry`/`borderRadius`.
|
||||
- Put text in `paragraph` and inline emphasis in child `run` nodes.
|
||||
- Put real data in native `table` and `chart` nodes.
|
||||
- Model-facing examples use string sizing and local track objects instead of
|
||||
imported sizing helpers such as `wrap(...)`, `grow(...)`, and `fr(...)`.
|
||||
|
||||
## JSX Usage Rules
|
||||
|
||||
Use JSX props for layout and token strings for common visual styling:
|
||||
|
||||
| Need | Use |
|
||||
| --- | --- |
|
||||
| Layout sizing | `width="fill"`, `height={320}`, `gap={24}`, `padding={{ x: 32, y: 24 }}` |
|
||||
| Flex flow | `<row align="center" justify="between">` and `<column gap={16}>` |
|
||||
| Grid tracks | local arrays such as `[{ mode: "fr", value: 1 }]` |
|
||||
| Visual tokens | `className="bg-white rounded-xl shadow-sm"` |
|
||||
| Exact text | `style="font: 700 28px Inter; color: #0f172a; leading: 1.1"` |
|
||||
| Gradients | `fill="linear(135deg, #fff 0%, sky-100 100%)"` |
|
||||
| Image masks | `<image geometry="ellipse" crop={...} fit="cover" />` |
|
||||
|
||||
## Canonical Node Set
|
||||
|
||||
### Slide Roots
|
||||
|
||||
| Node | Purpose | Common props |
|
||||
| --- | --- | --- |
|
||||
| `slide` | Whole-slide JSX root | `id`, `name`, `width`, `height`, `padding`, `gap`, `align`, `justify`, `background`, `backgroundRef` |
|
||||
| `background` | Slide background metadata | `fill`, `ref` |
|
||||
|
||||
Most code composes directly into an existing `slide` facade rather than using a
|
||||
`<slide>` root.
|
||||
|
||||
### Layout Nodes
|
||||
|
||||
| Node | Purpose | Common props |
|
||||
| --- | --- | --- |
|
||||
| `row` | Horizontal flex-like layout | `width`, `height`, `gap`, `align`, `justify`, `padding` |
|
||||
| `column` | Vertical flex-like layout | `width`, `height`, `gap`, `align`, `justify`, `padding` |
|
||||
| `grid` | Track layout with spans | `columns`, `rows`, `autoRows`, `columnGap`, `rowGap`, `alignItems`, `justifyItems`, `padding` |
|
||||
| `layers` | Overlay children in one frame | `width`, `height`, `padding`, `alignItems`, `justifyItems` |
|
||||
| `box` | Surface/container with one child region | `width`, `height`, `padding`, `align`, `justify`, `fill`, `line`, `borderRadius`, `shadow`, `className` |
|
||||
|
||||
`align` controls the cross axis. `justify` controls the main axis. Supported
|
||||
values are `"start"`, `"center"`, `"end"`, `"stretch"` for alignment and
|
||||
`"start"`, `"center"`, `"end"`, `"between"` for distribution.
|
||||
|
||||
All direct grid children support `columnSpan` and `rowSpan`, including
|
||||
`row`, `column`, `box`, `paragraph`, `shape`, `image`, `table`, and `chart`.
|
||||
|
||||
### Content Nodes
|
||||
|
||||
| Node | Purpose | Common props |
|
||||
| --- | --- | --- |
|
||||
| `paragraph` | Text block | `width`, `height`, `style`, `className`, `transform`, `bulletCharacter`, `marginLeft`, `indent`, `spaceBefore`, `spaceAfter`, `styleId`, `paragraphStyle` |
|
||||
| `run` | Inline text run | children, `textStyle`, `className`, `link` |
|
||||
| `shape` | Primitive drawing | `geometry`, `width`, `height`, `fill`, `line`, `borderRadius`, `shadow`, `className` |
|
||||
| `image` | Raster/vector image | `path`, `blob`, `dataUrl`, `svg`, `prompt`, `contentType`, `fit`, `alt`, `geometry`, `borderRadius`, `crop`, `rotation`, `flipHorizontal`, `flipVertical`, `lockAspectRatio`, `width`, `height` |
|
||||
| `rule` | Divider line | `stroke`, `weight`, `opacity`, `width`, `height` |
|
||||
| `table` | Native table | `rows`, `columns`, `values`, `style`, `styleOptions`, `width`, `height` |
|
||||
| `chart` | Native chart | `chartType`, `title`, `categories`, `series`, `legend`, `xAxis`, `yAxis`, `width`, `height` |
|
||||
|
||||
`id` and `name` are supported on materialized nodes. Use deterministic
|
||||
kebab-case `name` values on composed roots and important descendants:
|
||||
`content-frame`, `primary-heading`, `metrics-grid`, `chart-frame`, `revenue-chart`.
|
||||
Names should describe role, not visual position. Use `id` when the calling code
|
||||
controls stability across edits.
|
||||
|
||||
### Chart Child Nodes
|
||||
|
||||
Use a compact chart config when it is clearest. Use nested chart nodes when the
|
||||
JSX tree should expose structure.
|
||||
|
||||
| Node | Purpose |
|
||||
| --- | --- |
|
||||
| `bar`, `line`, `area`, `scatter`, `bubble`, `radar`, `pie`, `doughnut`, `treemap`, `sunburst`, `map`, `waterfall`, `funnel`, `histogram`, `boxWhisker`, `stock`, `surface`, `surface3D`, `pareto`, `combo`, `line3D`, `pie3D`, `area3D`, `bar3D`, `ofPie` | Chart family selector/options |
|
||||
| `legend`, `data-labels`, `data-table`, `x-axis`, `y-axis`, `axis`, `major-gridlines`, `minor-gridlines` | Chart chrome and axes |
|
||||
| `series`, `marker`, `point`, `data-label`, `trendline`, `trendline-label`, `error-bars` | Series and point-level options |
|
||||
| `view-3d` | 3D camera options |
|
||||
|
||||
## Sizing And Frames
|
||||
|
||||
Use these forms first:
|
||||
|
||||
| Intent | JSX |
|
||||
| --- | --- |
|
||||
| Fill parent | `width="fill"` or `height="fill"` |
|
||||
| Fit content | `width="hug"` or `height="hug"` |
|
||||
| Fixed pixels | `width={320}` or `height={180}` |
|
||||
| Equal children in a row/column | give each child `width="fill"` or `height="fill"` |
|
||||
| One fixed region plus remaining space | one child `width={520}`, sibling `width="fill"` |
|
||||
| Fixed slide region | `slide.compose(node, { frame: { left, top, width, height } })` |
|
||||
|
||||
`frame` uses numeric pixels. JSX size props accept strings for `"fill"` and
|
||||
`"hug"` plus raw pixel numbers.
|
||||
|
||||
Use `1280 x 720` as the default canvas unless the task or source deck requires
|
||||
another size. A common content frame is:
|
||||
|
||||
```ts
|
||||
const PAGE = { left: 72, top: 64, width: 1136, height: 592 };
|
||||
```
|
||||
|
||||
## Alignment Matrix
|
||||
|
||||
| Node | Main axis | Cross axis | Distribution prop | Cross-axis prop | Defaults |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `row` | horizontal | vertical | `justify`: `start`, `center`, `end`, `between` | `align`: `start`, `center`, `end`, `stretch` | `justify="start"`, `align="start"` |
|
||||
| `column` | vertical | horizontal | `justify`: `start`, `center`, `end`, `between` | `align`: `start`, `center`, `end`, `stretch` | `justify="start"`, `align="start"` |
|
||||
| `grid` | tracks | cells | `justifyItems`: `start`, `center`, `end`, `stretch` | `alignItems`: `start`, `center`, `end`, `stretch` | both `stretch` |
|
||||
| `layers` | shared frame | shared frame | `justifyItems`: `start`, `center`, `end`, `stretch` | `alignItems`: `start`, `center`, `end`, `stretch` | both `stretch` |
|
||||
|
||||
## Layout Recipes
|
||||
|
||||
This top-level reference stays close to the JSX API. For copy-paste row,
|
||||
column, 3-column, 12-grid, alignment, mask, overlay, and gradient recipes, use
|
||||
[`cookbook/layout.md`](./cookbook/layout.md).
|
||||
|
||||
## Text Examples
|
||||
|
||||
```tsx
|
||||
<paragraph className="text-slate-950 text-4xl font-bold leading-tight">
|
||||
A paragraph can contain plain text.
|
||||
</paragraph>
|
||||
|
||||
<paragraph className="text-slate-600 text-lg leading-relaxed">
|
||||
Use <run textStyle={{ bold: true, color: "sky-600" }}>runs</run> for inline
|
||||
emphasis or links.
|
||||
</paragraph>
|
||||
|
||||
<column width="fill" height="hug" gap={8}>
|
||||
<paragraph
|
||||
width="fill"
|
||||
className="text-slate-700 text-lg leading-relaxed"
|
||||
>
|
||||
First paragraph.
|
||||
</paragraph>
|
||||
<paragraph bulletCharacter="•" marginLeft={18} indent={-10}>
|
||||
Bulleted paragraph with native list metadata.
|
||||
</paragraph>
|
||||
</column>
|
||||
```
|
||||
|
||||
Use `style={{ ... }}` for exact text config and `className` for tokenized
|
||||
common text styling. A string `style` containing `:` or `;` is parsed as a
|
||||
compact text declaration; any other string is treated as a named presentation
|
||||
style id.
|
||||
|
||||
```tsx
|
||||
<paragraph style="font: 700 22px Inter; color: #334155; leading: 1.25; wrap: none">
|
||||
Exact style string
|
||||
</paragraph>
|
||||
```
|
||||
|
||||
## Tables And Charts
|
||||
|
||||
Prefer compact config for data objects.
|
||||
|
||||
```tsx
|
||||
<table
|
||||
rows={3}
|
||||
columns={3}
|
||||
values={[
|
||||
["Metric", "Q1", "Q2"],
|
||||
["Revenue", 12, 18],
|
||||
["Margin", "42%", "45%"],
|
||||
]}
|
||||
style="TableStyleMedium2"
|
||||
styleOptions={{ headerRow: true, bandedRows: true }}
|
||||
width="fill"
|
||||
height={220}
|
||||
/>
|
||||
|
||||
<chart
|
||||
chartType="bar"
|
||||
title="Pipeline"
|
||||
categories={["Q1", "Q2", "Q3"]}
|
||||
series={[{ name: "Revenue", values: [12, 18, 24], fill: "sky-500" }]}
|
||||
xAxis={{ textStyle: { fontSize: 10, fill: "slate-600" } }}
|
||||
yAxis={{ majorGridlines: { style: "solid", fill: "slate-200", width: 1 } }}
|
||||
width="fill"
|
||||
height={280}
|
||||
/>
|
||||
```
|
||||
|
||||
Use nested chart nodes when the chart needs explicit series, point, trendline,
|
||||
axis, or label structure in the JSX tree.
|
||||
|
||||
## Image Sources
|
||||
|
||||
| Source prop | Use when |
|
||||
| --- | --- |
|
||||
| `blob={bytes}` | Export must embed the actual image bytes. |
|
||||
| `dataUrl="data:image/..."` | Bytes are already encoded inline. |
|
||||
| `path="/assets/image.png"` | A downloaded image is available as a local file. |
|
||||
| `prompt="..."` | The slide should contain an image-generation placeholder. |
|
||||
|
||||
Use `fit="contain"` when the full image must remain visible. Use `fit="cover"`
|
||||
when cropping is deliberate. Keep labels and data as editable slide text layered
|
||||
with the image.
|
||||
|
||||
## Reference Tests
|
||||
|
||||
- `tests/presentation/jsx.spec.tsx`: JSX normalization and compose behavior.
|
||||
- `tests/presentation/jsx-style-language.spec.tsx`: compact style strings.
|
||||
- `tests/presentation/tailwind-tokens.sanity.spec.ts`: token coverage.
|
||||
Generated
Vendored
+155
@@ -0,0 +1,155 @@
|
||||
# Layouts
|
||||
|
||||
Layouts define reusable placeholder structure for slides.
|
||||
|
||||
## Create A Layout
|
||||
|
||||
```ts
|
||||
const layout = presentation.layouts.add(layoutName);
|
||||
layout.placeholders.add({
|
||||
type: placeholderType,
|
||||
index: placeholderIndex,
|
||||
text: placeholderText,
|
||||
geometry: "textbox",
|
||||
});
|
||||
```
|
||||
|
||||
## Placeholder Inline Type
|
||||
|
||||
```ts
|
||||
type PlaceholderConfig = {
|
||||
type?:
|
||||
| "title"
|
||||
| "subtitle"
|
||||
| "body"
|
||||
| "picture"
|
||||
| "chart"
|
||||
| "table"
|
||||
| "content";
|
||||
index?: number;
|
||||
text?: TextValue;
|
||||
geometry?: "textbox" | "rect" | "roundRect" | string;
|
||||
position?: { left?: number; top?: number; width?: number; height?: number };
|
||||
fill?: FillConfig;
|
||||
line?: LineConfig;
|
||||
};
|
||||
```
|
||||
|
||||
## Shape-Based Placeholders
|
||||
|
||||
```ts
|
||||
const placeholder = layout.shapes.addPlaceholder(placeholderName);
|
||||
placeholder.placeholder.type = placeholderType;
|
||||
placeholder.placeholder.index = placeholderIndex;
|
||||
placeholder.text = placeholderText;
|
||||
```
|
||||
|
||||
## Use A Layout
|
||||
|
||||
```ts
|
||||
slide.setLayout(layout);
|
||||
|
||||
const target = slide.placeholders.getItem(placeholderType);
|
||||
target.text = textValue;
|
||||
```
|
||||
|
||||
## Discover
|
||||
|
||||
```ts
|
||||
const layoutSummary = layout.placeholders.summary();
|
||||
const resolved = presentation.layouts.getById(layout.id);
|
||||
const importedGuides = layout.slideGuides;
|
||||
const actualPlaceholders = slide.placeholders.items;
|
||||
const emptyContentPlaceholders = slide.placeholders.editable;
|
||||
const allVisibleEmptyPlaceholders = slide.placeholders.unfilled;
|
||||
const missingLayoutSlots = slide.placeholders.availableFromLayout;
|
||||
```
|
||||
|
||||
These getters do not modify saved slide content.
|
||||
`items` includes filled placeholders. `editable` contains visible empty content
|
||||
shapes with positive bounds; `unfilled` also includes empty furniture.
|
||||
`availableFromLayout` contains missing layout slots for explicit creation.
|
||||
`getAll()` retains layout/master discovery, and `getItem()` creates a local
|
||||
instance when the requested placeholder exists only in the layout or master.
|
||||
|
||||
## Preview And Insert A Layout
|
||||
|
||||
```ts
|
||||
presentation.view.showPlaceholders();
|
||||
const image = await layout.export({ format: "png", scale: 0.25 });
|
||||
|
||||
const { slide } = presentation.slides.insert({
|
||||
after: selectedSlide,
|
||||
layoutId: layout.id,
|
||||
});
|
||||
slide.placeholders.addFromLayout();
|
||||
slide.placeholders.getItem("title").text = titleText;
|
||||
```
|
||||
|
||||
`addFromLayout()` creates missing content placeholders once and returns the
|
||||
created shapes. Adding a slide alone leaves placeholder creation to the caller.
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Branded title/body layout.
|
||||
const layout = presentation.layouts.add("Title Body");
|
||||
layout.placeholders.add({
|
||||
type: "title",
|
||||
index: 0,
|
||||
geometry: "textbox",
|
||||
position: { left: 72, top: 64, width: 920, height: 88 },
|
||||
text: "Title",
|
||||
});
|
||||
layout.placeholders.add({
|
||||
type: "body",
|
||||
index: 0,
|
||||
geometry: "roundRect",
|
||||
position: { left: 72, top: 180, width: 760, height: 360 },
|
||||
fill: "slate-50",
|
||||
line: { style: "solid", fill: "slate-200", width: 1 },
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Use placeholders for repeated structure; override slide content locally.
|
||||
const slide = presentation.slides.add({ layout: "Title Body" });
|
||||
slide.placeholders.getItem("title").text = "Market overview";
|
||||
slide.placeholders.getItem("body").text = "Three editable points go here.";
|
||||
```
|
||||
|
||||
## Read A Rendered Slide's Layout
|
||||
|
||||
Each `presentation.render()` preview is an image Blob with a `.layout` JSON Blob.
|
||||
The paired files use the same stem, for example `slide-1.png` and
|
||||
`slide-1.layout.json`. A complete render replaces the previous render set;
|
||||
a subset render updates only the selected slides' pairs.
|
||||
|
||||
```ts
|
||||
const preview = await presentation.render({ slide: 0 });
|
||||
const layout = JSON.parse(await preview.layout.text());
|
||||
const title = layout.elements.find((element) => element.name === "cover-title");
|
||||
if (title) presentation.resolve(title.id).text = "Updated title";
|
||||
```
|
||||
|
||||
The default `openai.presentation.layout/v5` view is compact and uses pixels and
|
||||
canonical IDs. Request `slide.export({ format: "layout", detail: "full" })` for
|
||||
inherited paint layers, paragraph/run formatting, and table-cell details.
|
||||
Both views use the same IDs and editing coordinates:
|
||||
|
||||
| Field | Meaning |
|
||||
| ---------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| `slide.id`, `slide.index` | Canonical slide ID and zero-based deck index. |
|
||||
| `slide.position` | Slide bounds: `{ left, top, width, height }`. |
|
||||
| `elements[].id`, `kind`, `name` | Canonical element ID, element kind, and optional authored name. |
|
||||
| `elements[].position` | Bounds using the same keys as edit configuration. |
|
||||
| `elements[].text`, `style` | Text and effective text styling, including `style.fontSize`. |
|
||||
| `elements[].crop`, `fit`, `mask` | Image crop, fitting, and geometry configuration. |
|
||||
| `elements[].scope`, `editable` | Owned slide content is editable; inherited layout/master content is identified separately. |
|
||||
| `tableCell.tableId`, `cells[].ownedElementIds` | Canonical IDs connecting a table, its cells, and cell-owned elements. |
|
||||
| `inheritedLayers[].id` | Canonical `ly/…` ID of a layout or master. |
|
||||
|
||||
Pass IDs from editable records to `presentation.resolve()` or
|
||||
`presentation.delete()`. In the full view, inherited content has `editable: false`; its IDs identify
|
||||
where the content came from and are not slide-owned edit targets. Raw PowerPoint
|
||||
IDs, asset IDs, and paragraph style IDs are not part of this public view.
|
||||
Generated
Vendored
+57
@@ -0,0 +1,57 @@
|
||||
# Masters
|
||||
|
||||
Masters share theme, background, and color-map structure with child layouts.
|
||||
|
||||
## Create And Link
|
||||
|
||||
```ts
|
||||
const master = presentation.masters.add(masterName);
|
||||
const layout = presentation.layouts.add(layoutName);
|
||||
|
||||
layout.setParentLayoutId(master.id);
|
||||
```
|
||||
|
||||
## Color Map And Background
|
||||
|
||||
```ts
|
||||
master.setColorMap(colorMapConfig);
|
||||
master.background.ref = backgroundRef;
|
||||
|
||||
const slide = presentation.slides.add();
|
||||
slide.setLayout(layout);
|
||||
```
|
||||
|
||||
## Master Inline Types
|
||||
|
||||
```ts
|
||||
type ColorMapConfig = Partial<Record<
|
||||
"bg1" | "tx1" | "bg2" | "tx2" | "accent1" | "accent2" | "accent3" | "accent4" | "accent5" | "accent6" | "hlink" | "folHlink",
|
||||
"bg1" | "tx1" | "bg2" | "tx2" | "accent1" | "accent2" | "accent3" | "accent4" | "accent5" | "accent6" | "hlink" | "folHlink"
|
||||
>>;
|
||||
```
|
||||
|
||||
## Resolve
|
||||
|
||||
```ts
|
||||
const resolved = presentation.layouts.getById(master.id);
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Shared brand master with inherited layout.
|
||||
const master = presentation.masters.add("Brand Master");
|
||||
master.setColorMap({ bg1: "bg1", tx1: "tx1", accent1: "accent1" });
|
||||
master.background.ref = "bg1";
|
||||
|
||||
const layout = presentation.layouts.add("Brand Title");
|
||||
layout.setParentLayoutId(master.id);
|
||||
layout.placeholders.add({
|
||||
type: "title",
|
||||
geometry: "textbox",
|
||||
position: { left: 72, top: 72, width: 1000, height: 96 },
|
||||
});
|
||||
```
|
||||
|
||||
Before editing a master in an imported deck, inspect affected layouts and
|
||||
slides; master edits have intentional global blast radius.
|
||||
Generated
Vendored
+291
@@ -0,0 +1,291 @@
|
||||
# Presentation Facade
|
||||
|
||||
## Create And Load
|
||||
|
||||
```ts
|
||||
const presentation = Presentation.create({ slideSize });
|
||||
const loaded = await Presentation.load("input.pptx");
|
||||
const imported = Presentation.load(proto);
|
||||
```
|
||||
|
||||
## Create Inline Type
|
||||
|
||||
```ts
|
||||
type PresentationCreateOptions = {
|
||||
slideSize?: { width: number; height: number };
|
||||
};
|
||||
```
|
||||
|
||||
## Presentation Slide Collection
|
||||
|
||||
```ts
|
||||
const slide = presentation.slides.add({ layout, layoutId, background: { fill } });
|
||||
const inserted = presentation.slides.insert({ after, layout, layoutId });
|
||||
const byIndex = presentation.slides.getItem(slideIndex);
|
||||
presentation.slides.keep([0, 2, 4]);
|
||||
presentation.slides.reorder(orderedSlideIds);
|
||||
```
|
||||
|
||||
`keep` accepts an array of zero-based indexes or an array of canonical `sl/` IDs.
|
||||
It validates the selection against the current slide list, then preserves the
|
||||
selected slides in their existing relative order. Repeated selections are ignored;
|
||||
an empty array deletes all slides. `reorder` requires the complete desired order,
|
||||
with every current slide ID exactly once. Invalid selections fail before mutation.
|
||||
|
||||
## Presentation Slide Collection Inline Types
|
||||
|
||||
```ts
|
||||
type SlideAddOptions = {
|
||||
layout?: string;
|
||||
layoutId?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
background?: { fill: FillConfig };
|
||||
};
|
||||
|
||||
type SlideInsertOptions = SlideAddOptions & {
|
||||
after?: Slide | number | null;
|
||||
};
|
||||
|
||||
interface SlideCollection {
|
||||
keep(selection: readonly number[] | readonly string[]): void;
|
||||
reorder(ids: readonly string[]): void;
|
||||
}
|
||||
|
||||
interface Presentation {
|
||||
delete(ids: string | readonly string[]): void;
|
||||
}
|
||||
```
|
||||
|
||||
## Discover And Edit
|
||||
|
||||
```ts
|
||||
const snapshot = await presentation.inspect({
|
||||
kind,
|
||||
search,
|
||||
limit,
|
||||
offset,
|
||||
});
|
||||
|
||||
const target = presentation.resolve(anchorId);
|
||||
const targets = presentation.resolve(anchorIds);
|
||||
presentation.delete(anchorIds);
|
||||
```
|
||||
|
||||
`delete` accepts one canonical ID or an array. It supports slides (`sl/`) and owned
|
||||
shapes, images, charts, tables, and embedded artifacts (`sh/`, `im/`, `ch/`, `tb/`,
|
||||
`ea/`). All IDs are validated first. Repeated IDs are ignored; selecting a slide
|
||||
and its children deletes the slide once. Inherited elements, notes, text ranges,
|
||||
and the presentation itself are not delete targets.
|
||||
|
||||
`inspect` returns stable anchor ids for slides, shapes, images, tables, charts, text ranges, speaker notes, and comment threads. `resolve` maps one anchor id to its facade, or an array of ids to facades in the same order. Layout records expose canonical `ly/...` IDs with `editable: false` for search and comparison; pass only `pr/`, `sl/`, `sh/`, `im/`, `tb/`, `ch/`, `nt/`, `th/`, and `tr/` anchors to `resolve`.
|
||||
|
||||
## Inspect
|
||||
|
||||
Use `presentation.inspect({ select, include, fileName })` with JSONPath over the
|
||||
public presentation tree. `include` is an exact array of typed fields, including
|
||||
nested paths such as `elements.text`. The query writes all selected records to
|
||||
NDJSON in the session output directory; ordinary printing shows the count and
|
||||
file metadata. See [Inspect](./inspect.md) and the
|
||||
[inspection JSON Schema](./inspect.schema.json) for content and layout queries.
|
||||
|
||||
## Help
|
||||
|
||||
```ts
|
||||
const help = presentation.help(query, {
|
||||
search,
|
||||
include,
|
||||
maxChars,
|
||||
});
|
||||
```
|
||||
|
||||
## Help Inline Type
|
||||
|
||||
```ts
|
||||
type PresentationHelpOptions = {
|
||||
search?: string;
|
||||
include?: string[]; // common: ["index", "examples", "notes"]
|
||||
maxChars?: number;
|
||||
};
|
||||
```
|
||||
|
||||
## Presentation View
|
||||
|
||||
```ts
|
||||
presentation.view.showGridlines();
|
||||
presentation.view.showGuides();
|
||||
presentation.view.showPlaceholders();
|
||||
|
||||
const gridlinesVisible = presentation.view.gridlinesVisible;
|
||||
const guidesVisible = presentation.view.guidesVisible;
|
||||
const placeholdersVisible = presentation.view.placeholdersVisible;
|
||||
const horizontalGridSpacingEmu = presentation.view.gridSpacingCxEmu;
|
||||
const verticalGridSpacingEmu = presentation.view.gridSpacingCyEmu;
|
||||
|
||||
presentation.view.hideGridlines();
|
||||
presentation.view.hideGuides();
|
||||
presentation.view.hidePlaceholders();
|
||||
|
||||
const nextGridlineState = presentation.view.toggleGridlines();
|
||||
const nextGuideState = presentation.view.toggleGuides();
|
||||
const nextPlaceholderState = presentation.view.togglePlaceholders();
|
||||
```
|
||||
|
||||
## Render And Export
|
||||
|
||||
```ts
|
||||
const overview = await presentation.render({ montage: true, fileName: "overview.png" });
|
||||
const selectedPreviews = await presentation.render({ slide: [0, 2] }); // PNG/layout pairs
|
||||
const allPreviews = await presentation.render(); // pairs in deck order
|
||||
const firstPreview = await presentation.render({ slide: 0 }); // one image Blob with .layout
|
||||
const pptxBlob = await presentation.export({ format: "pptx", fileName: "presentation.pptx" });
|
||||
const deckPdfBlob = await presentation.export({ format: "pdf" });
|
||||
const slidePdfBlob = await presentation.export({ slide, format: "pdf" });
|
||||
const layoutBlob = await slide.export({ format: "layout" });
|
||||
const proto = presentation.toProto();
|
||||
```
|
||||
|
||||
### Montage overview
|
||||
|
||||
`render({ montage: true })` includes every slide in deck order, regardless of
|
||||
which slide is active. It returns one image Blob without per-slide layout files.
|
||||
The default format is PNG and the default filename is `presentation-montage.png`.
|
||||
A custom `fileName` names the overview. In an Artifact Session, it is published
|
||||
as one render output under the session output directory.
|
||||
|
||||
Read the montage and content inspection first, then render selected slides for
|
||||
full-size PNGs and companion layout JSON files. A montage cannot combine with
|
||||
`slide`; use a separate selected render for detailed text and layout review.
|
||||
|
||||
Pass a montage options object to configure the grid. Dimensions are pixels before
|
||||
`scale`. Defaults are 320 pixels per slide, 16 pixels of padding and gap, and
|
||||
`ceil(sqrt(slideCount))` columns. Slides retain their aspect ratios; each row uses
|
||||
its tallest slide's height. `montage.width` sets the total width and overrides
|
||||
`slideWidth`. `montage.format` overrides the outer raster format. Widths and scale
|
||||
must be positive and finite, columns must be a positive integer, and padding and
|
||||
gap must be nonnegative and finite. Montages support PNG, JPEG, and WebP.
|
||||
|
||||
### Individual slide previews
|
||||
|
||||
Without a montage, `render()` defaults to every slide. An omitted `slide` or an
|
||||
index array returns an array of image Blobs; a single index or `Slide` returns one
|
||||
image Blob. Selected arrays preserve their requested order. Default output names
|
||||
use the actual slide number, such as `slide-1.png` and `slide-3.png` for
|
||||
`slide: [0, 2]`. A custom `fileName` requires a single selected slide.
|
||||
|
||||
Each returned image Blob has a `.layout` JSON Blob containing the same slide's
|
||||
layout view. Session outputs publish both files as render outputs with matching
|
||||
stems, such as `slide-1.png` and `slide-1.layout.json`. Full-deck renders replace
|
||||
both parts of the previous render set; subset renders update only the selected
|
||||
pairs. Rendering a montage does not replace that per-slide set. See
|
||||
[the layout reference](layout.spec.md#read-a-rendered-slides-layout) for the schema.
|
||||
An empty deck or empty selection returns `[]` for individual slide rendering.
|
||||
|
||||
Use `export({ format: "pptx" })` for the editable deliverable. Existing raster
|
||||
and montage `export` options remain supported; raster `export` without a montage
|
||||
retains its single-active-slide default.
|
||||
|
||||
Use `export({ format: "pdf" })` for one PDF containing every slide in deck order,
|
||||
or pass `slide` to export one slide as PDF.
|
||||
|
||||
## Render And Export Inline Types
|
||||
|
||||
```ts
|
||||
type PresentationMontageOptions = {
|
||||
format?: "png" | "jpeg" | "webp";
|
||||
width?: number;
|
||||
slideWidth?: number;
|
||||
padding?: number;
|
||||
gap?: number;
|
||||
background?: string;
|
||||
columns?: number;
|
||||
};
|
||||
|
||||
type PresentationExportOptions = {
|
||||
fileName?: string;
|
||||
slide?: Slide;
|
||||
format?: "png" | "jpeg" | "webp" | "pdf" | "layout" | "pptx";
|
||||
width?: number;
|
||||
height?: number;
|
||||
scale?: number;
|
||||
quality?: number;
|
||||
montage?: boolean | PresentationMontageOptions;
|
||||
};
|
||||
|
||||
type PresentationRenderOptions = Omit<
|
||||
PresentationExportOptions,
|
||||
"format" | "slide"
|
||||
> & {
|
||||
format?: "png" | "jpeg" | "webp";
|
||||
slide?: Slide | number | number[];
|
||||
};
|
||||
|
||||
type PresentationRenderResult = Blob & { layout: Blob };
|
||||
|
||||
interface Presentation {
|
||||
render(options: PresentationRenderOptions & { montage: true | PresentationMontageOptions; slide?: never }): Promise<Blob>;
|
||||
render(options: PresentationRenderOptions & { montage?: false; slide: Slide | number }): Promise<PresentationRenderResult>;
|
||||
render(options?: PresentationRenderOptions & { montage?: false; slide?: number[] }): Promise<PresentationRenderResult[]>;
|
||||
}
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
```ts
|
||||
const result = presentation.scripts.run(scriptKind, scriptOptions);
|
||||
```
|
||||
|
||||
Scripts provide high-level authoring recipes. Use `presentation.help(...)` to discover available script keys and option shapes.
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// New deck skeleton: create, set theme, add slides, render checks.
|
||||
const presentation = Presentation.create({
|
||||
slideSize: { width: 1280, height: 720 },
|
||||
});
|
||||
presentation.theme.colorScheme = {
|
||||
name: "Clean Product",
|
||||
themeColors: {
|
||||
accent1: "#2563eb",
|
||||
accent2: "#0f766e",
|
||||
accent3: "#f59e0b",
|
||||
accent4: "#dc2626",
|
||||
accent5: "#7c3aed",
|
||||
accent6: "#16a34a",
|
||||
bg1: "#ffffff",
|
||||
bg2: "#f8fafc",
|
||||
tx1: "#0f172a",
|
||||
tx2: "#475569",
|
||||
dk1: "#000000",
|
||||
dk2: "#1e293b",
|
||||
lt1: "#ffffff",
|
||||
lt2: "#e2e8f0",
|
||||
hlink: "#2563eb",
|
||||
folHlink: "#7c3aed",
|
||||
},
|
||||
};
|
||||
|
||||
const first = presentation.slides.add();
|
||||
const second = presentation.slides.add();
|
||||
const third = presentation.slides.add();
|
||||
|
||||
await presentation.render({
|
||||
slide: first,
|
||||
scale: 1,
|
||||
});
|
||||
const snapshot = await presentation.inspect({
|
||||
kind: "deck,slide,textbox,chart,table",
|
||||
limit: 20,
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Existing deck: inspect first, then resolve exact anchors.
|
||||
const before = await presentation.inspect({
|
||||
kind: "slide,textbox,shape,image,table,chart,notes,thread,layout",
|
||||
search: "Customer growth",
|
||||
limit: 20,
|
||||
});
|
||||
const target = presentation.resolve(anchorIdFromBefore);
|
||||
```
|
||||
Generated
Vendored
+256
@@ -0,0 +1,256 @@
|
||||
# Rich Text
|
||||
|
||||
Shape text accepts strings, paragraph arrays, and structured runs.
|
||||
|
||||
## Set Text
|
||||
|
||||
```ts
|
||||
shape.text = textValue;
|
||||
shape.text = paragraphs;
|
||||
shape.text = structuredRuns;
|
||||
```
|
||||
|
||||
## Text Value Inline Types
|
||||
|
||||
```ts
|
||||
type TextValue = string | string[] | StructuredTextInput | Text;
|
||||
|
||||
type StructuredTextInput =
|
||||
| ParagraphRunsInput
|
||||
| StructuredTextParagraphInput
|
||||
| Array<ParagraphRunsInput | StructuredTextParagraphInput>;
|
||||
|
||||
type ParagraphRunsInput = Array<string | number | TextRunInput>;
|
||||
|
||||
type StructuredTextParagraphInput = {
|
||||
runs?: ParagraphRunsInput;
|
||||
bulletCharacter?: string;
|
||||
marginLeft?: number;
|
||||
indent?: number;
|
||||
spaceBefore?: number;
|
||||
spaceAfter?: number;
|
||||
styleId?: string;
|
||||
paragraphStyle?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
type TextRunInput = {
|
||||
run: string;
|
||||
style?: {
|
||||
bold?: boolean;
|
||||
italic?: boolean;
|
||||
underline?: string;
|
||||
fontSize?: string;
|
||||
typeface?: string;
|
||||
color?: FillConfig;
|
||||
};
|
||||
textStyle?: TextRunInput["style"]; // Compatibility alias.
|
||||
link?: { uri: string; isExternal: boolean; action?: string };
|
||||
};
|
||||
```
|
||||
|
||||
`style` takes precedence as a complete object when both `style` and `textStyle` are supplied.
|
||||
|
||||
Structured run `fontSize` accepts unit strings such as `"20pt"` and `"28px"`.
|
||||
Shape text style setters use numeric pixels with `fontSize` and numeric points
|
||||
with `fontSizePt`.
|
||||
|
||||
## Structured Paragraphs
|
||||
|
||||
```ts
|
||||
shape.text.set([
|
||||
[{ run: "Status", style: { bold: true } }, { run: " review" }],
|
||||
{
|
||||
bulletCharacter: "•",
|
||||
marginLeft: 18,
|
||||
indent: -10,
|
||||
runs: [
|
||||
"Open the",
|
||||
{
|
||||
run: " rollout notes",
|
||||
style: { underline: "sng", color: "#2563eb" },
|
||||
link: { uri: "https://example.com", isExternal: true },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
```
|
||||
|
||||
The paragraph-object form is the non-JSX peer of `<paragraph>...</paragraph>`. Use it when the text needs paragraph metadata plus authored runs.
|
||||
|
||||
## JSX Rich Text
|
||||
|
||||
```tsx
|
||||
/** @jsxRuntime automatic */
|
||||
|
||||
slide.compose(
|
||||
<column width="fill" height="hug" gap={8}>
|
||||
<paragraph width="fill" className="text-slate-950 text-2xl leading-tight">
|
||||
<run textStyle={{ bold: true }}>Status</run>
|
||||
<run> review</run>
|
||||
</paragraph>
|
||||
<paragraph
|
||||
width="fill"
|
||||
className="text-slate-950 text-2xl leading-tight"
|
||||
bulletCharacter="•"
|
||||
marginLeft={18}
|
||||
indent={-10}
|
||||
>
|
||||
Open the
|
||||
<run
|
||||
textStyle={{ underline: "sng", color: "#2563eb" }}
|
||||
link={{ uri: "https://example.com", isExternal: true }}
|
||||
>
|
||||
{" rollout notes"}
|
||||
</run>
|
||||
</paragraph>
|
||||
</column>,
|
||||
{
|
||||
frame: { left: 48, top: 40, width: 864, height: 160 },
|
||||
baseUnit: 8,
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
## Shape Text Style
|
||||
|
||||
```ts
|
||||
shape.text.style = {
|
||||
styleName,
|
||||
fontSize: fontSizePx,
|
||||
color: colorConfig,
|
||||
fill: fillConfig,
|
||||
outline: lineConfig,
|
||||
alignment,
|
||||
verticalAlignment,
|
||||
autoFit: autoFitMode,
|
||||
wrap: wrapMode,
|
||||
insets,
|
||||
};
|
||||
```
|
||||
|
||||
Use grouped `text.style = { ... }` for whole-shape text formatting. Use single
|
||||
property setters for focused edits:
|
||||
|
||||
```ts
|
||||
shape.text.fontSize = fontSizePx;
|
||||
shape.text.color = colorConfig;
|
||||
shape.text.fill = fillConfig;
|
||||
shape.text.outline = lineConfig;
|
||||
shape.text.alignment = alignment;
|
||||
shape.text.verticalAlignment = verticalAlignment;
|
||||
shape.text.autoFit = autoFitMode;
|
||||
shape.text.wrap = wrapMode;
|
||||
shape.text.insets = 0; // Set all four sides; use an object for individual sides.
|
||||
```
|
||||
|
||||
`shape.text.color` uses `ColorConfig`. `shape.text.fill`, run `style.fill`,
|
||||
and text ranges accept the shared `FillConfig`, including linear and path
|
||||
gradients. `shape.text.outline`, run `style.outline`, and text ranges accept
|
||||
`LineConfig`; the outline line fill can be a solid, pattern, or gradient fill.
|
||||
|
||||
```ts
|
||||
shape.text.fill = {
|
||||
type: "gradient",
|
||||
gradientKind: "linear",
|
||||
angleDeg: 0,
|
||||
stops: [
|
||||
{ offset: 0, color: "#ff5a5f" },
|
||||
{ offset: 100000, color: "#4f46e5" },
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
Path gradients use the same fill config with `gradientKind: "path"`, `pathType`, and optional
|
||||
`fillRect` in thousandths of a percent (`100000` = 100%).
|
||||
|
||||
## Text Style Inline Type
|
||||
|
||||
```ts
|
||||
type TextStyleConfig = {
|
||||
styleName?: string;
|
||||
className?: string;
|
||||
bold?: boolean;
|
||||
italic?: boolean;
|
||||
fontSize?: number;
|
||||
lineSpacing?: number;
|
||||
alignment?: "left" | "center" | "right" | "justify";
|
||||
verticalAlignment?: "top" | "middle" | "bottom";
|
||||
underline?: string;
|
||||
fill?: FillConfig;
|
||||
color?: ColorConfig;
|
||||
outline?: LineConfig;
|
||||
wrap?: "square" | "none";
|
||||
autoFit?: "none" | "shrinkText" | "resizeShapeToFitText";
|
||||
insets?: number | { top?: number; right?: number; bottom?: number; left?: number };
|
||||
typeface?: string;
|
||||
};
|
||||
```
|
||||
|
||||
## Ranges
|
||||
|
||||
```ts
|
||||
const range = shape.text.get(searchText);
|
||||
range.bold = isBold;
|
||||
range.italic = isItalic;
|
||||
range.fill = fillConfig;
|
||||
range.outline = lineConfig;
|
||||
range.link = linkConfig;
|
||||
|
||||
const fixedRange = shape.text.getRange(start, length);
|
||||
fixedRange.style = styleName;
|
||||
```
|
||||
|
||||
## Lists
|
||||
|
||||
```ts
|
||||
shape.text = listParagraphs;
|
||||
shape.text.style = listStyleName;
|
||||
shape.text.get(itemText).lineSpacing = lineSpacing;
|
||||
```
|
||||
|
||||
## Links
|
||||
|
||||
```ts
|
||||
shape.text.get(linkText).link = {
|
||||
uri,
|
||||
isExternal,
|
||||
};
|
||||
```
|
||||
|
||||
## Link Inline Type
|
||||
|
||||
```ts
|
||||
type LinkConfig = {
|
||||
uri: string;
|
||||
isExternal: boolean;
|
||||
action?: string;
|
||||
};
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Title with emphasized suffix.
|
||||
shape.text.set([
|
||||
[
|
||||
{ run: "Revenue", style: { bold: true, color: "#0f172a" } },
|
||||
{ run: " momentum", style: { color: "#2563eb" } },
|
||||
],
|
||||
]);
|
||||
shape.text.style = { fontSize: 44, lineSpacing: 0.92 };
|
||||
```
|
||||
|
||||
```ts
|
||||
// Bullets with bold lead-ins.
|
||||
shape.text.set([
|
||||
{ bulletCharacter: "•", marginLeft: 22, indent: -12, runs: [{ run: "Quality:", style: { bold: true } }, " defect rate down 31%"] },
|
||||
{ bulletCharacter: "•", marginLeft: 22, indent: -12, runs: [{ run: "Speed:", style: { bold: true } }, " p95 latency under target"] },
|
||||
]);
|
||||
```
|
||||
|
||||
```ts
|
||||
// Edit one phrase inside imported text.
|
||||
const range = shape.text.get("legacy workflow");
|
||||
range.text = "new workflow";
|
||||
range.className = "text-emerald-700 font-bold";
|
||||
```
|
||||
Generated
Vendored
+279
@@ -0,0 +1,279 @@
|
||||
# Shapes
|
||||
|
||||
`slide.shapes` creates and edits drawable slide elements.
|
||||
|
||||
## Preset Shape
|
||||
|
||||
```ts
|
||||
const shape = slide.shapes.add({
|
||||
geometry,
|
||||
name,
|
||||
position,
|
||||
fill,
|
||||
line,
|
||||
adjustmentList,
|
||||
borderRadius,
|
||||
shadow,
|
||||
className,
|
||||
text: { text: textValue, style: { styleName: textStyleName, fontSize, bold, color } },
|
||||
});
|
||||
|
||||
shape.position = nextPosition;
|
||||
```
|
||||
|
||||
`geometry` is a string preset shape name, `"textbox"`, `"connector"`, or `"custom"`.
|
||||
Set `shape.text.insets = 0` to remove all text margins. A number sets every side;
|
||||
an object sets individual sides. Creation styles also accept `insets: 0`.
|
||||
|
||||
## Resolved From Inspect
|
||||
|
||||
```ts
|
||||
const shape = presentation.resolve("sh/a1b2c3d4");
|
||||
shape.text = "Updated copy";
|
||||
shape.fill = "accent1+18/90";
|
||||
shape.line = { style: "solid", fill: "slate-200", width: 1 };
|
||||
shape.geometry = "roundRect";
|
||||
shape.geometry; // "roundRect"
|
||||
shape.borderRadius = "rounded-2xl";
|
||||
shape.shadow = "shadow-sm";
|
||||
```
|
||||
|
||||
Use `presentation.inspect({ kind: "shape,textbox", search })` to find the
|
||||
`sh/...` anchor id. Keep the resolved facade type-aware; do not rebuild an
|
||||
imported shape unless the task requires a new object.
|
||||
|
||||
## Preset Shape Inline Type
|
||||
|
||||
```ts
|
||||
type ShapePresetName = string; // common: "textbox", "rect", "roundRect", "ellipse", "line", "rightArrow"
|
||||
// Full preset list: rg "SHAPE_GEOMETRY_NAME_TO_PROTO" src/models/presentation src/assets
|
||||
|
||||
type PositionConfig = {
|
||||
left?: number;
|
||||
top?: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
rotation?: number;
|
||||
horizontalFlip?: boolean;
|
||||
verticalFlip?: boolean;
|
||||
};
|
||||
|
||||
type PresetShapeConfig = {
|
||||
geometry: ShapePresetName;
|
||||
name?: string;
|
||||
position?: PositionConfig;
|
||||
fill?: FillConfig;
|
||||
line?: LineConfig;
|
||||
adjustmentList?: Array<{ name: string; formula: string }>;
|
||||
borderRadius?: number | string; // number = pixels; string = supported rounded-* token
|
||||
shadow?: string; // shadow token, "shadow-none", or custom "2px 7px 19px #000000/17"
|
||||
className?: string;
|
||||
text?: TextValue | { text: TextValue; style?: string | ShapeTextStyleConfig };
|
||||
placeholderType?: "title" | "subtitle" | "body" | "picture" | "chart" | "table" | "content";
|
||||
placeholderIndex?: number;
|
||||
};
|
||||
```
|
||||
|
||||
## Rounded Corners
|
||||
|
||||
Prefer `borderRadius` for rect-like rounded corners:
|
||||
|
||||
```ts
|
||||
slide.shapes.add({
|
||||
geometry: "rect",
|
||||
position: { left: 80, top: 120, width: 320, height: 160 },
|
||||
fill: "white",
|
||||
borderRadius: "rounded-2xl",
|
||||
});
|
||||
|
||||
shape.borderRadius = 24;
|
||||
```
|
||||
|
||||
Numbers are pixels. Strings use supported `rounded-*` tokens. `borderRadius`
|
||||
requires a shape with width/height and is supported for `rect`, `textbox`, and
|
||||
`roundRect`-like shapes. Use `adjustmentList` only when you need exact OpenXML
|
||||
preset adjustment formulas.
|
||||
|
||||
## Rounded Rect Adjustment
|
||||
|
||||
```ts
|
||||
const rounded = slide.shapes.add({
|
||||
geometry: "roundRect",
|
||||
position,
|
||||
fill,
|
||||
line,
|
||||
adjustmentList: [{ name: "adj", formula: adjustmentFormula }],
|
||||
});
|
||||
|
||||
rounded.adjustmentList = [{ name: "adj", formula: nextAdjustmentFormula }];
|
||||
rounded.adjustmentList;
|
||||
```
|
||||
|
||||
The `adj` value uses the OpenXML shape adjustment scale for the corner radius.
|
||||
|
||||
## Custom Path
|
||||
|
||||
```ts
|
||||
const custom = slide.shapes.add({
|
||||
geometry: "custom",
|
||||
position,
|
||||
fill,
|
||||
line,
|
||||
customPaths: [
|
||||
{
|
||||
width,
|
||||
height,
|
||||
commands,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
custom.customPaths = nextCustomPaths;
|
||||
custom.customPaths;
|
||||
```
|
||||
|
||||
Custom path coordinates use pixels in the path viewport.
|
||||
|
||||
## Bézier Curve
|
||||
|
||||
```ts
|
||||
const curve = slide.shapes.add({
|
||||
geometry: "custom",
|
||||
name: "Bezier curve",
|
||||
position: { left: 120, top: 190, width: 720, height: 240 },
|
||||
fill: "none",
|
||||
line: { style: "solid", fill: "#2463EB", width: 3 },
|
||||
customPaths: [{
|
||||
width: 720,
|
||||
height: 240,
|
||||
commands: [
|
||||
{ moveTo: { x: 0, y: 150 } },
|
||||
{ cubicBezTo: { x1: 100, y1: 150, x2: 120, y2: 0, x: 240, y: 40 } },
|
||||
{ cubicBezTo: { x1: 360, y1: 80, x2: 320, y2: 240, x: 480, y: 190 } },
|
||||
{ cubicBezTo: { x1: 620, y1: 130, x2: 620, y2: 80, x: 720, y: 100 } },
|
||||
],
|
||||
}],
|
||||
});
|
||||
```
|
||||
|
||||
Each cubic starts at the previous endpoint; `(x1, y1)` and `(x2, y2)` are its
|
||||
control points, and `(x, y)` is its endpoint. Omit `close` for an open curve.
|
||||
These coordinates define the curve directly; `adjustmentList` is for named
|
||||
geometry parameters. Use `slide.shapes.connect(..., { kind: "curved" })` for
|
||||
a connector that follows attached shapes.
|
||||
|
||||
## Custom Path Inline Type
|
||||
|
||||
```ts
|
||||
type CustomShapeConfig = Omit<PresetShapeConfig, "geometry"> & {
|
||||
geometry: "custom";
|
||||
customPaths: Array<{
|
||||
id?: string;
|
||||
width: number;
|
||||
height: number;
|
||||
commands: Array<
|
||||
| { moveTo: { x: number; y: number } }
|
||||
| { lineTo: { x: number; y: number } }
|
||||
| { quadBezTo: { x1: number; y1: number; x: number; y: number } }
|
||||
| { cubicBezTo: { x1: number; y1: number; x2: number; y2: number; x: number; y: number } }
|
||||
| { close: Record<string, never> }
|
||||
>;
|
||||
}>;
|
||||
};
|
||||
```
|
||||
|
||||
## Connector
|
||||
|
||||
```ts
|
||||
const connector = slide.shapes.connect(sourceShape, targetShape, {
|
||||
kind: "elbow",
|
||||
fromSide: "right",
|
||||
toSide: "left",
|
||||
line: { style: "solid", fill: "slate-400", width: 2 },
|
||||
head: { type: "arrow", width: "med", length: "med" },
|
||||
});
|
||||
```
|
||||
|
||||
Use [`connectors.md`](./connectors.md) for connector routing, side anchors,
|
||||
direct `geometry: "connector"` creation, arrowheads, and endpoint edits.
|
||||
|
||||
## Line Primitive Decision
|
||||
|
||||
| Need | Use |
|
||||
| --- | --- |
|
||||
| Divider inside compose JSX | `<rule stroke="slate-200" weight={1} />` |
|
||||
| Free-positioned line | `slide.shapes.add({ geometry: "line", position, fill: "none", line })` |
|
||||
| Freeform curve with Bézier control points | `slide.shapes.add({ geometry: "custom", position, fill: "none", line, customPaths })` |
|
||||
| Arrow connected to shapes | `slide.shapes.connect(fromShape, toShape, { line, head })` |
|
||||
| Border around a surface | shape or box `line={{ style: "solid", fill: "slate-200", width: 1 }}` |
|
||||
|
||||
## Shadows
|
||||
|
||||
Supported shadow tokens:
|
||||
|
||||
```text
|
||||
shadow-none, shadow-sm, shadow, shadow-md, shadow-lg, shadow-xl, shadow-2xl
|
||||
```
|
||||
|
||||
Custom shadow strings are also supported when the presentation has a theme
|
||||
context:
|
||||
|
||||
```ts
|
||||
shape.shadow = "shadow-md";
|
||||
shape.shadow = "2px 7px 19px #000000/17";
|
||||
shape.shadow = "shadow-none";
|
||||
```
|
||||
|
||||
## Ordering
|
||||
|
||||
```ts
|
||||
shape.bringToFront();
|
||||
shape.bringForward();
|
||||
shape.sendToBack();
|
||||
shape.sendBackward();
|
||||
```
|
||||
|
||||
These inherited methods also apply to images, tables, charts, embedded workbooks, and SmartArt. Forward/backward moves one position in the owning surface’s stack; front/back moves to an end.
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// KPI metric surface.
|
||||
const metricSurface = slide.shapes.add({
|
||||
geometry: "roundRect",
|
||||
name: "kpi-surface",
|
||||
position: { left: 64, top: 132, width: 260, height: 148 },
|
||||
fill: "white",
|
||||
line: { style: "solid", fill: "slate-200", width: 1 },
|
||||
borderRadius: "rounded-2xl",
|
||||
shadow: "shadow-md",
|
||||
});
|
||||
metricSurface.text = "Revenue\n$12.4M";
|
||||
metricSurface.text.style = {
|
||||
className: "text-slate-950 text-2xl font-bold leading-tight",
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
// Pill label.
|
||||
const pill = slide.shapes.add({
|
||||
geometry: "roundRect",
|
||||
position: { left: 64, top: 64, width: 148, height: 34 },
|
||||
fill: "emerald-50",
|
||||
line: { style: "solid", fill: "emerald-200", width: 1 },
|
||||
borderRadius: "rounded-full",
|
||||
});
|
||||
pill.text = "ON TRACK";
|
||||
pill.text.style = { className: "text-emerald-800 text-sm font-bold" };
|
||||
```
|
||||
|
||||
```ts
|
||||
// Directional connector between two shapes.
|
||||
slide.shapes.connect(sourceShape, targetShape, {
|
||||
kind: "elbow",
|
||||
fromSide: "right",
|
||||
toSide: "left",
|
||||
line: { style: "solid", fill: "slate-400", width: 2 },
|
||||
head: { type: "triangle", width: "sm", length: "sm" },
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+199
@@ -0,0 +1,199 @@
|
||||
# Slide Facade
|
||||
|
||||
## Slide Show Visibility
|
||||
|
||||
```ts
|
||||
slide.hidden = isHidden;
|
||||
```
|
||||
|
||||
Hidden slides stay in the deck but are skipped during a slide show.
|
||||
|
||||
## Content Collections
|
||||
|
||||
```ts
|
||||
const shape = slide.shapes.add(shapeConfig);
|
||||
const image = slide.images.add(imageConfig);
|
||||
const table = slide.tables.add(tableConfig);
|
||||
const chart = slide.charts.add(chartType, chartConfig);
|
||||
```
|
||||
|
||||
## Content Config Pointers
|
||||
|
||||
```ts
|
||||
type ShapeConfig = PresetShapeConfig | CustomShapeConfig | ConnectorConfig; // see shapes.spec.md
|
||||
type ImageConfig = ImageAddOptions; // see images.spec.md
|
||||
type TableConfig = TableAddOptions | TableCellValue[][]; // see tables.spec.md
|
||||
type ChartConfig = {
|
||||
position?: { left?: number; top?: number; width?: number; height?: number };
|
||||
title?: string;
|
||||
categories?: string[];
|
||||
series?: Array<{ name: string; values?: number[] }>;
|
||||
}; // see charts.spec.md for axes, legend, labels, and series styling
|
||||
```
|
||||
|
||||
## Background
|
||||
|
||||
```ts
|
||||
const slide = presentation.slides.add({ background: { fill: fillConfig } });
|
||||
slide.background.fill = fillConfig;
|
||||
```
|
||||
|
||||
`fillConfig` accepts theme color strings, hex strings, solid configs, gradient configs, pattern configs, and image-fill configs.
|
||||
|
||||
## Layouts And Placeholders
|
||||
|
||||
```ts
|
||||
slide.setLayout(layout);
|
||||
|
||||
const placeholder = slide.placeholders.getItem(placeholderName);
|
||||
placeholder.text = placeholderText;
|
||||
placeholder.text.style = placeholderStyleName;
|
||||
```
|
||||
|
||||
```ts
|
||||
const actualPlaceholders = slide.placeholders.items;
|
||||
const emptyContentPlaceholders = slide.placeholders.editable;
|
||||
const allVisibleEmptyPlaceholders = slide.placeholders.unfilled;
|
||||
const missingLayoutSlots = slide.placeholders.availableFromLayout;
|
||||
const createdPlaceholders = slide.placeholders.addFromLayout();
|
||||
```
|
||||
|
||||
## Frame And Export
|
||||
|
||||
```ts
|
||||
const frame = slide.frame;
|
||||
const preview = await slide.export({ format, scale });
|
||||
const pdf = await slide.export({ format: "pdf" });
|
||||
```
|
||||
|
||||
## Compose Layout
|
||||
|
||||
```tsx
|
||||
/** @jsxRuntime automatic */
|
||||
|
||||
slide.compose(
|
||||
<row width="fill" height="fill" gap={20}>
|
||||
<column width={340} height="fill" gap={12}>
|
||||
<paragraph name="summary" className="text-slate-950 text-3xl font-bold">
|
||||
Summary
|
||||
</paragraph>
|
||||
<paragraph className="text-slate-600 text-sm">
|
||||
Compose-first layouts stay readable and export cleanly.
|
||||
</paragraph>
|
||||
</column>
|
||||
<box name="surface" width="fill" height="fill" padding={16} fill="#ffffff">
|
||||
<column height="fill" gap={10}>
|
||||
<rule stroke="#0f172a" weight={2} />
|
||||
</column>
|
||||
</box>
|
||||
</row>,
|
||||
{
|
||||
frame: { left: 48, top: 40, width: 864, height: 460 },
|
||||
baseUnit: 8,
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
`slide.compose(...)` accepts either compose helper nodes or a JSX-authored tree.
|
||||
It still returns the materialized elements. Use `name` on materializing nodes
|
||||
when the slide needs stable inspect or layout-export anchors.
|
||||
|
||||
## Export Inline Type
|
||||
|
||||
```ts
|
||||
type SlideExportOptions = {
|
||||
format?: "png" | "jpeg" | "webp" | "pdf" | "layout";
|
||||
width?: number;
|
||||
height?: number;
|
||||
scale?: number;
|
||||
quality?: number;
|
||||
};
|
||||
```
|
||||
|
||||
`format: "layout"` exports the composed layout tree alongside the materialized slide elements. That is the most useful export when you need stable names, hierarchy paths, and resolved text for follow-up targeting.
|
||||
|
||||
## Auto Layout
|
||||
|
||||
```ts
|
||||
slide.autoLayout(shapes, {
|
||||
direction,
|
||||
frame,
|
||||
align,
|
||||
horizontalGap,
|
||||
verticalGap,
|
||||
horizontalPadding,
|
||||
verticalPadding,
|
||||
});
|
||||
```
|
||||
|
||||
## Auto Layout Inline Type
|
||||
|
||||
```ts
|
||||
type AutoLayoutOptions = {
|
||||
direction?: "horizontal" | "vertical";
|
||||
frame?:
|
||||
| "slide"
|
||||
| Shape
|
||||
| { left: number; top: number; width: number; height: number };
|
||||
align?:
|
||||
| "center"
|
||||
| "topLeft"
|
||||
| "topCenter"
|
||||
| "topRight"
|
||||
| "left"
|
||||
| "right"
|
||||
| "bottomLeft"
|
||||
| "bottomCenter"
|
||||
| "bottomRight";
|
||||
horizontalGap?: number | "auto";
|
||||
verticalGap?: number | "auto";
|
||||
horizontalPadding?: number;
|
||||
verticalPadding?: number;
|
||||
};
|
||||
```
|
||||
|
||||
## Speaker Notes
|
||||
|
||||
```ts
|
||||
slide.speakerNotes.text = notesText;
|
||||
slide.speakerNotes.setVisible(visible);
|
||||
```
|
||||
|
||||
## Visual QA Loop
|
||||
|
||||
```ts
|
||||
const preview = await slide.export({ format: "png", scale: 2 });
|
||||
const layout = await slide.export({ format: "layout" });
|
||||
const after = await presentation.inspect({
|
||||
kind: "slide,textbox,shape,image,table,chart,notes",
|
||||
target: { id: slideAnchorId, beforeLines: 2, afterLines: 8 },
|
||||
maxChars: 4000,
|
||||
});
|
||||
```
|
||||
|
||||
Check the PNG for clipping, overlap, weak contrast, illegible text, bad image
|
||||
crops, accidental rasterized labels, and off-canvas elements. Check the layout
|
||||
export or inspect output for stable `name` values on important nodes.
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Gradient background plus editable content.
|
||||
slide.background.fill = "linear(180deg, slate-950 0%, blue-950 100%)";
|
||||
const title = slide.shapes.add({
|
||||
geometry: "textbox",
|
||||
name: "title",
|
||||
position: { left: 72, top: 72, width: 760, height: 120 },
|
||||
fill: "none",
|
||||
line: { style: "solid", fill: "none", width: 0 },
|
||||
});
|
||||
title.text = "Editable headline";
|
||||
title.text.style = { fontSize: 44, bold: true, color: "white" };
|
||||
```
|
||||
|
||||
```ts
|
||||
// Clone rhythm from another slide, then change content.
|
||||
const next = sourceSlide.duplicate();
|
||||
next.moveTo(3);
|
||||
next.placeholders.getItem("title").text = "Updated section title";
|
||||
```
|
||||
Generated
Vendored
+48
@@ -0,0 +1,48 @@
|
||||
# Speaker Notes
|
||||
|
||||
Speaker notes live on `slide.speakerNotes`.
|
||||
|
||||
## Set Text
|
||||
|
||||
```ts
|
||||
const speakerNotes = slide.speakerNotes;
|
||||
speakerNotes.text = notesText;
|
||||
const savedText = speakerNotes.text;
|
||||
```
|
||||
|
||||
## Notes Text Inline Type
|
||||
|
||||
```ts
|
||||
type NotesTextValue = string | string[] | StructuredTextInput;
|
||||
|
||||
type TextRunInput = {
|
||||
run: string;
|
||||
style?: { bold?: boolean; italic?: boolean; fontSize?: string; color?: FillConfig };
|
||||
textStyle?: TextRunInput["style"]; // Compatibility alias.
|
||||
};
|
||||
```
|
||||
|
||||
## Visibility And Clearing
|
||||
|
||||
```ts
|
||||
speakerNotes.setVisible(visible);
|
||||
const visibleState = speakerNotes.isVisible();
|
||||
speakerNotes.clear();
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Structured presenter notes.
|
||||
slide.speakerNotes.text = [
|
||||
"Open with the customer problem, not the feature list.",
|
||||
"Call out the chart source before discussing the slope.",
|
||||
"Pause for questions before the implementation timeline.",
|
||||
];
|
||||
slide.speakerNotes.setVisible(true);
|
||||
```
|
||||
|
||||
```ts
|
||||
// Append without deleting imported notes.
|
||||
slide.speakerNotes.append("\nFollow-up: confirm launch date with PM.");
|
||||
```
|
||||
Generated
Vendored
+85
@@ -0,0 +1,85 @@
|
||||
# Named Text Styles
|
||||
|
||||
`presentation.styles` stores reusable text styles for shapes and text ranges.
|
||||
|
||||
## Style Surface Map
|
||||
|
||||
| Need | API |
|
||||
| --- | --- |
|
||||
| Deck-level tokenized text style ids | `presentation.theme.textStyles({...})` |
|
||||
| Slide-scoped generated text style ids | `slide.theme.textStyles({...})` |
|
||||
| Explicit named styles by facade | `presentation.styles.add(name)` |
|
||||
|
||||
## Built-In Styles
|
||||
|
||||
```ts
|
||||
const styles = presentation.styles;
|
||||
const style = styles.get(styleName);
|
||||
const summary = styles.describe(styleName);
|
||||
const allStyles = styles.describe();
|
||||
```
|
||||
|
||||
## Custom Style
|
||||
|
||||
```ts
|
||||
const custom = presentation.styles.add(styleName);
|
||||
custom.description = styleDescription;
|
||||
custom.color = styleColor;
|
||||
custom.bold = isBold;
|
||||
custom.italic = isItalic;
|
||||
custom.fontSize = fontSizePx;
|
||||
custom.alignment = alignment;
|
||||
```
|
||||
|
||||
## Named Style Facade Fields
|
||||
|
||||
```ts
|
||||
type NamedStyleFacade = {
|
||||
description?: string;
|
||||
usageHint?: string;
|
||||
bold?: boolean;
|
||||
italic?: boolean;
|
||||
fontSize?: number;
|
||||
alignment?: "left" | "center" | "right" | "justify";
|
||||
underline?: string;
|
||||
color?: ColorConfig;
|
||||
};
|
||||
```
|
||||
|
||||
Use broader `TextStyleConfig` objects on `shape.text.style = { ... }`,
|
||||
`presentation.theme.textStyles(...)`, and `slide.theme.textStyles(...)`.
|
||||
|
||||
## Use A Style
|
||||
|
||||
```ts
|
||||
shape.text = textValue;
|
||||
shape.text.style = styleName;
|
||||
|
||||
const range = shape.text.get(rangeText);
|
||||
range.style = styleName;
|
||||
```
|
||||
|
||||
Named styles are block-level for paragraph style assignments and range-level for selected text ranges.
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Deck-level type scale.
|
||||
const display = presentation.styles.add("Display");
|
||||
display.fontSize = 52;
|
||||
display.bold = true;
|
||||
display.color = "#0f172a";
|
||||
display.usageHint = "Hero and section titles";
|
||||
|
||||
const body = presentation.styles.add("Body");
|
||||
body.fontSize = 20;
|
||||
body.color = "#475569";
|
||||
body.usageHint = "Readable body copy";
|
||||
```
|
||||
|
||||
```ts
|
||||
// Apply a style, then emphasize one range.
|
||||
shape.text = "Revenue accelerated across enterprise accounts.";
|
||||
shape.text.style = "Body";
|
||||
shape.text.get("Revenue").style = "Display";
|
||||
```
|
||||
Generated
Vendored
+198
@@ -0,0 +1,198 @@
|
||||
# Tables
|
||||
|
||||
`slide.tables` creates and edits PowerPoint-style tables.
|
||||
|
||||
## Resolved From Inspect
|
||||
|
||||
```ts
|
||||
const table = presentation.resolve("tb/d4e5f6a7");
|
||||
table.cells.set(1, 2, "$4.2M");
|
||||
table.getCell(1, 2).text.style = "Body Small";
|
||||
table.borders.assign({ style: "solid", fill: "slate-200", width: 1 });
|
||||
```
|
||||
|
||||
Use `presentation.inspect({ kind: "table", search })` to find the `tb/...`
|
||||
anchor id. If an imported table resolves as an image, preserve it as an image or
|
||||
rebuild it as a native table intentionally.
|
||||
|
||||
## Add Table
|
||||
|
||||
```ts
|
||||
const table = slide.tables.add({
|
||||
rows,
|
||||
columns,
|
||||
left,
|
||||
top,
|
||||
width,
|
||||
height,
|
||||
columnTracks: [fr(2), fr(1), fixed(120)],
|
||||
values,
|
||||
});
|
||||
```
|
||||
|
||||
Primitive matrices and structured text runs are accepted for `values`. Use `columnTracks` with `fr(...)` and `fixed(...)` when a table should fill its frame with proportional columns. Use `columnWidths` only for explicit pixel widths.
|
||||
|
||||
## Table Inline Types
|
||||
|
||||
```ts
|
||||
type TableAddOptions = {
|
||||
rows: number;
|
||||
columns: number;
|
||||
left?: number;
|
||||
top?: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
values?: TableCellValue[][];
|
||||
columnTracks?: TableColumnTrack[];
|
||||
columnWidths?: number[];
|
||||
};
|
||||
|
||||
type TableColumnTrack =
|
||||
| { mode: "fr"; value: number }
|
||||
| { mode: "fixed"; value: number };
|
||||
|
||||
type TableCellValue = string | number | string[] | StructuredTextInput | Text;
|
||||
```
|
||||
|
||||
## Cells
|
||||
|
||||
```ts
|
||||
const cell = table.getCell(rowIndex, columnIndex);
|
||||
cell.value = cellValue;
|
||||
cell.fill = fillConfig;
|
||||
cell.text.style = textStyleName;
|
||||
|
||||
table.cells.set(rowIndex, columnIndex, textObjectOrValue);
|
||||
```
|
||||
|
||||
## Ranges And Merges
|
||||
|
||||
```ts
|
||||
table.merge({
|
||||
startRow,
|
||||
endRow,
|
||||
startColumn,
|
||||
endColumn,
|
||||
});
|
||||
|
||||
const range = table.cells.block(rangeConfig);
|
||||
range.fill = fillConfig;
|
||||
range.textStyle.bold = isBold;
|
||||
range.textStyle.color = textColor;
|
||||
range.textStyle.fontSize = fontSizePx;
|
||||
range.borders = borderConfig;
|
||||
|
||||
table.unmerge({ startRow, endRow, startColumn, endColumn });
|
||||
```
|
||||
|
||||
## Insert And Delete Rows Or Columns
|
||||
|
||||
```ts
|
||||
table.insertRows({ index: rowIndex, count: 2 });
|
||||
table.deleteRows({ index: rowIndex, count: 1 });
|
||||
table.insertColumns({ index: columnIndex });
|
||||
table.deleteColumns({ index: columnIndex });
|
||||
```
|
||||
|
||||
## Range And Merge Inline Types
|
||||
|
||||
```ts
|
||||
type TableMergeRange = {
|
||||
startRow: number;
|
||||
endRow: number;
|
||||
startColumn: number;
|
||||
endColumn: number;
|
||||
};
|
||||
|
||||
type TableCellRangeConfig = {
|
||||
row: number;
|
||||
column: number;
|
||||
rowCount: number;
|
||||
columnCount: number;
|
||||
};
|
||||
```
|
||||
|
||||
## Style
|
||||
|
||||
```ts
|
||||
table.style = tableStyleId;
|
||||
table.styleOptions = tableStyleOptions;
|
||||
table.columnTracks = [fr(2), fr(1), fixed(120)];
|
||||
table.rows[0].height = headerHeightPx;
|
||||
table.columns.get(columnIndex).width = columnWidthPx;
|
||||
table.borders.assign(borderConfig);
|
||||
|
||||
table.cells.block({ row, column, rowCount, columnCount }).assign({
|
||||
fill,
|
||||
textStyle,
|
||||
borders,
|
||||
margins,
|
||||
anchor,
|
||||
horizontalOverflow,
|
||||
});
|
||||
```
|
||||
|
||||
## Style Inline Types
|
||||
|
||||
```ts
|
||||
type TableStyleOptions = {
|
||||
headerRow?: boolean;
|
||||
totalRow?: boolean;
|
||||
firstColumn?: boolean;
|
||||
lastColumn?: boolean;
|
||||
bandedRows?: boolean;
|
||||
bandedColumns?: boolean;
|
||||
};
|
||||
|
||||
type TableBorderLineConfig = {
|
||||
style?: "solid" | "dashed" | "dotted" | "dash-dot" | "dash-dot-dot" | string;
|
||||
width?: number;
|
||||
fill?: FillConfig;
|
||||
color?: FillConfig;
|
||||
};
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Compact KPI table.
|
||||
const table = slide.tables.add({
|
||||
rows: 4,
|
||||
columns: 3,
|
||||
left: 96,
|
||||
top: 168,
|
||||
width: 680,
|
||||
height: 220,
|
||||
values: [
|
||||
["Metric", "Current", "Delta"],
|
||||
["Revenue", "$12.4M", "+18%"],
|
||||
["Retention", "94%", "+3 pts"],
|
||||
["Latency", "182 ms", "-22 ms"],
|
||||
],
|
||||
});
|
||||
table.styleOptions = { headerRow: true, bandedRows: true };
|
||||
table.getCell(0, 0).fill = "slate-950";
|
||||
table.getCell(0, 1).fill = "slate-950";
|
||||
table.getCell(0, 2).fill = "slate-950";
|
||||
table.borders.assign({ style: "solid", fill: "slate-200", width: 1 });
|
||||
```
|
||||
|
||||
```ts
|
||||
// Spanning title row.
|
||||
table.merge({ startRow: 0, endRow: 0, startColumn: 0, endColumn: 2 });
|
||||
table.getCell(0, 0).value = "Regional performance";
|
||||
table.getCell(0, 0).text.style = "title";
|
||||
```
|
||||
|
||||
```ts
|
||||
// Highlight a cell range.
|
||||
const riskRange = table.cells.block({
|
||||
row: 2,
|
||||
column: 2,
|
||||
rowCount: 2,
|
||||
columnCount: 1,
|
||||
});
|
||||
riskRange.fill = "amber-50";
|
||||
riskRange.textStyle.color = "#92400e";
|
||||
riskRange.textStyle.bold = true;
|
||||
```
|
||||
Generated
Vendored
+97
@@ -0,0 +1,97 @@
|
||||
# Theme
|
||||
|
||||
Themes provide default fonts, named colors, and text style tokens.
|
||||
|
||||
## Default Font
|
||||
|
||||
```ts
|
||||
presentation.theme.defaultFont = "Aptos";
|
||||
```
|
||||
|
||||
New presentations default to Aptos. Set `defaultFont: string` once during setup
|
||||
to choose the theme's Latin heading and body font. Shape text with no explicit
|
||||
`typeface` inherits the theme; a local `typeface` overrides it. The choice persists with
|
||||
the presentation. Imported presentations retain their existing font schemes;
|
||||
changing `defaultFont` preserves language-specific font mappings.
|
||||
|
||||
## Color Scheme
|
||||
|
||||
```ts
|
||||
presentation.theme.colorScheme = {
|
||||
name: themeName,
|
||||
themeColors,
|
||||
};
|
||||
|
||||
const hexMap = presentation.theme.hexColorMap;
|
||||
```
|
||||
|
||||
`themeColors` maps every theme color name to a color config value. Assigning
|
||||
`presentation.theme.colorScheme` replaces the active scheme, so provide the
|
||||
full map.
|
||||
|
||||
## Color Scheme Inline Type
|
||||
|
||||
```ts
|
||||
type ThemeColorName =
|
||||
| "accent1" | "accent2" | "accent3" | "accent4" | "accent5" | "accent6"
|
||||
| "bg1" | "bg2" | "tx1" | "tx2" | "dk1" | "lt1" | "dk2" | "lt2"
|
||||
| "hlink" | "folHlink";
|
||||
|
||||
type ColorSchemeConfig = {
|
||||
name: string;
|
||||
themeColors: Record<ThemeColorName, ColorConfig>;
|
||||
};
|
||||
```
|
||||
|
||||
## Theme Colors In Content
|
||||
|
||||
```ts
|
||||
const shape = slide.shapes.add({
|
||||
geometry,
|
||||
position,
|
||||
fill: themeColorName,
|
||||
line: { style: lineStyle, fill: lineColor, width: lineWidthPx },
|
||||
});
|
||||
```
|
||||
|
||||
## Text Styles
|
||||
|
||||
```ts
|
||||
const styles = slide.theme.textStyles({
|
||||
[styleName]: textStyleConfig,
|
||||
});
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Business/product palette.
|
||||
presentation.theme.colorScheme = {
|
||||
name: "Product Editorial",
|
||||
themeColors: {
|
||||
accent1: "#2563eb",
|
||||
accent2: "#0f766e",
|
||||
accent3: "#f59e0b",
|
||||
accent4: "#dc2626",
|
||||
accent5: "#7c3aed",
|
||||
accent6: "#16a34a",
|
||||
bg1: "#ffffff",
|
||||
bg2: "#f8fafc",
|
||||
tx1: "#0f172a",
|
||||
tx2: "#475569",
|
||||
dk1: "#000000",
|
||||
dk2: "#1e293b",
|
||||
lt1: "#ffffff",
|
||||
lt2: "#e2e8f0",
|
||||
hlink: "#2563eb",
|
||||
folHlink: "#7c3aed",
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
// Use theme tokens in content so later theme changes flow through.
|
||||
slide.background.fill = "bg1";
|
||||
shape.fill = "accent1";
|
||||
shape.text.style = { color: "tx1" };
|
||||
```
|
||||
Generated
Vendored
+447
@@ -0,0 +1,447 @@
|
||||
# Presentation Token Reference
|
||||
|
||||
This reference covers the Tailwind-like tokens supported by presentation
|
||||
shapes, text, and JSX. These are presentation tokens, not browser CSS.
|
||||
|
||||
## Where Tokens Work
|
||||
|
||||
| Surface | Token entry |
|
||||
| --- | --- |
|
||||
| Shape/box fill | `fill="sky-500"`, `fill="rose-500/80"` |
|
||||
| Shape/box line | `line={{ style: "solid", fill: "slate-200", width: 1 }}` |
|
||||
| Shape/box radius | `borderRadius="rounded-xl"` |
|
||||
| Image radius | `borderRadius="rounded-2xl"` |
|
||||
| Shape shadow | `shadow="shadow-md"` |
|
||||
| Shape/box className | `className="bg-white rounded-xl shadow-sm"` |
|
||||
| Text className | `className="text-slate-700 text-lg font-bold leading-tight"` |
|
||||
| Imperative shape | `shape.className = "bg-sky-50 rounded-lg shadow"` |
|
||||
| Imperative text | `shape.text.style = { className: "text-slate-800 text-xl leading-relaxed" }` |
|
||||
| Text range | `shape.text.get("Total").className = "text-emerald-600 font-bold"` |
|
||||
|
||||
Explicit props override `className` on JSX nodes. For example,
|
||||
`<box className="bg-slate-900" fill="white" />` uses the explicit `fill`.
|
||||
`className` is only for visual/text tokens. Use real JSX props for layout:
|
||||
`width`, `height`, `gap`, `padding`, `align`, and `justify`.
|
||||
|
||||
## Decision Table
|
||||
|
||||
| Need | Use |
|
||||
| --- | --- |
|
||||
| Common shape styling | `className="bg-white rounded-xl shadow-sm"` |
|
||||
| Exact fill or gradient | `fill="#0f172a"` or `fill="linear(135deg, #fff 0%, sky-100 100%)"` |
|
||||
| Exact line | `line={{ style: "solid", fill: "slate-200", width: 1 }}` |
|
||||
| Common text styling | `className="text-slate-700 text-lg font-bold leading-tight"` |
|
||||
| Exact text style | `style="font: 700 22px Inter; color: #334155; leading: 1.25; wrap: none"` |
|
||||
| Inline emphasis | `<run textStyle={{ bold: true, color: "sky-600" }}>...</run>` |
|
||||
| Layout | real props such as `gap={24}`, `padding={{ x: 32, y: 24 }}`, `align="center"` |
|
||||
|
||||
## Token Cookbook
|
||||
|
||||
Transparent overlay:
|
||||
|
||||
```tsx
|
||||
<shape geometry="rect" width="fill" height="fill" fill="black/45" />
|
||||
<paragraph className="text-white/80 text-xl">Readable over an image</paragraph>
|
||||
```
|
||||
|
||||
Theme color with a transform:
|
||||
|
||||
```tsx
|
||||
<box fill="accent1+18/90" />
|
||||
<paragraph style="font: 700 18px Inter; color: tx1-10/85; wrap: none">
|
||||
Theme-aware text
|
||||
</paragraph>
|
||||
```
|
||||
|
||||
`+` lightens, `-` darkens, and `/` sets opacity. The suffix accepts unit
|
||||
fractions, numbers, or percentages: `accent1+0.18/0.9`, `accent1+18/90`, and
|
||||
`accent1+18%/90%` are equivalent.
|
||||
|
||||
Soft surface with exact line:
|
||||
|
||||
```tsx
|
||||
<box
|
||||
fill="slate-50"
|
||||
line={{ style: "solid", fill: "slate-200", width: 1 }}
|
||||
borderRadius="rounded-2xl"
|
||||
shadow="shadow-sm"
|
||||
/>
|
||||
```
|
||||
|
||||
No fill, visible stroke:
|
||||
|
||||
```tsx
|
||||
<shape
|
||||
geometry="ellipse"
|
||||
fill="none"
|
||||
line={{ style: "dashed", fill: "sky-500/70", width: 2 }}
|
||||
width={96}
|
||||
height={96}
|
||||
/>
|
||||
```
|
||||
|
||||
Gradient background plus transparent edge:
|
||||
|
||||
```tsx
|
||||
<box fill="linear(135deg, #ffffff 0%, sky-100 58%, #ffffff/0 100%)" />
|
||||
```
|
||||
|
||||
Radial highlight:
|
||||
|
||||
```tsx
|
||||
<shape
|
||||
geometry="ellipse"
|
||||
fill="radial(white/80 0%, emerald-200/45 48%, emerald-700/0 100%)"
|
||||
width={420}
|
||||
height={260}
|
||||
/>
|
||||
```
|
||||
|
||||
Custom shadow:
|
||||
|
||||
```tsx
|
||||
<box fill="white" borderRadius="rounded-2xl" shadow="2px 7px 19px #000000/17" />
|
||||
```
|
||||
|
||||
Exact text style string:
|
||||
|
||||
```tsx
|
||||
<paragraph style="font: 700 24px Inter; color: #334155; leading: 1.2; wrap: none">
|
||||
One-line label
|
||||
</paragraph>
|
||||
```
|
||||
|
||||
Tokenized text with arbitrary size and leading:
|
||||
|
||||
```tsx
|
||||
<paragraph className="text-slate-950 text-[32px] font-bold leading-[1.12]">
|
||||
Precise headline
|
||||
</paragraph>
|
||||
```
|
||||
|
||||
## Color Tokens
|
||||
|
||||
Color tokens can be used directly as fill/color strings or through `bg-*` and
|
||||
`text-*` class names.
|
||||
|
||||
```tsx
|
||||
<box fill="slate-950" line={{ style: "solid", fill: "slate-700", width: 1 }} />
|
||||
<box className="bg-sky-50 rounded-xl shadow-sm" />
|
||||
<paragraph className="text-slate-700 text-lg">Readable text</paragraph>
|
||||
```
|
||||
|
||||
Alpha suffixes are supported:
|
||||
|
||||
```tsx
|
||||
<shape geometry="rect" fill="black/45" width="fill" height="fill" />
|
||||
<paragraph className="text-white/80 text-xl">Muted overlay text</paragraph>
|
||||
<box className="bg-rose-500/75 rounded-full" />
|
||||
```
|
||||
|
||||
Theme colors and aliases are supported as color strings:
|
||||
|
||||
```tsx
|
||||
<box fill="accent1" />
|
||||
<box fill="accent2+20/80" />
|
||||
<paragraph style="font: 600 18px Inter; color: text1/80; wrap: none">
|
||||
Uses the presentation theme text color
|
||||
</paragraph>
|
||||
```
|
||||
|
||||
Theme names:
|
||||
|
||||
```text
|
||||
accent1, accent2, accent3, accent4, accent5, accent6,
|
||||
bg1, bg2, tx1, tx2, dk1, dk2, lt1, lt2, hlink, folHlink
|
||||
```
|
||||
|
||||
Aliases:
|
||||
|
||||
```text
|
||||
background1 -> bg1
|
||||
background2 -> bg2
|
||||
text1 -> tx1
|
||||
text2 -> tx2
|
||||
dark1 -> dk1
|
||||
dark2 -> dk2
|
||||
light1 -> lt1
|
||||
light2 -> lt2
|
||||
```
|
||||
|
||||
Supported color names:
|
||||
|
||||
| Family | Tokens |
|
||||
| --- | --- |
|
||||
| Neutrals | `slate`, `gray`, `zinc`, `neutral`, `stone` |
|
||||
| Warm | `red`, `orange`, `amber`, `yellow`, `lime` |
|
||||
| Green/blue | `green`, `emerald`, `teal`, `cyan`, `sky`, `blue` |
|
||||
| Violet/pink | `indigo`, `violet`, `purple`, `fuchsia`, `pink`, `rose` |
|
||||
| Additional muted sets | `mauve`, `mist`, `olive`, `taupe` |
|
||||
| Singletons | `black`, `white` |
|
||||
|
||||
For palette families, supported shades are:
|
||||
|
||||
```text
|
||||
50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950
|
||||
```
|
||||
|
||||
Use `family-shade`, for example `slate-50`, `slate-900`, `sky-500`,
|
||||
`emerald-700`, or `rose-950`.
|
||||
|
||||
Alpha values accept percent-like numbers, percentages, or unit fractions:
|
||||
|
||||
```text
|
||||
sky-500/80
|
||||
sky-500/80%
|
||||
sky-500/0.8
|
||||
black/10
|
||||
white/65
|
||||
```
|
||||
|
||||
Hex, short hex, RGB, RGBA, and `transparent` are accepted:
|
||||
|
||||
```tsx
|
||||
<box fill="#0F172A/12" />
|
||||
<box fill="#0F172A1F" />
|
||||
<box fill="rgb(15 23 42 / 12%)" />
|
||||
<box fill="rgba(15, 23, 42, 0.12)" />
|
||||
<shape geometry="rect" fill="transparent" />
|
||||
```
|
||||
|
||||
Use `fill="none"` when the object should have no fill. Use
|
||||
`fill="transparent"` or `#00000000` when the object should keep an editable
|
||||
transparent solid fill. Express transparent and no-fill cases with the explicit
|
||||
`fill` prop.
|
||||
|
||||
## Gradient Strings
|
||||
|
||||
Gradient fill strings are supported wherever `FillConfig` strings are accepted.
|
||||
Use them for editable vector backgrounds and surfaces:
|
||||
|
||||
```tsx
|
||||
<box fill="linear(135deg, #ffffff 0%, sky-100 55%, #ffffff/0 100%)" />
|
||||
<shape geometry="ellipse" fill="radial(#ffffff 0%, emerald-200 48%, emerald-700 100%)" />
|
||||
```
|
||||
|
||||
`linear(...)` accepts an optional angle first. `radial(...)` is a path gradient.
|
||||
Stops use color plus optional offset percentages.
|
||||
|
||||
Offsets are optional; when omitted, stops are distributed evenly:
|
||||
|
||||
```tsx
|
||||
<box fill="linear(slate-950, blue-800, sky-400)" />
|
||||
```
|
||||
|
||||
Use explicit offsets when a narrow band or fade matters:
|
||||
|
||||
```tsx
|
||||
<box fill="linear(90deg, black/80 0%, black/36 42%, black/0 100%)" />
|
||||
<shape geometry="ellipse" fill="radial(accent1+35/55 0%, accent1/12 58%, accent1/0 100%)" />
|
||||
```
|
||||
|
||||
## Shape Class Tokens
|
||||
|
||||
Shape and box `className` supports:
|
||||
|
||||
```text
|
||||
bg-*
|
||||
rounded
|
||||
rounded-none
|
||||
rounded-sm
|
||||
rounded-md
|
||||
rounded-lg
|
||||
rounded-xl
|
||||
rounded-2xl
|
||||
rounded-3xl
|
||||
rounded-full
|
||||
shadow-none
|
||||
shadow-sm
|
||||
shadow
|
||||
shadow-md
|
||||
shadow-lg
|
||||
shadow-xl
|
||||
shadow-2xl
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```tsx
|
||||
<box
|
||||
width="fill"
|
||||
height={180}
|
||||
className="bg-white rounded-xl shadow-md"
|
||||
line={{ style: "solid", fill: "slate-200", width: 1 }}
|
||||
/>
|
||||
```
|
||||
|
||||
Radius values:
|
||||
|
||||
| Token | Radius |
|
||||
| --- | ---: |
|
||||
| `rounded-none` | `0px` |
|
||||
| `rounded-sm` | `2px` |
|
||||
| `rounded` | `4px` |
|
||||
| `rounded-md` | `6px` |
|
||||
| `rounded-lg` | `8px` |
|
||||
| `rounded-xl` | `12px` |
|
||||
| `rounded-2xl` | `16px` |
|
||||
| `rounded-3xl` | `24px` |
|
||||
| `rounded-full` | `9999px` |
|
||||
|
||||
Shadow tokens:
|
||||
|
||||
```text
|
||||
shadow-none, shadow-sm, shadow, shadow-md, shadow-lg, shadow-xl, shadow-2xl
|
||||
```
|
||||
|
||||
Custom shadow strings are also supported on `shadow`:
|
||||
|
||||
```tsx
|
||||
<box shadow="2px 7px 19px #000000/17" />
|
||||
```
|
||||
|
||||
## Text Class Tokens
|
||||
|
||||
Text `className` supports color, size, weight, italic, and leading:
|
||||
|
||||
```tsx
|
||||
<paragraph className="text-slate-950 text-5xl font-bold leading-tight">
|
||||
Large headline
|
||||
</paragraph>
|
||||
<paragraph className="text-slate-600 text-lg leading-relaxed">
|
||||
Body copy with looser line spacing.
|
||||
</paragraph>
|
||||
```
|
||||
|
||||
Text sizes:
|
||||
|
||||
| Token | Size |
|
||||
| --- | ---: |
|
||||
| `text-xs` | `12px` |
|
||||
| `text-sm` | `14px` |
|
||||
| `text-base` | `16px` |
|
||||
| `text-lg` | `18px` |
|
||||
| `text-xl` | `20px` |
|
||||
| `text-2xl` | `24px` |
|
||||
| `text-3xl` | `30px` |
|
||||
| `text-4xl` | `36px` |
|
||||
| `text-5xl` | `48px` |
|
||||
| `text-6xl` | `60px` |
|
||||
| `text-[32px]` | arbitrary positive pixel size |
|
||||
|
||||
Font weight tokens:
|
||||
|
||||
| Bold flag | Tokens |
|
||||
| --- | --- |
|
||||
| `true` | `font-semibold`, `font-bold`, `font-black` |
|
||||
| `false` | `font-thin`, `font-extralight`, `font-light`, `font-normal`, `font-medium`, `font-extrabold` |
|
||||
|
||||
Font weight maps to a boolean bold flag, not numeric weights. Use only
|
||||
`font-semibold`, `font-bold`, or `font-black` when the text should be bold. Use
|
||||
`font-normal` when the text should not be bold. `font-extrabold` maps to the
|
||||
non-bold side because exact `500`/`600`/`700`/`800` differences are not
|
||||
preserved.
|
||||
|
||||
`italic` sets italic text.
|
||||
|
||||
Leading tokens:
|
||||
|
||||
| Token | Line spacing |
|
||||
| --- | ---: |
|
||||
| `leading-none` | `1` |
|
||||
| `leading-tight` | `1.25` |
|
||||
| `leading-snug` | `1.375` |
|
||||
| `leading-normal` | `1.5` |
|
||||
| `leading-relaxed` | `1.625` |
|
||||
| `leading-loose` | `2` |
|
||||
| `leading-3` through `leading-10` | `12px` through `40px`, converted against current font size |
|
||||
| `leading-[1.35]` | arbitrary multiplier |
|
||||
| `leading-[150%]` | percentage multiplier |
|
||||
| `leading-[28px]` | absolute pixels, converted against current font size |
|
||||
|
||||
When using absolute leading such as `leading-7` or `leading-[28px]`, put the
|
||||
text size token before the leading token in the class string so conversion uses
|
||||
the intended font size:
|
||||
|
||||
```tsx
|
||||
<paragraph className="text-2xl leading-8">24px text with 32px leading</paragraph>
|
||||
```
|
||||
|
||||
## Direct Props Versus Class Names
|
||||
|
||||
Use direct props when a value is part of the object schema:
|
||||
|
||||
```tsx
|
||||
<shape
|
||||
geometry="rect"
|
||||
fill="emerald-500"
|
||||
line={{ style: "solid", fill: "emerald-700", width: 1 }}
|
||||
borderRadius="rounded-lg"
|
||||
shadow="shadow-sm"
|
||||
width={160}
|
||||
height={96}
|
||||
/>
|
||||
```
|
||||
|
||||
Use `className` when grouping common style tokens:
|
||||
|
||||
```tsx
|
||||
<box className="bg-emerald-50 rounded-xl shadow-sm">
|
||||
<paragraph className="text-emerald-900 text-xl font-bold leading-tight">
|
||||
Compact token styling
|
||||
</paragraph>
|
||||
</box>
|
||||
```
|
||||
|
||||
Use object `style` for exact text settings that tokens do not cover:
|
||||
|
||||
```tsx
|
||||
<paragraph
|
||||
style={{
|
||||
typeface: "Aptos",
|
||||
fontSize: 22,
|
||||
color: "slate-700",
|
||||
alignment: "center",
|
||||
lineSpacing: 1.2,
|
||||
}}
|
||||
>
|
||||
Exact text config
|
||||
</paragraph>
|
||||
```
|
||||
|
||||
Use a compact style string when the exact settings fit on one line:
|
||||
|
||||
```tsx
|
||||
<paragraph style="font: italic 600 20px Aptos; color: slate-700; leading: 1.25; align: center">
|
||||
Compact exact text config
|
||||
</paragraph>
|
||||
```
|
||||
|
||||
Supported text style declarations:
|
||||
|
||||
```text
|
||||
font, size, font-size, family, font-family, typeface,
|
||||
weight, font-weight, italic, font-style, color, fill,
|
||||
leading, align, alignment, wrap, underline, inset, insets,
|
||||
padding, autofit, auto-fit
|
||||
```
|
||||
|
||||
Use `leading`, not `line-height`, in style strings.
|
||||
|
||||
## ClassName Scope
|
||||
|
||||
The token parser covers visual and text styling. JSX layout props represent
|
||||
layout utilities such as padding, gap, width, height, flex flow, grid flow,
|
||||
alignment, and distribution:
|
||||
|
||||
```tsx
|
||||
<row width="fill" height="fill" gap={24} align="center" justify="between" />
|
||||
<box padding={{ x: 32, y: 24 }} line={{ style: "solid", fill: "slate-200", width: 1 }} />
|
||||
```
|
||||
|
||||
## Source References
|
||||
|
||||
- `src/models/presentation/utils/tailwind/*.ts`: token parsers.
|
||||
- `src/models/presentation/utils/tailwind/tailwind-colors.generated.ts`: full
|
||||
color token map.
|
||||
- `tests/presentation/tailwind-tokens.sanity.spec.ts`: visual token coverage.
|
||||
Generated
Vendored
+503
@@ -0,0 +1,503 @@
|
||||
# Using artifact_tool APIs (JavaScript)
|
||||
|
||||
Library version: 2.8.58+
|
||||
|
||||
## Required Imports + Startup
|
||||
|
||||
Import existing workbook only when needed:
|
||||
```js
|
||||
import { FileBlob, SpreadsheetFile } from "@oai/artifact-tool";
|
||||
|
||||
const input = await FileBlob.load("path/to/input.xlsx");
|
||||
const workbook = await SpreadsheetFile.importXlsx(input);
|
||||
```
|
||||
|
||||
Import CSV text directly when the source or intermediate data is CSV:
|
||||
```js
|
||||
import fs from "node:fs/promises";
|
||||
import { Workbook } from "@oai/artifact-tool";
|
||||
|
||||
const csvText = await fs.readFile("path/to/input.csv", "utf8");
|
||||
const workbook = await Workbook.fromCSV(csvText, { sheetName: "Sheet1" });
|
||||
```
|
||||
Prefer `Workbook.fromCSV(...)` over hand-parsing CSV rows; clean or analyze CSV with Python/Node first only when needed.
|
||||
CSV fields import as strings. Convert intended numeric/date columns before calculations; number formatting alone does not convert text to numbers.
|
||||
|
||||
Create new workbook:
|
||||
|
||||
```js
|
||||
import fs from "node:fs/promises";
|
||||
import { SpreadsheetFile, Workbook } from "@oai/artifact-tool";
|
||||
|
||||
const workbook = Workbook.create();
|
||||
const sheet = workbook.worksheets.add("Inputs");
|
||||
```
|
||||
|
||||
Final export:
|
||||
```js
|
||||
await fs.mkdir(outputDir, { recursive: true });
|
||||
const output = await SpreadsheetFile.exportXlsx(workbook);
|
||||
await output.save(`${outputDir}/output.xlsx`);
|
||||
```
|
||||
|
||||
## Build Patterns
|
||||
- Prefer block writes (`range.values`, `range.formulas`) over per-cell loops. Normally match the matrix shape to the target range (e.g. "D4:M4" → 1×10). To intentionally expand a larger matrix from an anchor, target a single cell or use `range.write(matrix)`.
|
||||
- `range.values = [[value]]` repeats that value across the range; range.formulas does not broadcast a single formula. For merged ranges, write to the top-left cell or `mergedRange.values = [[value]]` where `mergedRange` is a single merged range.
|
||||
- Seed scalar formulas once, then `fillDown()` / `fillRight()`. For dynamic-array formulas (`SEQUENCE`, `UNIQUE`, `FILTER`, `SORT`, `VSTACK`, `HSTACK`), write only the anchor cell and let the result spill after.
|
||||
- Use `range.displayFormulas` plus `range.formulaInfos` when you need to understand a spill child or a data-table output cell.
|
||||
- Formulas calculate automatically.
|
||||
- Prefer real `Date` objects for sortable/charted/formula date columns.
|
||||
- Number and date formats must be applied explicitly (for example `yyyy-mm-dd`).
|
||||
- Use JSON-serializable values for non-Date cells: `string | number | boolean | null`.
|
||||
- If a cell is intended to display literal text that begins with `=`, write it as a value prefixed with a single quote (for example `'=B2*C2`). This includes formula descriptions, validation examples, and labels; do not write these cells through `range.formulas`.
|
||||
- Create every worksheet referenced by formulas before writing any cross-sheet formulas.
|
||||
- Verify with `await workbook.inspect(...)`; use `workbook.help(...)` only when the quick surface below is insufficient.
|
||||
|
||||
## Conventions
|
||||
- Use camelCase API names and option keys.
|
||||
- Cell/range addressing: A1 notation (`sheet.getRange("A1:C10")`).
|
||||
- Drawing anchors (`sheet.charts`, `sheet.shapes`, `sheet.images`): 0-based `{ row, col }`.
|
||||
- Drawing offsets/extents use pixels (`rowOffsetPx`, `colOffsetPx`, `widthPx`, `heightPx`).
|
||||
|
||||
## API Discovery Policy (Strict)
|
||||
- Use this quick API surface first.
|
||||
- Use `workbook.help(...)` only when the supplied public documentation leaves a required operation unclear. Start with one bounded exact feature/path lookup, such as `range.dataValidation` or `chart.series.add`.
|
||||
- If that lookup returns no useful match, one bounded reformulation is allowed. Stop after those two attempts; do not repeat similar queries, inspect package internals/prototypes/nearby tests, or invent enum values and setters. Use a documented equivalent that preserves the task.
|
||||
- The examples below are alternatives for the relevant operation, not a discovery checklist to execute in full.
|
||||
- `render` can be used to examine an existing workbook visually and for visual verifications.
|
||||
|
||||
## Supported Formulas
|
||||
- Look up formula syntax with `fx.<formula>`, e.g. `workbook.help("fx.PMT", { include: "index,examples,notes", maxChars: 3000 })`. A help entry does not guarantee working calculation or Excel export.
|
||||
- To browse a family of formulas, use `fx.*` with a category regex. Useful categories: `financial`, `math-trig`, `statistical`, `lookup-reference`, `logical`, `text`, `date-time`, `information`, `engineering`, `database`.
|
||||
- For intent-based lookup, use a short natural query plus a narrow `search` regex of likely functions.
|
||||
- Keep `maxChars` bounded; if results are noisy, narrow `search` rather than issuing many similar queries.
|
||||
|
||||
Useful `help` calls:
|
||||
```js
|
||||
console.log(workbook.help("shape.add", { include: "examples,notes" }).ndjson);
|
||||
console.log(
|
||||
workbook.help("*", {
|
||||
search: "fill|borders|autofit",
|
||||
include: "index,examples,notes",
|
||||
maxChars: 6000,
|
||||
}).ndjson,
|
||||
);
|
||||
console.log(workbook.help("fx.PMT", { include: "index,examples,notes" }).ndjson);
|
||||
console.log(workbook.help("fx.*", { search: "financial", include: "index,examples", maxChars: 4000 }).ndjson);
|
||||
console.log(workbook.help("fx.*", { search: "math-trig", include: "index,examples", maxChars: 4000 }).ndjson);
|
||||
console.log(workbook.help("lookup with fallback", { search: "XLOOKUP|INDEX|MATCH|IFERROR", include: "index,examples,notes", maxChars: 4000 }).ndjson);
|
||||
```
|
||||
|
||||
### Known formula/export limitations (not exhaustive)
|
||||
If a formula fails, use a verified equivalent that preserves the intended result.
|
||||
|
||||
Known issues:
|
||||
- Avoid `MAP`, `REDUCE`, `SCAN`, `MAKEARRAY`, `GROUPBY`, `PIVOTBY`. Use helper cells and supported scalar formulas;
|
||||
- Prefix `XLOOKUP`, `TEXTJOIN`, `MINIFS`, `MAXIFS`, `IFS`, and `RANK.EQ` with `_xlfn.`, including nested calls: e.g. `'=_xlfn.TEXTJOIN(", ",TRUE,B2:C2)'`.
|
||||
- For `LET`, `LAMBDA`, `BYROW`, and `BYCOL`, prefix function names with `_xlfn.` and every LET/LAMBDA local-variable declaration and reference with `_xlpm.`.
|
||||
- PivotTable APIs exist, but XLSX export is unreliable; use formula summaries.
|
||||
- `COUNTIF` / `COUNTIFS` with an empty-string criterion can miss blank cells, even in bounded ranges. For unconditional blank counts, use `COUNTBLANK(range)`.
|
||||
|
||||
|
||||
## Reading existing/imported workbooks
|
||||
- On existing/imported workbooks, get a compact summary via `inspect` to understand what already exists and where.
|
||||
- Prefer `inspect(...)` for workbook understanding and discovery across broad areas.
|
||||
- Prefer direct getters like `range.formulas` when you already know the target range and need the exact rectangular formula matrix.
|
||||
- If formula locations are unknown, prefer `inspect({ kind: "formula", ... })` over reading `range.formulas` across a very large area.
|
||||
- Prefer to set `maxChars`, `tableMaxRows`, `tableMaxCols`, and/or `maxResults` to prevent large dumps of data.
|
||||
- For suspicious or high-impact outputs, use `workbook.trace("Sheet!A1")` to audit the dependency tree from final output/check cell back to source cells. Trace output can be large, so summarize by depth/node count before logging.
|
||||
|
||||
### Inspect for workbook understanding
|
||||
- Compact summary:
|
||||
```js
|
||||
await wb.inspect({
|
||||
kind: "workbook,sheet,table",
|
||||
maxChars: 6000,
|
||||
tableMaxRows: 6,
|
||||
tableMaxCols: 6,
|
||||
tableMaxCellChars: 80,
|
||||
});
|
||||
```
|
||||
- Quick overview of sheet ids and names: `await wb.inspect({ kind: "sheet", include: "id,name" })`
|
||||
- Formula discovery in a targeted area: `await wb.inspect({ kind: "formula", sheetId: firstSheetName, range: "A1:Z30", maxChars: 2500, options: {maxResults:50} })`
|
||||
- Checking existing styles in a targeted area: `await wb.inspect({ kind: "computedStyle", sheetId: firstSheetName, range: "A1:E10", maxChars: 2500 })`
|
||||
- Common `kind` tokens: `workbook`, `sheet`, `table`, `region`, `match`, `formula`, `thread`, `computedStyle`, `definedName`, `drawing`
|
||||
- Inspects can also be used to zoom in on specific areas, especially for target edits:
|
||||
```js
|
||||
await wb.inspect({
|
||||
kind: "region",
|
||||
sheetId: firstSheetName,
|
||||
range: "A1:Z30",
|
||||
maxChars: 2500,
|
||||
});
|
||||
```
|
||||
- Inspect output may include JSON records with `"id"` values (for example `"ws/r5qsk5"`), which you can resolve back to workbook objects with `wb.resolve(...)`:
|
||||
- `wb.resolve("ws/...")` -> worksheet
|
||||
- `wb.resolve("th/...")` -> comment thread
|
||||
|
||||
## Known Gotchas (Do not repeat)
|
||||
- Do not set undocumented attributes on remote objects.
|
||||
- `Workbook.create()` starts with no sheets; add one before calling `getActiveWorksheet()`.
|
||||
- Create every worksheet referenced by formulas before writing cross-sheet formulas.
|
||||
- Prefer bounded formula ranges with explicit start/end rows, e.g. `$A$6:$A$205`. Full-column references such as `A:A`, `$A:$A`, or `Sheet!B:B` can be truncated to each column's populated extent: unequal extents can make `COUNTIFS` / `SUMIFS` return `#VALUE!`, and `ROWS` / `INDEX` can differ from Excel.
|
||||
- If export fails, isolate the cause by checkpoint-export after major blocks to isolate the cause: base sheets, values/formulas, formatting, conditional formatting, tables, charts/rendering. For charts, first simplify optional styling first: nested border configs, custom chart axis/series mutations, broad autofit/formatting, then nonessential drawings.
|
||||
|
||||
## Additional feature-specific notes
|
||||
|
||||
### Merging cells
|
||||
- `range.merge()` merges the target range into one cell; `range.merge(true)` merges across each row in the target range.
|
||||
- `range.unmerge()` reverses a merge.
|
||||
For example:
|
||||
```js
|
||||
const range = sheet.getRange("I23:N24");
|
||||
range.merge();
|
||||
range.values = [["Source note spanning the recommendation panel"]];
|
||||
```
|
||||
|
||||
## Quick API Surface (High-Value + Common)
|
||||
|
||||
### Core workbook/file APIs
|
||||
- `import { FileBlob, SpreadsheetFile, Workbook } from "@oai/artifact-tool"`
|
||||
- `const workbook = Workbook.create()` to create an empty workbook
|
||||
- `const sheet = workbook.worksheets.add("Sheet1")` to add a sheet
|
||||
- `const workbook = await SpreadsheetFile.importXlsx(arrayBufferOrFileBlob)`
|
||||
- `const xlsx = await SpreadsheetFile.exportXlsx(workbook); await xlsx.save("output.xlsx")`
|
||||
- `const inspect = await workbook.inspect({ kind: "sheet", include: "id,name", sheetId, range: "A1:C10" })`
|
||||
- `const help = workbook.help("worksheet.getRange", { include: "index,examples" })`
|
||||
- Preferred: `const preview = await workbook.render({ sheetName: "Sheet1", autoCrop: "all", scale: 1, format: "png" })`
|
||||
- To get the bytes and/or save the blob to file:
|
||||
```js
|
||||
const previewBytes = new Uint8Array(await preview.arrayBuffer());
|
||||
await fs.writeFile(`${outputDir}/preview.png`, previewBytes);
|
||||
```
|
||||
- `const workbook = await Workbook.fromCSV(csvText, { sheetName: "Sheet1" })`
|
||||
- `await workbook.fromCSV(csvText, { sheetName: "ImportedData" })` requires an empty workbook; it does not append CSV to a populated workbook. Prefer static `Workbook.fromCSV(...)`.
|
||||
|
||||
### Worksheet selection/creation
|
||||
- `workbook.worksheets.add(name)`
|
||||
- `workbook.worksheets.getItem(name)`
|
||||
- `workbook.worksheets.getItemAt(index)`
|
||||
- `workbook.worksheets.getActiveWorksheet()` (only after at least one sheet exists)
|
||||
|
||||
### Worksheet operations
|
||||
- `sheet.getRange("A1:C10")`, `sheet.getRangeByIndexes(startRow, startCol, rowCount, colCount)`, `sheet.getCell(row, col)`
|
||||
- `sheet.getUsedRange(valuesOnly?)`
|
||||
- `sheet.mergeCells("A1:C1")`, `sheet.unmergeCells("A1:C1")`
|
||||
- `sheet.freezePanes.freezeRows(rowCount)`, `sheet.freezePanes.freezeColumns(columnCount)`, `sheet.freezePanes.unfreeze()`
|
||||
- `sheet.tabColor = "#1F4E78"` sets the worksheet tab color; the getter returns a `Color` object.
|
||||
- `sheet.tables`, `sheet.charts`, `sheet.sparklineGroups` (`sheet.sparklines` alias), `sheet.shapes`, `sheet.images`
|
||||
- `sheet.showGridLines = false`
|
||||
- `sheet.dataTables`, `sheet.conditionalFormattings`, `sheet.dataValidations`
|
||||
- `sheet.deleteAllDrawings()` removes all drawings, including charts, shapes, and images.
|
||||
|
||||
### Range values/formulas
|
||||
- `const range = sheet.getRange("A1:C10")`
|
||||
- `range.values = [[...], ...]` (2D matrix of values).
|
||||
- `range.formulas = [["=..."], ...]`
|
||||
- `range.formulasR1C1 = [["=RC[-1]*2"]]`
|
||||
- To read: `range.values` / `range.formulas` / `range.displayFormulas` / `range.formulaInfos` (for spill/array formulas)
|
||||
- `range.write(matrixOrPayload)` (auto-sizes/spills from anchor as needed)
|
||||
- `range.writeValues(matrixOrRows)`
|
||||
- `range.fillDown()`, `range.fillRight()`
|
||||
- `sheet.getRange("D2").formulas = [["=..."]]`
|
||||
- `sheet.getRange("D2:D200").fillDown()`
|
||||
- `range.clear({ applyTo: "contents" | "formats" | "all" })` clears cell contents, formatting, or both; drawings remain.
|
||||
- `range.copyFrom(sourceRange, "values" | "formulas" | "all")`. Prefer matching shapes; a single-cell value source can broadcast across a larger destination.
|
||||
- `range.copyTo(destRange, "values" | "formulas" | "all")`
|
||||
- `range.offset(rowOffset, colOffset)`, `range.resize(rowCount, columnCount)`, `range.getCurrentRegion()`, `range.getRow(i)`, `range.getColumn(j)`
|
||||
- `range.getRangeByIndexes(startRow, startCol, rowCount, colCount)`, `range.getCell(row, col)` (relative to the range)
|
||||
- `range.merge()`, `range.merge(true)` to merge across, `range.unmerge()`
|
||||
|
||||
### Formatting
|
||||
- `range.format` supports `fill`, `font`, `numberFormat`, `borders`, alignments, `wrapText`
|
||||
- `range.format.verticalAlignment = "center"` maps to Excel Middle Align
|
||||
- `range.format.autofitColumns()`, `range.format.autofitRows()`
|
||||
- Excel unit sizing: `range.format.columnWidth = 18`, `range.format.rowHeight = 24`
|
||||
- Pixel sizing: `range.format.columnWidthPx = 120`, `range.format.rowHeightPx = 24`
|
||||
- `range.setNumberFormat("yyyy-mm-dd")`
|
||||
- `range.format.numberFormat = [["0"], ["0.00"], ["@"]]`
|
||||
- Borders: There are two ways to set borders on a range (1) simple form (2) per edge form. Example:
|
||||
```js
|
||||
// (1) Preferred simple form
|
||||
// `preset` can be "none" | "outside" | "inside" | "all" | "doubleBottom"
|
||||
// "outside" will just set borders on the outside edges of the range.
|
||||
// `style` are Excel/OpenXML-style names such as "thin", "medium", "thick", "dashed", and "dotted".
|
||||
range.format.borders = { preset: "all", style: "thin", color: "#D9D9D9" };
|
||||
|
||||
// (2) Per-edge form. Use top/bottom/left/right, not edgeTop/edgeBottom/etc.
|
||||
// Format: {style?: string; color?: ColorConfig; weight?: number;}
|
||||
// Prefer setting `style` over `weight` unless you want granular control.
|
||||
range.format.borders = {
|
||||
insideHorizontal: { style: "thin", color: "#D9D9D9" },
|
||||
insideVertical: { style: "medium", color: "#D9D9D9" },
|
||||
top: { style: "thick", color: "#D9D9D9" },
|
||||
bottom: { style: "dashed", color: "#D9D9D9" },
|
||||
left: { style: "dotted", color: "#D9D9D9" },
|
||||
right: { style: "thin", color: "#D9D9D9" },
|
||||
};
|
||||
```
|
||||
|
||||
### Data Validation
|
||||
- `range.dataValidation = { rule: { type: "list", formula1: "Categories!$A$2:$A$4" } }`
|
||||
- `range.dataValidation = { rule: { type: "list", values: ["Not Started", "In Progress"] } }`
|
||||
- `sheet.dataValidations.add({ range: "B2:B100", rule: { type: "whole", operator: "between", formula1: 1, formula2: 10 } })`
|
||||
|
||||
### Conditional formatting
|
||||
- Use `range.conditionalFormats.add(ruleType, ConditionalFormatConfig);`.
|
||||
- Use `range.conditionalFormats.add(ruleType, {operator, formula, format});`. Choose ruleType, operator, color, and style strings from the inline types below.
|
||||
```
|
||||
type ConditionalFormatRuleType =
|
||||
| "cellIs" | "CellValue" | "Custom" | "expression"
|
||||
| "colorScale" | "dataBar" | "iconSet"
|
||||
| "containsText" | "notContainsText" | "beginsWith" | "endsWith"
|
||||
| "containsBlanks" | "notContainsBlanks" | "containsErrors" | "notContainsErrors"
|
||||
| "duplicateValues" | "uniqueValues" | "timePeriod" | "top10" | "aboveAverage";
|
||||
|
||||
type CellIsOperator =
|
||||
| "greaterThan"
|
||||
| "greaterThanOrEqual"
|
||||
| "lessThan"
|
||||
| "lessThanOrEqual"
|
||||
| "equal"
|
||||
| "notEqual"
|
||||
| "between"
|
||||
| "notBetween";
|
||||
|
||||
type ConditionalFormatConfig =
|
||||
| { operator: CellIsOperator; formula: string | number | Array<string | number>; format?: DifferentialFormatConfig }
|
||||
| { formula: string | number; format?: DifferentialFormatConfig }
|
||||
| { colors?: ColorConfig[]; thresholds?: CfvoInput[] }
|
||||
| { color?: ColorConfig; thresholds?: CfvoInput[]; gradient?: boolean }
|
||||
| { iconSet: string; showValue?: boolean; reverse?: boolean; thresholds?: CfvoInput[] }
|
||||
| { text: string; format?: DifferentialFormatConfig }
|
||||
| { timePeriod: "yesterday" | "today" | "tomorrow" | "last7Days" | "lastWeek" | "thisWeek" | "nextWeek" | "lastMonth" | "thisMonth" | "nextMonth"; format?: DifferentialFormatConfig }
|
||||
| { rank?: number; percent?: boolean; bottom?: boolean; format?: DifferentialFormatConfig }
|
||||
| { aboveAverage?: boolean; equalAverage?: boolean; stdDev?: number; format?: DifferentialFormatConfig };
|
||||
|
||||
type DifferentialFormatConfig = {
|
||||
fill?: FillConfig;
|
||||
font?: { bold?: boolean; italic?: boolean; color?: ColorConfig };
|
||||
border?: RangeBordersConfig; // Per-edge top/bottom/left/right only; presets are ignored here.
|
||||
numberFormat?: string;
|
||||
};
|
||||
|
||||
type CfvoInput =
|
||||
| "min"
|
||||
| "max"
|
||||
| number
|
||||
| `${number}%`
|
||||
| { type: "min" | "max" | "num" | "percent" | "percentile"; value?: string | number };
|
||||
```
|
||||
- Rule types (`ConditionalFormatRuleType`): "cellIs" | "CellValue" | "Custom" | "expression"
|
||||
| "colorScale" | "dataBar" | "iconSet"
|
||||
| "containsText" | "notContainsText" | "beginsWith" | "endsWith"
|
||||
| "containsBlanks" | "notContainsBlanks" | "containsErrors" | "notContainsErrors"
|
||||
| "duplicateValues" | "uniqueValues" | "timePeriod" | "top10" | "aboveAverage";
|
||||
- XLSX `iconSet` names: `3Arrows`, `4Arrows`, `5Arrows`, `3ArrowsGray`, `4ArrowsGray`, `5ArrowsGray`, `3TrafficLights1`, `3Signs`, `4RedToBlack`, `3TrafficLights2`, `4TrafficLights`, `3Symbols`, `3Flags`, `3Symbols2`, `5Quarters`, `4Rating`, `5Rating`. Avoid `3Stars`, `3Triangles`, and `5Boxes`: their current XLSX serialization is not reliable.
|
||||
- Custom conditional formatting: `range.conditionalFormats.addCustom(expression, {fill, font, border});`
|
||||
- `range.conditionalFormats.deleteAll()` / `range.conditionalFormats.clear()`
|
||||
|
||||
```js
|
||||
const grid = sheet.getRange("B2:J10");
|
||||
grid.conditionalFormats.add("colorScale", {
|
||||
colors: ["#2563EB", "#FDE047", "#DC2626"],
|
||||
thresholds: ["min", { type: "percentile", value: 50 }, "max"]
|
||||
});
|
||||
```
|
||||
|
||||
### Tables
|
||||
- When adding new tables, set explicit unique names (`TasksTable`, `SummaryTable`).
|
||||
- Do not overlap tables; the API does not reject overlaps. Check existing table ranges in the initial compact `inspect` summary before adding one.
|
||||
- `const table = sheet.tables.add("A1:H200", true, "TasksTable")`
|
||||
- `table.rows.add(null, [[...], ...])`, `table.getDataRows()`, `table.getHeaderRowRange()`
|
||||
- Read tables: `sheet.tables.items` -> `Table[]`
|
||||
- Set + Getters: `table.name`, `table.style`, `table.showHeaders`
|
||||
- Toggles for table utilities (set/get): `table.showTotals`, `table.showBandedColumns = true`, `table.showFilterButton`
|
||||
- `table.delete()`
|
||||
|
||||
### Images
|
||||
- `sheet.images.add({dataUrl: "data:image/png;base64,...", anchor: {from: { row: 1, col: 2 }, extent: { widthPx: 160, heightPx: 120 }}})`
|
||||
|
||||
|
||||
### Threaded Comments
|
||||
This is the API to create a threaded comment in Excel, which requires a user-visible author.
|
||||
- Required: Before adding a comment, create its visible author with `workbook.comments.setSelf({"displayName": <user_display_string>})`, where `<user_display_string>` is a string such as "User"
|
||||
- Create a new thread with a single comment: `const thread = workbook.comments.addThread({"cell": sheet.getRange("E2")}, "Source: <website>")`
|
||||
- To reply to a threaded comment: `thread.addReply("This is a reply to the comment")`
|
||||
- To resolve/re-open a thread: `thread.resolve()`, `thread.reopen()`
|
||||
|
||||
### Charts
|
||||
- Place charts in reserved blank areas with gutter rows/columns; do not cover data.
|
||||
- Prefer range-backed charts so source edits update the chart. Headers are detected when the first row contains text and no numeric cells.
|
||||
|
||||
|
||||
#### Fast-chart path
|
||||
- For contiguous data: pass categories first, then one column per series:
|
||||
```js
|
||||
sheet.getRange("F4:H6").values = [
|
||||
["Month", "Revenue", "EBITDA"],
|
||||
["Jan", 100, 10],
|
||||
["Feb", 120, 18],
|
||||
];
|
||||
const chart = sheet.charts.add("line", sheet.getRange("F4:H6"));
|
||||
```
|
||||
- For nonadjacent columns: pass equal-height, single-column ranges with categories first:
|
||||
```js
|
||||
const chart = sheet.charts.add("bar", [
|
||||
sheet.getRange("A1:A10"),
|
||||
sheet.getRange("D1:D10"),
|
||||
sheet.getRange("G1:G10"),
|
||||
]);
|
||||
chart.series.items[0].fill = "#F472B6";
|
||||
```
|
||||
- Both paths create source-cell references and show a bottom legend. Apply requested formatting once after creation:
|
||||
```js
|
||||
chart.setPosition("J4", "Q20"); // always set
|
||||
const fontFamily = "Arial";
|
||||
|
||||
chart.title = "Revenue and EBITDA Trend";
|
||||
chart.titleTextStyle.fontSize = 12;
|
||||
chart.titleTextStyle.typeface = fontFamily;
|
||||
|
||||
chart.legend = { position: "top", textStyle: { typeface: fontFamily } };
|
||||
chart.xAxis = { axisType: "textAxis", textStyle: { typeface: fontFamily, fontSize: 10 } };
|
||||
// Number formatting on chart axis must be set separately even if the source range is already formatted.
|
||||
chart.yAxis = { numberFormatCode: "$#,##0", numberFormatSourceLinked: false, textStyle: { typeface: fontFamily }, tickLabelInterval: 2 };
|
||||
chart.xAxis.title.text = "Month";
|
||||
chart.yAxis.title.text = "Revenue and EBITDA";
|
||||
```
|
||||
- Chart `textStyle.fontSize` uses pixels; `typeface` sets the family. Style axes, legend, and titles separately (`xAxis.textStyle`, `yAxis.textStyle`, `legend.textStyle`, `titleTextStyle`); cell fonts do not configure chart fonts.
|
||||
- Only set/style intended titles; styling an absent title can create a placeholder.
|
||||
- For custom axis formats, set `numberFormatSourceLinked: false`. For $M labels, use `$0.0,,"M"` for dollars, `$0.0,"M"` for thousands, or `$0.0"M"` for millions. Fix formatting without changing source data.
|
||||
- `chart.setData(range)` replaces categories/series but preserves title, legend, and axes. Apply series styling after binding data.
|
||||
- For month/date labels, use helper cells containing strings such as `Jan 2025`; date-axis formats may show serial numbers in previews.
|
||||
- Inspect series through `chart.series.items`; source bindings are `series.formula` and `series.categoryFormula`.
|
||||
- Additional chart getters: `chart.type`, `chart.title.text`, `chart.categories` (may be empty for range-backed charts; inspect series references).
|
||||
- Collection methods: `sheet.charts.getItemOrNullObject("Chart 1")`, `sheet.charts.deleteAll()`.
|
||||
- XLSX chart types: `"bar" | "line" | "area" | "pie" | "doughnut" | "scatter" | "bubble" | "radar" | "stock"`.
|
||||
- `"treemap"`, `"sunburst"`, `"histogram"`, `"boxWhisker"`, `"waterfall"`, `"funnel"`, and `"map"` are accepted by the API but omitted from XLSX exports in this runtime. Do not use them for Excel deliverables.
|
||||
|
||||
### Sparklines
|
||||
```js
|
||||
const group = sheet.sparklineGroups.add({
|
||||
type: "line",
|
||||
targetRange: "E2:E4",
|
||||
sourceData: "A2:C4",
|
||||
seriesColor: "#2563EB",
|
||||
markers: { high: true, low: true },
|
||||
});
|
||||
```
|
||||
- Sparkline type is a string. Use the public options documented below. Do not set internal/proto enum values for empty-cell display or axis modes; if a required option is not documented for the selected runtime, follow the bounded discovery policy.
|
||||
- Avoid `dateAxisRange` for XLSX output; it is not serialized. Keep automatic axis limits: `manualMin` / `manualMax` alone do not select custom limits in Excel.
|
||||
- Sparkline Inline Type:
|
||||
```
|
||||
type SparklineConfig = {
|
||||
type: "line" | "column" | "stacked";
|
||||
targetRange: Range | string;
|
||||
sourceData: Range | string;
|
||||
lineWeight?: number;
|
||||
displayHidden?: boolean;
|
||||
seriesColor?: ColorConfig;
|
||||
negativeColor?: ColorConfig;
|
||||
axisColor?: ColorConfig;
|
||||
markersColor?: ColorConfig;
|
||||
firstMarkerColor?: ColorConfig;
|
||||
lastMarkerColor?: ColorConfig;
|
||||
highMarkerColor?: ColorConfig;
|
||||
lowMarkerColor?: ColorConfig;
|
||||
markers?: SparklineMarkersOptions;
|
||||
axis?: SparklineAxisOptions;
|
||||
};
|
||||
|
||||
type SparklineMarkersOptions = {
|
||||
show?: boolean;
|
||||
high?: boolean;
|
||||
low?: boolean;
|
||||
first?: boolean;
|
||||
last?: boolean;
|
||||
negative?: boolean;
|
||||
};
|
||||
|
||||
type SparklineAxisOptions = {
|
||||
showAxis?: boolean;
|
||||
rightToLeft?: boolean;
|
||||
};
|
||||
```
|
||||
- Range Alias: `const group = targetRange.sparklines.add(type, sourceRange, sparklineConfig);`
|
||||
- Edit And Delete
|
||||
```js
|
||||
group.seriesColor = "#2563EB";
|
||||
group.markers.high = true;
|
||||
group.axis.showAxis = true;
|
||||
sheet.sparklineGroups.delete(group);
|
||||
sheet.sparklineGroups.deleteAll();
|
||||
```
|
||||
|
||||
### Help / Grep
|
||||
Use `workbook.help(...)` primarily for obscure/advanced surfaces (for example deep chart axis settings, unusual drawing configs, pivot APIs, or uncommon option schemas).
|
||||
- `workbook.help("enum.ShapeGeometry", { include: "index,notes" }).ndjson`
|
||||
- `workbook.help("enum.*", { search: "ShapeGeometry|LineStyle", include: "index" }).ndjson`
|
||||
- `workbook.help("shape.add", { include: "examples,notes" }).ndjson`
|
||||
- `workbook.help("fx.RATE", { include: "index,examples,notes" }).ndjson`
|
||||
- `workbook.help("cash flow return rate", { search: "IRR|XIRR|NPV|XNPV", include: "index,examples,notes", maxChars: 4000 }).ndjson`
|
||||
- `workbook.help("*", { search: "fill|borders|autofit", include: "index,examples,notes", maxChars: 6000 }).ndjson`
|
||||
|
||||
### Trace
|
||||
For tracing the full tree of how a formula is calculated, `workbook.trace("Sheet!A1")` is available. For complex formulas, the full tree can be extremely large, so output should be capped or outputted to a separate temp file (never dump raw traces). It takes only a cell reference.
|
||||
|
||||
|
||||
### JavaScript example snippet (runnable)
|
||||
|
||||
```js
|
||||
import fs from "node:fs/promises";
|
||||
import { SpreadsheetFile, Workbook } from "@oai/artifact-tool";
|
||||
|
||||
const fontFamily = "Arial";
|
||||
|
||||
const outputDir = "output";
|
||||
await fs.mkdir(outputDir, { recursive: true });
|
||||
|
||||
const workbook = Workbook.create();
|
||||
const sheet = workbook.worksheets.add("Summary");
|
||||
|
||||
sheet.getRange("A1:C4").values = [
|
||||
["Month", "Revenue", "EBITDA"],
|
||||
["Jan", 100, 10],
|
||||
["Feb", 120, 18],
|
||||
["Mar", 130, 22],
|
||||
];
|
||||
sheet.getRange("D1").values = [["Margin"]];
|
||||
sheet.getRange("D2").formulas = [["=C2/B2"]];
|
||||
sheet.getRange("D2:D4").fillDown();
|
||||
|
||||
sheet.getRange("A1:G4").format.font = { name: fontFamily, size: 11 };
|
||||
sheet.getRange("A1:D1").format = {
|
||||
fill: "#0F766E",
|
||||
font: { name: fontFamily, bold: true, color: "#FFFFFF" },
|
||||
};
|
||||
sheet.getRange("B2:C4").format.numberFormat = "$#,##0";
|
||||
sheet.getRange("D2:D4").format.numberFormat = "0.0%";
|
||||
|
||||
// Helper range links to source cells so edits update the chart.
|
||||
sheet.getRange("F1:G1").values = [["Month", "Revenue"]];
|
||||
sheet.getRange("F2:G2").formulas = [["=A2", "=B2"]];
|
||||
sheet.getRange("F2:G4").fillDown();
|
||||
const chart = sheet.charts.add("line", sheet.getRange("F1:G4"));
|
||||
chart.title = "Revenue Trend";
|
||||
chart.titleTextStyle.typeface = fontFamily;
|
||||
chart.hasLegend = false;
|
||||
chart.xAxis = { axisType: "textAxis", textStyle: { typeface: fontFamily } };
|
||||
chart.yAxis = { numberFormatCode: "$#,##0", numberFormatSourceLinked: false, textStyle: { typeface: fontFamily } };
|
||||
chart.setPosition("I1", "P15");
|
||||
|
||||
const preview = await workbook.render({
|
||||
sheetName: "Summary",
|
||||
autoCrop: "all",
|
||||
scale: 1,
|
||||
format: "png",
|
||||
});
|
||||
await fs.writeFile(`${outputDir}/summary.png`, new Uint8Array(await preview.arrayBuffer()));
|
||||
|
||||
const xlsx = await SpreadsheetFile.exportXlsx(workbook);
|
||||
await xlsx.save(`${outputDir}/summary.xlsx`);
|
||||
```
|
||||
Generated
Vendored
+210
@@ -0,0 +1,210 @@
|
||||
# Workbook API Docs
|
||||
|
||||
Use the workbook facades to create and edit Excel-style workbooks in TypeScript,
|
||||
including worksheets, ranges, formulas, tables, charts, drawings, comments,
|
||||
named ranges, import/export helpers, inspection, and recorded patches.
|
||||
|
||||
## Conventions
|
||||
|
||||
- **A1 addresses for ranges**: use `sheet.getRange("A1:B2")` for A1 ranges.
|
||||
Use `getRangeByIndexes(row, column, rowCount, columnCount)` and
|
||||
`getCell(row, column)` for zero-based index access.
|
||||
- **Matrices are row-major**: range values and formulas use `rows x columns`
|
||||
arrays. Single-row and single-column ranges accept one-dimensional arrays.
|
||||
- **Formulas include `=`**: assigning a string starting with `=` through
|
||||
`values` stores a formula; prefix with `'` to store a literal leading `=`.
|
||||
- **Use `write` for shape-matched writes**: `range.write(...)` can resize from
|
||||
the target top-left cell.
|
||||
- **Record user edits**: wrap edits in `workbook.record(() => { ... })` when a
|
||||
patch, id map, or CRDT update is needed.
|
||||
- **Inspect before editing imported workbooks**: use `inspect`, `findCells`,
|
||||
and `resolve` to locate exact sheets, tables, charts, and threads.
|
||||
- **Config-first creation**: prefer worksheet/range/table/chart config objects
|
||||
where available.
|
||||
- **PDF export**: `workbook.export({ format: "pdf" })` exports all worksheets.
|
||||
Set `pageSizing: "uniform"` for equal page sizes.
|
||||
|
||||
## Quick Start
|
||||
|
||||
```ts
|
||||
const workbook = Workbook.create();
|
||||
const sheet = workbook.worksheets.add("Data");
|
||||
|
||||
sheet.getRange("A1:C4").values = [
|
||||
["Region", "Q1", "Q2"],
|
||||
["North", 10, 12],
|
||||
["South", 8, 9],
|
||||
["Total", null, null],
|
||||
];
|
||||
sheet.getRange("B4:C4").formulas = [["=SUM(B2:B3)", "=SUM(C2:C3)"]];
|
||||
workbook.recalculate();
|
||||
|
||||
const table = sheet.tables.add("A1:C4", true, "DataTable");
|
||||
table.rows.add(null, [["West", 7, 11]]);
|
||||
|
||||
const chart = sheet.charts.add("bar", {
|
||||
from: { row: 1, col: 4 },
|
||||
extent: { widthPx: 420, heightPx: 260 },
|
||||
});
|
||||
chart.title = "Quarterly values";
|
||||
chart.categories = ["North", "South", "West"];
|
||||
const series = chart.series.add("Q1");
|
||||
series.values = [10, 8, 7];
|
||||
series.categories = chart.categories;
|
||||
|
||||
const preview = await workbook.export({
|
||||
sheet,
|
||||
range: "A1:C5",
|
||||
format: "png",
|
||||
scale: 2,
|
||||
});
|
||||
const layoutBlob = await workbook.export({
|
||||
sheet,
|
||||
range: "A1:C5",
|
||||
format: "layout",
|
||||
});
|
||||
const pdfBlob = await workbook.export({ format: "pdf" });
|
||||
const uniformPdfBlob = await workbook.export({
|
||||
format: "pdf",
|
||||
pageSizing: "uniform",
|
||||
headers: true,
|
||||
});
|
||||
const proto = workbook.toProto();
|
||||
```
|
||||
|
||||
## Load Existing Workbook Data
|
||||
|
||||
```ts
|
||||
const workbook = Workbook.load(proto, { validate: true });
|
||||
|
||||
const before = await workbook.inspect({
|
||||
kind: "sheet,table,formula,chart,thread",
|
||||
search: "Revenue",
|
||||
maxChars: 8000,
|
||||
});
|
||||
|
||||
const sheet = workbook.resolve(sheetAnchorId);
|
||||
sheet.getRange("B2").values = [["Updated"]];
|
||||
|
||||
const after = await workbook.inspect({
|
||||
target: { id: sheetAnchorId, beforeLines: 1, afterLines: 6 },
|
||||
kind: "sheet,table",
|
||||
});
|
||||
```
|
||||
|
||||
## Recorded Edit
|
||||
|
||||
```ts
|
||||
const { result, patch, idMap, crdtUpdateV2 } = workbook.record(() => {
|
||||
const sheet = workbook.worksheets.getItem("Data");
|
||||
sheet.getRange("A1:B2").values = [
|
||||
["Name", "Value"],
|
||||
["A", 1],
|
||||
];
|
||||
return sheet.tables.add("A1:B2", true, "DataTable");
|
||||
});
|
||||
```
|
||||
|
||||
`record` hydrates collaborative state when needed and returns the callback
|
||||
result, a workbook patch, created-id aliases, and a merged CRDT update when
|
||||
collaborative edits occurred.
|
||||
|
||||
## Core API Sequence
|
||||
|
||||
- Create workbooks with `Workbook.create()` and load with
|
||||
`Workbook.load(proto, { validate })`.
|
||||
- Import simple tabular data with `Workbook.fromCSV(...)`,
|
||||
`workbook.fromCSV(...)`, and `Workbook.fromMarkdown(...)`.
|
||||
- Add or select sheets with `workbook.worksheets.add(...)`, `getItem(...)`,
|
||||
`getActiveWorksheet()`, and
|
||||
`setActiveWorksheet(...)`.
|
||||
- Edit data with `sheet.getRange("A1:B2").values`, `.formulas`,
|
||||
`.formulasR1C1`, `.write(...)`, `.clear(...)`, `.merge(...)`, and
|
||||
`.copyFrom(...)`.
|
||||
- Add tables with `sheet.tables.add(range, hasHeaders, name)` and edit rows,
|
||||
columns, styles, totals, and filters on the table facade.
|
||||
- Add charts, images, shapes, sparklines, conditional formats, data
|
||||
validations, freeze panes, pivot tables, slicers, comments, notes, and names
|
||||
through their worksheet/workbook facades.
|
||||
- Recalculate formulas with `workbook.recalculate()` and inspect dependencies
|
||||
with `workbook.trace("Sheet!A1")`.
|
||||
- Inspect imported workbooks with `workbook.inspect(...)`, `findCells(...)`,
|
||||
`help(...)`, and `resolve(...)`.
|
||||
- Render previews with `workbook.render(...)` or `workbook.export(...)`.
|
||||
- Export all worksheets as PDF with `workbook.export({ format: "pdf" })`.
|
||||
Pass `sheet`, `sheetName`, or `sheetIndex` to export one worksheet.
|
||||
- Set PDF `pageSizing` to `"per-sheet"` (default) or `"uniform"`.
|
||||
- Export grid and style evidence with `workbook.export({ format: "layout" })`
|
||||
when template reconstruction needs cell frames, style regions, merged ranges,
|
||||
validations, defined names, and drawing anchors.
|
||||
- Serialize workbook data with `workbook.toProto()`.
|
||||
|
||||
## Output Map
|
||||
|
||||
| Output | API | Result |
|
||||
| --------------- | --------------------------------------------- | --------------------------------------------- |
|
||||
| Serialized data | `workbook.toProto()` | Serializable workbook proto |
|
||||
| Inspect records | `await workbook.inspect(options)` | Structured records and NDJSON |
|
||||
| Cell search | `workbook.findCells(options)` | Matches with sheet/address/value/formula info |
|
||||
| Help records | `workbook.help(query, options)` | Bounded NDJSON API help records |
|
||||
| Image preview | `workbook.export({ format: "png" })` | Workbook/sheet/range render blob |
|
||||
| PDF | `workbook.export({ format: "pdf" })` | PDF `Blob` |
|
||||
| Layout JSON | `workbook.export({ format: "layout" })` | Typed grid and style evidence |
|
||||
| Native workbook | `workbook.export({ format: "xlsx" })` | Editable XLSX `Blob` |
|
||||
| Render blob | `workbook.render(options)` | Render-provider blob |
|
||||
| HTML table | `workbook.toHTML(sheetIndex, range, options)` | Excel/Sheets-compatible HTML |
|
||||
| Recorded patch | `workbook.record(fn)` | `{ result, patch, idMap, crdtUpdateV2 }` |
|
||||
|
||||
## Minimal Patterns
|
||||
|
||||
```ts
|
||||
// Data + formulas.
|
||||
const workbook = Workbook.create();
|
||||
const sheet = workbook.worksheets.add("Calc");
|
||||
sheet.getRange("A1:B2").values = [
|
||||
[2, 3],
|
||||
[5, 7],
|
||||
];
|
||||
sheet.getRange("C1:C2").formulas = [["=A1+B1"], ["=A2+B2"]];
|
||||
workbook.recalculate();
|
||||
```
|
||||
|
||||
```ts
|
||||
// Inspect, resolve, edit, re-inspect.
|
||||
const snapshot = await workbook.inspect({
|
||||
kind: "sheet,table,formula,thread,chart",
|
||||
search: "Status",
|
||||
});
|
||||
const sheet = workbook.resolve(sheetAnchorId);
|
||||
sheet.getRange("B2").values = [["Closed"]];
|
||||
const updated = await workbook.inspect({
|
||||
target: { id: sheetAnchorId },
|
||||
kind: "sheet,table",
|
||||
});
|
||||
```
|
||||
|
||||
## Reference Map
|
||||
|
||||
- [`references/workbook.spec.md`](./references/workbook.spec.md) -
|
||||
`Workbook` create/load/import/export/inspect/help/record surface.
|
||||
- [`references/worksheets.spec.md`](./references/worksheets.spec.md) -
|
||||
worksheet collection and worksheet facade.
|
||||
- [`references/ranges.spec.md`](./references/ranges.spec.md) - values,
|
||||
formulas, indexing, formatting, clearing, merging, fill, and copy.
|
||||
- [`references/tables.spec.md`](./references/tables.spec.md) - worksheet
|
||||
tables, rows, columns, headers, totals, and recorded patches.
|
||||
- [`references/pivot-tables.spec.md`](./references/pivot-tables.spec.md) -
|
||||
pivot creation, calculations, layout, filtering, and editing.
|
||||
- [`references/formulas.spec.md`](./references/formulas.spec.md) -
|
||||
recalculation, formula assignment, dynamic arrays, trace, and names.
|
||||
- [`references/formatting.spec.md`](./references/formatting.spec.md) - range
|
||||
formats, workbook theme, conditional formatting, data validation, and freeze
|
||||
panes.
|
||||
- [`references/charts-drawings.spec.md`](./references/charts-drawings.spec.md)
|
||||
- worksheet charts, images, shapes, sparklines, and drawing layout.
|
||||
- [`references/comments-notes-names.spec.md`](./references/comments-notes-names.spec.md)
|
||||
- comments, notes, workbook-scoped names, and sheet-scoped names.
|
||||
- [`references/inspect-help.md`](./references/inspect-help.md) - inspect,
|
||||
resolve, findCells, and help workflows.
|
||||
- [`references/import-export.md`](./references/import-export.md) - CSV,
|
||||
Markdown, HTML, image import, rendering, export, and Google Sheets adapters.
|
||||
Generated
Vendored
+264
@@ -0,0 +1,264 @@
|
||||
# Charts And Drawings
|
||||
|
||||
Worksheets expose drawing collections for charts, images, and shapes.
|
||||
|
||||
## Charts
|
||||
|
||||
```ts
|
||||
const chart = sheet.charts.add("bar", {
|
||||
from: { row: 1, col: 4 },
|
||||
extent: { widthPx: 420, heightPx: 260 },
|
||||
});
|
||||
chart.title = "Values";
|
||||
chart.categories = ["A", "B", "C"];
|
||||
const series = chart.series.add("Value");
|
||||
series.values = [3, 5, 8];
|
||||
series.categories = chart.categories;
|
||||
```
|
||||
|
||||
Charts can be resolved from inspect anchors:
|
||||
|
||||
```ts
|
||||
const chart = workbook.resolve("ch/<chartId>");
|
||||
```
|
||||
|
||||
### Edit The Chart Frame
|
||||
|
||||
```ts
|
||||
chart.roundedCorners = true;
|
||||
chart.roundedCorners = false;
|
||||
chart.roundedCorners = null;
|
||||
const roundedCorners = chart.roundedCorners;
|
||||
```
|
||||
|
||||
### Edit Chart Family Options
|
||||
|
||||
```ts
|
||||
histogram.apply({ histogramOptions: { binCount: 8, underflow: 0, overflow: 30 } });
|
||||
histogram.apply({ histogramOptions: { binWidth: null, binCount: null } });
|
||||
histogram.apply({ histogramOptions: { underflow: null, overflow: null } });
|
||||
bubble.bubbleOptions = { scale: 150, sizeRepresents: "width" };
|
||||
bubble.bubbleOptions = { scale: null, sizeRepresents: null };
|
||||
const settings = bubble.bubbleOptions;
|
||||
```
|
||||
|
||||
[Chart family options](../../../presentations/api/references/charts.spec.md#chart-family-options)
|
||||
|
||||
### Edit Error Bars
|
||||
|
||||
```ts
|
||||
const errorBars = chart.series.getItemAt(0).errorBars;
|
||||
errorBars.apply("y", { type: "fixedValue", value: 2 });
|
||||
errorBars.apply("y", {
|
||||
display: "both",
|
||||
endStyle: "cap",
|
||||
line: { fill: "accent1", width: 1.5, style: "solid" },
|
||||
});
|
||||
const editableDirections = errorBars.directions;
|
||||
const settings = errorBars.get("y");
|
||||
errorBars.apply("y", { line: { width: null } });
|
||||
errorBars.apply("y", { type: "none" });
|
||||
```
|
||||
|
||||
### Edit Individual Trendlines
|
||||
|
||||
```ts
|
||||
const trendlines = chart.series.getItemAt(0).trendlines;
|
||||
const types = trendlines.supportedTypes;
|
||||
const trendline = trendlines.add("linear", { name: "Forecast" });
|
||||
trendline.apply({
|
||||
forecastForward: 2,
|
||||
displayEquation: true,
|
||||
line: { fill: "accent2", width: 2, style: "dashed" },
|
||||
label: {
|
||||
numberFormatCode: "0.00",
|
||||
numberFormatSourceLinked: false,
|
||||
textStyle: { fontSizePt: 12, typeface: "Arial", color: "accent2" },
|
||||
manualLayout: { x: 0.2, y: 0.3 },
|
||||
fill: "#FFFFFF",
|
||||
line: { fill: "accent2", width: 1 },
|
||||
},
|
||||
});
|
||||
trendline.apply({ forecastForward: null });
|
||||
trendlines.deleteAt(0);
|
||||
```
|
||||
|
||||
### Replace Chart Data
|
||||
|
||||
```ts
|
||||
chart.setData("A1:C8");
|
||||
chart.setData("'Source data'!A1:C8");
|
||||
chart.setData(["'Source data'!A1:A8", "D1:D8", "G1:G8"]);
|
||||
```
|
||||
|
||||
| Chart | Source columns |
|
||||
| --- | --- |
|
||||
| Bar, line, area, pie | Categories, then one column per series |
|
||||
| Scatter | X values, then one Y column per series |
|
||||
| Bubble | X, Y, Size per series |
|
||||
| Treemap or sunburst | Outer-to-inner category levels, then values |
|
||||
| Box and whisker or histogram | One numeric column per sample series |
|
||||
|
||||
### Empty Cells
|
||||
|
||||
```ts
|
||||
chart.displayBlanksAs = "gap";
|
||||
chart.displayBlanksAs = "zero";
|
||||
chart.displayBlanksAs = "span";
|
||||
chart.displayBlanksAs = null;
|
||||
chart.displayBlanksAsOptions;
|
||||
```
|
||||
|
||||
### Edit One Series Binding
|
||||
|
||||
```ts
|
||||
const series = chart.series.getItemAt(0);
|
||||
series.valuesSource = "'Source data'!D2:D8";
|
||||
series.categoriesSource = "A2:A8";
|
||||
series.xValuesSource = "B2:B8";
|
||||
// Bubble charts:
|
||||
series.bubbleSizesSource = "C2:C8";
|
||||
// Treemap and sunburst charts:
|
||||
series.categoryPathsSource = "A2:B8";
|
||||
```
|
||||
|
||||
### Edit An Axis
|
||||
|
||||
```ts
|
||||
const axes = chart.getAxisTargets(); // { axisId: number, axis: "x" | "y" }[]
|
||||
const axisId = axes[0].axisId;
|
||||
const axis = chart.getAxisById(axisId);
|
||||
chart.applyAxis(axisId, {
|
||||
min: 0,
|
||||
max: 100,
|
||||
title: { text: "Value", textStyle: { bold: true } },
|
||||
});
|
||||
```
|
||||
|
||||
### Scoped Data Labels
|
||||
|
||||
```ts
|
||||
const target = { scope: "point", seriesIndex: 0, pointIndex: 1 } as const;
|
||||
const targetExists = chart.hasDataLabelTarget(target);
|
||||
const labels = chart.getDataLabels(target);
|
||||
chart.applyDataLabels(target, { textStyle: { bold: true }, separator: " / " });
|
||||
chart.applyDataLabels(target, { showValue: false });
|
||||
chart.applyDataLabels(target, { showValue: null }); // Restore the parent flag.
|
||||
chart.applyDataLabels(target, null); // Remove the entire point override.
|
||||
chart.applyDataLabels({ scope: "series", seriesIndex: 0 }, {
|
||||
showValue: true, numberFormatCode: "0.00",
|
||||
});
|
||||
chart.applyDataLabels({ scope: "chart" }, { position: "outEnd" });
|
||||
```
|
||||
|
||||
### Series Markers And Bar Spacing
|
||||
|
||||
```ts
|
||||
chart.applySeriesStyle(0, {
|
||||
marker: { symbol: "diamond", size: 8, fill: "#156082" },
|
||||
});
|
||||
chart.applySeriesStyle(0, { marker: { size: 12 } });
|
||||
chart.applySeriesStyle(0, { stroke: { style: "dashed", compound: "double" } });
|
||||
chart.applySeriesStyle(0, { stroke: { width: 3 } });
|
||||
chart.format.apply({ barOptions: { gapWidth: 150, overlap: 0 } });
|
||||
```
|
||||
|
||||
## Chart To Image
|
||||
|
||||
```ts
|
||||
const result = await workbook.chartToImage(0, chart.id);
|
||||
```
|
||||
|
||||
## Images
|
||||
|
||||
```ts
|
||||
const image = sheet.images.add({
|
||||
blob: imageBytes,
|
||||
contentType: "image/png",
|
||||
anchor: {
|
||||
from: { row: 1, col: 2 },
|
||||
extent: { widthPx: 240, heightPx: 160 },
|
||||
},
|
||||
});
|
||||
|
||||
image.id;
|
||||
image.bytes;
|
||||
image.contentType;
|
||||
image.prompt;
|
||||
image.uri;
|
||||
```
|
||||
|
||||
## Shapes
|
||||
|
||||
```ts
|
||||
const shape = sheet.shapes.add({
|
||||
geometry: "rect",
|
||||
anchor: {
|
||||
from: { row: 2, col: 3 },
|
||||
extent: { widthPx: 240, heightPx: 80 },
|
||||
},
|
||||
fill: "#f8fafc",
|
||||
line: { fill: "#334155", width: 1 },
|
||||
});
|
||||
shape.text = "Label";
|
||||
shape.geometry = "roundRect";
|
||||
shape.geometry; // "roundRect"
|
||||
shape.borderRadius = 16;
|
||||
shape.borderRadius;
|
||||
shape.borderRadiusApplies;
|
||||
```
|
||||
|
||||
## Sparklines
|
||||
|
||||
```ts
|
||||
const group = sheet.sparklineGroups.add({
|
||||
targetRange: sheet.getRange("D2:D10"),
|
||||
sourceData: sheet.getRange("B2:C10"),
|
||||
type: "line",
|
||||
});
|
||||
|
||||
group.apply({
|
||||
sourceData: "'Source data'!B2:C12",
|
||||
locationRange: "D2:D12",
|
||||
type: "line",
|
||||
lineWeight: 2,
|
||||
dateAxisRange: "'Source data'!B1:C1",
|
||||
displayHidden: false,
|
||||
axis: { manualMin: 0, manualMax: 100 },
|
||||
});
|
||||
|
||||
group.apply({ axis: { manualMin: undefined, manualMax: undefined } });
|
||||
group.apply({ dateAxisRange: undefined }); // Restore evenly spaced samples.
|
||||
|
||||
group.sourceAddress;
|
||||
group.dateAxisAddress;
|
||||
group.dateAxisFormula;
|
||||
group.uid;
|
||||
```
|
||||
|
||||
## Auto Layout
|
||||
|
||||
```ts
|
||||
sheet.autoLayoutDrawings(sheet.charts.items, {
|
||||
direction: "vertical",
|
||||
frame: { startCell: "E2", width: 800, height: 1200 },
|
||||
gap: 16,
|
||||
padding: 24,
|
||||
});
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
sheet.getRange("A1:B4").values = [
|
||||
["Name", "Value"],
|
||||
["A", 3],
|
||||
["B", 5],
|
||||
["C", 8],
|
||||
];
|
||||
|
||||
sheet.charts.add("bar", {
|
||||
from: { row: 1, col: 4 },
|
||||
extent: { widthPx: 420, heightPx: 260 },
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+78
@@ -0,0 +1,78 @@
|
||||
# Comments, Notes, And Names
|
||||
|
||||
Workbook comments, notes, and names are root-level facades. Sheet-scoped names
|
||||
are available from `worksheet.names`.
|
||||
|
||||
## Comments
|
||||
|
||||
```ts
|
||||
workbook.comments.setSelf({
|
||||
displayName: "Reviewer",
|
||||
initials: "RV",
|
||||
});
|
||||
|
||||
const thread = workbook.comments.addThread(
|
||||
{ cell: sheet.getRange("B2") },
|
||||
"Review this cell",
|
||||
);
|
||||
|
||||
thread.addReply("Updated.");
|
||||
thread.resolve();
|
||||
thread.reopen();
|
||||
```
|
||||
|
||||
Threads appear in `workbook.inspect({ kind: "thread" })` and resolve from
|
||||
`th/...` anchors.
|
||||
|
||||
## Notes
|
||||
|
||||
```ts
|
||||
workbook.notes;
|
||||
```
|
||||
|
||||
Notes serialize through `workbook.toProto()` and participate in recorded
|
||||
workbook state.
|
||||
|
||||
## Workbook-Scoped Names
|
||||
|
||||
```ts
|
||||
workbook.names.addRange("SalesRange", "Data!$A$1:$A$3", {
|
||||
description: "Sales data",
|
||||
});
|
||||
|
||||
const namedRange = workbook.names.getItem("SalesRange");
|
||||
const range = namedRange.getRange();
|
||||
namedRange.delete();
|
||||
```
|
||||
|
||||
## Functions
|
||||
|
||||
```ts
|
||||
workbook.names.addFunction("AddTax", {
|
||||
lambda: "=LAMBDA(amount, amount * 1.1)",
|
||||
description: "Add tax",
|
||||
});
|
||||
```
|
||||
|
||||
## Sheet-Scoped Names
|
||||
|
||||
```ts
|
||||
sheet.names.addRange("LocalRange", "Sheet1!$A$1:$A$10");
|
||||
```
|
||||
|
||||
## Alias
|
||||
|
||||
```ts
|
||||
workbook.definedNames === workbook.names;
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
const data = workbook.worksheets.add("Data");
|
||||
data.getRange("A1:A3").values = [[1], [2], [3]];
|
||||
workbook.names.add("SalesRange", data.getRange("A1:A3"));
|
||||
|
||||
workbook.comments.setSelf({ displayName: "Reviewer", initials: "RV" });
|
||||
workbook.comments.addThread({ cell: data.getRange("A1") }, "Check value.");
|
||||
```
|
||||
Generated
Vendored
+286
@@ -0,0 +1,286 @@
|
||||
# Formatting, Validation, And Theme
|
||||
|
||||
Use range formatting for cell style, worksheet collections for validation and
|
||||
conditional formatting, and `workbook.colorScheme` for workbook theme colors.
|
||||
|
||||
## Range Format
|
||||
|
||||
```ts
|
||||
range.format = {
|
||||
fill: "#f8fafc",
|
||||
font: {
|
||||
name: "Aptos",
|
||||
bold: true,
|
||||
underline: "single",
|
||||
color: "#0f172a",
|
||||
size: 11,
|
||||
},
|
||||
borders: {
|
||||
bottom: { style: "thin", color: "#94a3b8" },
|
||||
},
|
||||
numberFormat: "$#,##0.00",
|
||||
horizontalAlignment: "center",
|
||||
verticalAlignment: "middle",
|
||||
wrapText: true,
|
||||
rowHeightPx: 28,
|
||||
columnWidthPx: 120,
|
||||
};
|
||||
```
|
||||
|
||||
### Cell fills
|
||||
|
||||
```ts
|
||||
range.format.fill = {
|
||||
type: "gradient",
|
||||
angleDeg: 45,
|
||||
offsetScale: 100000,
|
||||
stops: [
|
||||
{ offset: 0, color: "accent1" },
|
||||
{ offset: 100000, color: "#ffffff" },
|
||||
],
|
||||
};
|
||||
range.format.fill = {
|
||||
type: "solid",
|
||||
color: "#ffffff",
|
||||
pattern: { type: "lightGrid", color: "#64748b" },
|
||||
};
|
||||
```
|
||||
|
||||
### Reading mixed formatting
|
||||
|
||||
```ts
|
||||
const summary = range.format.getSummary();
|
||||
if (summary.font.bold.state === "uniform") {
|
||||
console.log(summary.font.bold.value);
|
||||
}
|
||||
range.format = { font: { bold: true } };
|
||||
```
|
||||
|
||||
## Number Format
|
||||
|
||||
```ts
|
||||
range.setNumberFormat("0.0%");
|
||||
```
|
||||
|
||||
## Conditional Formatting
|
||||
|
||||
```ts
|
||||
sheet.getRange("B2:B10").conditionalFormats.add("cellIs", {
|
||||
operator: "greaterThan",
|
||||
formula: 10,
|
||||
format: {
|
||||
fill: "#dcfce7",
|
||||
font: { bold: true, color: "#166534" },
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Add and edit rules
|
||||
|
||||
```ts
|
||||
const rule = sheet.conditionalFormattings.add({
|
||||
range: "C2:C20",
|
||||
rule: {
|
||||
type: "cellIs",
|
||||
operator: "greaterThan",
|
||||
formula: "=$B2",
|
||||
format: { font: { bold: true, underline: "single" }, numberFormat: "0.0%" },
|
||||
},
|
||||
stopIfTrue: true,
|
||||
});
|
||||
rule.assign({ ranges: ["C2:C20", "E2:E20"] });
|
||||
rule.assign({ stopIfTrue: false });
|
||||
const sameRule = sheet.conditionalFormattings.getItem(rule.id);
|
||||
const matchingRules = sheet.conditionalFormattings.getIntersecting("C5");
|
||||
rule.moveBefore(null); // Last priority.
|
||||
```
|
||||
|
||||
### Edit rule formatting
|
||||
|
||||
```ts
|
||||
rule.assign({
|
||||
formatPatch: {
|
||||
font: { bold: false, color: null }, // Reset the font color override.
|
||||
border: { bottom: { style: "double" } },
|
||||
numberFormat: "0.00%",
|
||||
},
|
||||
});
|
||||
rule.assign({ ranges: ["E4:E20"], formatPatch: { font: { italic: true } } });
|
||||
```
|
||||
|
||||
### Text predicates
|
||||
|
||||
```ts
|
||||
const textRule = sheet.conditionalFormattings.add({
|
||||
range: "A2:A20",
|
||||
rule: {
|
||||
type: "containsText",
|
||||
text: "ready",
|
||||
formula: '=AND(ISNUMBER(SEARCH("ready",A2)),B2>0)',
|
||||
format: { fill: "accent2" },
|
||||
},
|
||||
});
|
||||
textRule.assign({
|
||||
predicatePatch: { type: "containsText", text: "approved" },
|
||||
formatPatch: { font: { bold: true } },
|
||||
ranges: ["C4:C22"],
|
||||
});
|
||||
textRule.assign({
|
||||
predicatePatch: { type: "containsText", formula: null },
|
||||
});
|
||||
```
|
||||
|
||||
### Date-period formula overrides
|
||||
|
||||
```ts
|
||||
const dates = sheet.conditionalFormattings.add({
|
||||
range: "B2:B20",
|
||||
rule: {
|
||||
type: "timePeriod",
|
||||
timePeriod: "last7Days",
|
||||
formula: "=AND(B2>=TODAY()-7,B2<=TODAY())",
|
||||
format: { fill: "accent2" },
|
||||
},
|
||||
});
|
||||
const dateConfig = dates.config;
|
||||
if (dateConfig.supported && dateConfig.rule.type === "timePeriod") {
|
||||
dates.assign({ rule: { ...dateConfig.rule, formula: "=B2=TODAY()" } });
|
||||
dates.assign({ rule: { ...dateConfig.rule, formula: undefined } });
|
||||
}
|
||||
```
|
||||
|
||||
### Data bars
|
||||
|
||||
```ts
|
||||
const bars = sheet.conditionalFormattings.add({
|
||||
range: "B2:B20",
|
||||
rule: {
|
||||
type: "dataBar",
|
||||
color: "accent1",
|
||||
gradient: false,
|
||||
showValue: true,
|
||||
minLength: 0,
|
||||
maxLength: 100,
|
||||
direction: "leftToRight", // "context" | "leftToRight" | "rightToLeft"
|
||||
axisPosition: "automatic", // "automatic" | "middle" | "none"
|
||||
border: true,
|
||||
borderColor: "accent1",
|
||||
negativeBarColorSameAsPositive: false,
|
||||
negativeFillColor: "accent2",
|
||||
negativeBarBorderColorSameAsPositive: false,
|
||||
negativeBorderColor: "accent2",
|
||||
axisColor: "text1",
|
||||
thresholds: [{ type: "autoMin" }, { type: "autoMax" }],
|
||||
},
|
||||
});
|
||||
const snapshot = bars.config;
|
||||
if (snapshot.supported && snapshot.rule.type === "dataBar") {
|
||||
bars.assign({ rule: { ...snapshot.rule, showValue: false } });
|
||||
}
|
||||
```
|
||||
|
||||
### Icon sets
|
||||
|
||||
```ts
|
||||
sheet.conditionalFormattings.add({
|
||||
range: "C2:C20",
|
||||
rule: {
|
||||
type: "iconSet",
|
||||
iconSet: "3Arrows",
|
||||
thresholds: [
|
||||
{ type: "num", value: 0 },
|
||||
{ type: "formula", value: "=$E$2", gte: false },
|
||||
{ type: "formula", value: "=$E$3", gte: true },
|
||||
],
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Clear and delete rules
|
||||
|
||||
```ts
|
||||
sheet.conditionalFormattings.clear("E5:E6");
|
||||
rule.delete();
|
||||
```
|
||||
|
||||
## Data Validation
|
||||
|
||||
```ts
|
||||
sheet.getRange("A2:A10").dataValidation = {
|
||||
list: {
|
||||
source: ["Open", "Closed"],
|
||||
inCellDropDown: true,
|
||||
},
|
||||
allowBlank: true,
|
||||
};
|
||||
```
|
||||
|
||||
The range setter accepts list assignments or validation config
|
||||
objects.
|
||||
|
||||
```ts
|
||||
sheet.getRange("B2:B20").dataValidation = {
|
||||
rule: { type: "whole", operator: "between", formula1: 0, formula2: 100 },
|
||||
ignoreBlanks: true,
|
||||
prompt: { show: true, title: "Score", message: "Enter 0–100." },
|
||||
errorAlert: {
|
||||
show: true,
|
||||
style: "warning",
|
||||
message: "Outside the expected range.",
|
||||
},
|
||||
};
|
||||
sheet.getRange("B5").dataValidation.clear();
|
||||
```
|
||||
|
||||
### Check cell values
|
||||
|
||||
```ts
|
||||
const cell = sheet.getRange("B2");
|
||||
const check = workbook.checkCellValue(sheet.name, "B2", 150);
|
||||
const result = cell.setValueChecked(150);
|
||||
if (
|
||||
!result.applied &&
|
||||
!result.validation.valid &&
|
||||
result.validation.style !== "stop"
|
||||
) {
|
||||
// After the user confirms the warning/information message:
|
||||
cell.setValueChecked(150, { acceptWarning: true });
|
||||
}
|
||||
```
|
||||
|
||||
## Freeze Panes
|
||||
|
||||
```ts
|
||||
sheet.freezePanes.freezeRows(1);
|
||||
sheet.freezePanes.freezeColumns(1);
|
||||
sheet.freezePanes.unfreeze();
|
||||
```
|
||||
|
||||
## Theme
|
||||
|
||||
```ts
|
||||
const current = workbook.colorScheme;
|
||||
console.log(current.name, current.themeColors.accent1);
|
||||
|
||||
workbook.colorScheme = {
|
||||
name: "Workbook Theme",
|
||||
themeColors: {
|
||||
accent1: "#2563eb",
|
||||
accent2: "#0f766e",
|
||||
bg1: "#ffffff",
|
||||
tx1: "#0f172a",
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
const header = sheet.getRange("A1:C1");
|
||||
header.format = {
|
||||
fill: "#0f172a",
|
||||
font: { bold: true, color: "#ffffff" },
|
||||
horizontalAlignment: "center",
|
||||
};
|
||||
sheet.freezePanes.freezeRows(1);
|
||||
```
|
||||
Generated
Vendored
+74
@@ -0,0 +1,74 @@
|
||||
# Formulas
|
||||
|
||||
Workbook formulas are stored on ranges and evaluated by `workbook.recalculate()`.
|
||||
|
||||
## Assign Formulas
|
||||
|
||||
```ts
|
||||
sheet.getRange("A1:B2").values = [
|
||||
[2, 3],
|
||||
[5, 7],
|
||||
];
|
||||
|
||||
sheet.getRange("C1:C2").formulas = [["=A1+B1"], ["=A2+B2"]];
|
||||
workbook.recalculate();
|
||||
```
|
||||
|
||||
Strings starting with `=` assigned through `values` are treated as formulas.
|
||||
Use a leading apostrophe for literal strings:
|
||||
|
||||
```ts
|
||||
sheet.getRange("C1").values = [["=SUM(A1:B1)"]];
|
||||
sheet.getRange("D1").values = [["'=SUM(A1:B1)"]];
|
||||
```
|
||||
|
||||
## Dynamic Arrays And Spill
|
||||
|
||||
```ts
|
||||
sheet.getRange("E1").formulas = [["=SEQUENCE(3, 2)"]];
|
||||
workbook.recalculate();
|
||||
```
|
||||
|
||||
Spill projection cells are not directly editable formula anchors.
|
||||
|
||||
## Trace
|
||||
|
||||
```ts
|
||||
const trace = workbook.trace("Sheet1!C1");
|
||||
```
|
||||
|
||||
`trace` recalculates first and returns a dependency tree for the target cell or
|
||||
`null` for an invalid reference.
|
||||
|
||||
## Formula Usage Stats
|
||||
|
||||
```ts
|
||||
const stats = workbook.collectFormulaUsageStats();
|
||||
```
|
||||
|
||||
## Names
|
||||
|
||||
```ts
|
||||
workbook.names.addRange("SalesRange", "Data!$A$1:$A$3", {
|
||||
description: "Sales data",
|
||||
});
|
||||
|
||||
workbook.names.addFunction("AddTax", {
|
||||
lambda: "=LAMBDA(amount, amount * 1.1)",
|
||||
description: "Add tax",
|
||||
});
|
||||
|
||||
sheet.names.addRange("LocalRange", "Sheet1!$A$1:$A$10");
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
const workbook = Workbook.create();
|
||||
const sheet = workbook.worksheets.add("Calc");
|
||||
sheet.getRange("A1:A3").values = [[1], [2], [3]];
|
||||
sheet.getRange("B1").formulas = [["=SUM(A1:A3)"]];
|
||||
workbook.recalculate();
|
||||
|
||||
const trace = workbook.trace("Calc!B1");
|
||||
```
|
||||
Generated
Vendored
+168
@@ -0,0 +1,168 @@
|
||||
# Import, Export, HTML, Images, And Google Sheets
|
||||
|
||||
Workbook import/export helpers cover CSV, Markdown, HTML copy/paste,
|
||||
image/chart conversion, rendering, and Google Sheets adapter flows.
|
||||
|
||||
## CSV
|
||||
|
||||
```ts
|
||||
const workbook = await Workbook.fromCSV(csv, {
|
||||
sheetName: "Data",
|
||||
});
|
||||
|
||||
const { sheet, range } = await workbook.fromCSV(csv, {
|
||||
sheetName: "Imported",
|
||||
});
|
||||
```
|
||||
|
||||
## Markdown Table
|
||||
|
||||
```ts
|
||||
const workbook = await Workbook.fromMarkdown(markdown, {
|
||||
sheetName: "Data",
|
||||
format: true,
|
||||
});
|
||||
```
|
||||
|
||||
Markdown import expects a Markdown table. With `format: true`, the imported
|
||||
range is formatted as a worksheet table and columns are autofit.
|
||||
|
||||
## HTML
|
||||
|
||||
```ts
|
||||
const html = source.toHTML(0, "A1:B2");
|
||||
const withFormulas = source.toHTML(0, "A1:B2", { formulas: true });
|
||||
|
||||
const result = target.fromHTML(0, html, "C3");
|
||||
const filled = target.fromHTML(0, html, "B2:C4");
|
||||
```
|
||||
|
||||
`sheetIndex` is zero-based. The optional range uses A1 syntax.
|
||||
|
||||
## Image Import
|
||||
|
||||
```ts
|
||||
const result = workbook.fromImage(
|
||||
0,
|
||||
{ bytes: imageBytes, contentType: "image/png" },
|
||||
"A1:D10",
|
||||
);
|
||||
```
|
||||
|
||||
### Worksheet Images
|
||||
|
||||
```ts
|
||||
const sheet = workbook.worksheets.getItem("Data");
|
||||
sheet.images.add({
|
||||
svg: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" /></svg>',
|
||||
anchor: {
|
||||
from: { row: 0, col: 4 },
|
||||
extent: { widthPx: 48, heightPx: 48 },
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Chart To Image
|
||||
|
||||
```ts
|
||||
const result = await workbook.chartToImage(0, chart.id);
|
||||
```
|
||||
|
||||
## Render And Export
|
||||
|
||||
```ts
|
||||
const renderBlob = await workbook.render({
|
||||
sheet: "Data",
|
||||
range: "A1:C10",
|
||||
format: "png",
|
||||
scale: 2,
|
||||
});
|
||||
|
||||
const exportBlob = await workbook.export({
|
||||
sheetName: "Data",
|
||||
range: "A1:C10",
|
||||
format: "png",
|
||||
scale: 2,
|
||||
headers: true,
|
||||
});
|
||||
|
||||
const layoutBlob = await workbook.export({
|
||||
sheetName: "Data",
|
||||
range: "A1:C10",
|
||||
format: "layout",
|
||||
});
|
||||
|
||||
const allSheetsPdf = await workbook.export({ format: "pdf" });
|
||||
const uniformSheetsPdf = await workbook.export({
|
||||
format: "pdf",
|
||||
pageSizing: "uniform",
|
||||
headers: true,
|
||||
});
|
||||
const oneSheetPdf = await workbook.export({
|
||||
sheetName: "Data",
|
||||
format: "pdf",
|
||||
scale: 2,
|
||||
});
|
||||
const xlsxBlob = await workbook.export({
|
||||
format: "xlsx",
|
||||
fileName: "report.xlsx",
|
||||
});
|
||||
```
|
||||
|
||||
`format: "pdf"` exports all worksheets in workbook order. `sheet`, `sheetName`,
|
||||
or `sheetIndex` selects one worksheet. PDF `pageSizing` accepts `"per-sheet"`
|
||||
(default) or `"uniform"`.
|
||||
|
||||
`format: "layout"` exports sheet/range geometry, cell frames, styles, merged
|
||||
ranges, validations, defined names, and drawing anchors. It supports sheet
|
||||
selection, `range`, and `autoCrop`. `center`, `width`, and `height` apply to
|
||||
preview and PDF exports, not layout.
|
||||
|
||||
## Export Inline Types
|
||||
|
||||
```ts
|
||||
type WorkbookExportFormat = "png" | "jpeg" | "layout" | "xlsx" | "pdf";
|
||||
|
||||
type WorkbookExportOptions = {
|
||||
fileName?: string;
|
||||
sheet?: Worksheet | string | number;
|
||||
sheetName?: string;
|
||||
sheetIndex?: number;
|
||||
range?: string;
|
||||
center?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
scale?: number;
|
||||
autoCrop?: "all" | "charts";
|
||||
headers?: boolean;
|
||||
format?: WorkbookExportFormat;
|
||||
quality?: number;
|
||||
pageSizing?: "per-sheet" | "uniform";
|
||||
};
|
||||
```
|
||||
|
||||
## Google Sheets
|
||||
|
||||
```ts
|
||||
const workbook = await Workbook.fromGoogleSheets(config);
|
||||
workbook.configureGoogleSheets(config);
|
||||
|
||||
const { patch } = workbook.record(() => {
|
||||
workbook.worksheets.getItem("Data").getRange("A1").values = [["Updated"]];
|
||||
});
|
||||
|
||||
await workbook.apply(patch, { target: "googleSheets" });
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
const workbook = await Workbook.fromCSV(csv, { sheetName: "Data" });
|
||||
const preview = await workbook.export({
|
||||
sheetName: "Data",
|
||||
range: "A1:D20",
|
||||
format: "png",
|
||||
scale: 2,
|
||||
});
|
||||
const proto = workbook.toProto();
|
||||
```
|
||||
Generated
Vendored
+152
@@ -0,0 +1,152 @@
|
||||
# Inspect and Help
|
||||
|
||||
`workbook.inspect({ select, include })` queries a semantic workbook tree with RFC 9535 JSONPath. The [JSON Schema](inspect.schema.json) describes the nodes and value semantics.
|
||||
|
||||
## Navigate before reading cells
|
||||
|
||||
```ts
|
||||
const overview = await workbook.inspect({
|
||||
select: "$.sheets[*]",
|
||||
include: ["name", "range", "tables.name", "tables.range", "tables.columns.name"],
|
||||
});
|
||||
console.log(overview.records);
|
||||
|
||||
const statistics = await workbook.inspect({
|
||||
select: "$.sheets[?(@.name == 'Data')].columns[?(@.letter == 'B')].statistics",
|
||||
include: ["numericCount", "min", "max", "sum", "average", "errorCount"],
|
||||
});
|
||||
console.log(statistics.records);
|
||||
```
|
||||
|
||||
The tree contains `sheets` and workbook-scoped `definedNames`. Sheets contain native `tables`, `charts`, `drawings`, `pivotTables`, `sparklines`, `slicers`, what-if `dataTables`, `threads`, classic `notes`, `dataValidations`, `conditionalFormats`, `mergedRanges`, `freezePanes`, and layout metadata. Select the fields needed for the decision. Objects retain public names, drawing IDs, or fully qualified A1 addresses for subsequent edits.
|
||||
|
||||
`regions` describes inferred data blocks separately from native tables. Each region bounds cells connected horizontally or vertically through nonblank values or formulas. Rectangles can contain blanks and can overlap; their statistics describe the full rectangle. Region column names are copied from text in the first row, without inferring a formal header or changing the workbook.
|
||||
|
||||
```ts
|
||||
const regions = await workbook.inspect({
|
||||
select: "$.sheets[*].regions[*]",
|
||||
include: ["sheet", "range", "rowCount", "columnCount", "columns.name"],
|
||||
});
|
||||
|
||||
const sources = await workbook.inspect({
|
||||
select: "$.sheets[*].charts[*]",
|
||||
include: ["sheet", "id", "title", "type", "series.name", "series.formula", "series.categoryFormula"],
|
||||
});
|
||||
```
|
||||
|
||||
Statistics use finite computed numbers. Numeric-looking strings, dates, booleans, blanks, and errors are counted separately. `min`, `max`, and `average` are `null` without numeric values; `sum` is zero. An overflowing sum is `null`. Native table column statistics exclude headers and totals. Sheet and inferred-region column statistics cover their reported ranges.
|
||||
|
||||
## Search content, formulas, and appearance
|
||||
|
||||
```ts
|
||||
const matches = await workbook.inspect({
|
||||
select: "$.sheets[*].cells[?search(@.text, 'Revenue')]",
|
||||
include: ["sheet", "address", "text"],
|
||||
});
|
||||
|
||||
const errors = await workbook.inspect({
|
||||
select: "$.sheets[*].cells[?(@.formula && @.valueType == 'error')]",
|
||||
include: ["sheet", "address", "formula", "error"],
|
||||
});
|
||||
|
||||
const formatting = await workbook.inspect({
|
||||
select: "$.sheets[?(@.name == 'Data')].cells[?(@.row <= 10 && @.column <= 4)]",
|
||||
include: ["address", "value", "text", "computedStyle.numberFormat", "computedStyle.fillColor"],
|
||||
});
|
||||
```
|
||||
|
||||
Cells are sparse, sorted by row and column, and include materialized styled blanks. Untouched blank positions are absent; whole-row and whole-column layout spans are represented separately. Cell row/column numbers are one-based; sheet index is zero-based. `value` is JSON-safe, dates are ISO timestamps, and `valueType` distinguishes dates and errors from strings. Formulas include `=`. Follow the workbook calculation lifecycle: recalculate after formula/input edits before querying current computed results.
|
||||
|
||||
`text` is displayed text. `computedStyle` follows the renderer, including inheritance, table/pivot formatting, theme colors, number-format colors, and supported conditional effects. Fields contain format codes, readable alignments, point font sizes, and resolved colors. Conditional rule definitions are separately available, including visual effects such as data bars and icon sets.
|
||||
|
||||
Mixed rich text exposes resolved `runs`; `computedStyle.font` describes the cell default when runs differ. Cells also expose their `links`, applicable `validation`, and containing `mergedRange`. Sheet `layout` reports authored/default dimensions and hidden spans, without expanding entire rows or columns into blank cell records.
|
||||
|
||||
Filters run before exact projection. `include` is an array of fields on selected nodes; dotted paths project nested objects and arrays. JSONPath slices, unions, recursive traversal, and standard `match()`/`search()` functions work without another inspection language.
|
||||
|
||||
`match()` and `search()` are case-sensitive. For example, `search(@.text, '[Rr]evenue')` matches both `Revenue` and `revenue`. A legacy case-insensitive regex needs an explicit equivalent when moving to JSONPath.
|
||||
|
||||
## Complete results and sessions
|
||||
|
||||
```ts
|
||||
const result = await workbook.inspect({
|
||||
select: "$.sheets[*].cells[?(@.formula)]",
|
||||
include: ["sheet", "address"],
|
||||
fileName: "formula-addresses.ndjson",
|
||||
});
|
||||
console.log(result.recordCount);
|
||||
```
|
||||
|
||||
Files contain every selected record, with no hidden preview truncation. Narrow `select` and `include` to control size. `records` and `ndjson` remain available programmatically; ordinary result serialization returns count and output metadata. Return `result.records` explicitly from a session callback for a small immediate answer. Completed files are listed separately by the session runner.
|
||||
|
||||
```ts
|
||||
type WorkbookInspectQueryOptions = {
|
||||
select: string;
|
||||
include?: readonly string[];
|
||||
fileName?: string;
|
||||
};
|
||||
```
|
||||
|
||||
The previous `kind`/`searchTerm` API remains a separate overload. JSONPath requests use `select`, `include`, and `fileName` only.
|
||||
|
||||
## Find cells and API guidance
|
||||
|
||||
```ts
|
||||
const matches = workbook.findCells({
|
||||
searchTerm: "East", sheetId: "Data",
|
||||
options: { maxResults: 10, matchFormulas: true },
|
||||
});
|
||||
```
|
||||
|
||||
Result matches include sheet, address, value/formula match metadata, and total
|
||||
count.
|
||||
|
||||
## Help
|
||||
|
||||
```ts
|
||||
const help = workbook.help("*", {
|
||||
search: "colorScheme|worksheet.charts.add",
|
||||
include: ["index", "examples", "notes"],
|
||||
maxChars: 12000,
|
||||
});
|
||||
console.log(help.ndjson);
|
||||
```
|
||||
|
||||
Common queries:
|
||||
|
||||
```text
|
||||
*, workbook.colorScheme, worksheet.charts.add, formulas, enum.ChartType
|
||||
```
|
||||
|
||||
## Navigate inspection results
|
||||
|
||||
Inspection IDs use each object's public navigation API. Select worksheets with `workbook.worksheets.getItem(id)`, cells with `sheet.getRange(address)`, and inferred regions with `sheet.getRange(range)`. Native table and slicer IDs are names for their sheet collections' `getItem(id)` methods; pivot IDs work with `workbook.pivotTables.getItem(id)`. Drawings retain their collection IDs. Include `sheet` when selecting objects across sheets.
|
||||
|
||||
Returned chart (`ch/<id>`) and thread (`th/<id>`) anchors work directly with `workbook.resolve`. Legacy worksheet anchors (`ws/<id>`) also continue to work; an inspection sheet's `id` is its public name, rather than a `ws/` anchor.
|
||||
|
||||
## Create/Edit Loop
|
||||
|
||||
```ts
|
||||
const before = await workbook.inspect({
|
||||
select: "$.sheets[?(@.name == 'Data')].cells[?(@.row == 2 && @.column == 2)]",
|
||||
include: ["address", "value", "formula"],
|
||||
});
|
||||
|
||||
const sheet = workbook.worksheets.getItem("Data");
|
||||
sheet.getRange("B2").values = [["Closed"]];
|
||||
workbook.recalculate();
|
||||
|
||||
const after = await workbook.inspect({
|
||||
select: "$.sheets[?(@.name == 'Data')].cells[?(@.row == 2 && @.column == 2)]",
|
||||
include: ["address", "value", "formula"],
|
||||
});
|
||||
```
|
||||
|
||||
## Inline Types
|
||||
|
||||
```ts
|
||||
type WorkbookHelpOptions = {
|
||||
include?: string[] | string;
|
||||
search?: string;
|
||||
maxChars?: number;
|
||||
};
|
||||
```
|
||||
Generated
Vendored
+2283
File diff suppressed because it is too large
Load Diff
Generated
Vendored
+122
@@ -0,0 +1,122 @@
|
||||
# Pivot Tables
|
||||
|
||||
## Create and Summarize
|
||||
|
||||
```ts
|
||||
const data = workbook.worksheets.add("Data");
|
||||
const output = workbook.worksheets.add("Summary");
|
||||
data.getRange("A1:C5").values = [
|
||||
["Region", "Product", "Sales"],
|
||||
["East", "A", 10],
|
||||
["East", "B", 20],
|
||||
["West", "A", 30],
|
||||
["West", "B", 40],
|
||||
];
|
||||
|
||||
const pivot = output.pivotTables.add(
|
||||
"SalesSummary",
|
||||
data.getRange("A1:C5"),
|
||||
output.getRange("A1"),
|
||||
);
|
||||
pivot.rowHierarchies.add(pivot.hierarchies.getItem("Region"));
|
||||
pivot.columnHierarchies.add(pivot.hierarchies.getItem("Product"));
|
||||
const sales = pivot.dataHierarchies.add(pivot.hierarchies.getItem("Sales"));
|
||||
sales.summarizeBy = "Sum";
|
||||
sales.name = "Revenue";
|
||||
sales.numberFormat = "#,##0.00";
|
||||
pivot.layout.layoutType = "Tabular";
|
||||
|
||||
sales.field.name;
|
||||
pivot.layout.getDataBodyRange().values;
|
||||
```
|
||||
|
||||
## Show Values As
|
||||
|
||||
```ts
|
||||
sales.showAs = { calculation: "PercentOfGrandTotal" };
|
||||
sales.numberFormat = "0.0%";
|
||||
|
||||
const region = pivot.hierarchies.getItem("Region").fields.getItem("Region");
|
||||
sales.showAs = {
|
||||
calculation: "DifferenceFrom",
|
||||
baseField: region,
|
||||
baseItem: region.items.getItem("East"),
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
sales.showAs = { calculation: "RunningTotal", baseField: region };
|
||||
sales.showAs = { calculation: "PercentRunningTotal", baseField: region };
|
||||
sales.showAs = { calculation: "RankDecending", baseField: region };
|
||||
sales.showAs = { calculation: "PercentOfParentRowTotal" };
|
||||
sales.showAs = { calculation: "Index" };
|
||||
```
|
||||
|
||||
## Layout, Subtotals, and Sorting
|
||||
|
||||
```ts
|
||||
pivot.layout.layoutType = "Tabular";
|
||||
pivot.layout.showRowGrandTotals = false;
|
||||
pivot.layout.showColumnGrandTotals = false;
|
||||
pivot.layout.subtotalLocation = "AtBottom"; // "AtTop" | "AtBottom" | "Off"
|
||||
pivot.layout.repeatAllItemLabels(true);
|
||||
pivot.layout.displayBlankLineAfterEachItem(false);
|
||||
pivot.styleName = "PivotStyleMedium2";
|
||||
pivot.layout.hideValuesRow = true;
|
||||
|
||||
region.subtotals = { automatic: false };
|
||||
region.subtotals = { sum: true, average: true, count: true };
|
||||
region.sortByLabels("Ascending");
|
||||
region.sortByValues("Descending", sales);
|
||||
```
|
||||
|
||||
```ts
|
||||
const product = pivot.hierarchies.getItem("Product").fields.getItem("Product");
|
||||
region.sortByValues("Descending", sales, [product.items.getItem("A")]);
|
||||
```
|
||||
|
||||
## Filter Fields
|
||||
|
||||
```ts
|
||||
region.applyFilter({ manualFilter: { selectedItems: ["East"] } });
|
||||
region.applyFilter({ labelFilter: { condition: "BeginsWith", substring: "E" } });
|
||||
region.applyFilter({
|
||||
valueFilter: { condition: "GreaterThan", comparator: 25, value: "Revenue" },
|
||||
});
|
||||
region.clearAllFilters();
|
||||
```
|
||||
|
||||
```ts
|
||||
region.getFilters();
|
||||
region.isFiltered();
|
||||
region.isFiltered("Value");
|
||||
region.clearFilter("Value");
|
||||
region.clearAllFilters();
|
||||
```
|
||||
|
||||
## Edit Hierarchies and Items
|
||||
|
||||
```ts
|
||||
const hierarchy = pivot.rowHierarchies.getItem("Region");
|
||||
hierarchy.name = "Area";
|
||||
hierarchy.position = 0;
|
||||
sales.position = 0;
|
||||
const item = region.items.getItem("East");
|
||||
item.name = "Atlantic";
|
||||
item.isExpanded = false;
|
||||
item.visible = false;
|
||||
```
|
||||
|
||||
## Read and Delete
|
||||
|
||||
```ts
|
||||
pivot.refresh();
|
||||
const existing = workbook.pivotTables.getItemOrNullObject("SalesSummary");
|
||||
if (existing !== null) {
|
||||
existing.dataHierarchies.items;
|
||||
existing.layout.getDataBodyRange();
|
||||
}
|
||||
pivot.rowHierarchies.remove(hierarchy);
|
||||
pivot.dataHierarchies.remove(sales);
|
||||
workbook.pivotTables.getItem("SalesSummary").delete();
|
||||
```
|
||||
Generated
Vendored
+150
@@ -0,0 +1,150 @@
|
||||
# Ranges
|
||||
|
||||
Ranges read and write cell values, formulas, formatting, validation,
|
||||
conditional formats, sparklines, merges, fills, and copies.
|
||||
|
||||
## Addressing
|
||||
|
||||
```ts
|
||||
const range = sheet.getRange("A1:B2");
|
||||
const byIndexes = sheet.getRangeByIndexes(0, 0, 2, 2);
|
||||
const cell = sheet.getCell(0, 0);
|
||||
|
||||
range.address;
|
||||
range.getAddress();
|
||||
range.rowIndex;
|
||||
range.columnIndex;
|
||||
range.rowCount;
|
||||
range.columnCount;
|
||||
```
|
||||
|
||||
## Values
|
||||
|
||||
```ts
|
||||
sheet.getRange("A1:B2").values = [
|
||||
[1, 2],
|
||||
[3, 4],
|
||||
];
|
||||
|
||||
sheet.getRange("B1:I1").values = [1, 2, 3, 4, 5, 6, 7, 8];
|
||||
sheet.getRange("A2:A5").values = ["a", "b", "c", "d"];
|
||||
```
|
||||
|
||||
Single-cell ranges can spill larger matrices:
|
||||
|
||||
```ts
|
||||
sheet.getRange("N9").values = [[1, 2, 3]];
|
||||
sheet.getRange("B2").values = [[1], [2], [3]];
|
||||
```
|
||||
|
||||
## Formulas
|
||||
|
||||
```ts
|
||||
sheet.getRange("C1").values = [["=SUM(A1:B1)"]];
|
||||
sheet.getRange("D1").values = [["'=SUM(A1:B1)"]];
|
||||
|
||||
sheet.getRange("C1:C2").formulas = [["=A1+B1"], ["=A2+B2"]];
|
||||
sheet.getRange("B3:E3").formulas = ["=1+1", "=2+2", "=3+3", "=4+4"];
|
||||
sheet.getRange("G2:G5").formulas = ["=10", "=11", "=12", "=13"];
|
||||
```
|
||||
|
||||
## Write
|
||||
|
||||
```ts
|
||||
sheet.getRange("A1").write([
|
||||
["Name", "Value"],
|
||||
["A", 1],
|
||||
]);
|
||||
|
||||
sheet.getRange("C1").write({ formulas: [["=SUM(B2:B10)"]] });
|
||||
sheet.getRange("E1").write({ values: [["Literal"]] }, { overwrite: "error" });
|
||||
```
|
||||
|
||||
## Format
|
||||
|
||||
```ts
|
||||
range.format = {
|
||||
fill: "#f8fafc",
|
||||
font: { bold: true, color: "#0f172a" },
|
||||
numberFormat: "$#,##0.00",
|
||||
horizontalAlignment: "center",
|
||||
verticalAlignment: "middle",
|
||||
wrapText: true,
|
||||
rowHeightPx: 28,
|
||||
columnWidthPx: 120,
|
||||
};
|
||||
|
||||
range.setNumberFormat("0.0%");
|
||||
```
|
||||
|
||||
## Navigation
|
||||
|
||||
```ts
|
||||
range.getCell(0, 1);
|
||||
range.getRow(0);
|
||||
range.getColumn(1);
|
||||
range.getRange("A1");
|
||||
range.getRangeByIndexes(0, 0, 1, 1);
|
||||
range.getOffsetRange(1, 0);
|
||||
range.getResizedRange(2, 3);
|
||||
range.getResizeRange(10, 4);
|
||||
range.offset(1, 0);
|
||||
range.resize(10, 4);
|
||||
range.getCurrentRegion();
|
||||
```
|
||||
|
||||
## Clear, Merge, Fill, Copy
|
||||
|
||||
```ts
|
||||
range.clear({ applyTo: "contents" });
|
||||
range.clear({ applyTo: "formats" });
|
||||
range.clear({ applyTo: "all" });
|
||||
|
||||
range.merge();
|
||||
range.unmerge();
|
||||
|
||||
range.fillDown();
|
||||
range.fillRight();
|
||||
range.fillFrom(sourceRange);
|
||||
|
||||
range.copyFrom(sourceRange);
|
||||
range.copyTo(targetRange);
|
||||
range.copyFrom(sourceRange, "values");
|
||||
range.copyTo(targetRange, "formulas");
|
||||
```
|
||||
|
||||
## Inline Types
|
||||
|
||||
```ts
|
||||
type CellValue = string | number | boolean | Date | null;
|
||||
|
||||
type RangeWriteOptions = {
|
||||
clear?: "contents" | "formats" | "all";
|
||||
overwrite?: "allow" | "error";
|
||||
resize?: "auto" | "none";
|
||||
};
|
||||
|
||||
type RangeWritePayload =
|
||||
| CellValue[][]
|
||||
| CellValue[]
|
||||
| null
|
||||
| {
|
||||
values?: CellValue[][] | CellValue[] | null;
|
||||
formulas?: string[][] | string[];
|
||||
formulasR1C1?: string[][] | string[];
|
||||
};
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
const data = sheet.getRange("A1:C4");
|
||||
data.values = [
|
||||
["Region", "Q1", "Q2"],
|
||||
["North", 10, 12],
|
||||
["South", 8, 9],
|
||||
["Total", null, null],
|
||||
];
|
||||
sheet.getRange("B4:C4").formulas = [["=SUM(B2:B3)", "=SUM(C2:C3)"]];
|
||||
data.format = { numberFormat: "General", wrapText: true };
|
||||
```
|
||||
Generated
Vendored
+93
@@ -0,0 +1,93 @@
|
||||
# Tables
|
||||
|
||||
Worksheet tables are created from an existing range and can edit rows, headers,
|
||||
data body ranges, names, style, and totals.
|
||||
|
||||
## Add Table
|
||||
|
||||
```ts
|
||||
const sheet = workbook.worksheets.add("Inventory");
|
||||
sheet.getRange("A1:C3").values = [
|
||||
["SKU", "Color", "Stock"],
|
||||
["100-001", "Black", 15],
|
||||
["100-002", "Sage", 40],
|
||||
];
|
||||
|
||||
const table = sheet.tables.add("A1:C3", true, "InventoryTable");
|
||||
```
|
||||
|
||||
## Read
|
||||
|
||||
```ts
|
||||
sheet.tables.items;
|
||||
sheet.tables.getItem("InventoryTable");
|
||||
sheet.tables.getItemAt(0);
|
||||
sheet.tables.getItemById(table.id);
|
||||
sheet.tables.getIntersecting(sheet.getRange("A1:C5"));
|
||||
|
||||
table.id;
|
||||
table.name;
|
||||
table.rowCount; // data rows, excluding headers and totals
|
||||
table.columnCount;
|
||||
table.columnNames;
|
||||
table.address;
|
||||
table.getRange();
|
||||
table.getHeaderRowRange();
|
||||
table.getDataRows();
|
||||
```
|
||||
|
||||
## Configure and Resize
|
||||
|
||||
```ts
|
||||
table.name = "InventoryTable";
|
||||
table.style = "TableStyleMedium9";
|
||||
table.showHeaders = true;
|
||||
table.showFilterButton = true;
|
||||
table.showTotals = false;
|
||||
table.showBandedRows = true;
|
||||
table.showBandedColumns = false;
|
||||
table.highlightFirstColumn = false;
|
||||
table.highlightLastColumn = false;
|
||||
table.resize("A1:C8");
|
||||
```
|
||||
|
||||
## Add Rows
|
||||
|
||||
```ts
|
||||
table.rows.add(null, [["100-003", "Denim", 12]]);
|
||||
```
|
||||
|
||||
## Headerless Table
|
||||
|
||||
```ts
|
||||
sheet.getRange("A1:B3").values = [
|
||||
["West", 12],
|
||||
["East", 9],
|
||||
["South", 15],
|
||||
];
|
||||
sheet.tables.add("A1:B3", false, "HeaderlessTable");
|
||||
```
|
||||
|
||||
## Recorded Table Edit
|
||||
|
||||
```ts
|
||||
const { patch } = workbook.record(() => {
|
||||
const table = sheet.tables.add("A1:C3", true, "InventoryTable");
|
||||
table.rows.add(null, [["100-003", "Denim", 12]]);
|
||||
});
|
||||
```
|
||||
|
||||
The recorded patch uses `table.add` followed by row/column/table operations for
|
||||
subsequent edits.
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
const table = sheet.tables.add("A1:D5", true, "DataTable");
|
||||
table.rows.add(null, [["West", "Ava", 12, 14]]);
|
||||
|
||||
sheet.getRange(table.address).format = {
|
||||
font: { name: "Aptos" },
|
||||
wrapText: true,
|
||||
};
|
||||
```
|
||||
Generated
Vendored
+129
@@ -0,0 +1,129 @@
|
||||
# Workbook Facade
|
||||
|
||||
## Create And Load
|
||||
|
||||
```ts
|
||||
const workbook = Workbook.create();
|
||||
const [sheet1, sheet2] = workbook.worksheets.add(["Sheet1", "Sheet2"]);
|
||||
const loaded = Workbook.load(proto);
|
||||
const validated = Workbook.load(proto, { validate: true });
|
||||
```
|
||||
|
||||
## Import
|
||||
|
||||
```ts
|
||||
const fromCsv = await Workbook.fromCSV(csv, { sheetName: "Data" });
|
||||
const fromMarkdown = await Workbook.fromMarkdown(markdown, {
|
||||
sheetName: "Data",
|
||||
format: true,
|
||||
});
|
||||
|
||||
const { sheet, range } = await workbook.fromCSV(csv, { sheetName: "Data" });
|
||||
```
|
||||
|
||||
## Root Collections
|
||||
|
||||
```ts
|
||||
workbook.worksheets;
|
||||
workbook.sheets; // alias
|
||||
workbook.pivotTables;
|
||||
workbook.slicers;
|
||||
workbook.comments;
|
||||
workbook.notes;
|
||||
workbook.names;
|
||||
workbook.definedNames; // alias
|
||||
workbook.awareness;
|
||||
```
|
||||
|
||||
## Theme
|
||||
|
||||
```ts
|
||||
workbook.colorScheme = {
|
||||
name: "Workbook Theme",
|
||||
themeColors: {
|
||||
accent1: "#2563eb",
|
||||
bg1: "#ffffff",
|
||||
tx1: "#0f172a",
|
||||
},
|
||||
};
|
||||
const theme = workbook.theme;
|
||||
```
|
||||
|
||||
## Recalculate And Trace
|
||||
|
||||
```ts
|
||||
workbook.recalculate();
|
||||
const trace = workbook.trace("Data!C2");
|
||||
const stats = workbook.collectFormulaUsageStats();
|
||||
```
|
||||
|
||||
## Inspect, Search, Help, Resolve
|
||||
|
||||
```ts
|
||||
const snapshot = await workbook.inspect({ kind: "sheet,table,formula" });
|
||||
const matches = workbook.findCells({
|
||||
searchTerm: "East",
|
||||
sheetId: "Revenue",
|
||||
options: { maxResults: 10, matchFormulas: true },
|
||||
});
|
||||
const help = workbook.help("*", {
|
||||
search: "colorScheme|worksheet.charts.add",
|
||||
include: ["index", "examples", "notes"],
|
||||
});
|
||||
const target = workbook.resolve(anchorId);
|
||||
```
|
||||
|
||||
## Record And Apply
|
||||
|
||||
```ts
|
||||
const { result, patch, idMap, crdtUpdateV2 } = workbook.record(() => {
|
||||
const sheet = workbook.worksheets.getItem("Data");
|
||||
sheet.getRange("A1").values = [["Value"]];
|
||||
return sheet;
|
||||
});
|
||||
|
||||
const applied = workbook.apply(patch);
|
||||
```
|
||||
|
||||
## CRDT
|
||||
|
||||
```ts
|
||||
workbook.hydrateCrdtFromProto();
|
||||
const ready = workbook.isCollaborativeStateReady();
|
||||
const unsubscribe = workbook.onCrdtUpdateV2((update, origin) => {
|
||||
send(update);
|
||||
});
|
||||
workbook.applyCrdtUpdateV2(remoteUpdate, { recalculate: true });
|
||||
unsubscribe();
|
||||
```
|
||||
|
||||
## Serialize
|
||||
|
||||
```ts
|
||||
const proto = workbook.toProto();
|
||||
```
|
||||
|
||||
## Utilities
|
||||
|
||||
```ts
|
||||
workbook.utils.columnToLetter(1); // "A"
|
||||
workbook.utils.letterToColumn("AA"); // 27
|
||||
workbook.utils.toA1String(1, 1, 3, 2); // "A1:B3"
|
||||
workbook.utils.fillRight([[1]], 3); // [[1, 1, 1]]
|
||||
workbook.utils.fillDown([[1]], 3); // [[1], [1], [1]]
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
const workbook = Workbook.create();
|
||||
const sheet = workbook.worksheets.add("Data");
|
||||
sheet.getRange("A1:B2").values = [
|
||||
["Name", "Value"],
|
||||
["A", 1],
|
||||
];
|
||||
|
||||
const { patch } = workbook.record(() => {
|
||||
sheet.getRange("B2").values = [[2]];
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+122
@@ -0,0 +1,122 @@
|
||||
# Worksheets
|
||||
|
||||
`workbook.worksheets` and `workbook.sheets` expose the worksheet collection.
|
||||
|
||||
## Collection
|
||||
|
||||
```ts
|
||||
const sheet = workbook.worksheets.add("Data");
|
||||
workbook.worksheets.add("New data", { ifExists: "error" });
|
||||
const existing = workbook.worksheets.getItem("Data");
|
||||
const maybe = workbook.worksheets.getItemOrNullObject("Data");
|
||||
const first = workbook.worksheets.getFirst();
|
||||
const active = workbook.worksheets.getActiveWorksheet();
|
||||
|
||||
workbook.worksheets.setActiveWorksheet("Data");
|
||||
const count = workbook.worksheets.getSheetCount();
|
||||
const index = workbook.worksheets.getSheetIndex("Data");
|
||||
const name = workbook.worksheets.getSheetNameByIndex(0);
|
||||
const byIndex = workbook.worksheets.getItemAt(0);
|
||||
```
|
||||
|
||||
## Worksheet Properties
|
||||
|
||||
```ts
|
||||
sheet.name = "Renamed";
|
||||
sheet.index = 0;
|
||||
sheet.showGridLines = false;
|
||||
sheet.tabColor = "#1F4E78";
|
||||
sheet.freezePanes.freezeRows(1);
|
||||
sheet.freezePanes.freezeColumns(1);
|
||||
|
||||
sheet.id;
|
||||
sheet.sheetId;
|
||||
sheet.tabColor;
|
||||
sheet.defaultRowHeight;
|
||||
sheet.defaultColWidth;
|
||||
sheet.baseColWidth;
|
||||
```
|
||||
|
||||
## Ranges
|
||||
|
||||
```ts
|
||||
const range = sheet.getRange("A1:B2");
|
||||
const byIndexes = sheet.getRangeByIndexes(0, 0, 2, 2);
|
||||
const cell = sheet.getCell(0, 0);
|
||||
const used = sheet.getUsedRange();
|
||||
const usedValuesOnly = sheet.getUsedRange(true);
|
||||
```
|
||||
|
||||
`getRange` accepts A1 strings only. Use zero-based row/column indexes with
|
||||
`getRangeByIndexes` and `getCell`.
|
||||
|
||||
## Worksheet Collections
|
||||
|
||||
```ts
|
||||
sheet.tables;
|
||||
sheet.charts;
|
||||
sheet.shapes;
|
||||
sheet.images;
|
||||
sheet.pivotTables;
|
||||
sheet.slicers;
|
||||
sheet.sparklineGroups;
|
||||
sheet.conditionalFormattings;
|
||||
sheet.dataValidations;
|
||||
sheet.freezePanes;
|
||||
sheet.names;
|
||||
sheet.cells;
|
||||
```
|
||||
|
||||
## Reset And Delete
|
||||
|
||||
```ts
|
||||
sheet.reset({
|
||||
clear: "used",
|
||||
applyTo: "all",
|
||||
deleteTables: true,
|
||||
deleteCharts: true,
|
||||
deleteDrawings: true,
|
||||
deleteSparklines: true,
|
||||
});
|
||||
|
||||
sheet.delete();
|
||||
```
|
||||
|
||||
## Merge
|
||||
|
||||
```ts
|
||||
sheet.mergeCells("A1:B2");
|
||||
sheet.unmergeCells("A1:B2");
|
||||
```
|
||||
|
||||
## Drawings
|
||||
|
||||
```ts
|
||||
sheet.deleteAllDrawings();
|
||||
sheet.autoLayoutDrawings(items, options);
|
||||
```
|
||||
|
||||
## Inline Types
|
||||
|
||||
```ts
|
||||
type WorksheetResetOptions = {
|
||||
clear?: "used" | "none";
|
||||
applyTo?: "contents" | "formats" | "all";
|
||||
deleteTables?: boolean;
|
||||
deleteCharts?: boolean;
|
||||
deleteDrawings?: boolean;
|
||||
deleteSparklines?: boolean;
|
||||
};
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
const sheet = workbook.worksheets.add("Data");
|
||||
sheet.getRange("A1:B2").values = [
|
||||
["Name", "Value"],
|
||||
["A", 1],
|
||||
];
|
||||
sheet.mergeCells("D1:E1");
|
||||
sheet.freezePanes.freezeRows(1);
|
||||
```
|
||||
Generated
Vendored
+56
@@ -0,0 +1,56 @@
|
||||
# Sparklines
|
||||
|
||||
```js
|
||||
const group = sheet.sparklineGroups.add({
|
||||
type: "line",
|
||||
targetRange: "E2:E4",
|
||||
sourceData: "A2:C4",
|
||||
seriesColor: "#2563EB",
|
||||
markers: { high: true, low: true },
|
||||
});
|
||||
```
|
||||
- Sparkline type is a string. Use the public options documented below. Do not set internal/proto enum values for empty-cell display or axis modes; if a required option is not documented for the selected runtime, follow the bounded discovery policy.
|
||||
- Avoid `dateAxisRange` for XLSX output; it is not serialized. Keep automatic axis limits: `manualMin` / `manualMax` alone do not select custom limits in Excel.
|
||||
- Sparkline Inline Type:
|
||||
```
|
||||
type SparklineConfig = {
|
||||
type: "line" | "column" | "stacked";
|
||||
targetRange: Range | string;
|
||||
sourceData: Range | string;
|
||||
lineWeight?: number;
|
||||
displayHidden?: boolean;
|
||||
seriesColor?: ColorConfig;
|
||||
negativeColor?: ColorConfig;
|
||||
axisColor?: ColorConfig;
|
||||
markersColor?: ColorConfig;
|
||||
firstMarkerColor?: ColorConfig;
|
||||
lastMarkerColor?: ColorConfig;
|
||||
highMarkerColor?: ColorConfig;
|
||||
lowMarkerColor?: ColorConfig;
|
||||
markers?: SparklineMarkersOptions;
|
||||
axis?: SparklineAxisOptions;
|
||||
};
|
||||
|
||||
type SparklineMarkersOptions = {
|
||||
show?: boolean;
|
||||
high?: boolean;
|
||||
low?: boolean;
|
||||
first?: boolean;
|
||||
last?: boolean;
|
||||
negative?: boolean;
|
||||
};
|
||||
|
||||
type SparklineAxisOptions = {
|
||||
showAxis?: boolean;
|
||||
rightToLeft?: boolean;
|
||||
};
|
||||
```
|
||||
- Range Alias: `const group = targetRange.sparklines.add(type, sourceRange, sparklineConfig);`
|
||||
- Edit And Delete
|
||||
```js
|
||||
group.seriesColor = "#2563EB";
|
||||
group.markers.high = true;
|
||||
group.axis.showAxis = true;
|
||||
sheet.sparklineGroups.delete(group);
|
||||
sheet.sparklineGroups.deleteAll();
|
||||
```
|
||||
Generated
Vendored
+97
@@ -0,0 +1,97 @@
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import { SpreadsheetFile, Workbook, ChartDataLabels } from "@oai/artifact-tool";
|
||||
|
||||
async function buildChartSuggestionWorkbook(outputDir: string): Promise<void> {
|
||||
await fs.mkdir(outputDir, { recursive: true });
|
||||
|
||||
const workbook = Workbook.create();
|
||||
const sheet = workbook.worksheets.add("Charts");
|
||||
sheet.showGridLines = false;
|
||||
|
||||
sheet.getRange("A1:C5").values = [
|
||||
["Month", "Revenue", "EBITDA"],
|
||||
["Jan", 100000, 18000],
|
||||
["Feb", 121000, 23000],
|
||||
["Mar", 132000, 28000],
|
||||
["Apr", 149000, 34000],
|
||||
];
|
||||
sheet.getRange("A1:C1").format = {
|
||||
fill: "#0F766E",
|
||||
font: { bold: true, color: "#FFFFFF" },
|
||||
};
|
||||
sheet.getRange("B2:C5").format.numberFormat = "$#,##0";
|
||||
sheet.getRange("A:C").format.columnWidthPx = 96;
|
||||
|
||||
// Fast chart path: chart a continuous helper range. The helper range is
|
||||
// formula-backed so edits to the source table update the chart.
|
||||
sheet.getRange("F1:H1").values = [["Month", "Revenue", "EBITDA"]];
|
||||
sheet.getRange("F2:H2").formulas = [["=A2", "=B2", "=C2"]];
|
||||
sheet.getRange("F2:H5").fillDown();
|
||||
const lineChart = sheet.charts.add("line", sheet.getRange("F1:H5"));
|
||||
lineChart.setPosition("J1", "Q15");
|
||||
lineChart.title = "Revenue and EBITDA Trend";
|
||||
lineChart.titleTextStyle.fontSize = 12;
|
||||
lineChart.hasLegend = true;
|
||||
lineChart.xAxis = { axisType: "textAxis" };
|
||||
lineChart.yAxis = { numberFormatCode: "$#,##0" };
|
||||
|
||||
const scatterPlot = sheet.charts.add("scatter", sheet.getRange("F1:H5"));
|
||||
scatterPlot.setPosition("J1", "Q15");
|
||||
scatterPlot.title = "Revenue and EBITDA Trend Scatter";
|
||||
scatterPlot.titleTextStyle.fontSize = 12;
|
||||
scatterPlot.hasLegend = true;
|
||||
scatterPlot.xAxis = { axisType: "textAxis" };
|
||||
scatterPlot.yAxis = { numberFormatCode: "$#,##0" };
|
||||
scatterPlot.dataLabels = new ChartDataLabels({showValue: true, position: 'above' });
|
||||
|
||||
// Advanced path: manually define a single series by formula.
|
||||
const barChart = sheet.charts.add("bar", {
|
||||
title: "EBITDA by Month",
|
||||
hasLegend: false,
|
||||
});
|
||||
const series = barChart.series.add("EBITDA");
|
||||
series.categoryFormula = "'Charts'!$A$2:$A$5";
|
||||
series.formula = "'Charts'!$C$2:$C$5";
|
||||
series.fill = "#F472B6";
|
||||
barChart.setPosition("J18", "Q32");
|
||||
barChart.title = "EBITDA by Month";
|
||||
barChart.titleTextStyle.fontSize = 12;
|
||||
barChart.xAxis = { axisType: "textAxis", textStyle: { fontSize: 10} };
|
||||
barChart.yAxis = { numberFormatCode: "$#,##0", textStyle: { fontSize: 10} };
|
||||
|
||||
barChart.xAxis.title.text = "EBITDA";
|
||||
|
||||
barChart.yAxis.title.text = "Month";
|
||||
barChart.yAxis.min = 10_000;
|
||||
barChart.yAxis.max = 40_000;
|
||||
barChart.yAxis.majorUnit = 5;
|
||||
// TODO @vicky set default title text to be size 12
|
||||
|
||||
// setData replaces the chart source range; use it when a chart exists before
|
||||
// the final source range is known.
|
||||
lineChart.setData(sheet.getRange("F1:H5"));
|
||||
|
||||
const preview = await workbook.render({
|
||||
sheetName: "Charts",
|
||||
autoCrop: "all",
|
||||
scale: 1,
|
||||
format: "png",
|
||||
});
|
||||
await fs.writeFile(
|
||||
`${outputDir}/typescript_chart_suggestions.png`,
|
||||
new Uint8Array(await preview.arrayBuffer()),
|
||||
);
|
||||
|
||||
const xlsx = await SpreadsheetFile.exportXlsx(workbook);
|
||||
await xlsx.save(`${outputDir}/typescript_chart_suggestions.xlsx`);
|
||||
|
||||
console.log(`Rendered ${outputDir}/typescript_chart_suggestions.png`);
|
||||
console.log(`Saved ${outputDir}/typescript_chart_suggestions.xlsx`);
|
||||
}
|
||||
|
||||
const outputDir = process.argv[2] ?? "output/chart_suggestions";
|
||||
buildChartSuggestionWorkbook(outputDir).catch((error: unknown) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
Generated
Vendored
+177
@@ -0,0 +1,177 @@
|
||||
import { Workbook } from "@oai/artifact-tool";
|
||||
|
||||
function clip(value: string, maxChars: number): string {
|
||||
return value.length > maxChars ? `${value.slice(0, maxChars)}...` : value;
|
||||
}
|
||||
|
||||
function summarizeTrace(
|
||||
root: any,
|
||||
options: { maxDepth?: number; maxNodes?: number; maxFormulaChars?: number } = {},
|
||||
): string[] {
|
||||
if (!root) return ["(no trace returned)"];
|
||||
|
||||
const maxDepth = options.maxDepth ?? 4;
|
||||
const maxNodes = options.maxNodes ?? 30;
|
||||
const maxFormulaChars = options.maxFormulaChars ?? 120;
|
||||
const lines: string[] = [];
|
||||
let nodeCount = 0;
|
||||
let truncated = false;
|
||||
|
||||
function walk(node: any, depth: number): void {
|
||||
if (nodeCount >= maxNodes) {
|
||||
truncated = true;
|
||||
return;
|
||||
}
|
||||
|
||||
nodeCount += 1;
|
||||
const indent = " ".repeat(depth);
|
||||
const formula = node.formula
|
||||
? ` formula=${clip(String(node.formula), maxFormulaChars)}`
|
||||
: "";
|
||||
const error = node.error ? ` error=${node.error}` : "";
|
||||
lines.push(`${indent}${node.cell} value=${JSON.stringify(node.value)}${formula}${error}`);
|
||||
|
||||
const children = (node.params ?? []) as any[];
|
||||
if (children.length === 0) return;
|
||||
if (depth >= maxDepth) {
|
||||
truncated = true;
|
||||
lines.push(`${indent} ... ${children.length} precedent(s) not shown`);
|
||||
return;
|
||||
}
|
||||
for (const child of children) {
|
||||
walk(child, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
walk(root, 0);
|
||||
if (truncated) lines.push(`... trace summary capped at depth ${maxDepth}, ${maxNodes} nodes`);
|
||||
return lines;
|
||||
}
|
||||
|
||||
function findTraceNode(root: any, cell: string): any | null {
|
||||
if (!root) return null;
|
||||
if (root.cell === cell) return root;
|
||||
for (const child of (root.params ?? []) as any[]) {
|
||||
const found = findTraceNode(child, cell);
|
||||
if (found) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function formatNumber(value: unknown): string {
|
||||
if (typeof value !== "number") return String(value);
|
||||
if (value !== 0 && Math.abs(value) < 0.01) return Number(value.toPrecision(3)).toString();
|
||||
return value.toLocaleString("en-US", { maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
function formatPercent(value: unknown): string {
|
||||
return typeof value === "number" ? `${(value * 100).toFixed(1)}%` : String(value);
|
||||
}
|
||||
|
||||
function explainRevenueCheck(trace: any): string {
|
||||
const status = findTraceNode(trace, "Checks!F2")?.value;
|
||||
const difference = findTraceNode(trace, "Checks!D2")?.value;
|
||||
const actual = findTraceNode(trace, "Checks!B2")?.value;
|
||||
const expected = findTraceNode(trace, "Checks!C2")?.value;
|
||||
const tolerance = findTraceNode(trace, "Checks!E2")?.value;
|
||||
const baseRevenue = findTraceNode(trace, "Inputs!B2")?.value;
|
||||
const growthRate = findTraceNode(trace, "Inputs!B3")?.value;
|
||||
const revenue2025 = findTraceNode(trace, "Model!B4")?.value;
|
||||
|
||||
return [
|
||||
`Checks!F2 returns "${status}" because the absolute difference is within the tolerance.`,
|
||||
`It compares Checks!D2 (${formatNumber(difference)}) against Checks!E2 (${formatNumber(tolerance)}).`,
|
||||
`Checks!D2 is actual revenue minus expected revenue: Checks!B2 (${formatNumber(actual)}) - Checks!C2 (${formatNumber(expected)}).`,
|
||||
`The actual value comes from Model!B5, which compounds Inputs!B2 (${formatNumber(baseRevenue)}) by the growth rate in Inputs!B3 (${formatPercent(growthRate)}) for two years: first to Model!B4 (${formatNumber(revenue2025)}), then to Model!B5 (${formatNumber(actual)}).`,
|
||||
`Caveat: the tiny difference shown is floating-point rounding noise, not a business variance.`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const workbook = Workbook.create();
|
||||
const inputs = workbook.worksheets.add("Inputs");
|
||||
const model = workbook.worksheets.add("Model");
|
||||
const checks = workbook.worksheets.add("Checks");
|
||||
|
||||
inputs.getRange("A1:B4").values = [
|
||||
["Metric", "Value"],
|
||||
["Revenue 2024", 100],
|
||||
["Growth Rate", 0.1],
|
||||
["Expected Revenue 2026", 121],
|
||||
];
|
||||
|
||||
model.getRange("A1:B5").values = [
|
||||
["Metric", "Value"],
|
||||
["Revenue 2024", null],
|
||||
["Growth Rate", null],
|
||||
["Revenue 2025", null],
|
||||
["Revenue 2026", null],
|
||||
];
|
||||
model.getRange("B2:B5").formulas = [
|
||||
["=Inputs!B2"],
|
||||
["=Inputs!B3"],
|
||||
["=B2*(1+B3)"],
|
||||
["=B4*(1+B3)"],
|
||||
];
|
||||
|
||||
checks.getRange("A1:F2").values = [
|
||||
["Check", "Actual", "Expected", "Difference", "Tolerance", "Status"],
|
||||
["Revenue 2026 ties to expected case", null, null, null, 0.001, null],
|
||||
];
|
||||
checks.getRange("B2:D2").formulas = [["=Model!B5", "=Inputs!B4", "=B2-C2"]];
|
||||
checks.getRange("F2").formulas = [["=IF(ABS(D2)<=E2,\"OK\",\"CHECK\")"]];
|
||||
|
||||
workbook.recalculate();
|
||||
const trace = workbook.trace("Checks!F2");
|
||||
|
||||
console.log("=== Formula trace for Checks!F2 ===");
|
||||
console.log(
|
||||
summarizeTrace(trace, {
|
||||
maxDepth: 4,
|
||||
maxNodes: 20,
|
||||
}).join("\n"),
|
||||
);
|
||||
|
||||
console.log("\n=== User-facing answer: How is Checks!F2 calculated? ===");
|
||||
console.log(explainRevenueCheck(trace));
|
||||
|
||||
console.log("\n=== Exact formula help: XLOOKUP ===");
|
||||
console.log(
|
||||
workbook.help("fx.XLOOKUP", {
|
||||
include: "index,examples,notes",
|
||||
maxChars: 2500,
|
||||
}).ndjson,
|
||||
);
|
||||
|
||||
console.log("\n=== Formula category browse: financial ===");
|
||||
console.log(
|
||||
workbook.help("fx.*", {
|
||||
search: "financial",
|
||||
include: "index,examples",
|
||||
maxChars: 2500,
|
||||
}).ndjson,
|
||||
);
|
||||
|
||||
console.log("\n=== Formula category browse: math-trig ===");
|
||||
console.log(
|
||||
workbook.help("fx.*", {
|
||||
search: "math-trig",
|
||||
include: "index,examples",
|
||||
maxChars: 2500,
|
||||
}).ndjson,
|
||||
);
|
||||
|
||||
console.log("\n=== Semantic formula search: lookup with fallback ===");
|
||||
console.log(
|
||||
workbook.help("lookup value with fallback", {
|
||||
search: "XLOOKUP|INDEX|MATCH|IFERROR",
|
||||
include: "index,examples,notes",
|
||||
maxChars: 3000,
|
||||
}).ndjson,
|
||||
);
|
||||
}
|
||||
|
||||
main().catch((error: unknown) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
Generated
Vendored
+113
@@ -0,0 +1,113 @@
|
||||
import * as fs from "node:fs/promises";
|
||||
import * as path from "node:path";
|
||||
|
||||
import {
|
||||
FileBlob,
|
||||
SpreadsheetFile,
|
||||
} from "../../../../oai_js_artifact_tool";
|
||||
|
||||
const DEFAULT_WORKBOOK_INPUTS = [
|
||||
"/Users/vicky/code/openai/output/spreadsheet-atv/fitness-tracker-20260409",
|
||||
];
|
||||
|
||||
type InspectResult = {
|
||||
ndjson: string;
|
||||
};
|
||||
|
||||
async function resolveWorkbookPath(inputPath: string): Promise<string> {
|
||||
const expandedPath = inputPath.startsWith("~")
|
||||
? path.join(process.env.HOME ?? "", inputPath.slice(1))
|
||||
: inputPath;
|
||||
const stats = await fs.stat(expandedPath);
|
||||
if (stats.isFile()) {
|
||||
return expandedPath;
|
||||
}
|
||||
if (stats.isDirectory()) {
|
||||
const candidates = (await fs.readdir(expandedPath))
|
||||
.filter((entry) => entry.endsWith(".xlsx"))
|
||||
.sort();
|
||||
if (candidates.length > 0) {
|
||||
return path.join(expandedPath, candidates[0]);
|
||||
}
|
||||
throw new Error(`No .xlsx files found in directory: ${expandedPath}`);
|
||||
}
|
||||
throw new Error(`Workbook path is not a file or directory: ${expandedPath}`);
|
||||
}
|
||||
|
||||
function printInspect(title: string, result: InspectResult): void {
|
||||
console.log(`\n=== ${title} ===`);
|
||||
if (result.ndjson) {
|
||||
console.log(result.ndjson);
|
||||
return;
|
||||
}
|
||||
console.log("(no rows returned)");
|
||||
}
|
||||
|
||||
async function inspectWorkbook(workbookPath: string): Promise<void> {
|
||||
const workbook = await SpreadsheetFile.importXlsx(await FileBlob.load(workbookPath));
|
||||
const firstSheet = workbook.worksheets.getItemAt(0);
|
||||
const firstSheetName = firstSheet.name;
|
||||
|
||||
console.log(`\n########## Inspecting ${workbookPath} ##########`);
|
||||
console.log(`First worksheet: ${firstSheetName}`);
|
||||
|
||||
const summary = await workbook.inspect({
|
||||
kind: "workbook,sheet,table",
|
||||
maxChars: 6000,
|
||||
tableMaxRows: 6,
|
||||
tableMaxCols: 6,
|
||||
tableMaxCellChars: 80,
|
||||
});
|
||||
printInspect("Workbook summary", summary);
|
||||
|
||||
const sheetsIndex = await workbook.inspect({
|
||||
kind: "sheet",
|
||||
include: "id,name",
|
||||
});
|
||||
printInspect("Sheets index", sheetsIndex);
|
||||
|
||||
const firstRegion = await workbook.inspect({
|
||||
kind: "region",
|
||||
sheetId: firstSheetName,
|
||||
range: "A1:Z30",
|
||||
maxChars: 2500,
|
||||
tableMaxRows: 12,
|
||||
tableMaxCols: 8,
|
||||
tableMaxCellChars: 50,
|
||||
});
|
||||
printInspect(`First sheet region preview (${firstSheetName}!A1:Z30)`, firstRegion);
|
||||
|
||||
const formulas = await workbook.inspect({
|
||||
kind: "formula",
|
||||
sheetId: firstSheetName,
|
||||
maxChars: 2000,
|
||||
});
|
||||
printInspect(`Formula snapshot (${firstSheetName})`, formulas);
|
||||
|
||||
const drawings = await workbook.inspect({
|
||||
kind: "drawing",
|
||||
sheetId: firstSheetName,
|
||||
maxChars: 2000,
|
||||
});
|
||||
printInspect(`Drawing snapshot (${firstSheetName})`, drawings);
|
||||
}
|
||||
|
||||
async function inspectExistingWorkbooks(inputPaths: string[]): Promise<void> {
|
||||
for (const inputPath of inputPaths) {
|
||||
const workbookPath = await resolveWorkbookPath(inputPath);
|
||||
await inspectWorkbook(workbookPath);
|
||||
}
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const inputPaths =
|
||||
process.argv.slice(2).length > 0
|
||||
? process.argv.slice(2)
|
||||
: DEFAULT_WORKBOOK_INPUTS;
|
||||
await inspectExistingWorkbooks(inputPaths);
|
||||
}
|
||||
|
||||
main().catch((error: unknown) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
Generated
Vendored
+146
@@ -0,0 +1,146 @@
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import { SpreadsheetFile, Workbook } from "@oai/artifact-tool";
|
||||
|
||||
/**
|
||||
* Quick Start Examples
|
||||
* This runnable TypeScript example mirrors:
|
||||
* lib/agent/tools/artifact_tool_v2/skills/python/spreadsheets/examples/quick_start_example.py
|
||||
*/
|
||||
async function quickApiExample(): Promise<void> {
|
||||
// Creating a workbook and adding sheets with data and basic formatting
|
||||
const workbook = Workbook.create();
|
||||
var sheet = workbook.worksheets.add("ExampleSheet");
|
||||
|
||||
sheet = workbook.worksheets.getItem("ExampleSheet");
|
||||
sheet.getRange("A1:D4").values = [
|
||||
["Name", "Personality Type", "Age", "Birthday"],
|
||||
["John Doe", "Introvert", 30, new Date("1990-01-01T00:00:00Z")],
|
||||
["Jane Smith", "Extrovert", 25, new Date("1995-02-15T00:00:00Z")],
|
||||
["Jim Very Long Name", "Ambivert", 40, new Date("1980-03-20T00:00:00Z")],
|
||||
];
|
||||
sheet.getRange("E1").values = [["Score"]];
|
||||
sheet.getRange("E2").formulas = [["=C2*10"]]; // score is 10 * age
|
||||
sheet.getRange("E2:E4").fillDown();
|
||||
const headerRange = sheet.getRange("A1:E1");
|
||||
|
||||
// Styling
|
||||
const headerFormats = {
|
||||
fill: "#0F766E",
|
||||
font: { bold: true, color: "#FFFFFF" },
|
||||
horizontalAlignment: "center",
|
||||
verticalAlignment: "center",
|
||||
rowHeight: 16,
|
||||
};
|
||||
headerRange.format = headerFormats;
|
||||
headerRange.format.autofitColumns();
|
||||
|
||||
const dataRange = sheet.getRange("A2:D4");
|
||||
dataRange.format.wrapText = true;
|
||||
sheet.showGridLines = false;
|
||||
|
||||
// Format dates properly.
|
||||
sheet.getRange("D2:D4").format.numberFormat = "MM/DD/YYYY";
|
||||
|
||||
// Conditional formatting
|
||||
sheet.getRange("C2:C4").conditionalFormats.add("dataBar", {
|
||||
color: "#704023",
|
||||
gradient: true,
|
||||
});
|
||||
sheet.getRange("E2:E4").conditionalFormats.add("cellIs", {
|
||||
operator: "greaterThan",
|
||||
formula: 300,
|
||||
format: { font: { color: "#B91C1C" } },
|
||||
});
|
||||
sheet.conditionalFormattings.add({
|
||||
range: "B2:B4",
|
||||
rule: {
|
||||
type: "expression",
|
||||
formula: '=B2="Introvert"',
|
||||
format: { fill: "#FCA5A5" },
|
||||
},
|
||||
});
|
||||
|
||||
// Data validation: Since Personality Type is a dropdown category, add data validation.
|
||||
sheet.getRange("B2:B4").dataValidation = {
|
||||
rule: {
|
||||
type: "list",
|
||||
values: ["Introvert", "Extrovert", "Ambivert"],
|
||||
// formula1: "CategoriesSheet!$A$2:$A$4", // Alternative: reference a tunable list
|
||||
},
|
||||
};
|
||||
|
||||
// Tables: Turn it into a table (for example purposes! Make sure table names are unique)
|
||||
// NOTE: If hasHeaders=true, the range must include the header row.
|
||||
const table = sheet.tables.add("A1:E4", true, "PeopleTable");
|
||||
table.getHeaderRowRange();
|
||||
|
||||
// First column is still wide since we only auto-fit the first row. Expand it manually.
|
||||
sheet.getRange("A1:A4").format.columnWidth = 20;
|
||||
|
||||
// Create a compact chart helper range that references the source table.
|
||||
sheet.getRange("H1:I1").merge();
|
||||
sheet.getRange("H1").values = [["Charts"]];
|
||||
sheet.getRange("H1").format = headerFormats;
|
||||
sheet.getRange("H3:I3").values = [["Person", "Score"]];
|
||||
sheet.getRange("H4:I4").formulas = [["=A2", "=E2"]];
|
||||
sheet.getRange("H4:I6").fillDown();
|
||||
const chart = sheet.charts.add("bar", sheet.getRange("H3:I6"));
|
||||
chart.title = "Person by Scores";
|
||||
chart.hasLegend = true;
|
||||
chart.displayBlanksAs = "zero";
|
||||
chart.barOptions.direction = "column";
|
||||
chart.barOptions.grouping = "clustered";
|
||||
chart.setPosition("K2", "R16");
|
||||
|
||||
// Granular control over chart axes
|
||||
chart.xAxis = {
|
||||
axisType: "textAxis",
|
||||
title: { text: "Person", textStyle: { fontSize: 13, bold: true } },
|
||||
position: "bottom",
|
||||
orientation: "minMax",
|
||||
textStyle: { fontSize: 10 },
|
||||
};
|
||||
chart.yAxis = {
|
||||
axisType: "textAxis",
|
||||
title: { text: "Scores", textStyle: { fontSize: 13, bold: true } },
|
||||
numberFormatCode: "0,000",
|
||||
numberFormatSourceLinked: false,
|
||||
};
|
||||
|
||||
// Sparklines: add to the right of table
|
||||
const sparklinesHeader = sheet.getRange("F1");
|
||||
sparklinesHeader.values = [["Sparklines"]];
|
||||
sparklinesHeader.format = headerFormats;
|
||||
sparklinesHeader.format.autofitColumns();
|
||||
|
||||
sheet.sparklines.add({
|
||||
type: "column", // "line" | "column" | "stacked"
|
||||
sourceData: sheet.getRange("E2:E4"),
|
||||
targetRange: sheet.getRange("F2:F4"),
|
||||
seriesColor: "#AAAAAA",
|
||||
});
|
||||
|
||||
// Render
|
||||
await fs.mkdir("output", { recursive: true });
|
||||
const pngBlob = await workbook.render({
|
||||
sheetName: "ExampleSheet",
|
||||
autoCrop: "all",
|
||||
scale: 1,
|
||||
format: "png",
|
||||
});
|
||||
const pngBytes = new Uint8Array(await pngBlob.arrayBuffer());
|
||||
await fs.writeFile("output/example_sheet.png", pngBytes);
|
||||
console.log("Rendered first sheet to 'output/example_sheet.png'");
|
||||
|
||||
// Export
|
||||
const out = "output/example_sheet.xlsx";
|
||||
const xlsx = await SpreadsheetFile.exportXlsx(workbook);
|
||||
await xlsx.save(out);
|
||||
console.log(`Spreadsheet saved to ${out}`);
|
||||
}
|
||||
|
||||
quickApiExample().catch((error: unknown) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
Generated
Vendored
+32
@@ -0,0 +1,32 @@
|
||||
# Database Formulas
|
||||
|
||||
Database formulas aggregate rows from headered ranges using criteria ranges.
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=DSUM(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
|
||||
`=DCOUNT(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
|
||||
`=DCOUNTA(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
|
||||
`=DAVERAGE(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
|
||||
`=DMIN(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
|
||||
`=DMAX(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
|
||||
`=DSTDEV(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
|
||||
`=DVAR(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Coverage
|
||||
|
||||
Supported families include database sum, count, average, min, max, product, standard deviation, variance, and single-value lookup.
|
||||
Generated
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
# Date And Time Formulas
|
||||
|
||||
Date and time formulas create, parse, extract, and compare serial dates and times.
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=DATE(${yearRef},${monthRef},${dayRef})`,
|
||||
`=TIME(${hourRef},${minuteRef},${secondRef})`,
|
||||
`=DATEVALUE(${textRef})`,
|
||||
`=TIMEVALUE(${textRef})`,
|
||||
`=YEAR(${dateRef})`,
|
||||
`=MONTH(${dateRef})`,
|
||||
`=DAY(${dateRef})`,
|
||||
`=WEEKDAY(${dateRef})`,
|
||||
`=WORKDAY(${startDateRef},${daysRef})`,
|
||||
`=NETWORKDAYS(${startDateRef},${endDateRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Coverage
|
||||
|
||||
Supported families include date/time construction, extraction, workday and network-day calculations, year fractions, week numbers, today/current time, and end-of-month helpers.
|
||||
Generated
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
# Engineering Formulas
|
||||
|
||||
Engineering formulas cover complex numbers, Bessel functions, bitwise operations, unit conversion, and number-base conversion.
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=COMPLEX(${realRef},${imaginaryRef})`,
|
||||
`=IMSUM(${complexRangeRef})`,
|
||||
`=IMPRODUCT(${complexRangeRef})`,
|
||||
`=IMABS(${complexRef})`,
|
||||
`=CONVERT(${valueRef},${fromUnitRef},${toUnitRef})`,
|
||||
`=BIN2DEC(${binaryRef})`,
|
||||
`=DEC2HEX(${decimalRef})`,
|
||||
`=BITAND(${valueRef1},${valueRef2})`,
|
||||
`=BITOR(${valueRef1},${valueRef2})`,
|
||||
`=BESSELJ(${valueRef},${orderRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Coverage
|
||||
|
||||
Supported families include complex arithmetic, bitwise functions, base conversions, Bessel functions, error functions, delta/threshold helpers, and unit conversions.
|
||||
Generated
Vendored
+32
@@ -0,0 +1,32 @@
|
||||
# Financial Formulas
|
||||
|
||||
Financial formulas cover loans, rates, cash flows, depreciation, securities, treasury bills, and coupon calculations.
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=PMT(${rateRef},${periodsRef},${presentValueRef})`,
|
||||
`=PV(${rateRef},${periodsRef},${paymentRef})`,
|
||||
`=FV(${rateRef},${periodsRef},${paymentRef})`,
|
||||
`=NPV(${rateRef},${cashFlowRangeRef})`,
|
||||
`=IRR(${cashFlowRangeRef})`,
|
||||
`=XNPV(${rateRef},${cashFlowRangeRef},${dateRangeRef})`,
|
||||
`=XIRR(${cashFlowRangeRef},${dateRangeRef})`,
|
||||
`=RATE(${periodsRef},${paymentRef},${presentValueRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Coverage
|
||||
|
||||
Supported families include payment and present/future value, net present value, return rate, depreciation, discount/yield, coupon date math, accrued interest, treasury bills, and compatibility variants.
|
||||
Generated
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
# Information Formulas
|
||||
|
||||
Information formulas inspect value types, errors, blank cells, sheet indexes, and references.
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=ISBLANK(${valueRef})`,
|
||||
`=ISNUMBER(${valueRef})`,
|
||||
`=ISTEXT(${valueRef})`,
|
||||
`=ISLOGICAL(${valueRef})`,
|
||||
`=ISERROR(${valueRef})`,
|
||||
`=ISNA(${valueRef})`,
|
||||
`=TYPE(${valueRef})`,
|
||||
`=ERROR.TYPE(${valueRef})`,
|
||||
`=SHEET(${referenceRef})`,
|
||||
`=SHEETS(${referenceRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Coverage
|
||||
|
||||
Supported families include type predicates, error predicates, blank checks, number/text/logical checks, N conversion, sheet lookup, and error type lookup.
|
||||
Generated
Vendored
+39
@@ -0,0 +1,39 @@
|
||||
# Logical Formulas
|
||||
|
||||
Logical formulas branch, combine conditions, and handle error values. Follow the main skill’s formula policy and the [XLSX compatibility guidance](../API_QUICK_START.md#known-formulaexport-limitations-not-exhaustive).
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Boolean And Branching Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=TRUE()`,
|
||||
`=FALSE()`,
|
||||
`=NA()`,
|
||||
`=AND(${conditionRef1},${conditionRef2})`,
|
||||
`=OR(${conditionRef1},${conditionRef2})`,
|
||||
`=NOT(${conditionRef})`,
|
||||
`=XOR(${conditionRef1},${conditionRef2})`,
|
||||
`=IF(${conditionRef},${trueValueRef},${falseValueRef})`,
|
||||
`=_xlfn.IFS(${conditionRef1},${valueRef1},${conditionRef2},${valueRef2})`,
|
||||
`=SWITCH(${valueRef},${caseRef1},${resultRef1},${defaultRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Error Handling Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=IFERROR(${valueRef},${replacementRef})`,
|
||||
`=IFNA(${valueRef},${replacementRef})`,
|
||||
];
|
||||
```
|
||||
Generated
Vendored
+24
@@ -0,0 +1,24 @@
|
||||
# Lookup And Reference Formulas
|
||||
|
||||
Lookup and reference formulas locate values and return addresses or dimensions. Follow the main skill’s scalar-formula policy and the [XLSX compatibility guidance](../API_QUICK_START.md#known-formulaexport-limitations-not-exhaustive).
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=_xlfn.XLOOKUP(${lookupRef},${lookupRangeRef},${returnRangeRef})`,
|
||||
`=VLOOKUP(${lookupRef},${tableRangeRef},${columnIndexRef},${exactRef})`,
|
||||
`=INDEX(${rangeRef},${rowIndexRef},${columnIndexRef})`,
|
||||
`=MATCH(${lookupRef},${lookupRangeRef},${matchModeRef})`,
|
||||
];
|
||||
```
|
||||
Generated
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
# Math And Trig Formulas
|
||||
|
||||
Math and trigonometry formulas cover arithmetic, rounding, aggregation, matrix math, random values, base conversion, and trig functions.
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=SUM(${rangeRef})`,
|
||||
`=PRODUCT(${rangeRef})`,
|
||||
`=ROUND(${valueRef},${digits})`,
|
||||
`=POWER(${valueRef},${power})`,
|
||||
`=MOD(${valueRef},${divisor})`,
|
||||
`=SIN(${angleRef})`,
|
||||
`=COS(${angleRef})`,
|
||||
`=TAN(${angleRef})`,
|
||||
`=MMULT(${matrixARef},${matrixBRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Coverage
|
||||
|
||||
Supported families include aggregate math, rounding, logarithms, powers, matrix functions, random generators, trig, hyperbolic trig, Roman/base conversion, subtotaling, and compatibility variants.
|
||||
Generated
Vendored
+32
@@ -0,0 +1,32 @@
|
||||
# Statistical Formulas
|
||||
|
||||
Statistical formulas summarize, rank, distribute, correlate, and forecast values.
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=AVERAGE(${rangeRef})`,
|
||||
`=MEDIAN(${rangeRef})`,
|
||||
`=STDEV.S(${rangeRef})`,
|
||||
`=VAR.P(${rangeRef})`,
|
||||
`=QUARTILE(${rangeRef},${quartileIndex})`,
|
||||
`=CORREL(${xRangeRef},${yRangeRef})`,
|
||||
`=FORECAST.LINEAR(${xRef},${knownYRangeRef},${knownXRangeRef})`,
|
||||
`=FORECAST.ETS(${targetDateRef},${valuesRangeRef},${timelineRangeRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Coverage
|
||||
|
||||
Supported families include averages, counts, rank and percentile functions, variance and standard deviation, distributions, regression, covariance/correlation, forecasting, and compatibility names.
|
||||
Generated
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
# Text Formulas
|
||||
|
||||
Text formulas transform, search, split, join, format, and extract strings.
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=TEXT(${valueRef},${formatRef})`,
|
||||
`=CONCAT(${rangeRef})`,
|
||||
`=_xlfn.TEXTJOIN(${delimiterRef},${ignoreEmptyRef},${rangeRef})`,
|
||||
`=LEFT(${textRef},${countRef})`,
|
||||
`=RIGHT(${textRef},${countRef})`,
|
||||
`=MID(${textRef},${startRef},${countRef})`,
|
||||
`=FIND(${needleRef},${textRef})`,
|
||||
`=SEARCH(${needleRef},${textRef})`,
|
||||
`=SUBSTITUTE(${textRef},${oldTextRef},${newTextRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Coverage
|
||||
|
||||
Supported families include length, casing, replacement, extraction, joining, splitting, number-to-text formatting, Unicode helpers, and regex helpers.
|
||||
Generated
Vendored
+62
@@ -0,0 +1,62 @@
|
||||
# Comments
|
||||
|
||||
Workbook comments use people, threads, replies, reactions, and thread state.
|
||||
|
||||
## Current Author
|
||||
|
||||
```ts
|
||||
workbook.comments.setSelf({
|
||||
displayName,
|
||||
initials,
|
||||
email,
|
||||
});
|
||||
```
|
||||
|
||||
## Person Inline Type
|
||||
|
||||
```ts
|
||||
type PersonConfig = {
|
||||
id?: string;
|
||||
displayName: string;
|
||||
initials?: string;
|
||||
email?: string;
|
||||
avatarUrl?: string;
|
||||
};
|
||||
```
|
||||
|
||||
## Cell And Range Threads
|
||||
|
||||
```ts
|
||||
const cellThread = workbook.comments.addThread(
|
||||
{ cell: sheet.getRange(cellAddress) },
|
||||
bodyText,
|
||||
);
|
||||
|
||||
const rangeThread = workbook.comments.addThread(
|
||||
{ range: sheet.getRange(rangeAddress) },
|
||||
bodyText,
|
||||
);
|
||||
```
|
||||
|
||||
## Thread Inline Types
|
||||
|
||||
```ts
|
||||
type WorkbookCommentTarget =
|
||||
| { cell: Range }
|
||||
| { range: Range };
|
||||
|
||||
type ThreadAddOptions = {
|
||||
author?: Person | PersonConfig | { id: string };
|
||||
createdAt?: string;
|
||||
position?: { x: number; y: number; unit?: "px" | "emu" };
|
||||
};
|
||||
```
|
||||
|
||||
## Replies And State
|
||||
|
||||
```ts
|
||||
const reply = cellThread.addReply(replyText);
|
||||
reply.toggleReaction(reactionText);
|
||||
cellThread.resolve();
|
||||
cellThread.reopen();
|
||||
```
|
||||
Generated
Vendored
+81
@@ -0,0 +1,81 @@
|
||||
# Conditional Formatting
|
||||
|
||||
Use `range.conditionalFormats` to add formatting rules to ranges.
|
||||
|
||||
## Rule Pattern
|
||||
|
||||
```ts
|
||||
range.conditionalFormats.add(ruleType, {
|
||||
operator,
|
||||
formula,
|
||||
format,
|
||||
});
|
||||
```
|
||||
|
||||
Choose `ruleType`, `operator`, color, and style strings from the inline types below.
|
||||
|
||||
## Rule Inline Types
|
||||
|
||||
```ts
|
||||
type ConditionalFormatRuleType =
|
||||
| "cellIs" | "CellValue" | "Custom" | "expression"
|
||||
| "colorScale" | "dataBar" | "iconSet"
|
||||
| "containsText" | "notContainsText" | "beginsWith" | "endsWith"
|
||||
| "containsBlanks" | "notContainsBlanks" | "containsErrors" | "notContainsErrors"
|
||||
| "duplicateValues" | "uniqueValues" | "timePeriod" | "top10" | "aboveAverage";
|
||||
|
||||
type CellIsOperator =
|
||||
| "greaterThan"
|
||||
| "greaterThanOrEqual"
|
||||
| "lessThan"
|
||||
| "lessThanOrEqual"
|
||||
| "equal"
|
||||
| "notEqual"
|
||||
| "between"
|
||||
| "notBetween";
|
||||
|
||||
type ConditionalFormatConfig =
|
||||
| { operator: CellIsOperator; formula: string | number | Array<string | number>; format?: DifferentialFormatConfig }
|
||||
| { formula: string | number; format?: DifferentialFormatConfig }
|
||||
| { colors?: ColorConfig[]; thresholds?: CfvoInput[] }
|
||||
| { color?: ColorConfig; thresholds?: CfvoInput[]; gradient?: boolean }
|
||||
| { iconSet: string; showValue?: boolean; reverse?: boolean; thresholds?: CfvoInput[] }
|
||||
| { text: string; format?: DifferentialFormatConfig }
|
||||
| { timePeriod: "yesterday" | "today" | "tomorrow" | "last7Days" | "lastWeek" | "thisWeek" | "nextWeek" | "lastMonth" | "thisMonth" | "nextMonth"; format?: DifferentialFormatConfig }
|
||||
| { rank?: number; percent?: boolean; bottom?: boolean; format?: DifferentialFormatConfig }
|
||||
| { aboveAverage?: boolean; equalAverage?: boolean; stdDev?: number; format?: DifferentialFormatConfig };
|
||||
|
||||
type DifferentialFormatConfig = {
|
||||
fill?: FillConfig;
|
||||
font?: { bold?: boolean; italic?: boolean; color?: ColorConfig };
|
||||
border?: RangeBordersConfig;
|
||||
numberFormat?: string;
|
||||
};
|
||||
|
||||
type CfvoInput =
|
||||
| "min"
|
||||
| "max"
|
||||
| number
|
||||
| `${number}%`
|
||||
| { type: "min" | "max" | "num" | "percent" | "percentile"; value?: string | number };
|
||||
```
|
||||
|
||||
## Custom Rule
|
||||
|
||||
```ts
|
||||
range.conditionalFormats.addCustom(expression, {
|
||||
fill,
|
||||
font,
|
||||
border,
|
||||
});
|
||||
```
|
||||
|
||||
## Rule Families
|
||||
|
||||
Supported rule families include cell value, custom expression, text, blank/error, duplicate/unique, time period, top/bottom, above/below average, color scale, data bar, and icon set.
|
||||
|
||||
## Clear Rules
|
||||
|
||||
```ts
|
||||
range.conditionalFormats.deleteAll();
|
||||
```
|
||||
Generated
Vendored
+31
@@ -0,0 +1,31 @@
|
||||
## Data tables (`worksheet.dataTables`)
|
||||
|
||||
Use data tables to project a formula across a row/column grid.
|
||||
|
||||
### Two-variable data table
|
||||
|
||||
```ts
|
||||
const sheet = workbook.worksheets.add("TwoVariable");
|
||||
|
||||
sheet.getRange("B3").values = [[0.095]]; // rate
|
||||
sheet.getRange("B4").values = [[360]]; // periods
|
||||
sheet.getRange("B5").values = [[80000]]; // principal
|
||||
|
||||
sheet.getRange("C2").formulas = [[`=PMT(B3/12,B4,-B5)`]];
|
||||
sheet.getRange("C3:C5").values = [[0.09], [0.0925], [0.095]];
|
||||
sheet.getRange("D2:E2").values = [[180, 360]];
|
||||
|
||||
sheet.dataTables.add("D3:E5", {
|
||||
rowInput: "B4",
|
||||
columnInput: "B3",
|
||||
});
|
||||
|
||||
workbook.recalculate();
|
||||
```
|
||||
|
||||
### Single-variable (row input only)
|
||||
|
||||
```ts
|
||||
sheet.dataTables.add("D3:E3", { rowInput: "B4" });
|
||||
workbook.recalculate();
|
||||
```
|
||||
Generated
Vendored
+73
@@ -0,0 +1,73 @@
|
||||
# Data Validations
|
||||
|
||||
Use range-level or worksheet-level data validation config.
|
||||
|
||||
## Range Assignment
|
||||
|
||||
```ts
|
||||
range.dataValidation = validationConfig;
|
||||
```
|
||||
|
||||
## Rule Config
|
||||
|
||||
```ts
|
||||
range.dataValidation.rule = {
|
||||
type,
|
||||
formula1,
|
||||
formula2,
|
||||
values,
|
||||
operator,
|
||||
};
|
||||
range.dataValidation.prompt = promptConfig;
|
||||
range.dataValidation.errorAlert = errorAlertConfig;
|
||||
range.dataValidation.ignoreBlanks = ignoreBlanks;
|
||||
range.dataValidation.inCellDropDown = inCellDropDown;
|
||||
```
|
||||
|
||||
## Validation Inline Types
|
||||
|
||||
```ts
|
||||
type DataValidationRule = {
|
||||
type: "none" | "whole" | "decimal" | "list" | "date" | "time" | "textLength" | "custom";
|
||||
operator?:
|
||||
| "between"
|
||||
| "notBetween"
|
||||
| "equal"
|
||||
| "notEqual"
|
||||
| "lessThan"
|
||||
| "lessThanOrEqual"
|
||||
| "greaterThan"
|
||||
| "greaterThanOrEqual";
|
||||
formula1?: string | number;
|
||||
formula2?: string | number;
|
||||
values?: string[];
|
||||
};
|
||||
|
||||
type ValidationConfig = {
|
||||
rule?: DataValidationRule | null;
|
||||
prompt?: { title?: string; message?: string; show?: boolean } | null;
|
||||
errorAlert?: {
|
||||
title?: string;
|
||||
message?: string;
|
||||
style?: "stop" | "warning" | "information";
|
||||
show?: boolean;
|
||||
} | null;
|
||||
ignoreBlanks?: boolean;
|
||||
inCellDropDown?: boolean;
|
||||
};
|
||||
```
|
||||
|
||||
## Collection Add
|
||||
|
||||
```ts
|
||||
sheet.dataValidations.add({
|
||||
range,
|
||||
rule,
|
||||
prompt,
|
||||
errorAlert,
|
||||
ignoreBlanks,
|
||||
inCellDropDown,
|
||||
});
|
||||
```
|
||||
|
||||
Validation type, operator, and error style values are the strings listed above.
|
||||
Generated
Vendored
+43
@@ -0,0 +1,43 @@
|
||||
## Defined names (`workbook.names`, `worksheet.names`)
|
||||
|
||||
Use defined names for reusable ranges and workbook functions.
|
||||
|
||||
### Named ranges
|
||||
|
||||
Workbook-scoped named range:
|
||||
|
||||
```ts
|
||||
const data = workbook.worksheets.add("Data");
|
||||
data.getRange("A1:A3").values = [[1], [2], [3]];
|
||||
|
||||
workbook.names.addRange("SalesRange", "Data!$A$1:$A$3", {
|
||||
description: "Input sales data",
|
||||
});
|
||||
|
||||
data.getRange("B1").formulas = [["=SUM(SalesRange)"]];
|
||||
workbook.recalculate();
|
||||
```
|
||||
|
||||
Sheet-scoped named range:
|
||||
|
||||
```ts
|
||||
const sheet1 = workbook.worksheets.add("Sheet1");
|
||||
sheet1.names.addRange("LocalRange", "Sheet1!$A$1:$A$10");
|
||||
|
||||
sheet1.getRange("B1").formulas = [["=SUM(LocalRange)"]];
|
||||
workbook.recalculate();
|
||||
```
|
||||
|
||||
### Named functions (LAMBDA)
|
||||
|
||||
```ts
|
||||
workbook.names.addFunction("AddTax", {
|
||||
lambda: "LAMBDA(price, tax, price*(1+tax))", // export may auto-prefix "="
|
||||
description: "Adds tax to a price",
|
||||
parameters: [
|
||||
{ name: "price", description: "Base price" },
|
||||
{ name: "tax", description: "Tax rate (e.g. 0.1)" },
|
||||
],
|
||||
returns: "Taxed price",
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+151
@@ -0,0 +1,151 @@
|
||||
# Worksheet Drawings
|
||||
|
||||
Worksheets support charts and shapes anchored to the cell grid.
|
||||
|
||||
## Units
|
||||
|
||||
- Anchor row and column indexes are zero-based.
|
||||
- Offsets and extents use pixels.
|
||||
- Use `rowOffsetPx`, `colOffsetPx`, `widthPx`, and `heightPx`.
|
||||
|
||||
## Chart From Source Cells
|
||||
|
||||
Bind charts to source ranges so edits update their data. Define shared axis
|
||||
configs at the top level of the persistent JavaScript REPL:
|
||||
|
||||
```js
|
||||
var chartStyle = {
|
||||
axisText: { typeface: "Arial", fontSize: 13, fill: "dk2" },
|
||||
};
|
||||
```
|
||||
|
||||
Inside a session callback:
|
||||
|
||||
```js
|
||||
const chart = sheet.charts.add("bar", sourceRange);
|
||||
chart.setPosition(startCell, endCell);
|
||||
chart.xAxis = { textStyle: chartStyle.axisText };
|
||||
chart.yAxis = { textStyle: chartStyle.axisText, numberFormatCode: "#,##0", numberFormatSourceLinked: false };
|
||||
```
|
||||
|
||||
Apply the workbook's font, palette, units, and [chart guidance](../API_QUICK_START.md#charts).
|
||||
For line charts, set the series line stroke explicitly. Use config-object chart
|
||||
creation for custom series; range-backed charts are the default when cells hold
|
||||
the source data. The common [spreadsheet quick start](../API_QUICK_START.md#charts) lists range binding
|
||||
and XLSX chart-type limitations.
|
||||
|
||||
## Chart Inline Types
|
||||
|
||||
```ts
|
||||
type WorksheetChartType =
|
||||
| "bar" | "line" | "area" | "pie" | "doughnut" | "scatter"
|
||||
| "bubble" | "radar" | "stock";
|
||||
|
||||
type WorksheetChartConfig = {
|
||||
from?: { row: number; col: number; rowOffsetPx?: number; colOffsetPx?: number };
|
||||
to?: { row: number; col: number; rowOffsetPx?: number; colOffsetPx?: number };
|
||||
extent?: { widthPx?: number; heightPx?: number };
|
||||
title?: string;
|
||||
titleTextStyle?: TextStyleConfig;
|
||||
categories?: string[];
|
||||
series?: Array<{ name: string; values?: number[]; categories?: string[]; fill?: FillConfig; line?: LineConfig }>;
|
||||
hasLegend?: boolean;
|
||||
legend?: { position?: "left" | "top" | "topRight" | "right" | "bottom"; overlay?: boolean; textStyle?: TextStyleConfig };
|
||||
xAxis?: ChartAxisConfig;
|
||||
yAxis?: ChartAxisConfig;
|
||||
dataLabels?: { showValue?: boolean; position?: "center" | "inEnd" | "outEnd"; textStyle?: TextStyleConfig };
|
||||
dataTable?: { visible?: boolean; showLegendKey?: boolean; textStyle?: TextStyleConfig };
|
||||
};
|
||||
|
||||
type TextStyleConfig = {
|
||||
typeface?: string;
|
||||
bold?: boolean;
|
||||
italic?: boolean;
|
||||
fontSize?: number;
|
||||
color?: ColorConfig;
|
||||
fill?: FillConfig;
|
||||
alignment?: "left" | "center" | "right" | "justify";
|
||||
};
|
||||
|
||||
type ChartAxisConfig = {
|
||||
title?: string | { text?: string; textStyle?: TextStyleConfig };
|
||||
min?: number;
|
||||
max?: number;
|
||||
numberFormatCode?: string;
|
||||
numberFormatSourceLinked?: boolean;
|
||||
position?: "left" | "right" | "top" | "bottom";
|
||||
tickLabelPosition?: "high" | "low" | "nextTo" | string;
|
||||
textStyle?: TextStyleConfig;
|
||||
line?: LineConfig;
|
||||
majorGridlines?: LineConfig | null;
|
||||
minorGridlines?: LineConfig | null;
|
||||
};
|
||||
```
|
||||
|
||||
## Chart From Range
|
||||
|
||||
```ts
|
||||
const chart = sheet.charts.add(chartType, sourceRange, seriesBy);
|
||||
chart.setPosition(startRange, endRange);
|
||||
chart.width = widthPx;
|
||||
chart.height = heightPx;
|
||||
```
|
||||
|
||||
## Shape Config
|
||||
|
||||
```ts
|
||||
const shape = sheet.shapes.add({
|
||||
geometry,
|
||||
anchor,
|
||||
fill,
|
||||
line,
|
||||
name,
|
||||
});
|
||||
```
|
||||
|
||||
## Shape Inline Type
|
||||
|
||||
```ts
|
||||
type WorksheetShapeConfig = {
|
||||
geometry: string; // common: "rect", "roundRect", "ellipse", "textbox"; full list is the slide shape preset list
|
||||
anchor?: DrawingAnchorConfig;
|
||||
fill?: FillConfig;
|
||||
line?: LineConfig;
|
||||
name?: string;
|
||||
};
|
||||
|
||||
type DrawingAnchorConfig = {
|
||||
from: { row: number; col: number; rowOffsetPx?: number; colOffsetPx?: number };
|
||||
to?: { row: number; col: number; rowOffsetPx?: number; colOffsetPx?: number };
|
||||
extent?: { widthPx?: number; heightPx?: number };
|
||||
};
|
||||
```
|
||||
|
||||
## Rebuild And Layout
|
||||
|
||||
For an authorized rebuild, delete only the drawings being replaced.
|
||||
|
||||
```ts
|
||||
const drawings = [...sheet.charts.items, ...sheet.shapes.items];
|
||||
sheet.autoLayoutDrawings(drawings, {
|
||||
direction,
|
||||
frame,
|
||||
gap,
|
||||
padding,
|
||||
});
|
||||
```
|
||||
|
||||
## Auto Layout Inline Type
|
||||
|
||||
```ts
|
||||
type WorksheetDrawingAutoLayoutOptions = {
|
||||
direction?: "vertical" | "horizontal" | "grid";
|
||||
align?: "start" | "center" | "end";
|
||||
columns?: number; // used for grid
|
||||
gap?: number;
|
||||
padding?: number;
|
||||
frame?:
|
||||
| { left: number; top: number; width: number; height: number }
|
||||
| { startCell: string; width: number; height: number };
|
||||
};
|
||||
```
|
||||
Generated
Vendored
+647
@@ -0,0 +1,647 @@
|
||||
# Workbook.apply enums (v0)
|
||||
|
||||
Shared enum value lists referenced by `Workbook.apply` ops.
|
||||
|
||||
## `props.axis.maxMode`
|
||||
|
||||
- `custom`
|
||||
- `group`
|
||||
- `individual`
|
||||
- `unspecified`
|
||||
|
||||
## `props.axis.minMode`
|
||||
|
||||
- `custom`
|
||||
- `group`
|
||||
- `individual`
|
||||
- `unspecified`
|
||||
|
||||
## `props.borders.preset`
|
||||
|
||||
- `all`
|
||||
- `doubleBottom`
|
||||
- `inside`
|
||||
- `none`
|
||||
- `outside`
|
||||
|
||||
## `props.chartType`
|
||||
|
||||
- `area`
|
||||
- `area3D`
|
||||
- `bar`
|
||||
- `bar3D`
|
||||
- `boxWhisker`
|
||||
- `bubble`
|
||||
- `combo`
|
||||
- `doughnut`
|
||||
- `funnel`
|
||||
- `histogram`
|
||||
- `line`
|
||||
- `line3D`
|
||||
- `map`
|
||||
- `ofPie`
|
||||
- `pareto`
|
||||
- `pie`
|
||||
- `pie3D`
|
||||
- `radar`
|
||||
- `scatter`
|
||||
- `stock`
|
||||
- `sunburst`
|
||||
- `surface`
|
||||
- `surface3D`
|
||||
- `treemap`
|
||||
- `waterfall`
|
||||
|
||||
## `props.displayBlanksAs`
|
||||
|
||||
- `gap`
|
||||
- `span`
|
||||
- `zero`
|
||||
|
||||
## `props.displayEmptyCellsAs`
|
||||
|
||||
- `gap`
|
||||
- `span`
|
||||
- `unspecified`
|
||||
- `zero`
|
||||
|
||||
## `props.errorAlert.style`
|
||||
|
||||
- `information`
|
||||
- `stop`
|
||||
- `warning`
|
||||
|
||||
## `props.fill.color.value`
|
||||
|
||||
- `accent1`
|
||||
- `accent2`
|
||||
- `accent3`
|
||||
- `accent4`
|
||||
- `accent5`
|
||||
- `accent6`
|
||||
- `bg1`
|
||||
- `bg2`
|
||||
- `dk1`
|
||||
- `dk2`
|
||||
- `folHlink`
|
||||
- `hlink`
|
||||
- `lt1`
|
||||
- `lt2`
|
||||
- `tx1`
|
||||
- `tx2`
|
||||
|
||||
## `props.fill.gradientKind`
|
||||
|
||||
- `linear`
|
||||
- `path`
|
||||
|
||||
## `props.fill.pattern.type`
|
||||
|
||||
- `cross`
|
||||
- `darkDown`
|
||||
- `darkGray`
|
||||
- `darkGrid`
|
||||
- `darkHorizontal`
|
||||
- `darkTrellis`
|
||||
- `darkUp`
|
||||
- `darkVertical`
|
||||
- `dashedDownwardDiagonal`
|
||||
- `dashedHorizontal`
|
||||
- `dashedUpwardDiagonal`
|
||||
- `dashedVertical`
|
||||
- `diagonalBrick`
|
||||
- `diagonalCross`
|
||||
- `divot`
|
||||
- `dotGrid`
|
||||
- `dottedDiamond`
|
||||
- `downwardDiagonal`
|
||||
- `gray0625`
|
||||
- `gray125`
|
||||
- `horizontal`
|
||||
- `horizontalBrick`
|
||||
- `largeCheck`
|
||||
- `largeConfetti`
|
||||
- `largeGrid`
|
||||
- `lightDown`
|
||||
- `lightGray`
|
||||
- `lightGrid`
|
||||
- `lightHorizontal`
|
||||
- `lightTrellis`
|
||||
- `lightUp`
|
||||
- `lightVertical`
|
||||
- `mediumGray`
|
||||
- `narrowHorizontal`
|
||||
- `narrowVertical`
|
||||
- `none`
|
||||
- `openDiamond`
|
||||
- `percent10`
|
||||
- `percent20`
|
||||
- `percent25`
|
||||
- `percent30`
|
||||
- `percent40`
|
||||
- `percent5`
|
||||
- `percent50`
|
||||
- `percent60`
|
||||
- `percent70`
|
||||
- `percent75`
|
||||
- `percent80`
|
||||
- `percent90`
|
||||
- `plaid`
|
||||
- `shingle`
|
||||
- `smallCheck`
|
||||
- `smallConfetti`
|
||||
- `smallGrid`
|
||||
- `solid`
|
||||
- `solidDiamond`
|
||||
- `sphere`
|
||||
- `trellis`
|
||||
- `upwardDiagonal`
|
||||
- `vertical`
|
||||
- `wave`
|
||||
- `weave`
|
||||
- `wideDownwardDiagonal`
|
||||
- `wideUpwardDiagonal`
|
||||
- `zigZag`
|
||||
|
||||
## `props.geometry`
|
||||
|
||||
- `accentBorderCallout1`
|
||||
- `accentBorderCallout2`
|
||||
- `accentBorderCallout3`
|
||||
- `accentCallout1`
|
||||
- `accentCallout2`
|
||||
- `accentCallout3`
|
||||
- `actionButtonBackPrevious`
|
||||
- `actionButtonBeginning`
|
||||
- `actionButtonBlank`
|
||||
- `actionButtonDocument`
|
||||
- `actionButtonEnd`
|
||||
- `actionButtonForwardNext`
|
||||
- `actionButtonHelp`
|
||||
- `actionButtonHome`
|
||||
- `actionButtonInformation`
|
||||
- `actionButtonMovie`
|
||||
- `actionButtonReturn`
|
||||
- `actionButtonSound`
|
||||
- `arc`
|
||||
- `bentArrow`
|
||||
- `bentConnector2`
|
||||
- `bentConnector3`
|
||||
- `bentConnector4`
|
||||
- `bentConnector5`
|
||||
- `bentUpArrow`
|
||||
- `bevel`
|
||||
- `blockArc`
|
||||
- `borderCallout1`
|
||||
- `borderCallout2`
|
||||
- `borderCallout3`
|
||||
- `bracePair`
|
||||
- `bracketPair`
|
||||
- `callout1`
|
||||
- `callout2`
|
||||
- `callout3`
|
||||
- `can`
|
||||
- `chartPlus`
|
||||
- `chartStar`
|
||||
- `chartX`
|
||||
- `chevron`
|
||||
- `chord`
|
||||
- `circularArrow`
|
||||
- `cloud`
|
||||
- `cloudCallout`
|
||||
- `corner`
|
||||
- `cornerTabs`
|
||||
- `cube`
|
||||
- `curvedConnector2`
|
||||
- `curvedConnector3`
|
||||
- `curvedConnector4`
|
||||
- `curvedConnector5`
|
||||
- `curvedDownArrow`
|
||||
- `curvedLeftArrow`
|
||||
- `curvedRightArrow`
|
||||
- `curvedUpArrow`
|
||||
- `decagon`
|
||||
- `diagStripe`
|
||||
- `diamond`
|
||||
- `dodecagon`
|
||||
- `donut`
|
||||
- `doubleWave`
|
||||
- `downArrow`
|
||||
- `downArrowCallout`
|
||||
- `ellipse`
|
||||
- `ellipseRibbon`
|
||||
- `ellipseRibbon2`
|
||||
- `flowChartAlternateProcess`
|
||||
- `flowChartCollate`
|
||||
- `flowChartConnector`
|
||||
- `flowChartDecision`
|
||||
- `flowChartDelay`
|
||||
- `flowChartDisplay`
|
||||
- `flowChartDocument`
|
||||
- `flowChartExtract`
|
||||
- `flowChartInputOutput`
|
||||
- `flowChartInternalStorage`
|
||||
- `flowChartMagneticDisk`
|
||||
- `flowChartMagneticDrum`
|
||||
- `flowChartMagneticTape`
|
||||
- `flowChartManualInput`
|
||||
- `flowChartManualOperation`
|
||||
- `flowChartMerge`
|
||||
- `flowChartMultidocument`
|
||||
- `flowChartOfflineStorage`
|
||||
- `flowChartOffpageConnector`
|
||||
- `flowChartOnlineStorage`
|
||||
- `flowChartOr`
|
||||
- `flowChartPredefinedProcess`
|
||||
- `flowChartPreparation`
|
||||
- `flowChartProcess`
|
||||
- `flowChartPunchedCard`
|
||||
- `flowChartPunchedTape`
|
||||
- `flowChartSort`
|
||||
- `flowChartSummingJunction`
|
||||
- `flowChartTerminator`
|
||||
- `foldedCorner`
|
||||
- `frame`
|
||||
- `funnel`
|
||||
- `gear6`
|
||||
- `gear9`
|
||||
- `halfFrame`
|
||||
- `heart`
|
||||
- `heptagon`
|
||||
- `hexagon`
|
||||
- `homePlate`
|
||||
- `horizontalScroll`
|
||||
- `irregularSeal1`
|
||||
- `irregularSeal2`
|
||||
- `leftArrow`
|
||||
- `leftArrowCallout`
|
||||
- `leftBrace`
|
||||
- `leftBracket`
|
||||
- `leftCircularArrow`
|
||||
- `leftRightArrow`
|
||||
- `leftRightArrowCallout`
|
||||
- `leftRightCircularArrow`
|
||||
- `leftRightRibbon`
|
||||
- `leftRightUpArrow`
|
||||
- `leftUpArrow`
|
||||
- `lightningBolt`
|
||||
- `line`
|
||||
- `lineInv`
|
||||
- `mathDivide`
|
||||
- `mathEqual`
|
||||
- `mathMinus`
|
||||
- `mathMultiply`
|
||||
- `mathNotEqual`
|
||||
- `mathPlus`
|
||||
- `moon`
|
||||
- `noSmoking`
|
||||
- `nonIsoscelesTrapezoid`
|
||||
- `notchedRightArrow`
|
||||
- `octagon`
|
||||
- `parallelogram`
|
||||
- `pentagon`
|
||||
- `pie`
|
||||
- `pieWedge`
|
||||
- `plaque`
|
||||
- `plaqueTabs`
|
||||
- `plus`
|
||||
- `quadArrow`
|
||||
- `quadArrowCallout`
|
||||
- `rect`
|
||||
- `ribbon`
|
||||
- `ribbon2`
|
||||
- `rightArrow`
|
||||
- `rightArrowCallout`
|
||||
- `rightBrace`
|
||||
- `rightBracket`
|
||||
- `round1Rect`
|
||||
- `round2DiagRect`
|
||||
- `round2SameRect`
|
||||
- `roundRect`
|
||||
- `rtTriangle`
|
||||
- `smileyFace`
|
||||
- `snip1Rect`
|
||||
- `snip2DiagRect`
|
||||
- `snip2SameRect`
|
||||
- `snipRoundRect`
|
||||
- `squareTabs`
|
||||
- `star10`
|
||||
- `star12`
|
||||
- `star16`
|
||||
- `star24`
|
||||
- `star32`
|
||||
- `star4`
|
||||
- `star5`
|
||||
- `star6`
|
||||
- `star7`
|
||||
- `star8`
|
||||
- `straightConnector1`
|
||||
- `stripedRightArrow`
|
||||
- `sun`
|
||||
- `swooshArrow`
|
||||
- `teardrop`
|
||||
- `textbox`
|
||||
- `trapezoid`
|
||||
- `triangle`
|
||||
- `upArrow`
|
||||
- `upArrowCallout`
|
||||
- `upDownArrow`
|
||||
- `upDownArrowCallout`
|
||||
- `uturnArrow`
|
||||
- `verticalScroll`
|
||||
- `wave`
|
||||
- `wedgeEllipseCallout`
|
||||
- `wedgeRectCallout`
|
||||
- `wedgeRoundRectCallout`
|
||||
|
||||
## `props.horizontalAlignment`
|
||||
|
||||
- `Center`
|
||||
- `CenterAcrossSelection`
|
||||
- `Distributed`
|
||||
- `Fill`
|
||||
- `General`
|
||||
- `Justify`
|
||||
- `Left`
|
||||
- `Right`
|
||||
|
||||
## `props.legend.position`
|
||||
|
||||
- `bottom`
|
||||
- `left`
|
||||
- `right`
|
||||
- `top`
|
||||
- `topRight`
|
||||
|
||||
## `props.line.style`
|
||||
|
||||
- `dash-dot`
|
||||
- `dash-dot-dot`
|
||||
- `dashed`
|
||||
- `dotted`
|
||||
- `solid`
|
||||
|
||||
## `props.rule.format.fill.color.value`
|
||||
|
||||
- `accent1`
|
||||
- `accent2`
|
||||
- `accent3`
|
||||
- `accent4`
|
||||
- `accent5`
|
||||
- `accent6`
|
||||
- `bg1`
|
||||
- `bg2`
|
||||
- `dk1`
|
||||
- `dk2`
|
||||
- `folHlink`
|
||||
- `hlink`
|
||||
- `lt1`
|
||||
- `lt2`
|
||||
- `tx1`
|
||||
- `tx2`
|
||||
|
||||
## `props.rule.format.fill.gradientKind`
|
||||
|
||||
- `linear`
|
||||
- `path`
|
||||
|
||||
## `props.rule.format.fill.pattern.type`
|
||||
|
||||
- `cross`
|
||||
- `darkDown`
|
||||
- `darkGray`
|
||||
- `darkGrid`
|
||||
- `darkHorizontal`
|
||||
- `darkTrellis`
|
||||
- `darkUp`
|
||||
- `darkVertical`
|
||||
- `dashedDownwardDiagonal`
|
||||
- `dashedHorizontal`
|
||||
- `dashedUpwardDiagonal`
|
||||
- `dashedVertical`
|
||||
- `diagonalBrick`
|
||||
- `diagonalCross`
|
||||
- `divot`
|
||||
- `dotGrid`
|
||||
- `dottedDiamond`
|
||||
- `downwardDiagonal`
|
||||
- `gray0625`
|
||||
- `gray125`
|
||||
- `horizontal`
|
||||
- `horizontalBrick`
|
||||
- `largeCheck`
|
||||
- `largeConfetti`
|
||||
- `largeGrid`
|
||||
- `lightDown`
|
||||
- `lightGray`
|
||||
- `lightGrid`
|
||||
- `lightHorizontal`
|
||||
- `lightTrellis`
|
||||
- `lightUp`
|
||||
- `lightVertical`
|
||||
- `mediumGray`
|
||||
- `narrowHorizontal`
|
||||
- `narrowVertical`
|
||||
- `none`
|
||||
- `openDiamond`
|
||||
- `percent10`
|
||||
- `percent20`
|
||||
- `percent25`
|
||||
- `percent30`
|
||||
- `percent40`
|
||||
- `percent5`
|
||||
- `percent50`
|
||||
- `percent60`
|
||||
- `percent70`
|
||||
- `percent75`
|
||||
- `percent80`
|
||||
- `percent90`
|
||||
- `plaid`
|
||||
- `shingle`
|
||||
- `smallCheck`
|
||||
- `smallConfetti`
|
||||
- `smallGrid`
|
||||
- `solid`
|
||||
- `solidDiamond`
|
||||
- `sphere`
|
||||
- `trellis`
|
||||
- `upwardDiagonal`
|
||||
- `vertical`
|
||||
- `wave`
|
||||
- `weave`
|
||||
- `wideDownwardDiagonal`
|
||||
- `wideUpwardDiagonal`
|
||||
- `zigZag`
|
||||
|
||||
## `props.rule.operator`
|
||||
|
||||
- `between`
|
||||
- `equal`
|
||||
- `greaterThan`
|
||||
- `greaterThanOrEqual`
|
||||
- `lessThan`
|
||||
- `lessThanOrEqual`
|
||||
- `notBetween`
|
||||
- `notEqual`
|
||||
|
||||
## `props.rule.thresholds[].type`
|
||||
|
||||
- `max`
|
||||
- `min`
|
||||
- `num`
|
||||
- `percent`
|
||||
- `percentile`
|
||||
|
||||
## `props.rule.type`
|
||||
|
||||
- `custom`
|
||||
- `date`
|
||||
- `decimal`
|
||||
- `list`
|
||||
- `none`
|
||||
- `textLength`
|
||||
- `time`
|
||||
- `whole`
|
||||
|
||||
## `props.series[].marker.symbol`
|
||||
|
||||
- `circle`
|
||||
- `diamond`
|
||||
- `dot`
|
||||
- `none`
|
||||
- `plus`
|
||||
- `square`
|
||||
- `star`
|
||||
- `triangle`
|
||||
- `x`
|
||||
|
||||
## `props.series[].stroke.fill.color.value`
|
||||
|
||||
- `accent1`
|
||||
- `accent2`
|
||||
- `accent3`
|
||||
- `accent4`
|
||||
- `accent5`
|
||||
- `accent6`
|
||||
- `bg1`
|
||||
- `bg2`
|
||||
- `dk1`
|
||||
- `dk2`
|
||||
- `folHlink`
|
||||
- `hlink`
|
||||
- `lt1`
|
||||
- `lt2`
|
||||
- `tx1`
|
||||
- `tx2`
|
||||
|
||||
## `props.series[].stroke.fill.gradientKind`
|
||||
|
||||
- `linear`
|
||||
- `path`
|
||||
|
||||
## `props.series[].stroke.fill.pattern.type`
|
||||
|
||||
- `cross`
|
||||
- `darkDown`
|
||||
- `darkGray`
|
||||
- `darkGrid`
|
||||
- `darkHorizontal`
|
||||
- `darkTrellis`
|
||||
- `darkUp`
|
||||
- `darkVertical`
|
||||
- `dashedDownwardDiagonal`
|
||||
- `dashedHorizontal`
|
||||
- `dashedUpwardDiagonal`
|
||||
- `dashedVertical`
|
||||
- `diagonalBrick`
|
||||
- `diagonalCross`
|
||||
- `divot`
|
||||
- `dotGrid`
|
||||
- `dottedDiamond`
|
||||
- `downwardDiagonal`
|
||||
- `gray0625`
|
||||
- `gray125`
|
||||
- `horizontal`
|
||||
- `horizontalBrick`
|
||||
- `largeCheck`
|
||||
- `largeConfetti`
|
||||
- `largeGrid`
|
||||
- `lightDown`
|
||||
- `lightGray`
|
||||
- `lightGrid`
|
||||
- `lightHorizontal`
|
||||
- `lightTrellis`
|
||||
- `lightUp`
|
||||
- `lightVertical`
|
||||
- `mediumGray`
|
||||
- `narrowHorizontal`
|
||||
- `narrowVertical`
|
||||
- `none`
|
||||
- `openDiamond`
|
||||
- `percent10`
|
||||
- `percent20`
|
||||
- `percent25`
|
||||
- `percent30`
|
||||
- `percent40`
|
||||
- `percent5`
|
||||
- `percent50`
|
||||
- `percent60`
|
||||
- `percent70`
|
||||
- `percent75`
|
||||
- `percent80`
|
||||
- `percent90`
|
||||
- `plaid`
|
||||
- `shingle`
|
||||
- `smallCheck`
|
||||
- `smallConfetti`
|
||||
- `smallGrid`
|
||||
- `solid`
|
||||
- `solidDiamond`
|
||||
- `sphere`
|
||||
- `trellis`
|
||||
- `upwardDiagonal`
|
||||
- `vertical`
|
||||
- `wave`
|
||||
- `weave`
|
||||
- `wideDownwardDiagonal`
|
||||
- `wideUpwardDiagonal`
|
||||
- `zigZag`
|
||||
|
||||
## `props.series[].stroke.style`
|
||||
|
||||
- `dash-dot`
|
||||
- `dash-dot-dot`
|
||||
- `dashed`
|
||||
- `dotted`
|
||||
- `solid`
|
||||
|
||||
## `props.seriesColor.value`
|
||||
|
||||
- `accent1`
|
||||
- `accent2`
|
||||
- `accent3`
|
||||
- `accent4`
|
||||
- `accent5`
|
||||
- `accent6`
|
||||
- `bg1`
|
||||
- `bg2`
|
||||
- `dk1`
|
||||
- `dk2`
|
||||
- `folHlink`
|
||||
- `hlink`
|
||||
- `lt1`
|
||||
- `lt2`
|
||||
- `tx1`
|
||||
- `tx2`
|
||||
|
||||
## `props.type`
|
||||
|
||||
- `column`
|
||||
- `line`
|
||||
- `stacked`
|
||||
|
||||
## `props.verticalAlignment`
|
||||
|
||||
- `bottom`
|
||||
- `middle`
|
||||
- `top`
|
||||
Generated
Vendored
+84
@@ -0,0 +1,84 @@
|
||||
# Worksheet Images
|
||||
|
||||
Use `sheet.images.add(...)` to attach images to cell-grid anchors.
|
||||
Download remote images first, then pass the local `path` or embedded `blob` bytes.
|
||||
|
||||
## Add Image
|
||||
|
||||
```ts
|
||||
const image = sheet.images.add({
|
||||
path,
|
||||
blob,
|
||||
dataUrl,
|
||||
prompt,
|
||||
alt,
|
||||
anchor,
|
||||
});
|
||||
|
||||
const icon = sheet.images.add({
|
||||
svg: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="#2563eb"/></svg>',
|
||||
anchor: { from: { row: 1, col: 5 }, extent: { widthPx: 48, heightPx: 48 } },
|
||||
});
|
||||
```
|
||||
|
||||
## Image Inline Types
|
||||
|
||||
```ts
|
||||
type WorksheetImageConfig = ImageSource & {
|
||||
alt?: string;
|
||||
contentType?: string;
|
||||
anchor?: DrawingAnchorConfig;
|
||||
};
|
||||
|
||||
type ImageSource =
|
||||
| { path: string }
|
||||
| { svg: string }
|
||||
| { blob: ArrayBuffer }
|
||||
| { dataUrl: string }
|
||||
| { prompt: string };
|
||||
```
|
||||
|
||||
## Anchor
|
||||
|
||||
```ts
|
||||
const anchor = {
|
||||
from,
|
||||
to,
|
||||
extent,
|
||||
};
|
||||
```
|
||||
|
||||
`from`, `to`, and `extent` use the same zero-based anchor and pixel extent shapes as worksheet charts and shapes.
|
||||
|
||||
## Anchor Inline Type
|
||||
|
||||
```ts
|
||||
type DrawingAnchorConfig = {
|
||||
from: AnchorInput;
|
||||
to?: AnchorInput;
|
||||
extent?: {
|
||||
widthPx?: number;
|
||||
heightPx?: number;
|
||||
widthEmu?: number;
|
||||
heightEmu?: number;
|
||||
};
|
||||
};
|
||||
|
||||
type AnchorInput = {
|
||||
row: number;
|
||||
col: number;
|
||||
rowOffsetPx?: number;
|
||||
colOffsetPx?: number;
|
||||
rowOffsetEmu?: number;
|
||||
colOffsetEmu?: number;
|
||||
};
|
||||
```
|
||||
|
||||
## Edit
|
||||
|
||||
```ts
|
||||
image.anchor = anchor;
|
||||
image.alt = altText;
|
||||
image.replace(sourceConfig);
|
||||
image.delete();
|
||||
```
|
||||
Generated
Vendored
+86
@@ -0,0 +1,86 @@
|
||||
# chart ops
|
||||
|
||||
Ops in the `chart.*` namespace for `Workbook.apply`.
|
||||
|
||||
## Ops index
|
||||
|
||||
- `chart.add`: Add a chart anchored to worksheet cells.
|
||||
|
||||
## `chart.add`
|
||||
|
||||
Add a chart anchored to worksheet cells.
|
||||
|
||||
**Required fields**
|
||||
- `op`
|
||||
- `props`
|
||||
- `sheet`
|
||||
- `props.anchor`
|
||||
- `props.chartType`
|
||||
|
||||
**Optional fields**
|
||||
- `as`
|
||||
- `props.categories`
|
||||
- `props.dataLabels`
|
||||
- `props.displayBlanksAs`
|
||||
- `props.hasLegend`
|
||||
- `props.legend`
|
||||
- `props.series`
|
||||
- `props.title`
|
||||
|
||||
**Enums**
|
||||
- `props.chartType`: See [enums](../enums.md).
|
||||
- `props.displayBlanksAs`: See [enums](../enums.md).
|
||||
- `props.legend.position`: See [enums](../enums.md).
|
||||
- `props.series[].marker.symbol`: See [enums](../enums.md).
|
||||
- `props.series[].stroke.fill.color.value`: See [enums](../enums.md).
|
||||
- `props.series[].stroke.fill.gradientKind`: See [enums](../enums.md).
|
||||
- `props.series[].stroke.fill.pattern.type`: See [enums](../enums.md).
|
||||
- `props.series[].stroke.style`: See [enums](../enums.md).
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "chart.add",
|
||||
"sheet": "Charts",
|
||||
"props": {
|
||||
"chartType": "line",
|
||||
"anchor": {
|
||||
"from": {
|
||||
"row": 1,
|
||||
"col": 1,
|
||||
"rowOffsetPx": 4,
|
||||
"colOffsetPx": 8
|
||||
},
|
||||
"extent": {
|
||||
"widthPx": 520,
|
||||
"heightPx": 280
|
||||
}
|
||||
},
|
||||
"title": "Milky Way Star Birth Rate",
|
||||
"categories": [
|
||||
"2020",
|
||||
"2021",
|
||||
"2022",
|
||||
"2023"
|
||||
],
|
||||
"series": [
|
||||
{
|
||||
"name": "Milky Way",
|
||||
"values": [
|
||||
1.8,
|
||||
1.9,
|
||||
2,
|
||||
2.2
|
||||
]
|
||||
}
|
||||
],
|
||||
"hasLegend": true,
|
||||
"legend": {
|
||||
"position": "bottom"
|
||||
},
|
||||
"dataLabels": {
|
||||
"showValue": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
Generated
Vendored
+29
@@ -0,0 +1,29 @@
|
||||
# comments ops
|
||||
|
||||
Ops in the `comments.*` namespace for `Workbook.apply`.
|
||||
|
||||
## Ops index
|
||||
|
||||
- `comments.self.set`: Set the current comment author identity.
|
||||
|
||||
## `comments.self.set`
|
||||
|
||||
Set the current comment author identity.
|
||||
|
||||
**Required fields**
|
||||
- `op`
|
||||
- `person`
|
||||
|
||||
**Optional fields**
|
||||
- (none)
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "comments.self.set",
|
||||
"person": {
|
||||
"displayName": "Artifact Bot",
|
||||
"initials": "AB"
|
||||
}
|
||||
}
|
||||
```
|
||||
Generated
Vendored
+52
@@ -0,0 +1,52 @@
|
||||
# conditionalformat ops
|
||||
|
||||
Ops in the `conditionalformat.*` namespace for `Workbook.apply`.
|
||||
|
||||
## Ops index
|
||||
|
||||
- `conditionalformat.add`: Add a conditional formatting rule to a range.
|
||||
|
||||
## `conditionalformat.add`
|
||||
|
||||
Add a conditional formatting rule to a range.
|
||||
|
||||
**Required fields**
|
||||
- `op`
|
||||
- `props`
|
||||
- `target`
|
||||
- `props.rule`
|
||||
|
||||
**Optional fields**
|
||||
- (none)
|
||||
|
||||
**Enums**
|
||||
- `props.rule.format.fill.color.value`: See [enums](../enums.md).
|
||||
- `props.rule.format.fill.gradientKind`: See [enums](../enums.md).
|
||||
- `props.rule.format.fill.pattern.type`: See [enums](../enums.md).
|
||||
- `props.rule.operator`: See [enums](../enums.md).
|
||||
- `props.rule.thresholds[].type`: See [enums](../enums.md).
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "conditionalformat.add",
|
||||
"target": {
|
||||
"sheet": "CF",
|
||||
"range": "A1:A3"
|
||||
},
|
||||
"props": {
|
||||
"rule": {
|
||||
"type": "cellIs",
|
||||
"operator": "greaterThan",
|
||||
"formula": 3,
|
||||
"format": {
|
||||
"fill": "accent2",
|
||||
"font": {
|
||||
"bold": true,
|
||||
"color": "accent3"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
Generated
Vendored
+59
@@ -0,0 +1,59 @@
|
||||
# datavalidation ops
|
||||
|
||||
Ops in the `datavalidation.*` namespace for `Workbook.apply`.
|
||||
|
||||
## Ops index
|
||||
|
||||
- `datavalidation.set`: Set data validation rules for a range.
|
||||
|
||||
## `datavalidation.set`
|
||||
|
||||
Set data validation rules for a range.
|
||||
|
||||
**Required fields**
|
||||
- `op`
|
||||
- `props`
|
||||
- `target`
|
||||
- `props.rule`
|
||||
|
||||
**Optional fields**
|
||||
- `props.errorAlert`
|
||||
- `props.ignoreBlanks`
|
||||
- `props.inCellDropDown`
|
||||
- `props.prompt`
|
||||
|
||||
**Enums**
|
||||
- `props.errorAlert.style`: See [enums](../enums.md).
|
||||
- `props.rule.operator`: See [enums](../enums.md).
|
||||
- `props.rule.type`: See [enums](../enums.md).
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "datavalidation.set",
|
||||
"target": {
|
||||
"sheet": "Validation",
|
||||
"range": "B2:B10"
|
||||
},
|
||||
"props": {
|
||||
"rule": {
|
||||
"type": "list",
|
||||
"values": [
|
||||
"Dog",
|
||||
"Cat",
|
||||
"Bat"
|
||||
]
|
||||
},
|
||||
"prompt": {
|
||||
"title": "Pick an animal",
|
||||
"show": true
|
||||
},
|
||||
"errorAlert": {
|
||||
"title": "Invalid choice",
|
||||
"show": true
|
||||
},
|
||||
"ignoreBlanks": true,
|
||||
"inCellDropDown": true
|
||||
}
|
||||
}
|
||||
```
|
||||
Generated
Vendored
+47
@@ -0,0 +1,47 @@
|
||||
# image ops
|
||||
|
||||
Ops in the `image.*` namespace for `Workbook.apply`.
|
||||
|
||||
## Ops index
|
||||
|
||||
- `image.add`: Add an image anchored to worksheet cells.
|
||||
|
||||
## `image.add`
|
||||
|
||||
Add an image anchored to worksheet cells.
|
||||
|
||||
**Required fields**
|
||||
- `op`
|
||||
- `props`
|
||||
- `sheet`
|
||||
|
||||
**Optional fields**
|
||||
- `as`
|
||||
- `props.alt`
|
||||
- `props.anchor`
|
||||
- `props.contentType`
|
||||
- `props.dataUrl`
|
||||
- `props.path`
|
||||
- `props.prompt`
|
||||
- `props.uri`
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "image.add",
|
||||
"sheet": "Images",
|
||||
"props": {
|
||||
"dataUrl": "data:image/png;base64,...",
|
||||
"anchor": {
|
||||
"from": {
|
||||
"row": 1,
|
||||
"col": 2
|
||||
},
|
||||
"extent": {
|
||||
"widthPx": 160,
|
||||
"heightPx": 120
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
Generated
Vendored
+67
@@ -0,0 +1,67 @@
|
||||
# names ops
|
||||
|
||||
Ops in the `names.*` namespace for `Workbook.apply`.
|
||||
|
||||
## Ops index
|
||||
|
||||
- `names.function.add`: Define a workbook or worksheet named function (LAMBDA).
|
||||
- `names.range.add`: Define a workbook or worksheet named range.
|
||||
|
||||
## `names.function.add`
|
||||
|
||||
Define a workbook or worksheet named function (LAMBDA).
|
||||
|
||||
**Required fields**
|
||||
- `lambda`
|
||||
- `name`
|
||||
- `op`
|
||||
|
||||
**Optional fields**
|
||||
- `description`
|
||||
- `parameters`
|
||||
- `returns`
|
||||
- `sheet`
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "names.function.add",
|
||||
"name": "AddTax",
|
||||
"lambda": "LAMBDA(price, tax, price*(1+tax))",
|
||||
"description": "Adds tax to a price",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "price",
|
||||
"description": "Base price"
|
||||
},
|
||||
{
|
||||
"name": "tax",
|
||||
"description": "Tax rate (e.g. 0.1)"
|
||||
}
|
||||
],
|
||||
"returns": "Taxed price"
|
||||
}
|
||||
```
|
||||
|
||||
## `names.range.add`
|
||||
|
||||
Define a workbook or worksheet named range.
|
||||
|
||||
**Required fields**
|
||||
- `formula`
|
||||
- `name`
|
||||
- `op`
|
||||
|
||||
**Optional fields**
|
||||
- `description`
|
||||
- `sheet`
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "names.range.add",
|
||||
"name": "SalesRange",
|
||||
"formula": "Data!$A$1:$A$3",
|
||||
"description": "Input sales data"
|
||||
}
|
||||
```
|
||||
Generated
Vendored
+165
@@ -0,0 +1,165 @@
|
||||
# range ops
|
||||
|
||||
Ops in the `range.*` namespace for `Workbook.apply`.
|
||||
|
||||
## Ops index
|
||||
|
||||
- `range.format.set`: Apply formatting to a range.
|
||||
- `range.formulas.set`: Set formulas for a range.
|
||||
- `range.merge`: Merge cells in a range.
|
||||
- `range.unmerge`: Unmerge any merged blocks intersecting the range.
|
||||
- `range.values.set`: Set cell values for a range.
|
||||
|
||||
## `range.format.set`
|
||||
|
||||
Apply formatting to a range.
|
||||
|
||||
**Required fields**
|
||||
- `op`
|
||||
- `props`
|
||||
- `target`
|
||||
|
||||
**Optional fields**
|
||||
- `props.borders`
|
||||
- `props.columnWidth`
|
||||
- `props.fill`
|
||||
- `props.font`
|
||||
- `props.horizontalAlignment`
|
||||
- `props.numberFormat`
|
||||
- `props.rowHeight`
|
||||
- `props.verticalAlignment`
|
||||
- `props.wrapText`
|
||||
|
||||
**Enums**
|
||||
- `props.borders.preset`: See [enums](../enums.md).
|
||||
- `props.fill.color.value`: See [enums](../enums.md).
|
||||
- `props.fill.gradientKind`: See [enums](../enums.md).
|
||||
- `props.fill.pattern.type`: See [enums](../enums.md).
|
||||
- `props.horizontalAlignment`: See [enums](../enums.md).
|
||||
- `props.verticalAlignment`: See [enums](../enums.md).
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "range.format.set",
|
||||
"target": {
|
||||
"sheet": "Scorecard",
|
||||
"range": "A1:C1"
|
||||
},
|
||||
"props": {
|
||||
"fill": "accent1",
|
||||
"font": {
|
||||
"bold": true,
|
||||
"size": 14
|
||||
},
|
||||
"horizontalAlignment": "Center"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## `range.formulas.set`
|
||||
|
||||
Set formulas for a range.
|
||||
|
||||
**Required fields**
|
||||
- `formulas`
|
||||
- `op`
|
||||
- `target`
|
||||
|
||||
**Optional fields**
|
||||
- (none)
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "range.formulas.set",
|
||||
"target": {
|
||||
"sheet": "Inventory",
|
||||
"range": "E2"
|
||||
},
|
||||
"formulas": [
|
||||
[
|
||||
"=AVERAGE(C2:C4)"
|
||||
]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## `range.merge`
|
||||
|
||||
Merge cells in a range.
|
||||
|
||||
**Required fields**
|
||||
- `op`
|
||||
- `target`
|
||||
|
||||
**Optional fields**
|
||||
- `across`
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "range.merge",
|
||||
"target": {
|
||||
"sheet": "Report",
|
||||
"range": "A1:D1"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## `range.unmerge`
|
||||
|
||||
Unmerge any merged blocks intersecting the range.
|
||||
|
||||
**Required fields**
|
||||
- `op`
|
||||
- `target`
|
||||
|
||||
**Optional fields**
|
||||
- (none)
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "range.unmerge",
|
||||
"target": {
|
||||
"sheet": "Report",
|
||||
"range": "A1:D4"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## `range.values.set`
|
||||
|
||||
Set cell values for a range.
|
||||
|
||||
**Required fields**
|
||||
- `op`
|
||||
- `target`
|
||||
- `values`
|
||||
|
||||
**Optional fields**
|
||||
- (none)
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "range.values.set",
|
||||
"target": {
|
||||
"sheet": "Inventory",
|
||||
"range": "A1:C2"
|
||||
},
|
||||
"values": [
|
||||
[
|
||||
"SKU",
|
||||
"Color",
|
||||
"Stock"
|
||||
],
|
||||
[
|
||||
"100-001",
|
||||
"Black",
|
||||
15
|
||||
]
|
||||
]
|
||||
}
|
||||
```
|
||||
Generated
Vendored
+57
@@ -0,0 +1,57 @@
|
||||
# shape ops
|
||||
|
||||
Ops in the `shape.*` namespace for `Workbook.apply`.
|
||||
|
||||
## Ops index
|
||||
|
||||
- `shape.add`: Add a shape anchored to worksheet cells.
|
||||
|
||||
## `shape.add`
|
||||
|
||||
Add a shape anchored to worksheet cells.
|
||||
|
||||
**Required fields**
|
||||
- `op`
|
||||
- `props`
|
||||
- `sheet`
|
||||
- `props.geometry`
|
||||
|
||||
**Optional fields**
|
||||
- `as`
|
||||
- `props.anchor`
|
||||
- `props.fill`
|
||||
- `props.line`
|
||||
|
||||
**Enums**
|
||||
- `props.fill.color.value`: See [enums](../enums.md).
|
||||
- `props.fill.gradientKind`: See [enums](../enums.md).
|
||||
- `props.fill.pattern.type`: See [enums](../enums.md).
|
||||
- `props.geometry`: See [enums](../enums.md).
|
||||
- `props.line.style`: See [enums](../enums.md).
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "shape.add",
|
||||
"sheet": "Shapes",
|
||||
"props": {
|
||||
"geometry": "rect",
|
||||
"anchor": {
|
||||
"from": {
|
||||
"row": 2,
|
||||
"col": 3
|
||||
},
|
||||
"extent": {
|
||||
"widthPx": 260,
|
||||
"heightPx": 140
|
||||
}
|
||||
},
|
||||
"fill": "accent1",
|
||||
"line": {
|
||||
"style": "dashed",
|
||||
"fill": "accent4",
|
||||
"width": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
Generated
Vendored
+26
@@ -0,0 +1,26 @@
|
||||
# sheet ops
|
||||
|
||||
Ops in the `sheet.*` namespace for `Workbook.apply`.
|
||||
|
||||
## Ops index
|
||||
|
||||
- `sheet.add`: Add a worksheet to the workbook.
|
||||
|
||||
## `sheet.add`
|
||||
|
||||
Add a worksheet to the workbook.
|
||||
|
||||
**Required fields**
|
||||
- `op`
|
||||
|
||||
**Optional fields**
|
||||
- `as`
|
||||
- `name`
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "sheet.add",
|
||||
"name": "Inventory"
|
||||
}
|
||||
```
|
||||
Generated
Vendored
+69
@@ -0,0 +1,69 @@
|
||||
# sparkline ops
|
||||
|
||||
Ops in the `sparkline.*` namespace for `Workbook.apply`.
|
||||
|
||||
## Ops index
|
||||
|
||||
- `sparkline.add`: Create a sparkline group backed by source data.
|
||||
|
||||
## `sparkline.add`
|
||||
|
||||
Create a sparkline group backed by source data.
|
||||
|
||||
**Required fields**
|
||||
- `op`
|
||||
- `props`
|
||||
- `props.sourceData`
|
||||
- `props.targetRange`
|
||||
- `props.type`
|
||||
|
||||
**Optional fields**
|
||||
- `props.axis`
|
||||
- `props.axisColor`
|
||||
- `props.dateAxisRange`
|
||||
- `props.displayEmptyCellsAs`
|
||||
- `props.displayHidden`
|
||||
- `props.firstMarkerColor`
|
||||
- `props.highMarkerColor`
|
||||
- `props.lastMarkerColor`
|
||||
- `props.lineWeight`
|
||||
- `props.lowMarkerColor`
|
||||
- `props.markers`
|
||||
- `props.markersColor`
|
||||
- `props.negativeColor`
|
||||
- `props.seriesColor`
|
||||
|
||||
**Enums**
|
||||
- `props.axis.maxMode`: See [enums](../enums.md).
|
||||
- `props.axis.minMode`: See [enums](../enums.md).
|
||||
- `props.displayEmptyCellsAs`: See [enums](../enums.md).
|
||||
- `props.seriesColor.value`: See [enums](../enums.md).
|
||||
- `props.type`: See [enums](../enums.md).
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "sparkline.add",
|
||||
"props": {
|
||||
"type": "line",
|
||||
"targetRange": {
|
||||
"sheet": "KPIs",
|
||||
"range": "H2:H3"
|
||||
},
|
||||
"sourceData": {
|
||||
"sheet": "KPIs",
|
||||
"range": "B2:G3"
|
||||
},
|
||||
"dateAxisRange": {
|
||||
"sheet": "KPIs",
|
||||
"range": "B1:G1"
|
||||
},
|
||||
"seriesColor": "accent1",
|
||||
"markers": {
|
||||
"show": true,
|
||||
"high": true,
|
||||
"low": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
Generated
Vendored
+71
@@ -0,0 +1,71 @@
|
||||
# table ops
|
||||
|
||||
Ops in the `table.*` namespace for `Workbook.apply`.
|
||||
|
||||
## Ops index
|
||||
|
||||
- `table.add`: Create a table from a range.
|
||||
- `table.rows.add`: Append or insert rows into a table.
|
||||
|
||||
## `table.add`
|
||||
|
||||
Create a table from a range.
|
||||
|
||||
**Required fields**
|
||||
- `op`
|
||||
- `props`
|
||||
- `props.range`
|
||||
|
||||
**Optional fields**
|
||||
- `as`
|
||||
- `props.hasHeaders`
|
||||
- `props.name`
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "table.add",
|
||||
"props": {
|
||||
"range": {
|
||||
"sheet": "Inventory",
|
||||
"range": "A1:C3"
|
||||
},
|
||||
"hasHeaders": true,
|
||||
"name": "InventoryTable"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## `table.rows.add`
|
||||
|
||||
Append or insert rows into a table.
|
||||
|
||||
**Required fields**
|
||||
- `op`
|
||||
- `props`
|
||||
- `target`
|
||||
- `props.values`
|
||||
|
||||
**Optional fields**
|
||||
- `props.index`
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "table.rows.add",
|
||||
"target": {
|
||||
"name": "InventoryTable",
|
||||
"sheet": "Inventory"
|
||||
},
|
||||
"props": {
|
||||
"index": null,
|
||||
"values": [
|
||||
[
|
||||
"100-003",
|
||||
"Denim",
|
||||
12
|
||||
]
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
Generated
Vendored
+97
@@ -0,0 +1,97 @@
|
||||
# thread ops
|
||||
|
||||
Ops in the `thread.*` namespace for `Workbook.apply`.
|
||||
|
||||
## Ops index
|
||||
|
||||
- `thread.add`: Create a threaded comment on a cell or range.
|
||||
- `thread.reopen`: Reopen a resolved comment thread.
|
||||
- `thread.reply`: Reply to a comment thread.
|
||||
- `thread.resolve`: Resolve a comment thread.
|
||||
|
||||
## `thread.add`
|
||||
|
||||
Create a threaded comment on a cell or range.
|
||||
|
||||
**Required fields**
|
||||
- `body`
|
||||
- `op`
|
||||
- `target`
|
||||
|
||||
**Optional fields**
|
||||
- `author`
|
||||
- `createdAt`
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "thread.add",
|
||||
"target": {
|
||||
"cell": {
|
||||
"sheet": "Sheet1",
|
||||
"address": "F5"
|
||||
}
|
||||
},
|
||||
"body": "Cell comment"
|
||||
}
|
||||
```
|
||||
|
||||
## `thread.reopen`
|
||||
|
||||
Reopen a resolved comment thread.
|
||||
|
||||
**Required fields**
|
||||
- `op`
|
||||
- `target`
|
||||
|
||||
**Optional fields**
|
||||
- (none)
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "thread.reopen",
|
||||
"target": "threadId"
|
||||
}
|
||||
```
|
||||
|
||||
## `thread.reply`
|
||||
|
||||
Reply to a comment thread.
|
||||
|
||||
**Required fields**
|
||||
- `body`
|
||||
- `op`
|
||||
- `target`
|
||||
|
||||
**Optional fields**
|
||||
- `author`
|
||||
- `createdAt`
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "thread.reply",
|
||||
"target": "threadId",
|
||||
"body": "Reply on cell"
|
||||
}
|
||||
```
|
||||
|
||||
## `thread.resolve`
|
||||
|
||||
Resolve a comment thread.
|
||||
|
||||
**Required fields**
|
||||
- `op`
|
||||
- `target`
|
||||
|
||||
**Optional fields**
|
||||
- (none)
|
||||
|
||||
**Examples**
|
||||
```json
|
||||
{
|
||||
"op": "thread.resolve",
|
||||
"target": "threadId"
|
||||
}
|
||||
```
|
||||
Generated
Vendored
+68
@@ -0,0 +1,68 @@
|
||||
## Ranges API
|
||||
|
||||
Use `Worksheet.getRange(address)` to read and write grid data using Excel A1 notation.
|
||||
|
||||
### Values
|
||||
|
||||
`range.values` is a 2D array of `CellValue`:
|
||||
|
||||
- `string | number | boolean | Date | null`
|
||||
- `null` represents an empty cell
|
||||
|
||||
```ts
|
||||
sheet.getRange("A1:C1").values = [["Date", "Dog", "Resting HR (bpm)"]];
|
||||
sheet.getRange("A2:C4").values = [
|
||||
["2025-01-02", "Nova", 58],
|
||||
["2025-01-03", "Nova", 61],
|
||||
["2025-01-03", "Comet", 72],
|
||||
];
|
||||
```
|
||||
|
||||
### Checkboxes
|
||||
|
||||
Assign boolean values to create Excel checkbox cells. Use `range.values = null` to clear a range and remove the checkbox control.
|
||||
|
||||
```ts
|
||||
sheet.getRange("A1").values = [[true]];
|
||||
sheet.getRange("A2").values = [[false]];
|
||||
|
||||
sheet.getRange("A1:A2").values = null;
|
||||
```
|
||||
|
||||
### Merged cells
|
||||
|
||||
Use `range.merge()` to merge a rectangular range into a single cell region, and `range.unmerge()` to remove merges that intersect the range.
|
||||
|
||||
```ts
|
||||
// Merge a header across columns
|
||||
sheet.getRange("B1:H1").merge();
|
||||
|
||||
// Merge across rows (one merge per row, like Excel “Merge Across”)
|
||||
sheet.getRange("B2:H4").merge(true);
|
||||
|
||||
// Remove merges touching the range
|
||||
sheet.getRange("B1:H4").unmerge();
|
||||
```
|
||||
|
||||
### Formulas
|
||||
|
||||
`range.formulas` is a 2D array of strings. Call `workbook.recalculate()` before reading computed `values`.
|
||||
|
||||
```ts
|
||||
sheet.getRange("E1").values = [["Average HR"]];
|
||||
sheet.getRange("E2").formulas = [[`=AVERAGE(C2:C4)`]];
|
||||
|
||||
workbook.recalculate();
|
||||
const average = sheet.getRange("E2").values[0]?.[0];
|
||||
```
|
||||
|
||||
### A1 addressing conventions
|
||||
|
||||
Supported addressing patterns include:
|
||||
|
||||
- `A1` (single cell)
|
||||
- `A1:C10` (rectangle)
|
||||
- `A:A` (entire column)
|
||||
- `2:2` (entire row)
|
||||
|
||||
In formulas, quote sheet names that contain spaces/punctuation: `'Cost Summary'!A1`.
|
||||
Generated
Vendored
+145
@@ -0,0 +1,145 @@
|
||||
# Range Formatting
|
||||
|
||||
Use `range.format` to style cells with fills, fonts, borders, number formats, sizing, and alignment.
|
||||
|
||||
## Reusable Formats
|
||||
|
||||
Define shared configs at the top level of the persistent JavaScript REPL. Apply
|
||||
them to ranges inside session callbacks; use object spread for local overrides.
|
||||
|
||||
```js
|
||||
var formats = {
|
||||
header: { fill: "accent1", font: { bold: true, color: "lt1" } },
|
||||
amount: { numberFormat: "#,##0.00" },
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
sheet.getRange("A1:D1").format = formats.header;
|
||||
sheet.getRange("B2:D10").format = formats.amount;
|
||||
sheet.getRange("B11:D11").format = { ...formats.amount, font: { bold: true } };
|
||||
```
|
||||
|
||||
A config is applied at assignment time; changing it later does not restyle
|
||||
existing ranges. Spread is shallow: merge nested objects explicitly when needed.
|
||||
Use `workbook.colorScheme = { name, themeColors }` once for new workbooks, with
|
||||
the XLSX slots below. Reuse those tokens in formats; preserve existing themes
|
||||
and the task's domain color meanings. `bg*`/`tx*` aliases are not independent
|
||||
XLSX scheme slots. Font `size` is in points; drawing/chart `fontSize` is in pixels.
|
||||
|
||||
## Shared Color And Fill Inline Types
|
||||
|
||||
```ts
|
||||
type ThemeColorName =
|
||||
| "accent1" | "accent2" | "accent3" | "accent4" | "accent5" | "accent6"
|
||||
| "dk1" | "lt1" | "dk2" | "lt2"
|
||||
| "hlink" | "folHlink";
|
||||
|
||||
type ColorConfig =
|
||||
| string
|
||||
| { type: "rgb"; value: string; transform?: { opacity?: number; lighten?: number; darken?: number } }
|
||||
| { type: "theme"; value: ThemeColorName; transform?: { opacity?: number; lighten?: number; darken?: number } };
|
||||
|
||||
type FillConfig =
|
||||
| string
|
||||
| { type: "none" }
|
||||
| { type: "solid"; color: ColorConfig }
|
||||
| { type: "gradient"; stops: Array<{ offset: number; color: ColorConfig }>; angleDeg?: number; gradientKind?: "linear" | "path" };
|
||||
```
|
||||
|
||||
## Grouped Format
|
||||
|
||||
```ts
|
||||
range.format = {
|
||||
fill,
|
||||
font,
|
||||
horizontalAlignment,
|
||||
verticalAlignment,
|
||||
wrapText,
|
||||
borders,
|
||||
numberFormat,
|
||||
};
|
||||
```
|
||||
|
||||
## Format Inline Types
|
||||
|
||||
```ts
|
||||
type RangeFormatConfig = {
|
||||
fill?: FillConfig | null;
|
||||
font?: RangeFontConfig | null;
|
||||
borders?: RangeBordersConfig;
|
||||
numberFormat?: string | string[][];
|
||||
wrapText?: boolean;
|
||||
horizontalAlignment?:
|
||||
| "general"
|
||||
| "left"
|
||||
| "center"
|
||||
| "right"
|
||||
| "fill"
|
||||
| "justify"
|
||||
| "centerAcrossSelection"
|
||||
| "distributed";
|
||||
verticalAlignment?: "top" | "middle" | "bottom" | "center";
|
||||
rowHeight?: number; // points
|
||||
rowHeightPx?: number;
|
||||
columnWidth?: number; // Excel width units
|
||||
columnWidthPx?: number;
|
||||
};
|
||||
|
||||
type RangeFontConfig = {
|
||||
bold?: boolean;
|
||||
italic?: boolean;
|
||||
size?: number;
|
||||
name?: string;
|
||||
color?: ColorConfig;
|
||||
};
|
||||
```
|
||||
|
||||
## Sizing
|
||||
|
||||
```ts
|
||||
range.format.rowHeightPx = rowHeightPx;
|
||||
range.format.columnWidthPx = columnWidthPx;
|
||||
```
|
||||
|
||||
Pixel sizing is the preferred surface for layout-sensitive work. Point row heights and Excel-width column widths are also available through `rowHeight` and `columnWidth`.
|
||||
|
||||
## Borders
|
||||
|
||||
```ts
|
||||
range.format.borders = {
|
||||
preset,
|
||||
style,
|
||||
color,
|
||||
};
|
||||
```
|
||||
|
||||
Use the border preset strings below. Border style strings are Excel/OpenXML-style names such as `"thin"`, `"medium"`, `"thick"`, `"dashed"`, and `"dotted"`.
|
||||
|
||||
## Border Inline Type
|
||||
|
||||
```ts
|
||||
type RangeBordersConfig =
|
||||
| {
|
||||
preset: "none" | "outside" | "inside" | "all" | "doubleBottom";
|
||||
style?: string; // common: "thin", "medium", "thick", "dashed", "dotted"
|
||||
color?: ColorConfig;
|
||||
}
|
||||
| {
|
||||
top?: BorderLineInput;
|
||||
bottom?: BorderLineInput;
|
||||
left?: BorderLineInput;
|
||||
right?: BorderLineInput;
|
||||
inside?: BorderLineInput;
|
||||
insideHorizontal?: BorderLineInput;
|
||||
insideVertical?: BorderLineInput;
|
||||
diagonalUp?: BorderLineInput;
|
||||
diagonalDown?: BorderLineInput;
|
||||
};
|
||||
|
||||
type BorderLineInput = {
|
||||
style?: string;
|
||||
color?: ColorConfig;
|
||||
weight?: number;
|
||||
};
|
||||
```
|
||||
Generated
Vendored
+55
@@ -0,0 +1,55 @@
|
||||
# Worksheet Tables
|
||||
|
||||
Use `sheet.tables` to add and edit Excel-style tables.
|
||||
|
||||
## Add Table
|
||||
|
||||
```ts
|
||||
const table = sheet.tables.add(rangeAddress, hasHeaders, tableName);
|
||||
```
|
||||
|
||||
## Add Inline Type
|
||||
|
||||
```ts
|
||||
type WorksheetTableAddArgs = {
|
||||
range: string | Range;
|
||||
hasHeaders?: boolean;
|
||||
name?: string;
|
||||
};
|
||||
```
|
||||
|
||||
## Rows And Values
|
||||
|
||||
```ts
|
||||
table.rows.add(rowIndex, rowValues);
|
||||
table.getRange().values = tableValues;
|
||||
```
|
||||
|
||||
## Table Style
|
||||
|
||||
```ts
|
||||
table.name = tableName;
|
||||
table.showTotals = showTotals;
|
||||
table.style = tableStyleName;
|
||||
table.styleOptions = tableStyleOptions;
|
||||
```
|
||||
|
||||
## Table Inline Type
|
||||
|
||||
```ts
|
||||
type WorkbookTableStyleOptions = {
|
||||
showHeaders?: boolean;
|
||||
showTotals?: boolean;
|
||||
bandedRows?: boolean;
|
||||
bandedColumns?: boolean;
|
||||
firstColumn?: boolean;
|
||||
lastColumn?: boolean;
|
||||
};
|
||||
```
|
||||
|
||||
## Delete
|
||||
|
||||
```ts
|
||||
table.delete();
|
||||
sheet.tables.deleteAll();
|
||||
```
|
||||
Generated
Vendored
+31
@@ -0,0 +1,31 @@
|
||||
## Workbook API
|
||||
|
||||
Use `Workbook` to create, edit, recalculate, and export spreadsheet artifacts.
|
||||
|
||||
### Quick start
|
||||
|
||||
```ts
|
||||
import { Workbook } from "@oai/artifact-tool";
|
||||
|
||||
const workbook = Workbook.create();
|
||||
const sheet = workbook.worksheets.add("Sheet1");
|
||||
|
||||
sheet.getRange("A1").values = [["Hello"]];
|
||||
workbook.recalculate();
|
||||
|
||||
const proto = workbook.toProto();
|
||||
```
|
||||
|
||||
### Workbook lifecycle
|
||||
|
||||
- `Workbook.create()` — start a new workbook.
|
||||
- `Workbook.load(proto)` — hydrate from an existing artifact, edit, then `toProto()` again.
|
||||
- `workbook.recalculate()` — evaluate formulas.
|
||||
- `workbook.toProto()` — produce the protobuf-like JSON artifact.
|
||||
|
||||
### Worksheets
|
||||
|
||||
- `workbook.worksheets.add(name)` — add (or return) a worksheet by name.
|
||||
- `workbook.worksheets.getItem(name | index)` — fetch by name or index.
|
||||
- `workbook.worksheets.getActiveWorksheet()` — fetch the active worksheet.
|
||||
- `workbook.worksheets.count` — number of sheets.
|
||||
Reference in New Issue
Block a user