Skip to content
pptx

Editing

Move, resize, edit, and format text in presentations.

No presentation open

Pick a .pptx file to render it here, then edit, reorder, and save it back.

Editing requires two things: loading the presentation with readOnly={false}, and placing Presentation.Selection inside Presentation.Slide.

<Presentation.Root file={file} readOnly={false}>
  <Presentation.Viewport autoFit>
    <Presentation.Slide>
      <Presentation.Selection />
    </Presentation.Slide>
  </Presentation.Viewport>
</Presentation.Root>

Features

  • Move shapes by dragging them
  • Resize shapes by dragging their handles (hold Shift on a corner handle to lock the aspect ratio)
  • Rotate shapes with the handle above the selection (hold Shift to step by 15°)
  • Right-click a shape to select it before opening a context menu; right-clicking empty canvas clears the selection
  • Snap to the slide's edges and center and to other shapes while moving or resizing, with guides showing what lined up (see Snapping)
  • Edit text inline: click a selected shape again, double-click it, or start typing
  • Edit tables by pressing a cell; Tab and the arrow keys move between cells, and dragging a border resizes a row or column
  • Select cells by dragging or Shift + click, then format, merge, copy, or paste them
  • Keyboard: Tab and ShiftTab move through the slide's shapes, and screen readers hear what's selected
  • Multi-select with Shift/Ctrl/Cmd + click, Ctrl/CmdA, or by dragging a marquee on the empty canvas
  • Delete selected shapes with Delete or Backspace
  • Duplicate the selection with Ctrl/CmdD
  • Copy, cut, and paste shapes with Ctrl/CmdC, Ctrl/CmdX, and Ctrl/CmdV, within a deck or between decks on the page; paste an image to insert it
  • Arrange with Ctrl/Cmd] and Ctrl/Cmd[ (one step forward or backward), or with Shift held (to the front or back)
  • Nudge with the arrow keys (1 px, or 10 px while holding Shift)
  • Undo and redo with Ctrl/CmdZ and Ctrl/CmdShiftZ (or Ctrl/CmdY)

Undo and redo shortcuts are off by default to avoid conflicts with your app. Enable them with undoRedoShortcuts, or call store.undo() and store.redo() yourself:

<Presentation.Selection undoRedoShortcuts />

Snapping

Moving and resizing snap to the slide and to other shapes. Hold Alt, or Cmd on macOS, while dragging to place a shape freely.

// Snap from further away
<Presentation.Selection snapThreshold={10} />

// No snapping
<Presentation.Selection snapping={false} />

snapThreshold is in screen pixels and defaults to 6.

Styling the overlay

Presentation.Selection renders every part with default styles. Pass parts as children to render and style those individually.

<Presentation.Selection>
  <Presentation.SelectionBox className="ring-1 ring-blue-500 data-[mode=text]:ring-2">
    <Presentation.ResizeHandle className="size-2.5 rounded-full border border-blue-500 bg-white" />
    <Presentation.RotateHandle className="size-3 rounded-full border border-blue-500 bg-white" />
  </Presentation.SelectionBox>
  <Presentation.SnapGuide className="bg-orange-500" />
  <Presentation.Marquee className="border border-blue-500 bg-blue-500/10" />
</Presentation.Selection>

The overlay positions each part and repeats it as needed. Give handles a size, since they have none of their own.

PartRenderedStateAttributes
Presentation.SelectionBoxOnce per selected shapenode, mode, dragging, rotating, rotationdata-presentation-selection-box, data-mode, data-dragging, data-rotating
Presentation.ResizeHandleEight per outline, inside SelectionBoxdirectiondata-presentation-resize-handle (nw, n, ne, ...)
Presentation.RotateHandleOne per outline, inside SelectionBoxrotation, rotatingdata-presentation-rotate-handle, data-rotating
Presentation.SnapGuideOnce per snapped line while draggingaxis, positiondata-presentation-snap-guide (x or y)
Presentation.MarqueeWhile dragging across empty canvas, or drawing with a draw tooldata-presentation-marquee, data-draw while drawing

Like the other primitives, every part accepts render, and className and style can also be functions of the part's state:

// Corner handles only
<Presentation.ResizeHandle
  className={({ direction }) =>
    direction.length === 2 ? "size-2.5 rounded-full border bg-white" : "hidden"
  }
/>

The rotate handle is hidden on tables and charts. A snap guide is drawn by its background color.

Theming the default look

Set these CSS variables on Presentation.Selection or any ancestor:

VariableDefaultStyles
--presentation-selection#1a73e8Selection outline, resize handles, and marquee
--presentation-snap-guide#f43f5eSnap guides
--presentation-snap-guide-width1pxSnap guide thickness
--presentation-rotate-handle-offset20pxDistance of the rotate handle above the outline
--presentation-rotate-cursorcrosshairCursor over the rotate handle and while rotating
.editor {
  --presentation-selection: var(--ring);
  --presentation-snap-guide: #f97316;
}

Target a part's attributes to add anything else:

[data-presentation-snap-guide] {
  box-shadow: 0 0 4px var(--presentation-snap-guide);
}

Edit callbacks

Undo and redo callbacks receive (status, error?), and node callbacks receive (nodeId, error?):

<Presentation.Selection
  onUndo={(status) => {
    if (status === "empty") toast.error("Nothing to undo");
  }}
  onRedo={(status, error) => {
    if (error)
      toast.error(error instanceof Error ? error.message : "Redo failed");
    else if (status === "empty") toast.error("Nothing to redo");
  }}
  onNodeTransform={(nodeId, error) => {
    if (error) toast.error("Could not move shape");
  }}
  onNodeDelete={(nodeId, error) => {
    if (error) toast.error("Could not delete shape");
  }}
  onTextChange={(nodeId, error) => {
    if (error) toast.error("Text edit failed");
  }}
/>

Programmatic edits

Use store.edit() to apply undoable changes from outside the overlay. See Store for every operation.

import { copyNodes, useCreatePresentationStore } from "@diceui/pptx";

const store = useCreatePresentationStore();

// Change a shape's fill color
await store.edit({
  type: "setSolidFill",
  slideId,
  nodeId,
  color: "#ef4444",
});

// Move a shape (slide pixels at 96 DPI)
await store.edit({
  type: "setNodeTransform",
  slideId,
  nodeId,
  position: { x: 100, y: 200 },
  size: { w: 400, h: 300 },
});

// Edit text
await store.edit({
  type: "setTextBody",
  slideId,
  nodeId,
  paragraphs: [
    {
      sourceParagraphIndex: 0, // copy this paragraph's formatting; -1 for none
      runs: [{ text: "Hello world" }],
    },
  ],
});

// Format text: the whole text body, or a range of it
await store.edit({
  type: "setTextStyle",
  slideId,
  nodeId,
  style: { bold: true, color: "#2563eb", fontFamily: "Arial", fontSize: 24 },
  range: {
    start: { paragraphIndex: 0, offset: 0 },
    end: { paragraphIndex: 0, offset: 5 },
  },
});

// Align paragraphs
await store.edit({
  type: "setParagraphStyle",
  slideId,
  nodeId,
  style: { align: "center" },
});

// Add a slide from a layout (defaults to the layout of `afterSlideId`)
const { createdSlideId } = await store.edit({
  type: "addSlide",
  afterSlideId: slideId,
});

// Switch a slide to another layout, moving its content into the new placeholders
await store.edit({ type: "setSlideLayout", slideId, layoutId });

// Set or clear (`null`) a slide's own background
await store.edit({ type: "setSlideBackground", slideId, color: "#f8fafc" });

// Duplicate a shape (offset 10px by default) and change the stacking order
const { createdNodeIds } = await store.edit({
  type: "duplicateNode",
  slideId,
  nodeId,
});
await store.edit({ type: "reorderNode", slideId, nodeId, order: "front" }); // or "back", "forward", "backward"

// Insert an image: its own size scaled to fit, centered, unless you pass `size` and `position`
await store.edit({
  type: "addImage",
  slideId,
  data: new Uint8Array(await file.arrayBuffer()),
  contentType: file.type, // "image/png", "image/jpeg", or "image/gif"
  name: file.name,
});

// Add a text box (centered and empty by default)
await store.edit({ type: "addTextBox", slideId, text: "Hello" });

// Add a preset shape ("rect", "ellipse", "rightArrow", …), styled from the theme like PowerPoint's
await store.edit({ type: "addShape", slideId, geometry: "roundRect" });

// Add a table, then fill in a cell
const { createdNodeIds } = await store.edit({
  type: "addTable",
  slideId,
  rows: 3,
  columns: 4,
});
await store.edit({
  type: "setTextBody",
  slideId,
  nodeId: createdNodeIds![0],
  cell: { row: 0, column: 0 },
  paragraphs: [{ sourceParagraphIndex: 0, runs: [{ text: "Name" }] }],
});

// Set a shape's or picture's outline (width in points); `color: null` removes it
await store.edit({
  type: "setOutline",
  slideId,
  nodeId,
  color: "#0f172a",
  width: 1.5,
});

// Copy shapes out of one deck and paste them into another (or the same one)
const clipboard = await copyNodes(sourceDeck, sourceSlideId, nodeIds);
await targetStore.edit({
  type: "pasteNodes",
  slideId: targetSlideId,
  clipboard,
});

copyNodes skips shapes that refer to other parts, such as charts and video, and lists them in clipboard.omittedNodeIds.

In setTextStyle, null clears a value so it inherits from the layout, and a range's end is exclusive. Edits that create nodes return their ids in createdNodeIds.

presentation.layouts lists each layout and its name for a "new slide from layout" picker.

For a "Layout" picker like PowerPoint's, getLayouts(presentation) lists the layouts in the deck's order, and getLayoutGroups(presentation) splits them into groups at the section divider layouts some templates add. Render each one with Presentation.LayoutPreview. setSlideLayout moves each placeholder into one of the new layout's with the same type and index, then the same type, and a picture, table, or chart into a content placeholder. Content with no match stays where it was, and empty placeholders with no match are removed.

Formatting toolbar

useSelection gives a toolbar the selection and formatting commands. While editing text they format the selection, or the word at the caret; otherwise they format the whole shape.

Wrap the toolbar in Presentation.Controls so pressing it keeps the selection and text editing. Popovers and menus it renders count too, even when they portal out.

import { Presentation, useSelection } from "@diceui/pptx";

function FormattingToolbar() {
  const { textStyle, setTextStyle, setParagraphStyle } = useSelection();

  return (
    <Presentation.Controls>
      <button
        aria-pressed={textStyle?.bold ?? false}
        disabled={!textStyle}
        onClick={() => void setTextStyle({ bold: !textStyle?.bold })}
      >
        Bold
      </button>
      <button
        disabled={!textStyle}
        onClick={() => void setParagraphStyle({ align: "center" })}
      >
        Center
      </button>
    </Presentation.Controls>
  );
}

For UI that Presentation.Controls can't wrap, such as a context menu around the slide, put data-presentation-controls on the element itself.

textStyle describes the selected text, with null for mixed values. It is null when nothing with text is selected.

The hook also returns:

  • mode, anchor, nodeIds, and nodes for the current selection
  • select, clear, duplicate, remove, and reorder to change it
  • editText(nodeId, cell?) to start editing a shape's text or a table cell
  • insertTextBox, insertShape, and insertTable to add content
  • cell, cellRange, changeTable, and setTableCellStyle for tables
  • startDrawing and drawTool to place a text box or shape by clicking or dragging

getPresentationFonts(presentation) lists the deck's fonts for a font picker, and getPresetShapePath(geometry, width, height) returns SVG path data for a shape picker.

Floating toolbar

anchor is a virtual element for the selection's bounds that Base UI, Radix, and Floating UI accept. Show the toolbar while mode is "selected" or "text" so it hides during drags.

import { Popover } from "@base-ui/react/popover";
import { useSelection } from "@diceui/pptx";

function FloatingToolbar() {
  const { anchor, mode } = useSelection();

  return (
    <Popover.Root
      open={anchor !== null && (mode === "selected" || mode === "text")}
    >
      <Popover.Portal>
        <Popover.Positioner anchor={anchor} side="top" sideOffset={8}>
          <Popover.Popup initialFocus={false} finalFocus={false}>
            <FormattingToolbar />
          </Popover.Popup>
        </Popover.Positioner>
      </Popover.Portal>
    </Popover.Root>
  );
}

Batch operations

Group multiple edits into a single undoable step with "batch":

await store.edit({
  type: "batch",
  operations: [
    { type: "deleteNode", slideId, nodeId: "2" },
    { type: "deleteNode", slideId, nodeId: "3" },
  ],
});

Saving

Call store.save() to get the edited presentation as a Uint8Array, then trigger a download:

async function onSave() {
  const bytes = await store.save();
  const blob = new Blob([bytes], {
    type: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = "edited.pptx";
  a.click();
  URL.revokeObjectURL(url);
}

Untouched parts are saved byte-for-byte; only edited slides are re-serialized.

Undo / redo stack

store.canUndo();
store.canRedo();
await store.undo();
await store.redo();

Reordering slides

The thumbnail strip ships no drag-and-drop, so wrap Presentation.ThumbnailItem with your sortable library and commit the drop as a moveSlide edit:

async function onDragEnd({ active, over }: DragEndEvent) {
  if (!over || active.id === over.id) return;
  const toIndex = slideIds.indexOf(String(over.id));
  await store.edit({ type: "moveSlide", slideId: String(active.id), toIndex });
}

With dnd-kit:

  • Drop role and tabIndex from attributes so the list keeps its roving focus.
  • Give the pointer sensor an activation distance ({ distance: 4 }) so a click still selects.
  • Hold the dropped order in local state until store.edit() settles to avoid a flicker.
  • Clamp the drag with restrictToFirstScrollableAncestor, or dragging past the end scrolls forever.
  • Give a drag overlay's thumbnail the decorative prop so it stays out of focus and announcements.
<DragOverlay>
  {draggedId ? (
    <Presentation.ThumbnailItem decorative slideId={draggedId}>
      <Presentation.ThumbnailItemNumber />
      <Presentation.ThumbnailItemPreview />
    </Presentation.ThumbnailItem>
  ) : null}
</DragOverlay>

Render the overlay inside Presentation.ThumbnailList. The list owns ↑/↓/Home/End, so bind a keyboard drag sensor to modifier combinations instead.

The demo above wires this up with dnd-kit in SortableThumbnailList (apps/docs/src/components/presentation-editor.tsx).

Unsaved changes

store.isDirty() reports whether the presentation changed since it was last saved, and turns false again if the changes are undone.

window.addEventListener("beforeunload", (event) => {
  if (store.isDirty()) event.preventDefault();
});

In the component tree, use useHistory:

function Toolbar() {
  const store = usePresentationStore();
  const { canUndo, canRedo, isDirty, undo, redo } = useHistory();

  return (
    <>
      <button disabled={!canUndo} onClick={() => void undo()}>
        Undo
      </button>
      <button disabled={!canRedo} onClick={() => void redo()}>
        Redo
      </button>
      <button onClick={() => void store.save()}>
        {isDirty ? "Save" : "Saved"}
      </button>
    </>
  );
}

Outside the tree, the same values come through onHistoryChange:

<Presentation.Root
  file={file}
  readOnly={false}
  onHistoryChange={({ canUndo, canRedo, isDirty }) => {
    setHasUnsavedChanges(isDirty);
  }}
/>

On this page