Skip to main content

Shapes

Shapes are DrawingML objects: the 187 preset geometries of ECMA-376 and custom geometry, with fills, outlines, theme styles, shadows, glow, soft edges and blur, and text inside. VML shapes in older documents are read into the same model. Shapes are commands and state like everything else: insert one, read the selection, change it.

import type { ColourValue, Editor, FillValue, ThemeColour } from '@twip/web';

export async function shapes(editor: Editor) {
// A shape at the caret's paragraph, in front of the text, in the theme's default style. It is selected.
await editor.commands.insertShape({ preset: 'roundRect', width: 144, height: 72 });

// The selection describes it as written: a theme colour stays a theme colour.
const shape = editor.getState().selection.object?.shape;
if (shape && 'fromStyle' in shape.fill) console.log('styled fill', shape.fill.fromStyle);

// Accent 1 at 75% luminance, a 2 pt dashed outline, a soft shadow, a quarter turn.
const accent: ColourValue = { theme: 'accent1', transforms: [{ kind: 'lumMod', value: 0.75 }] };
await editor.commands.setShapeFill({ type: 'solid', colour: accent });
await editor.commands.setShapeLine({ width: 2, dash: 'dash', fill: { type: 'solid', colour: { theme: 'text1' } } });
await editor.commands.setShapeEffects({
outerShadow: { colour: { rgb: '#000000', transforms: [{ kind: 'alpha', value: 0.4 }] }, blur: 4, distance: 3, direction: 45 },
});
await editor.commands.setObjectRotation(90);

// `fromStyle` takes the explicit fill away again.
await editor.commands.setShapeFill({ type: 'fromStyle' });
}

// A colour picker from the document's theme colours (state.themeColours, in ThemeColour order).
export function themePicker(editor: Editor): { colour: ThemeColour; rgb: string; fill: FillValue }[] {
const names: ThemeColour[] = [
'text1', 'background1', 'text2', 'background2', 'accent1', 'accent2',
'accent3', 'accent4', 'accent5', 'accent6', 'hyperlink', 'followedHyperlink',
];
return names.map((colour, i) => ({
colour,
rgb: editor.getState().themeColours[i] ?? '#000000',
fill: { type: 'solid', colour: { theme: colour } },
}));
}

// An "Insert shape" menu from Word's gallery groups.
export function galleryMenu(editor: Editor) {
return editor.shapeGallery.map((group) => ({
label: group.label,
items: group.presets.map((preset) => ({ label: preset, run: () => editor.commands.insertShape({ preset }) })),
}));
}

// Grouping: select two floating shapes (Shift+click in the view), then group, and ungroup again.
export async function group(editor: Editor) {
if ((editor.getState().selection.object?.count ?? 0) >= 2) {
await editor.commands.groupObjects();
await editor.commands.ungroupObjects();
}
}
// A shape at the caret's paragraph, in front of the text, in the theme's default style. It is selected.
await session.Commands.InsertShapeAsync(new ShapePreset("roundRect"), Length.FromPoints(144), Length.FromPoints(72));

// The selection describes it as written: a theme colour stays a theme colour.
var fill = session.State.Selection.Object?.Shape?.Fill;
if (fill?.FromStyle is { } styled) Console.WriteLine($"styled fill {styled}");

// Accent 1 at 75% luminance, a 2 pt dashed outline, a soft shadow, a quarter turn.
var accent = ShapeColor.FromTheme(ThemeColor.Accent1, new ColorTransform(ColorTransformKind.LumMod, 0.75));
await session.Commands.SetShapeFillAsync(new FillValue.Solid(accent));
await session.Commands.SetShapeLineAsync(new LineChange(Width: Length.FromPoints(2), Dash: "dash"));
var shadow = new Shadow(ShapeColor.FromRgb(ColorValue.FromRgb(0, 0, 0)), Length.FromPoints(4), Length.FromPoints(3), 45);
await session.Commands.SetShapeEffectsAsync(new EffectsChange(OuterShadow: shadow));
await session.Commands.SetObjectRotationAsync(90);

// FromStyle takes the explicit fill away again.
await session.Commands.SetShapeFillAsync(new FillValue.FromStyle());

// Word's gallery groups, for an "Insert shape" menu, and the theme colours for a colour picker.
foreach (var group in session.ShapeGallery) Console.WriteLine($"{group.Label}: {group.Presets.Count}");
Console.WriteLine(string.Join(", ", session.State.ThemeColors));

Inserting​

insertShape({ preset, width?, height? }) puts a floating shape at the caret's paragraph, in front of the text, 72 × 72 pt by default (a line or connector 72 × 0), in Word's default style: the theme's accent 1 through its style references. The new shape is selected. shapeGallery lists the presets of Word's Insert > Shapes gallery in its eight groups (Lines, Rectangles, Basic Shapes, Block Arrows, Equation Shapes, Flowchart, Stars and Banners, Callouts), for an application's menu.

The selection​

state.selection.object describes the selected object: its kind (shape, line, group, picture, textBox), size, wrapping, rotation and flips, the selected group child's path, and how many objects are selected. Its shape gives the preset and adjust values, and the fill, outline and effects as written: { explicit: … } for the shape's own, { fromStyle: … } for its style's. A theme colour stays a theme colour with its transforms (accent 1 at 75% luminance), so a colour picker can show the theme swatch it came from. state.themeColours gives the document's 12 theme colours, in ThemeColour order.

Formatting​

CommandChanges
setShapePreset(preset)the geometry; text, fill, outline and effects stay, adjust values reset
setShapeAdjust({ index, value })one adjust value
setShapeFill(fill)none, solid, gradient, pattern, picture, or fromStyle to remove the explicit fill
setShapeLine(change)width, fill, dash, compound, cap, join, arrowheads; what isn't given is kept
setShapeEffects(change)outer and inner shadow, glow, soft edge, blur; null removes one
setShapeText(change)insets, anchor, autofit, wrapping, direction of the text inside
setPictureAdjust(change)a picture's transparency, greyscale, brightness, contrast, transparent colour
setObjectRotation(degrees), flipObject(axis)rotation and flips
arrangeObject(how)forward, backward, to front, to back, in front of or behind the text
groupObjects(), ungroupObjects()groups two or more selected floats, or ungroups the selected group

Each is one undo step; selectGroupChild('next') moves the selection through a group's children without one. With several objects selected (Shift or Ctrl and a click), a command applies to each of them.

In the view​

A press selects a shape on its ink: inside a filled shape or on its outline, wherever its rotation puts it. A second press on a selected group selects the child under the pointer, and Esc goes back to the group, then to the text. The selected shape shows a rotate handle above it (Shift snaps to 15°) and yellow adjust handles, and typing into a shape gives it text. Dragging a handle lays the document out live.

Watermarks and page colour​

setWatermark puts a text or picture watermark in every header of every section, written as Word writes it, so Word's Watermark dialog edits it; removeWatermark takes it out. setPageColor sets the page colour: a colour, a theme colour with its tint or shade, or a gradient, pattern, texture or picture fill. They are the Printed Watermark and Fill Effects dialogs (see Services). A page colour isn't drawn in a PDF export, as in Word's. A picture fill or watermark can be any format the document draws, including JPEG XR and EMF+ metafiles.

Saving​

Untouched drawings are saved byte for byte. An edited shape has only the properties that changed written again, in Word's form; 3D and other effects the engine doesn't draw are kept. Reflection, glow, soft edges and shadows are drawn. New shapes are written as Word writes them.