@nextgensoftwares/folio-slides-editor
A headless slide-deck editor: one immutable state (deck, current slide, selection, view mode), named commands that turn it into the next state, undo/redo, key bindings, events and a plugin registry. No React, no DOM: the default SlidesApp, your own shell, a test or a server drive the same API. Depends on @nextgensoftwares/folio-slides only. React bindings: @nextgensoftwares/folio-plugin-slides. Guide: Building your own slides shell.
import { createDeckEditor } from '@nextgensoftwares/folio-slides-editor';
const deck = createDeckEditor({ presentation, plugins: [myPlugin] });
deck.exec('slide.new', { layout: 'ppt/slideLayouts/slideLayout2.xml' });
deck.exec('shape.insert', { kind: 'shape', preset: 'ellipse' });
deck.exec('text.bold');
deck.undo();
deck.on('presentation', (state) => save(state.presentation));Editor
| Export | Description |
|---|---|
createDeckEditor(options), DeckEditor, DeckEditorOptions | { presentation?, plugins?, builtins?, readOnly?, mode?, index?, historyLimit?, history? } (history: your own DeckHistory subclass, e.g. live collaboration undoing only this user's steps); builtins: false leaves out coreCommandsPlugin |
deck.state, deck.getState(), deck.presentation, deck.ctx | the current DeckState; ctx is { deck, state } for commands |
deck.exec(id, args?), deck.can(id, args?), deck.isActive(id, args?), deck.command(id) | run a command (true when it changed something); would it; its toggle state; the registered command |
deck.update(change, history?) | apply a DeckChange directly (hosts writing edits made elsewhere); history is a HistoryMode |
deck.setPresentation(p, history?), deck.select(shapeIds, slides?), deck.goTo(index), deck.setMode(mode) | shortcuts (no undo step by default) |
deck.undo(), deck.redo(), deck.history | deck-level history (DeckHistory: canUndo, canRedo, clear()) |
deck.handleKey(event) | runs the bound command for a key event (any object with key, ctrlKey, metaKey, shiftKey, altKey) |
deck.on(event, fn), deck.subscribe(fn) | DeckEvent: 'change', 'presentation', 'index', 'selection', 'mode', 'exec'; subscribe is on('change') (fits useSyncExternalStore) |
deck.setTextTarget(target), deck.textTarget, deck.activeFormat() | text edited in place (TextTarget: exec(id, args), format()) takes the text.* commands; activeFormat() reads it, else the selected shapes (ActiveFormat: bold, italic, underline, strike, size, font, color, align, mixed) |
deck.clipboard | shapes copied by shape.copy / shape.cut |
deck.plugins, deck.destroy() | the composed plugins; runs plugin cleanups |
DeckHistory, HistoryEntry | undo steps of whole presentations (structure shared); same merge key inside its window = one step |
State and types
| Export | Description |
|---|---|
DeckState | { presentation, index, selection, mode, readOnly } |
DeckSelection | { slides: number[], shapes: string[] } (thumbnail selection; shape ids on the current slide) |
DeckMode | 'edit' | 'read' | 'sorter' | 'outline' | 'present' |
DeckChange | { presentation?, index?, selection?, mode? } |
HistoryMode | 'push', false, or { merge: key, ms? } |
DeckContext | { deck, state } |
DeckCommand | { label?, run(ctx, args) → DeckChange | null, can?, active?, reader?, feature?, history? } |
Plugins
A SlidesPlugin is the FolioPlugin contract for decks:
const stamp: SlidesPlugin = {
name: 'stamp',
commands: { 'stamp.add': { label: 'Stamp', run: (ctx) => ({ presentation: addStamp(ctx.state.presentation) }) } },
keymap: { 'Mod-Shift-s': 'stamp.add' },
ui: {
items: [{ id: 'stamp', label: 'Stamp', icon: 'pencil', group: 'plugins', command: 'stamp.add' }],
slots: [{ id: 'stamp.panel', slot: 'inspector', label: 'Stamp', component: StampPanel }],
},
};| Export | Description |
|---|---|
SlidesPlugin | { name, commands?, keymap?, ui?: { items?, slots?, hide? }, reader?, folio?, setup?(deck) }; folio lists document plugins (math, code...) the slide text editor composes |
DeckUIItem | { id, label, icon?, group?, order?, shortcut?, command?, args?, run?(ctx), when?, enabled?, active?, reader?, children?, surfaces?, render?, feature? }; surfaces: 'toolbar' (default), 'contextMenu', 'slideMenu', 'arrange', 'insert', or your own |
DeckSlotItem | { id, slot, label?, icon?, order?, when?, component, reader?, feature? } (feature, on items, slots and commands: the optional part of the app it belongs to, a host's SlidesFeatures key; left out when the host turns that part off); slots the default shell reads: 'inspector' |
DeckBinding | a command id, or { command, args } |
composeSlidesPlugins(list), ComposedSlidesPlugins | merged once: later plugins win per command, key, item and slot item |
deckItems(deck, surface, group?), deckSlots(deck, name) | visible items / slot components now (read-only decks keep reader ones) |
runDeckItem(deck, item), deckItemEnabled(deck, item), deckItemActive(deck, item), deckItemShortcut(deck, item) | for hosts rendering items; the shortcut is the key bound to the item's command in the deck's keymap, else its shortcut (tooltips) |
keyName(event), normalizeBinding(binding), KeyInput | Mod-Shift-z style names (Mod = Cmd on Apple, Ctrl elsewhere) |
Built-in commands
coreCommandsPlugin (always first unless builtins: false) with CORE_KEYMAP and CORE_ITEMS; the command maps are exported as slideCommands, shapeCommands, formatCommands.
| Command | Args |
|---|---|
slide.new | { layout?, at? } (default: the current slide's layout, after it) |
slide.duplicate, slide.delete, slide.hide | { indices? } (default: selected slides, else the current one); hide also { hidden? }; the last slide is never deleted |
slide.move | { from, to } or { indices?, to } (to counts the deck without the moved slides) |
slide.layout | { layout, indices? } |
slide.background | { fill | null, indices?, all? } |
slide.notes | { text, index? } (typing merges into one undo step) |
slide.transition | { transition | null, indices?, all? } |
slide.go, slide.next, slide.prev, slide.select | navigation and thumbnail selection ({ index }, { indices }; reader commands) |
shape.insert | a NewShapeSpec: { kind: 'shape', preset }, { kind: 'textBox', text? }, { kind: 'line', arrow? }, { kind: 'picture', src, w, h, alt? }, { kind: 'table', rows, cols }; optional xfrm |
shape.delete, shape.duplicate, shape.copy, shape.cut, shape.paste, shape.selectAll, shape.select | selection-based ({ ids? } where it applies) |
shape.move, shape.frame, shape.rotate, shape.flip | { dx, dy }; { id?, xfrm }; { by }; { axis: 'h' | 'v' } (inherited placeholder boxes materialize) |
shape.fill, shape.line, shape.shadow, shape.geometry | { fill | null }, { line | null }, { shadow | null } (shapes, groups, pictures and tables), { geom } |
shape.alt, shape.rename, shape.visibility | { text, id? }, { name, id }, { id, hidden? } |
text.body | { anchor?, autofit?, wrap?, insets?: { l?, t?, r?, b? } (px), warp?: { preset, adj? } | null }: text box options (margins, WordArt transform) |
text.code | { language: string | null, theme?: string | null }: the selected text boxes become code in language (TextBody.code: monospace, syntax colours; theme kept when left out, null removes it), or plain text again with language: null; the text is untouched. codeCommands, CodeTextArgs |
text.set | { id?, text }: replaces a shape's text with plain text (one paragraph per line), each paragraph keeping the formatting of the one it replaces |
deck.addOutline | { outline: { title, bullets: { text, level }[] }[], layout? }: appends one slide per entry (title and body placeholders) |
format.paste | { format: ShapeFormat, ids? }: the format painter (formatOf(shape) takes a shape's fill, line, shadow, body anchoring/insets/autofit/wrap and its first run's and paragraph's formatting, or a picture's line, corrections and shadow; applyFormat(shape, format) applies the parts that fit, groups to every child, tables to their runs) |
picture.replace, picture.crop | { src }, { crop | null } |
text.bold, text.italic, text.underline, text.strike | { on? } (toggle) |
text.size, text.font, text.color, text.highlight, text.align, text.bullets, text.body | { size }, { family }, { color } (ColorArg: hex, scheme slot or ColorRef; toColorRef), { color | null }, { align }, { type, char?, scheme? }, { anchor?, autofit?, wrap? } |
arrange.order, arrange.align, arrange.distribute, arrange.group, arrange.ungroup | { to: ZOrder }, { how: Align }, { axis } |
theme.colors, theme.fonts, deck.size | { colors }, { major?, minor? }, { w, h } |
history.undo, history.redo, view.mode, present.start, present.end | { mode }, { from? } |
| shape.add | { shape }: a ready-made shape (plugins), given a fresh id | | shape.lock, shape.opacity, shape.radius, picture.mask | { locked? } (PowerPoint's Lock), { value } (fill/outline alpha), { value } (0–0.5 of the shorter side; rectangles), { preset } | | slide.masterShapes | { show }: "hide background graphics" | | text.baseline, text.spacing, text.case, text.link | { to: 'super' \| 'sub' \| null }, { pts }, { cap }, { href \| null } (in place while text is edited) | | text.lineSpacing, text.paraSpacing, text.bulletColor, text.indent | { pct }, { before?, after? } (pt), { color \| null }, { delta: 1 \| -1 } (outline level) | | text.ruler (RulerEdit) | { level?, marL?, indent?, tabs? }: px, tab positions from the text area's start edge (SlideTab { pos, align? 'ctr' \| 'r' \| 'dec' }); the paragraphs being edited, else every paragraph of the selected shapes; level limits it to that outline level. rulerProps(props, edit) applies one to paragraph props | | shape.path | { id?, cmds, frame? }: edit points. Without frame: PathPoints in slide px (unrotated), and the box becomes their bounds. With frame: true: points in the shape's own frame (0..w × 0..h before rotation and flips), and the new box keeps every unmoved point where it was on the slide (rotation and flips kept). The geometry becomes custom | | connector.draw | { preset?, from, to, arrow? }: a connector (ConnectorPreset: line, straightConnector1, bentConnector3, curvedConnector3) between two ConnectorPoints ({ x, y, to?: ConnectionRef \| null }, slide px), each end glued when to names a shape's site; selected | | connector.end | { id?, end: 'st' \| 'end', at: ConnectorPoint }: moves one end, glued there or free | | shape.freeform | { points, closed?, recognize? }: a pen stroke as a smooth custom path, or the line/rectangle/ellipse/triangle it looks like | | table.insertRow, table.insertCol, table.deleteRow, table.deleteCol | { at? } (default: the end); the frame follows | | table.colors, table.borders | { header?, body?, banded? }, { line \| null } | | table.style, table.look | { styleId, keepCells? } (built-in or the deck's; explicit cell fills cleared), { firstRow?, lastRow?, bandRow?, firstCol?, lastCol?, bandCol? } | | table.cellFill, table.cellBorders, table.cellAnchor | { cells: CellRange, fill \| null }, { cells, line \| null }, { cells, anchor } (CellRange: { r0, c0, r1, c1 }) | | comment.add, comment.edit, comment.move, comment.set, comment.delete | { text, author, authorId?, initials?, x?, y?, date?, id? } (pinned beside the selection by default; refused when id exists), { id, text }, { id, x, y }, { id, comment: SlideComment \| null } (replaces, adds or removes a whole thread: replies, resolution, reactions), { id } | | deck.reuseSlides | { source, slides?, formatting?, at? }: slides of another presentation (reuseSlides; map its media: pictures first, withMedia), inserted after the current slide unless at, in one undo step; the first one becomes current and all of them are selected (reuseCommands) | | deck.importOutline, deck.importPictures | { doc, depth?, layout? } (a document's headings → slide titles, the rest → bullets), { images: [{ src, w, h, alt? }], layout?, size?, replaceEmpty? } (PDF pages, photos: one fitted picture per slide; size resizes the deck first, replaceEmpty drops slides with nothing on them, see emptySlide(slide)) | | deck.guides, deck.addGuide | { guides: SlideGuide[] } (replaces them all; [] removes them), { orient: 'h' \| 'v', pos?, color? } (default through the slide's centre): drawing guides, one undo step each (guideCommands) | | edit.duplicate | Ctrl/⌘+D: duplicates the selected shapes, or the selected slides when no shape is selected | | shape.fillSlide | { id? }: the picture covers the slide, cropped to keep its proportions (coverCrop(crop, frame, w, h)); other shapes are stretched to the slide | | slide.moveTop, slide.moveBottom | moves the selected slides to the start or the end | | picture.fit | { mode: 'fill' \| 'fit' \| 'stretch', natural: { w, h } }: PowerPoint's Crop ▸ Fill / Fit. fitCrop(mode, natural, frame) is the crop; a fit letterboxes with a negative crop | | picture.fitMode | { fit: 'stretch' \| 'cover' \| 'contain', dropCrop?, id? }: sets PicShape.fit (drawn from the image's size, so it holds when the frame or picture changes; the picture panel's Size in frame uses it). stretch also drops the crop; dropCrop drops a crop that only did the fitting | | picture.adjust | { brightness?, contrast?, saturation?, blur?, transparency?, grayscale?, reset? }: saturation is -1..1, written as a:hsl; blur is in px, written as a:blur | | shape.softEdge | { radius }: soft edges (a:softEdge), in px; 0 removes them | | shape.glow | { glow: SlideGlow \| null }: a glow on the selected shapes and pictures (a:glow), or none. glowPreset(accent, pt) is PowerPoint's Glow Variations (GLOW_SIZES 5, 8, 11, 18 pt on accents 1–6, 60% transparent) | | shape.reflection | { reflection: Partial<SlideReflection> \| null }: a whole reflection (REFLECTION_PRESETS: tight, half and full, touching or 4 / 8 pt offset, as PowerPoint's), the fields to change on the present one (a tight one when there is none), or none | | text.outline, text.shadow | { color \| null, width?, dash? } (px; dash an a:prstDash preset, solid when absent; color: null is No line), { on } (PowerPoint's Offset: Bottom Right): the run's a:ln and a:effectLst, in place while text is being edited. activeFormat() reports outline ({ color, width, dash? }) and shadow | | text.body direction | { vert }: horz (removes it), vert, vert270, wordArtVert (stacked), eaVert, wordArtVertRtl, mongolianVert (bodyPr vert; other values are ignored) | | text.body columns | { columns?, columnSpacing? }: text columns (numCol, spcCol) | | section.add, section.rename, section.remove, section.removeAll, section.move, section.moveSlides | { at?, name?, id? } (default: the first selected slide, "Untitled Section"), { id?, name } (default: the current slide's section), { id?, slides? } (the slides join the previous section, or with slides are deleted; never the whole deck), none, { id?, by: -1 \| 1 } (with its slides; the current slide follows), { indices?, to, id } (dropped into a section): PowerPoint's sections (sectionCommands) | | slide.headerFooter | { date?: { format, lang? } \| { text }, slideNumber?, footer?, notOnTitle?, all?, indices? }: Insert › Header & Footer (Apply to the selected slides, or all); see folio-slides setHeaderFooter. A new slide (slide.new) carries on the header and footer of the slide before it (carryHeaderFooter) | | text.insert | { text, font? }: Insert › Symbol, at the caret of the text being edited (the text target's text.insert), else in a new text box, selected | | notes.headerFooter | NotesHeaderFooter \| null: Header and Footer › Notes and Handouts (Apply to All) | | text.replaceMatches | { matches: DeckMatch[], text }: replaces found text (a spelling suggestion, Change All), one undo step | | media.playback, deck.mediaControls | { id?, autoPlay?, loop?, hideWhenStopped? }, { show }: PowerPoint's Playback and Show Media Controls (see folio-slides mediaPlayback) |
SOFT_EDGE_SIZES lists PowerPoint's Soft Edges Variations (pt) for shape.softEdge. Effect commands merge quick changes (a slider drag) into one undo step.
These come in extraCommands, drawCommands, connectorCommands, tableCommands, importCommands, commentCommands, parityCommands, effectCommands, sectionCommands and headerFooterCommands (all in coreCommandsPlugin).
DeckMode adds 'notes' (View › Notes Page).
targetSlides(ctx, indices?), onSlide(ctx, fn), patchSelected(ctx, fn) and notesText(slide) help write commands.
Model operations
Pure functions over the deck model, used by the commands and available to plugins: withSlide, findShape, mapShape, shapeIds, nextId, effectiveXfrm (a shape's box, inherited from its placeholder when it has none), selectedShapes, boundsOf, renumber; reorder, moveBy, setBoxes, align, distribute, group, ungroup (ZOrder, Align); patchRuns, patchParas, withText, selectionFormat; selectedTable(ctx), selectionOpacity(ctx); drawing: simplify(points, eps) (Ramer–Douglas–Peucker), freeformPath(points, closed?) (Catmull-Rom Béziers in the stroke's own box), recognize(points) → Recognized (Pt is { x, y }); paths: parsePathData(d), formatPathData(cmds), mapPath(cmds, f), pathBounds(cmds) (PathPoint: { op, p }); import: documentOutline(doc, depth?) (OutlineNode is any FolioDocument-shaped JSON), outlineSlides(pres, outline, layout?); createSlideShape(spec, id, size) and SHAPE_PRESETS (the gallery's presets by category, PowerPoint's Shapes menu: lines, rectangles, basic, arrows, equation, flowchart, stars and banners, callouts, action buttons).
Find and replace
Across every slide: shape text (groups included), table cells, SmartArt text (with smartArtPlugin(): the diagram's nodes as the text pane shows them, and a replace sets their text and lays the diagram out again once; without it, or for diagrams read without their parts, the drawn text, find only, so the diagram engine stays out of the bundle), chart titles and, unless notes: false, the speaker notes. Matching is the shared text search (Arabic-aware folding by default, match case, whole words, regular expressions).
| Export | Description |
|---|---|
findInDeck(presentation, query, DeckFindOptions?, limit?) → DeckMatch[] | every match in slide order; throws TextQueryError for an invalid regex |
DeckFindOptions | TextSearchOptions plus notes? (default true) |
DeckMatch, DeckMatchWhere | { slide, slideId, shapeId, where: 'shape' | 'table' | 'smartart' | 'chart' | 'notes', inner? (SmartArt: the drawn shape showing it), node? (SmartArt: the data node; para is its line), cell? [row, col], para, from, to, label, readOnly? } (offsets in paragraphText; fields and line breaks can't be replaced) |
replaceInDeck(presentation, matches, text) → { presentation, replaced } | one new deck with the replaceable matches replaced; replaced text keeps the run properties of its first character; untouched slides and shapes keep their identity |
DeckFind, DeckFindState | new DeckFind(deck, defaults?): setQuery(q, opts?), setOptions, state() (query, options, matches, current, error), subscribe, next / prev / go(i) (shows the slide and selects the shape), replace(text) (then the next match; never stops on its own replacement), replaceAll(text) → count (one deck.update: one undo step, one change for collaborators), canReplace (false in read-only decks), destroy(). Edits, undo and collaborators' changes re-count, keeping the current match |
deckWords(presentation, slides?) → SpellWord[], checkSpelling(words, check, cache: SpellCache) → Promise<SpellIssue[]> | spelling with folio-model's shared core: the words of slide text (text boxes, shapes, groups, tables) as matches with their run's lang, segmented by spellWords; checked with the host's checker (SpellCheckFn = SpellChecker) through the deck's SpellCache (new words only, Ignore All); SpellIssue adds suggestions |
paragraphText(paragraph), replaceInParagraph(paragraph, edits) | a paragraph's text as anchors count it (line break \n, field values); char ranges replaced keeping run properties |
Master view
DeckState.sheet (SheetRef: { kind: 'layout' | 'master', id }) puts the editor in master view (PowerPoint's Slide Master). sheetView(pres, ref) is the one-slide presentation it edits: the sheet's own shapes as the slide's, over what it inherits (a layout over its master, its own shapes taken off; a master over nothing), memoized per deck. onSlide (and so every shape, format, table and text command, and slide.background) acts on that slide and writeSheet(pres, ref, slide) writes its shapes and background back to the layout or master, as an ordinary undo step. currentSlide(state) and viewOf(state) ({ presentation, index }) are what UIs draw and edit; sheetSlide(pres, ref) the sheet's slide alone.
| Command | Args |
|---|---|
master.open | { sheet? } (default: the current slide's layout); not an undo step |
master.close | leaves master view |
handout.open | View › Handout Master: master view on { kind: 'handout' } (after loadHandoutView(); does nothing until it resolves); not an undo step |
handout.layout | { perPage?, order? }: Slides Per Page and their order (its frames; Save as PDF's default order) |
handout.orientation | { orientation: 'portrait' | 'landscape' }: the notes and handout page turned |
handout.placeholders | { hdr?, dt?, ftr?, sldNum?: boolean }: the handout master's header, date, footer and page number on or off |
master.rename | { sheet, name } |
masterCommands holds them (in coreCommandsPlugin).
Design presets
DESIGN_PRESETS (DesignPreset: { id, name, colors, fonts: { major, minor }, background?, dark? }, Folio's own palettes) and applyDesign(pres, design): the first theme's colours and fonts, the masters' colour map (light text on a dark background when dark) and their background. design.apply ({ id } or { design }) runs it as one undo step; slides with their own background keep it. Export writes the theme, the masters' p:clrMap and backgrounds.
Charts (add-on)
chartDataPlugin() registers two commands.
chart.insert({ kind: ChartKind, stacked? }) is PowerPoint's Insert ▸ Chart.ChartKindis aChartSpeckind or'filledRadar'. It adds a chart with sample data (sampleChartSpec(kind, stacked?)), centred and selected. On export it gets its own chart part and embedded workbook, written by folio-charts.chart.data({ id?, data: ChartData };ChartDatais{ categories, series: { name, values }[] }). It is not incoreCommandsPlugin. The command replaces a chart's data: series keep their colours by position, and the preview is redrawn withchartShapes. UsechartData(spec)to read a chart's grid andwithChartData(shape, data)to apply one.chartCommandsholds the command.
SmartArt (add-on)
smartArtPlugin({ measure? }) registers the text pane's commands. measure (DiagramMeasure: (text, sizePt) => number) returns a width in points and fits text with the host's fonts; without it, widths are estimated. Either command also takes a measure argument, which wins over the plugin's. folio-plugin-slides' text pane passes one built from the slide's theme font and the app's measurer (diagramTextWidth(pres, slide, measurer) from folio-slides).
smartart.text({ id?, node, text }) sets a node's text. Typing merges into one undo step.smartart.edit({ id?, edit: DiagramEdit }) adds, removes, moves, demotes or promotes a node, one undo step each.smartart.insert({ layout, colors?, style? }) is Insert ▸ SmartArt. It adds one of Folio's layouts (DIAGRAM_LAYOUTSids) with sample items, centred and selected.smartart.look({ id?, layout?, colors?, style? }) is SmartArt Design ▸ Layouts / Change colours / Styles: the diagram is laid out again with them (withDiagramLook).
Both lay the diagram out again (editDiagram) and do nothing for edits that change nothing. Node ids come from diagramOutline. withDiagramEdit(shape, edit, measure?) applies one edit (or several, laid out once) outside a command, and smartArtCommands holds the commands. The plugin also gives find and replace (and the slide editor, for edits on the slide) its diagramText (DiagramText: outline(frame), set(frame, edits), relayout(frame)); findInDeck(p, query, opts, limit, diagrams?) and replaceInDeck(p, matches, text, { diagram? }) take it directly.