# 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 { slide: inserted, index } = presentation.slides.insert({ after, layout, layoutId });
const byIndex = presentation.slides.getItem(slideIndex);
presentation.slides.keep([0, 2, 4]);
```

`after`: a slide from this presentation or an existing zero-based index; omitted/`null` appends. `index` is zero-based at insertion; `layoutId` overrides `layout`.

Slide indexes start at zero and must be less than
`presentation.slides.items.length`. After an edit completes, read the current
slide list before selecting or rendering a slide. If creation fails or its
outcome is unknown, inspect the saved document to see which slides exist.

Use `presentation.slides.getItem(0)` for a slide and
`chart.series.getItemAt(0)` for a chart series.
`presentation.slides.getItemAt` is not a method.

```ts
const firstSlide = presentation.slides.getItem(0);
const firstSeries = chart.series.getItemAt(0);
```

`layout` uses the first exact, case-sensitive name match. `layoutId` expects
the layout facade's raw `.id`, as in `presentation.slides.add({ layoutId: layout.id })`.
`slideRecord.layout.id` is a read-only `ly/...` anchor. Use the source
slide handle's `.layout.id` to preserve its layout when names repeat.

```ts
// "Title and image" must be an existing layout's exact name.
const layout = presentation.layouts.getItem("Title and image");
const slideByRawId = presentation.slides.add({ layoutId: layout.id });
const slideByName = presentation.slides.add({ layout: layout.name });
```

After an edit completes, select from the saved document's current slide list:

```ts
const slideCount = presentation.slides.items.length;
if (slideCount > 0) {
  const lastSlide = presentation.slides.getItem(slideCount - 1);
  await presentation.render({ slide: lastSlide });
}
```

`keep` accepts an array of zero-based indexes or an array of slide IDs. It
validates the selection against the current slide list, then preserves the
selected slides in their existing relative order. Repeated selections are ignored;
`keep([])` deletes all slides.

`delete` accepts one index or slide ID, or an array of indexes or slide IDs.
Indexes refer to the list at call entry. Repeated targets are deleted once;
`delete([])` leaves every slide in place.

`slide.delete()` removes that slide. Deleting an already removed slide handle does nothing.

`reorder` requires the complete desired order, with every current slide ID exactly
once. Invalid selections fail before mutation.

Read canonical `sl/` IDs from the current inspect or exported layout records.
`Slide.id` values can also be passed to `keep`, `reorder`, and `delete`.

```ts
const selected = await presentation.inspect({
  select: '$.slides[0,2]', include: ['id'],
});
presentation.slides.keep(selected.records.map(record => record.id));
```

```ts
const current = await presentation.inspect({
  select: '$.slides[*]', include: ['id'],
});
const orderedSlideIds = current.records.map(record => record.id).reverse();
presentation.slides.reorder(orderedSlideIds);
```

### Keep And Delete By Current Index

```ts
const presentation = Presentation.create();
for (let index = 0; index < 5; index++) presentation.slides.add();

presentation.slides.keep([0, 2, 4]);
// The three retained slides now have indexes 0, 1, and 2.
presentation.slides.delete([1, 2]);
// Only the original first slide remains.
```

### Delete Inspected Slides

```ts
const selected = await presentation.inspect({
  select: '$.slides[1,3]', include: ['id'],
});
presentation.slides.delete(selected.records.map(record => record.id));
```

## 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 {
  addCopy(source: Slide): Slide;
  keep(selection: readonly number[] | readonly string[]): void;
  delete(selection: number | string | readonly number[] | readonly string[]): void;
  reorder(ids: readonly string[]): void;
}

interface Presentation {
  delete(selection: string | { readonly id: string } | readonly unknown[]): void;
}
```

## Import Slides

To append another open deck, pass the complete proto from `sourcePresentation`.

```ts
const { slides, imageIds } = presentation.importSlides(sourcePresentation.toProto());
```

The source must contain a slide. Its masters, layouts and assets are imported with it.
For a same-deck copy, use `slide.duplicate()`.
Existing content, layouts and the presentation theme remain
unchanged. Imported slides, layouts and assets receive fresh IDs; repeated imports
remain independent. `imageIds` maps every source image ID to its imported ID,
including images used only by layouts.
Conflicting embedded font definitions are rejected before editing. Review comments
are not copied.

Each import step uses ordinary Undo/Redo history. Call `importSlides()` outside
synchronous `record()`. Hosts must save individual updates; a save failure can leave a partial
import, and reopening does not retain the local Undo history. Placeholder cleanup
belongs to the caller and is separate from the import action.

## Discover And Edit

```ts
const snapshot = await presentation.inspect({
  select: "$.slides[*].elements[*]",
  include: ["id", "kind", "text"],
});
```

`delete` accepts an ID, an inspect record with a canonical `id`, or an array of either. It supports slides (`sl/`) and owned
shapes, images, charts, tables, embedded artifacts, and widgets (`sh/`, `im/`,
`ch/`, `tb/`, `ea/`, `wg/`). 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.

Current `Slide.id` values are also accepted for slides when unambiguous. If a raw
slide ID also matches an element ID, including a nested child, use the canonical
ID from inspect or layout.

```ts
const slide = presentation.slides.add();
presentation.delete(slide.id);
```

`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/`, `ea/`, `wg/`, `nt/`, `th/`, and `tr/` anchors to `resolve`.

Copy the complete canonical ID from the current inspect or rendered layout
result. Adding `sh/`, `ch/`, or another prefix to a facade's raw `.id` does not
create an inspect ID. After deleting, replacing, or rebuilding an element,
inspect again before resolving it. Give elements explicit names for later
lookups. Names made from truncated text can differ from a later lookup string.

```js
// "headline" is an explicit authored name, not a slice of its text.
const headings = await presentation.inspect({
  select: "$.slides[*].elements[?(@.name == 'headline')]",
  include: ["id", "name", "text"],
});
if (headings.recordCount !== 1) {
  throw new Error("Expected one headline. Inspect current element names before editing.");
}
const headingId = headings.records[0].id;
presentation.resolve(headingId).text = "Updated headline";
```

```js
// Delete only the currently inspected obsolete captions.
const obsolete = await presentation.inspect({
  select: "$.slides[*].elements[?((@.kind == 'shape' || @.kind == 'textbox') && @.name == 'obsolete-caption')]",
  include: ["id"],
});
presentation.delete(obsolete.records);
```

## 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.

In a Spaces presentation session, await `presentation.export({ format: "pptx" })` inside the callback.
After `const run = await artifactSession.run(...)` commits, share `run.result.downloadUrl` for the latest saved
PowerPoint. Opening the link requires access to the deck. Local sessions publish the PowerPoint file in the run's output directory.

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({
  select: "$.slides[*]",
  include: ["id", "index", "title", "elements.id", "elements.kind", "elements.text"],
});
```

```ts
// Existing deck: inspect first, then resolve exact anchors.
const before = await presentation.inspect({
  select: "$.slides[*].elements[?(search(@.text, 'Customer growth'))]",
  include: ["id", "name", "text"],
});
const target = presentation.resolve(anchorIdFromBefore);
```
