@nextgensoftwares/folio-plugin-layers
Layered pages: positioned shapes, text boxes, pictures and groups with Word's wrap modes and z-order, page backgrounds and borders, section master objects and page objects. Guide: Layered pages.
| Entry | What |
|---|---|
@nextgensoftwares/folio-plugin-layers | everything below (React parts need the optional react peer) |
@nextgensoftwares/folio-plugin-layers/schema | the schema only |
@nextgensoftwares/folio-plugin-layers/reader | layersReaderPlugin for @nextgensoftwares/folio-reader: no React, editor or ProseMirror |
@nextgensoftwares/folio-plugin-layers/core | re-exports @nextgensoftwares/folio-layers-core (0.5+: its own package): model, sanitizing, geometry, layout (drawingRenderer, layersRenderer, page objects, text), paint plan and the PDF/canvas painters; no React, editor or ProseMirror (servers, workers, slides). New code imports folio-layers-core |
Plugin
| Export | Signature | Description |
|---|---|---|
layersPlugin | (options?: LayersPluginOptions) => LayersPlugin | schema, drawing renderer, painters, page layers, wrapLayout, commands, keymap, UI items, overlay and sidebar slots, exporters.pdf / .canvas / .docx |
type LayersPluginOptions | resolveSrc? (stored image src → URL, e.g. plugin-media's), insert?: boolean (toolbar Shapes menu, default true), sidebar?: boolean | { slot?, order?, label? } (Format shape panel, default the sidebar slot) | |
type LayersPlugin | FolioPlugin plus pageLayers and controller: LayersController | |
LAYER_ICONS | SVG path icons of the plugin's items (shapes, textBox, editText, wrap, arrange, format) | |
layersFind | FindSource | the plugin's find: text in shapes and text boxes (groups included) of drawings in the flow and of page-level objects (section masters, page objects) |
Reader
| Export | Signature | Description |
|---|---|---|
layersReaderPlugin | (options?: LayersReaderPluginOptions) => LayersReaderPlugin | a ReaderPlugin: drawing renderer, wrapLayout (linked text boxes, page-level layers), page layers (backgrounds, borders), DOM painters (a canvas per drawing), exporters.canvas / .pdf; guide: In the reader |
type LayersReaderPluginOptions | resolveSrc? (stored src → URL; null skips the picture), resolveSrcs? (a batch of srcs → URLs, wins). Without either, pictures go through the reader's resolveMedia | |
canvasDomPainter | (painters, resolve?) => ReaderDomPainter | a reader DOM painter drawing a custom fragment on a canvas over its box (plus DRAWING_BLEED px) with canvas painters |
Schema
| Export | Description |
|---|---|
DRAWING, drawingSpec | the drawing block node (atom): object (a validated DrawingObject), wrap, float (side), alignment, distT/B/L/R, relH (column/margin/page), relV (paragraph/margin/page), offsetX/Y, z, lockAnchor |
WRAPS | inline, square, tight, through, topBottom, behind, front |
layersSchema | the node plus the layers document attribute |
isDrawingObject(v), isLayersSettings(v) | attr validators: true when the value is exactly what the sanitizers would store |
LAYERS_ATTR | 'layers': page-level settings on doc.attrs |
Object model
| Export | Description |
|---|---|
type DrawingObject | ShapeObject | ImageObject | GroupObject |
type ObjectBase | id, x, y, w, h, rot? (degrees, clockwise), flipH?, flipV?, opacity?, name?, locked?, softEdge? (px), glow?, reflection? (shapes and pictures; drawn by the canvas and PDF painters, not by the SVG ObjectView) |
type ShapeObject | geom: Geometry, fill?, stroke? (null = none), shadow?, text?: TextBody |
type ImageObject | src, alt?, crop? ({ l, t, r, b } fractions), geom? (clip outline), stroke?, adjust? (ImageAdjust: { brightness?, contrast?, saturation?, grayscale?, blur? }; adjustFilter(adjust) is the CSS/canvas filter painters apply; the PDF painter hands adjust to ctx.image, which applies the same functions to the pixels) |
type GroupObject | children, child space cx?, cy?, cw?, ch? (DrawingML chOff/chExt) |
type Geometry, PRESETS, type Preset | DrawingML preset name (rect, roundRect, ellipse, stars, arrows, callouts, line...) or custom (path SVG data in a pw × ph box); adj adjustments (radius, inner, tailX/Y, head, shaft, inset); dml (any ECMA-376 preset shape name, drawn from the library once loaded, preset being its stand-in until then) with av (its adjust values as DrawingML stores them) |
type Fill, type GradientStop | none, solid, gradient (linear with angle / radial), image |
type Stroke, type Dash, type ArrowEnd | colour, width, dash, line ends (arrow, triangle, oval, diamond) |
type Shadow | color, blur, dx, dy |
type Glow, type Reflection | DrawingML a:glow (color with alpha, r px past the outline) and a:reflection (blur, stA/stPos/endA/endPos, dist, dir, fadeDir, sx/sy, kx/ky, algn, fixed: made in the page's axes, DrawingML rotWithShape="0"). The paint plan carries them on an object's first step (PaintStep.fx, resolved by resolveFx); the canvas painter draws the glow as the outline widened by half its size and blurred (stacked fading strokes where the canvas can't blur) and the reflection as the object's steps again, mirrored and faded through a layer; both load as a lazy chunk |
type TextBody | content (Folio blocks), pad?, vAlign?, autofit? (none/grow/shrink), next? (linked box id: any text box of the document, in another drawing or on another page), dir?, overflow? ('clip' default; 'visible' draws text past the box and keeps a middle/bottom anchor when it spills, as PowerPoint does; TextView.clip tells painters), keepWords? (with autofit: 'shrink': shrink until no word is cut across lines), wrap?: 'none' (lines never wrap at the box width; longer lines are laid out at their own width and placed by the first paragraph's alignment, a centred one spilling both ways), typingMarks? (marks the in-place editor gives text typed into an empty body, e.g. a shape's white 18pt style; sanitized to 8 plain marks), prompt? (Folio blocks laid out in place of empty content, e.g. a slide placeholder's "Click to add title"; not content, so never exported, and the in-place editor starts empty), turn? (degrees clockwise: quarter turns lay vertical text out in the turned box, insets turned with it; other angles turn the text about the box centre, DrawingML bodyPr rot; TextView.turn tells painters, turnBox / turnMatrix / turnCss place it; no grow; edited in place in its turned box, the caret and clicks following the turn), vertical? (with turn 90: upright: 'eastAsian' stands East Asian full-width characters upright in one-em cells (DrawingML eaVert), 'all' every character (stacked); the line items of upright graphemes carry TextItem.upright; reverse orders the lines (columns) left to right, anchored from the other end) |
type LayerWrap | the seven wrap modes (tight and through follow the object's outline) |
type LayersSettings, type SectionLayers, type PageBackground, type PageBorder, type PlacedObject, type PlacedWrap, type PageObject | page-level layers: per-section background, border, masters (hideMastersOnFirst), page objects by page number or section first page, hideMasters; a placed object's wrap? (square, tight, through, topBottom), dist? (top, right, bottom, left) and side? (both, left, right) make the body text wrap around it |
Validation (untrusted input)
| Export | Description |
|---|---|
sanitizeObject(raw, taken?) | a valid object tree or null: known fields only, clamped numbers, canonical colours, checked paths and sources, bounded counts/nesting/text (LIMITS), unique ids |
readObject(raw) | sanitizeObject memoized by identity (layout and painters read through it) |
sanitizeSettings(raw), readSettings(raw) | the same for page-level settings |
sanitizeFill, sanitizeStroke, sanitizeShadow, sanitizeGlow, sanitizeReflection, sanitizeText, sanitizeGeometry | field validators |
sanitizeContent(raw), contentText(blocks), paragraphOf(text?) | text bodies |
isSafeSrc(v), newId(prefix?) | image source check (http(s), data: images, blob:, paths, host schemes); fresh ids |
LIMITS | objects 500, depth 8, coordinates 20,000 px, 16 gradient stops, 400 text blocks / 200,000 characters, data: images 30 M characters... |
parseColor, normalizeColor, isColor, docxHex, alphaOf, type Rgba | the colour syntaxes accepted (hex, rgb(a), a few names) |
Creating objects
| Export | Description |
|---|---|
SHAPE_GALLERY, type GalleryItem | Insert ▸ Shapes entries in Word's order (lines, basic shapes, arrows, stars, callouts) with default sizes |
createShape(item, overrides?), DEFAULT_SHAPE_STYLE | a shape with Word's default look (blue fill, darker outline; lines: stroke + ends) |
createTextBox(content?, w?, h?, overrides?) | Word's Insert ▸ Text Box (white fill, thin outline, text at the top) |
createImage(src, w, h, overrides?), createGroup(children, w, h) | pictures and groups |
shapeText(text?) | centred white text for a shape |
Tree and geometry
| Export | Description |
|---|---|
walk, findObject, pathTo, updateObject, idsOf, countObjects, jsonEqual | tree helpers (updates keep untouched subtrees' identity) |
geometryPath(g, w, h), ellipsePath, roundRectPath | outlines as PathCmd[], shared by every renderer (a library preset: its filled paths) |
geometryParts(g, w, h) → GeometryPart[] | null | a library preset's paths with their paint modes ({ path, fill: PartFill, stroke }; PartFill is norm, none, darken, darkenLess, lighten, lightenLess), null when it is one outline filled and stroked as a whole; drawing views carry them as ObjectView.parts and every painter fills (and shades) the faces, then strokes the outlines |
loadPresetShapes(), presetShapesLoaded(), onPresetShapesLoaded(fn), isPresetShape(name) | the ECMA-376 preset shape library (all 186 presetShapeDefinitions, evaluated by the guide interpreter) is a separate chunk (~29 KB gzip) loaded on first use; listeners repaint when it lands |
presetConnectionSites(name, w, h, av?) → ConnectionSite[] ({ x, y, ang }), presetShapeDef(name) | a preset's connection sites (a:cxnLst, in stCxn/endCxn index order; a rectangle's four side midpoints until the library loads; none for lines and connectors); a loaded preset's raw definition |
presetShapeHandles(name, w, h, av?) → ShapeHandle[] ({ x, y, refs: { name, min, max }[] }), presetShapeDefaults(name), dragShapeHandle(name, w, h, av, index, target) | a preset's adjust handles (the yellow diamonds, from the definitions' ahXY/ahPolar) and the adjust values that put one nearest a dragged point |
presetShapeParts(name, w, h, av?), presetShapeTextRect(name, w, h, av?), type ShapeDef | a preset's paths (arcs as Béziers) and text rectangle from its definition (null until loaded) |
parsePath, toSvgPath, toPdfPath, scalePath, isPathData, isOpenPath, PATH_LIMITS, type PathCmd | SVG path data ↔ absolute M/L/C/Z commands |
arrowHeads(cmds, stroke), dashArray(stroke) | line ends as filled paths; dash patterns |
boxMatrix, boundsOf, rotatedBounds, multiply, invert, applyMatrix, cssMatrix, IDENTITY, type Matrix | 2D affine helpers |
wrapOutline(root), flattenPath(cmds, m?) | the tight-wrap outline of a drawing (its shape outline, rotated; a group's convex hull) and path flattening (curves sampled) |
Layout
| Export | Description |
|---|---|
drawingRenderer | the drawing block renderer: inline/reflow blocks, top-and-bottom blocks (below the anchor paragraph's top: a full-width float, so the anchor's lines above the drawing stay there, as in Word and LibreOffice), square floats and tight/through floats (polygon exclusions from the outline), behind/front overlays from the paragraph, margin (the text area, also in columns) or page edge |
layersRenderer, layersPageObjects | the renderer the plugin registers: drawingRenderer carrying pageObjects (masters and page objects as layout page objects: z stacks shared with anchored drawings, text wraps around wrapped ones) |
objectsOnPage, sectionOfPage, placedFragment, placedZone, outlineOf | page objects of a page, their fragments and wrap zones, a view's outline (memoized) |
threadDocument, THREAD_IN, type ThreadIn, overflowOf, threadRemainder, sliceTextblock, type ThreadBox | text threads across drawings and pages: the layout-only threadIn attr, what each box leaves the next (content, re-laid out at the next box's width; paragraphs continue mid-paragraph) |
viewFor(object, ctx), buildView, objectBoxes, type DrawingView, type ObjectView | the resolved drawing (matrices, outlines, laid-out text), memoized by object/theme/measurer |
drawingFragment, DRAWING_FRAGMENT, type DrawingFragmentAttrs, type DrawingSource | the layers.drawing custom fragment |
drawingPlacement, type DrawingPlacement, isPositioned, affectsText | placement attrs with Word's defaults |
layoutText, measureText, splitFlow, DEFAULT_PAD, type TextView | text bodies: insets, autofit, vertical alignment, overflow, linked boxes |
pageLayerFragments(page, z), attachPageLayers, pageLayersInput, pageSection, pageObjectsOf, sectionLayers, type PageLayersInput, BACKGROUND_FRAGMENT, BORDER_FRAGMENT | page-level layers per page (background and border; masters and page objects are in page.fragments); pageObjectsOf(page) lists a laid-out page's masters and page objects |
WordArt (text warps)
TextBody.warp (TextWarp: { preset, adj? }, DrawingML's a:prstTxWarp values) draws the text as glyph outlines bent through one of ECMA-376's 40 preset text warps, when the layout's measurer can return outlines (FontEngine.outline; Outliner, OutlineCmd). The text lays out unwrapped, warpText(fragments, warp, outline, box) → WarpedText ({ x, y, paths }) maps its outlines through warpMapper(warp, w, h, text): two-path presets (inflate, wave, slant, pour...) put the text between their top and bottom paths, one-path presets (arch, circle) run it along the path at its natural size. Painters fill the paths; the text stays underneath, invisible, so the PDF keeps it selectable and searchable. isWarp(preset), sanitizeWarp(raw) (names only: always available). The warp definitions are a lazy chunk (~3 KB gzip): loadTextWarps(), textWarpsLoaded(), onTextWarpsLoaded(fn) work like the preset shape library's; until they land WordArt draws as straight text. The upright-glyph layout of vertical text (TextBody.vertical.upright) is a lazy chunk too (~1 KB gzip): loadVerticalText(), verticalTextLoaded(), onVerticalTextLoaded(fn); until it lands such text lays out turned like vert. The presets are evaluated by DrawingML's shape guide language: guideBuiltins(w, h), guideFormula(f, guides), evaluateGuides(av, gd, w, h, adj?), guidePathPoints(cmds, guides, steps?) (moveTo, lnTo, arcTo, cubic and quadratic Béziers as a polyline).
Commands (one transaction, one undo step each)
| Export | Description |
|---|---|
type ObjectRef, type Holder, readHolder, writeHolder, updateRef, settingsOf, writeSettings, sameHolder | addressing an object in a drawing node, a master or a page object |
type Frame, type DrawingGeo, frameOf, childAt, chainMatrix, resizedRoot | page-space frames ↔ stored geometry (through groups' child spaces) |
setFrame, setFrames, applyFrame | move / resize / rotate (roots change anchor offsets, and an anchored drawing dragged over another paragraph is re-anchored to it unless lockAnchor; children change in their group) |
dropOnPage(items, anchorAt), canChangePage(state, ref), pageLock(state, ref), type PageDrop, type PageLock | a floating drawing dropped on another page: re-anchored before the paragraph anchorAt(y) gives on that page, offsets recomputed from each item's frame in that page's coordinates (one undo step); canChangePage is false for objects inside a group, in-line drawings, masters, page objects and locked anchors; pageLock says which (group, inline, fixed, locked; null when it can go) |
setObjectProps, type ObjectPatch, setPlacement, deleteObjects, insertDrawing, applyText | style, placement, delete, insert, text |
arrangeZ, type ZMove, alignFrames, distributeFrames, arrangeFrames, type AlignMode, visualBox | z-order, align, distribute |
groupObjects, ungroupObject, type Selected | group / ungroup |
Interaction
| Export | Description |
|---|---|
class LayersController, type SelectedObject, type Resolved, type Preview | selection, drag preview, guides, marquee, master mode, text editing state; grid (snap-to-grid spacing) and snapLines ({ xs, ys } in page px: extra lines moves snap to, e.g. a host's drawing guides) |
hitDrawing, drawingsOn, objectAt, originOf, isDrawing, textAt, type PlacedDrawing | hit testing in Word's order (front, flow, behind where no text) |
snapMove, snapTargets, snapAngle, resizeFrame, type SnapTargets, type Handle, type Box | smart guides, 15° steps, handle resizing |
class TextSession, type TextTarget, startTextEditing, canHoldText | in-place text editing (an editor delegate, like header editing): rotated boxes stay rotated and shrink-to-fit text is edited at its displayed size; carets and selection boxes carry the box transform (Caret.matrix) |
layersKeymap(ctrl) | arrows nudge, Delete, Escape, Tab, Enter, Mod-G / Mod-Shift-G |
insertItems, objectItems, insertObject | UI items |
createOverlay, layersHook, noteAltPress | the overlay slot component, its pointer hook, and the Alt state of a press (Alt+drag = marquee). The overlay takes touch: drag a selected object, tap it to edit its text, long-press for its menu. Its handles are .folio-handle hit zones |
hitSize() | a handle's hit zone in CSS px: 44 on coarse pointers, 24 on fine ones (for custom SVG handles) |
startMove, startResize, startRotate, startMarquee, marqueePick, marqueeSelect, pageMapper, type GestureEnv | pointer gestures (one transaction on release) and the rubber band's selection |
createPainters, createDrawingPainter, ObjectNode, ResolveContext, useImageSrc, type SrcResolver | React painters |
FormatPanel, createFormatControl, useLayers, WRAP_OPTIONS | Format shape panel |
Output
| Export | Description |
|---|---|
paintPlan, type PaintStep, fragmentMatrix, imageBox, gradientAt | the drawing as steps shared by PDF and canvas |
drawingPdf, backgroundPdf, borderPdf, layersPdfPainters, type LayersPdfContext | vector PDF |
drawingCanvas, backgroundCanvas, borderCanvas, layersCanvasPainters, type LayersCanvasContext | canvas |
drawingDocx, drawingRun, floatingOf, Z_BASE | DOCX DrawingML (wps:wsp + wps:txbx, wpg:wgp, wp:anchor with wrap, behindDoc, relativeHeight) |
shapeOptions, fillOf, lineOf, groupChildren, type LayersDocxContext | the docx/shapes options builders |
docxPageLayers, DOCX_PAGE_FRAGMENT | page-level layers as header shapes (masters keep their wrap) |
docxPageObjects, DOCX_PAGE_OBJECTS, placedRun | page objects anchored (from the page edge) in a paragraph on their page (attrs.anchor: 'body'; needs layout in the DOCX export) |