---
title: "Custom components"
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.reducto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Custom components

> **Warning:** Custom components are an alpha feature. The API can change in a future release.

A custom component is your own UI inside a presentation: an interactive 3D WebGL scene, a live chart, a KPI card, a sortable table. The editor mounts your live view over the fallback shape on the slide stage and in **Slide Show**. The `.pptx` file keeps plain PowerPoint shapes, so PowerPoint and PDF exports show it too.

A component has two parts:

- **Fallback.** Plain PowerPoint content built from the component's state: a picture, a table, or a group of shapes (`p:grpSp`). PowerPoint, the layout and the PDF show it.
- **Live view (optional).** DOM mounted over the fallback's box on the slide stage and in Slide Show (`ctx.presenting === true`). It edits the presentation only through `commit(state)`.

Every carrier stores the component's type, id and JSON state on its `p:cNvPr` (`@name = type:id` and an `a:extLst` entry). PowerPoint keeps this data through moves, resizes, rotations and copies. Deleting the shape (or ungrouping a group component) removes the component cleanly.

## A live 3D model (Three.js)

A live view can run anything the browser can draw. Here a Three.js CAD model of a phone stays interactive on the editor stage and fullscreen in **Slide Show** (click the Slide Show icon in the status bar).

Drag the model to move or resize it like any shape. Double-click it to orbit (in Slide Show, just drag), switch between **Assembled** and **Exploded**, then click **Snapshot** to bake the current view into the `.pptx` picture fallback as one undo step. PowerPoint and PDF export show that exact frame, callouts included.

On this page, `three` loads from [esm.sh](https://esm.sh). In your app, run `npm install three`.

```ts
import * as THREE from "three";
import { insertComponent } from "@reductoai/pptx/components";
import { PowerPointPresentation } from "@reductoai/pptx/officejs";
import { drawPicture, mountPptxEditor } from "@reductoai/pptx-editor";

const W = 600;
const H = 440;
const GAP = 2.3;
const PAPER = "#fafafa";
const INK = "#18181b";
const MUTED = "#71717a";
const ACCENT = "#f97316";

function outline(path, w, d, r) {
  const x = w / 2 - r;
  const y = d / 2 - r;
  path.moveTo(-x, -d / 2);
  path.lineTo(x, -d / 2);
  path.absarc(x, -y, r, -Math.PI / 2, 0);
  path.lineTo(w / 2, y);
  path.absarc(x, y, r, 0, Math.PI / 2);
  path.lineTo(-x, d / 2);
  path.absarc(-x, y, r, Math.PI / 2, Math.PI);
  path.lineTo(-w / 2, -y);
  path.absarc(-x, -y, r, Math.PI, Math.PI * 1.5);
  return path;
}

function buildScene() {
  const mat = (color, extra = {}) => new THREE.MeshStandardMaterial({ color, roughness: 0.55, metalness: 0.05, ...extra });
  const edge = new THREE.LineBasicMaterial({ color: INK, transparent: true, opacity: 0.6 });
  const M = {
    glass: mat(0xffffff, { transparent: true, opacity: 0.22, roughness: 0.05, depthWrite: false }),
    oled: mat(0x0b0b0f, { roughness: 0.3 }),
    titanium: mat(0xb8b2aa, { metalness: 0.7, roughness: 0.35 }),
    battery: mat(0xe4e4e7),
    board: mat(0x27272a),
    chip: mat(0x52525b),
    soc: mat(ACCENT, { roughness: 0.4 }),
    back: mat(0xe7e5e4, { roughness: 0.8 }),
    plateau: mat(0xd6d3d1, { roughness: 0.6 }),
    lens: mat(0x111113, { roughness: 0.15 }),
    ring: mat(0x9ca3af, { metalness: 0.8, roughness: 0.3 }),
  };

  const solid = (geo, material, x = 0, y = 0, z = 0) => {
    const g = new THREE.Group();
    g.add(new THREE.Mesh(geo, material));
    g.add(new THREE.LineSegments(new THREE.EdgesGeometry(geo, 25), edge));
    g.position.set(x, y, z);
    return g;
  };
  const slab = (w, d, r, t, material, hole = 0) => {
    const shape = outline(new THREE.Shape(), w, d, r);
    if (hole) shape.holes.push(outline(new THREE.Path(), w - hole * 2, d - hole * 2, Math.max(0.05, r - hole)));
    const geo = new THREE.ExtrudeGeometry(shape, { depth: t, bevelEnabled: false, curveSegments: 24 });
    geo.rotateX(-Math.PI / 2);
    return geo;
  };
  const box = (w, h, d) => new THREE.BoxGeometry(w, h, d).translate(0, h / 2, 0);
  const disc = (r, h) => new THREE.CylinderGeometry(r, r, h, 48).translate(0, h / 2, 0);

  const part = (name, spec, base, anchor, ...children) => {
    const group = new THREE.Group();
    group.add(...children);
    return { name, spec, base, anchor: new THREE.Vector3(...anchor), group };
  };

  const buttons = [
    [-3.6, -4.3, 0.5], [-3.6, -3.2, 0.8], [-3.6, -2.2, 0.8], [3.6, -3.0, 1.2], [3.6, 1.6, 0.9],
  ].map(([x, z, len]) => solid(box(0.1, 0.32, len), M.titanium, x, 0.23, z));

  const magsafe = new THREE.LineLoop(
    new THREE.BufferGeometry().setFromPoints(new THREE.EllipseCurve(0, 0, 1.8, 1.8).getPoints(64)),
    new THREE.LineBasicMaterial({ color: INK, transparent: true, opacity: 0.35 }),
  );
  magsafe.rotation.x = -Math.PI / 2;
  magsafe.position.set(0, 0.062, 0.8);

  const lenses = [[-0.65, -0.65], [-0.65, 0.65], [0.65, 0]].flatMap(([x, z]) => [
    solid(disc(0.58, 0.1), M.ring, x, 0.08, z),
    solid(disc(0.46, 0.16), M.lens, x, 0.08, z),
  ]);
  const camera = new THREE.Group();
  camera.add(solid(slab(2.95, 2.95, 0.72, 0.08, M.plateau), M.plateau), ...lenses, solid(disc(0.16, 0.12), M.battery, 0.75, 0.08, 0.95));
  camera.position.set(-1.72, 0, -5.3);

  const parts = [
    part("Cover glass", "Ceramic · 0.6 mm", 0, [2.6, 0.06, 4.6], solid(slab(6.69, 14.24, 0.85, 0.06), M.glass)),
    part("Display", "6.1 in OLED · 120 Hz", 0.06, [2.4, 0.05, 2.6], solid(slab(6.55, 14.1, 0.8, 0.05), M.oled)),
    part("Frame", "Grade 5 titanium", 0, [3.58, 0.78, 3.4], solid(slab(7.15, 14.7, 1.05, 0.78, M.titanium, 0.22), M.titanium), ...buttons),
    part("Battery", "3,561 mAh Li-ion", 0.14, [2.6, 0.42, 3.6], solid(slab(5.2, 7.4, 0.4, 0.42), M.battery, 0, 0, 2.3)),
    part("Logic board", "3 nm SoC · 8 GB", 0.14, [0.6, 0.2, -4.6],
      solid(slab(6.3, 4.4, 0.5, 0.08), M.board, 0, 0, -4.6),
      solid(box(1.3, 0.12, 1.3), M.soc, 0.6, 0.08, -4.6),
      solid(box(0.9, 0.08, 0.9), M.chip, -1.6, 0.08, -3.6),
      solid(box(0.7, 0.08, 1.1), M.chip, 2.3, 0.08, -3.5),
    ),
    part("Back glass", "Textured matte · Qi2 ring", 0.72, [2.6, 0.06, 4.2], solid(slab(6.69, 14.24, 0.85, 0.06), M.back), magsafe),
    part("Camera system", "48 MP · 5× telephoto", 0.78, [-1.07, 0.24, -5.3], camera),
  ];

  const rig = new THREE.Group();
  const grid = new THREE.GridHelper(20, 20, 0xe4e4e7, 0xe4e4e7);
  grid.material.transparent = true;
  grid.material.opacity = 0.6;
  grid.position.y = -0.6;
  rig.add(grid);
  for (const p of parts) {
    p.group.position.y = p.base;
    rig.add(p.group);
  }

  const scene = new THREE.Scene();
  scene.add(rig, new THREE.HemisphereLight(0xffffff, 0xd4d4d8, 2.4));
  const sun = new THREE.DirectionalLight(0xffffff, 1.8);
  sun.position.set(6, 12, 8);
  scene.add(sun);
  const cam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 200);
  return { scene, camera: cam, rig, parts };
}

function pose(model, explode, yaw, pitch, aspect) {
  const { camera, rig, parts } = model;
  const half = 11.5;
  const span = half * aspect;
  Object.assign(camera, { left: -0.84 * span, right: 1.16 * span, top: half, bottom: -half });
  camera.position.set(0, Math.sin(pitch) * 60, Math.cos(pitch) * 60);
  camera.lookAt(0, 0, 0);
  camera.updateProjectionMatrix();
  rig.rotation.y = yaw;
  parts.forEach((p, i) => (p.group.position.y = p.base + explode * GAP * i));
  rig.position.y = -(explode * GAP * (parts.length - 1) + 0.8) / 2;
  model.scene.updateMatrixWorld(true);
  camera.updateMatrixWorld();
}

function callouts(model, w, h) {
  const v = new THREE.Vector3();
  const marks = model.parts.map((p) => {
    v.copy(p.anchor);
    p.group.localToWorld(v).project(model.camera);
    return { name: p.name, spec: p.spec, ax: ((v.x + 1) / 2) * w, ay: ((1 - v.y) / 2) * h, lx: w * 0.77, ly: 0 };
  });
  const order = [...marks].sort((a, b) => a.ay - b.ay);
  let prev = -Infinity;
  for (const m of order) prev = m.ly = Math.max(m.ay, prev + h * 0.09);
  const overflow = prev - h * 0.84;
  if (overflow > 0) for (const m of order) m.ly -= overflow;
  return marks;
}

const fade = (explode) => Math.min(1, Math.max(0, (explode - 0.45) / 0.4));

const phone = {
  type: "acme.phone-cad",
  async fallback(state) {
    const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });
    renderer.setSize(W * 2, H * 2, false);
    renderer.setClearColor(0x000000, 0);
    const model = buildScene();
    pose(model, state.explode, state.yaw, state.pitch, W / H);
    renderer.render(model.scene, model.camera);
    const marks = callouts(model, W, H);
    const alpha = fade(state.explode);
    const picture = await drawPicture(W, H, (ctx) => {
      ctx.fillStyle = PAPER;
      ctx.fillRect(0, 0, W, H);
      ctx.drawImage(renderer.domElement, 0, 0, W, H);
      ctx.globalAlpha = alpha;
      for (const m of marks) {
        ctx.strokeStyle = INK;
        ctx.lineWidth = 0.6;
        ctx.beginPath();
        ctx.moveTo(m.ax, m.ay);
        ctx.lineTo(m.lx - 8, m.ly);
        ctx.lineTo(m.lx - 3, m.ly);
        ctx.stroke();
        ctx.fillStyle = ACCENT;
        ctx.beginPath();
        ctx.arc(m.ax, m.ay, 2.2, 0, Math.PI * 2);
        ctx.fill();
        ctx.textBaseline = "middle";
        ctx.fillStyle = INK;
        ctx.font = "600 10.5px system-ui, sans-serif";
        ctx.fillText(m.name, m.lx, m.ly - 6);
        ctx.fillStyle = MUTED;
        ctx.font = "500 8.5px ui-monospace, monospace";
        ctx.fillText(m.spec, m.lx, m.ly + 6);
      }
    }, { scale: 2, alt: state.explode > 0.5 ? "Exploded CAD view of a phone" : "CAD view of a phone" });
    renderer.dispose();
    renderer.forceContextLoss();
    return picture;
  },
  mount(el, ctx) {
    const { state, commit, readOnly, presenting } = ctx;
    const SVG = "http://www.w3.org/2000/svg";
    const wrap = document.createElement("div");
    wrap.style.cssText =
      "position:absolute;inset:0;user-select:none;touch-action:none;" +
      "font-family:Inter,system-ui,sans-serif;background:" + PAPER + ";color:" + INK;
    const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
    renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
    renderer.setClearColor(0x000000, 0);
    renderer.domElement.style.cssText = "position:absolute;inset:0;width:100%;height:100%";
    const svg = document.createElementNS(SVG, "svg");
    svg.style.cssText = "position:absolute;inset:0;width:100%;height:100%;pointer-events:none;overflow:visible";
    const tags = document.createElement("div");
    tags.style.cssText = "position:absolute;inset:0;pointer-events:none";
    wrap.append(renderer.domElement, svg, tags);

    const model = buildScene();
    const views = model.parts.map((p) => {
      const line = document.createElementNS(SVG, "polyline");
      line.setAttribute("fill", "none");
      line.setAttribute("stroke", INK);
      line.setAttribute("stroke-width", "0.75");
      const dot = document.createElementNS(SVG, "circle");
      dot.setAttribute("r", "3");
      dot.setAttribute("fill", ACCENT);
      svg.append(line, dot);
      const tag = document.createElement("div");
      tag.style.cssText = "position:absolute;transform:translateY(-50%);white-space:nowrap;line-height:1.25";
      tag.innerHTML =
        '<div style="font:600 1.75cqw Inter,system-ui,sans-serif">' + p.name + "</div>" +
        '<div style="font:500 1.4cqw ui-monospace,monospace;color:' + MUTED + '">' + p.spec + "</div>";
      tags.append(tag);
      return { line, dot, tag };
    });

    let yaw = state.yaw;
    let pitch = state.pitch;
    let explode = state.explode;
    let target = explode > 0.5 ? 1 : 0;
    let turntable = true;
    let dragging = null;

    const fit = () => {
      renderer.setSize(Math.max(1, wrap.clientWidth), Math.max(1, wrap.clientHeight), false);
    };
    const ro = new ResizeObserver(fit);
    ro.observe(wrap);
    fit();

    const hint = document.createElement("div");
    hint.style.cssText =
      "position:absolute;left:3%;top:3%;font:500 1.5cqw ui-monospace,monospace;color:" + MUTED + ";pointer-events:none";
    wrap.append(hint);
    const hintFor = () => {
      if (dragging) return "";
      if (presenting || readOnly) return turntable ? "Drag to orbit" : "";
      if (ctx.active) return "Drag to orbit · Esc when done";
      return ctx.selected ? "Double-click to orbit" : "";
    };

    const canvas = renderer.domElement;
    canvas.onpointerdown = (e) => {
      canvas.setPointerCapture(e.pointerId);
      turntable = false;
      dragging = [e.clientX, e.clientY, yaw, pitch];
    };
    canvas.onpointermove = (e) => {
      if (!dragging) return;
      yaw = dragging[2] + (e.clientX - dragging[0]) * 0.01;
      pitch = Math.max(0.15, Math.min(1.5, dragging[3] + (e.clientY - dragging[1]) * 0.01));
    };
    canvas.onpointerup = () => (dragging = null);

    const bar = document.createElement("div");
    bar.style.cssText =
      "position:absolute;left:3%;right:3%;bottom:3.5%;display:flex;align-items:center;gap:1cqw;" +
      "font:600 1.7cqw Inter,system-ui,sans-serif;pointer-events:none";
    const segment = document.createElement("div");
    segment.style.cssText =
      "pointer-events:auto;display:flex;padding:0.45cqw;gap:0.3cqw;border-radius:999px;" +
      "background:rgba(255,255,255,0.85);backdrop-filter:blur(8px);border:1px solid #e4e4e7;box-shadow:0 1px 2px rgba(0,0,0,.05)";
    const button = (text) => {
      const b = document.createElement("button");
      b.textContent = text;
      b.style.cssText =
        "cursor:pointer;border:0;border-radius:999px;padding:0.55em 1.2em;font:inherit;transition:background .2s,color .2s";
      return b;
    };
    const modes = ["Assembled", "Exploded"].map((label, i) => {
      const b = button(label);
      b.onclick = () => {
        target = i;
        paint();
      };
      segment.append(b);
      return b;
    });
    const paint = () =>
      modes.forEach((b, i) => {
        b.style.background = i === target ? INK : "transparent";
        b.style.color = i === target ? "#fff" : MUTED;
      });
    paint();
    bar.append(segment);
    if (!readOnly && !presenting) {
      const spacer = document.createElement("span");
      spacer.style.flex = "1";
      const snap = button("Snapshot");
      snap.style.cssText +=
        ";pointer-events:auto;background:#fff;color:" + INK + ";border:1px solid #e4e4e7;box-shadow:0 1px 2px rgba(0,0,0,.05)";
      snap.onclick = () => commit({ explode: target, yaw, pitch });
      bar.append(spacer, snap);
    }
    wrap.append(bar);
    el.append(wrap);

    let raf = 0;
    let last = performance.now();
    const tick = (now) => {
      const dt = Math.min(0.05, (now - last) / 1000);
      last = now;
      explode += (target - explode) * (1 - Math.exp(-dt * 5));
      if (turntable) yaw += dt * 0.2;
      const text = hintFor();
      if (hint.textContent !== text) hint.textContent = text;
      canvas.style.cursor = ctx.active ? (dragging ? "grabbing" : "grab") : "";
      const w = wrap.clientWidth;
      const h = wrap.clientHeight;
      pose(model, explode, yaw, pitch, w / Math.max(1, h));
      renderer.render(model.scene, model.camera);
      const alpha = String(fade(explode));
      callouts(model, w, h).forEach((m, i) => {
        const { line, dot, tag } = views[i];
        line.setAttribute("points", m.ax + "," + m.ay + " " + (m.lx - 12) + "," + m.ly + " " + (m.lx - 4) + "," + m.ly);
        dot.setAttribute("cx", String(m.ax));
        dot.setAttribute("cy", String(m.ay));
        line.style.opacity = dot.style.opacity = tag.style.opacity = alpha;
        tag.style.left = m.lx + "px";
        tag.style.top = m.ly + "px";
      });
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);

    return () => {
      cancelAnimationFrame(raf);
      ro.disconnect();
      renderer.dispose();
    };
  },
};

async function buildDeck() {
  const deck = await PowerPointPresentation.create();
  const blank = deck.slideMasters.items[0].layouts.items.find((l) => l.name === "Blank");
  const slide = deck.slides.add({ layoutId: blank.id });
  slide.background.fill.setSolidFill({ color: PAPER });

  const text = (value, box, font) =>
    Object.assign(slide.shapes.addTextBox(value, box).textFrame.textRange.font, font);
  text("FIG. 01 — EXPLODED VIEW", { left: 44, top: 206, width: 280, height: 20 }, { name: "Roboto Mono", size: 9, color: ACCENT, spacing: 1.5 });
  text("Every layer, one click apart.", { left: 40, top: 226, width: 290, height: 110 }, { name: "DM Sans", size: 38, bold: true, color: INK, spacing: -1.5 });

  await insertComponent(deck, phone, { explode: 1, yaw: -0.6, pitch: 0.55 }, { left: 340, top: 50 });
  return deck.toBytes();
}

const editor = mountPptxEditor(el, { components: [phone] });
buildDeck().then((bytes) => editor.open(bytes, "Phone-CAD.pptx"));
```

## Define a component

```ts
import { defineComponent, groupFallback, type ComponentFallback } from "@reductoai/pptx/components";

type Kpi = { label: string; value: number };

const kpi = defineComponent<Kpi>({
  type: "acme.kpi",
  fallback: (state): Promise<ComponentFallback> =>
    groupFallback((slide) => {
      const card = slide.shapes.addGeometricShape("RoundRectangle", {
        left: 0,
        top: 0,
        width: 240,
        height: 110,
      });
      card.fill.setSolidColor("#1e293b");
      card.textFrame.textRange.text = `${state.label}\r$${state.value}M`;
      Object.assign(card.textFrame.textRange.font, { color: "#f8fafc", size: 22, bold: true });
    }),
});
```

Fallback kinds:

- `picture`: PNG, JPEG, GIF, EMF, WMF or SVG `bytes`, with an optional `svg` next to a raster `bytes` fallback. Use `drawPicture(widthPt, heightPt, draw)` from `@reductoai/pptx-editor` to draw a PNG on a browser canvas.
- `table`: `rows` of strings and an optional built-in `style` (e.g. `"MediumStyle2Accent1"`). Implement `read(rows, stored)` to fold PowerPoint cell edits back into your state.
- `group`: a self-contained `.pptx` deck whose first slide's shapes are imported into one `p:grpSp`. Build one with `groupFallback((slide) => ...)`.

## Live views on the stage and in Slide Show

Pass components to `mountPptxEditor` (or `<PptxEditor>`) as `components`. `mount(el, ctx)` receives a container sized, positioned and rotated to match the fallback shape on both the slide stage and **Slide Show**.

- Size your view in `%` or `cqw`/`cqh` so it scales with zoom and fullscreen Slide Show.
- On the stage a view is inert, so a click selects the shape and a drag moves it. A double-click makes the whole view live (`ctx.active`) until Escape or a click outside. In Slide Show and read-only mode a view is always live.
- Controls with `pointer-events: auto` take input even when the view is inert, e.g. a toolbar on the view.
- A view keeps its place in z-order: the shapes above it paint over it, on the stage and in Slide Show. Send to Back puts it under your text.
- `ctx.selected` is true while the shape is selected; the host also carries `data-active` and `data-selected` for CSS.
- Check `ctx.presenting` to tailor the view for Slide Show mode (e.g. hide authoring buttons while keeping interactive controls live).
- `editor.components.list()` and `editor.components.commit(key, state)` let your own toolbar inspect or update components programmatically.

## Without the editor

`@reductoai/pptx/components` works on a `PowerPointPresentation` in Node or the browser:

```ts
import { PowerPointPresentation } from "@reductoai/pptx/node";
import { componentState, insertComponent, listComponents, updateComponent } from "@reductoai/pptx/components";

const deck = await PowerPointPresentation.open("review.pptx");
await insertComponent(deck, kpi, { label: "ARR", value: 4.2 }, { slide: 0, left: 80, top: 100 });
await deck.save("review-out.pptx");

const saved = await PowerPointPresentation.open("review-out.pptx");
for (const entry of listComponents(saved)) {
  if (entry.type !== kpi.type) continue;
  const state = componentState(kpi, entry);
  await updateComponent(saved, kpi, entry.key, { ...state, value: 5.1 });
}
```

Source: https://docs.reducto.ai/office/pptx/ui/custom-components/index.mdx
