Add raster tool with slide, layout, and master scopes
CI / build (push) Canceled after 0s

- Add 12 × 8 and 24 × 16 wireframe presets plus custom columns, rows, gutter, opacity, and colour
- Place the raster on the current slide, its layout, or the slide master so background rasters sit behind content
- Keep one raster per presentation: add clears every scope and remove cleans the whole presentation
- Share the colour swatch control across grids, guidelines, and rasters, including grey
- Add raster geometry tests and document scope, background, and export caveats
This commit is contained in:
schihei committed 2026-11-25 13:03:43 +01:00
1 parent e223dc61c8
commit 9889ce1025
10 files changed
+1106 -206

No files matched your search

+16 -1
View File
@@ -33,8 +33,9 @@ collapsed; click a section title to expand it.
- **Custom Grid**: Create a grid on the current slide with adjustable spacing, opacity, and color.
- **Guidelines**: Add horizontal or vertical guidelines at specific positions with customizable colors.
- **Raster**: Add a wireframe cell grid (12 × 8, 24 × 16, or custom) to the current slide, this slide's layout, or the slide master for placing objects, then remove it.
> Grids and guidelines are ordinary slide shapes. They are included in slideshow, print, and export output. Remove them before presenting.
> Grids, guidelines, and raster cells are ordinary shapes. They are included in slideshow, print, and export output. Remove them before presenting.
### Settings
@@ -205,6 +206,20 @@ manifest.xml # Add-in manifest
2. Click **Add guide** to create a guideline.
3. Click **Remove guides** to delete all guidelines on the current slide.
#### Raster
1. Select the slide where objects should be placed.
2. Choose **Place on**:
- **Current slide** - sits on top of the slide content.
- **This slide's layout (background)** - sits behind content on every slide using that layout.
- **Slide master (all slides)** - sits behind content on every slide in the presentation.
3. Choose the **12 × 8** or **24 × 16** preset, or select **Custom** and enter columns, rows, gutter, and opacity.
4. Pick a color. Gray at 100 % matches the template wireframes; lower opacity keeps existing content visible.
5. Click **Add raster**. Any existing raster in the presentation is replaced, so only one raster is active at a time.
6. Click **Remove raster** before presenting. This removes it from the current slide, all layouts, and the slide master.
The hint below the controls shows the resulting cell size in millimetres and the number of cells (maximum 600). Layout/master rasters are background graphics and do not appear on slides that use **Hide Background Graphics**. Because a layout/master raster is inherited by every slide that uses it, prefer **12 × 8** on large presentations.
## Tips
- **Selection order**: For Match Properties and Match Sizes, the source is the first shape in PowerPoint's selection/z-order, which is not guaranteed to be the shape you clicked first. Verify the source shape before applying.
+4 -1
View File
@@ -44,9 +44,11 @@ The diagrams under `docs/` predate the context/service refactoring and should be
│ │ ├── MatchProperties.tsx
│ │ ├── MatchSizes.tsx
│ │ ├── ProgressBarButtons.tsx
│ │ ├── RasterManager.tsx
│ │ ├── RoundImage.tsx
│ │ ├── SwapPositions.tsx
│ │ └── commonStyles.tsx
│ │ ├── commonStyles.tsx
│ │ └── ColorSwatches.tsx
│ ├── context/
│ │ ├── SettingsContext.tsx # Slide size preset (persisted)
│ │ └── StatusContext.tsx # Status, processing, progress
@@ -54,6 +56,7 @@ The diagrams under `docs/` predate the context/service refactoring and should be
│ │ ├── cancellation.ts # Cooperative cancellation flag
│ │ ├── markers.ts # Confidential/draft markers
│ │ ├── progressBar.ts # Progress bar add/remove
│ │ ├── raster.ts # Raster geometry + slide/layout/master targets
│ │ └── titles.ts # Title collection + ranking
│ ├── types/
│ │ ├── office-types.ts # Office.js helpers
+41
View File
@@ -28,6 +28,7 @@ The sections are:
- **Draft Watermark** - Add/remove draft watermarks
- **Alignment** - Tools for aligning shapes and objects
- **Grid & Guidelines** - Grids and guidelines for the current slide
- **Raster** - Wireframe cell grids for placing objects
- **Settings** - Slide size and version information
## Content Tools
@@ -181,6 +182,46 @@ Adds horizontal or vertical guidelines at specific positions.
**Tip:** Use different colors for different types of guidelines (for example blue for margins and red for key alignment points). Guidelines are also ordinary shapes and appear in output.
## Raster
Creates a wireframe cell grid on the current slide, its layout, or the slide
master. Use it to place objects on a consistent column and row structure, then
remove it before presenting.
**Presets (16:9):**
- **12 × 8** - Coarse wireframe; cells are 26.39 × 22.06 mm.
- **24 × 16** - Fine wireframe; cells are about 12.20 × 10.03 mm.
- **Custom** - Enter your own columns, rows, gutter, and opacity.
**Place on:**
- **Current slide** - Sits on top of the current slide's content.
- **This slide's layout (background)** - Sits behind content on every slide using
the current slide's layout. This is usually the best choice for a content grid.
- **Slide master (all slides)** - Sits behind content on every slide in the
presentation.
**How to use:**
1. Navigate to a slide that uses the layout or master you want to target.
2. Choose **Place on**, then choose a preset or set **Columns**, **Rows**,
**Gutter (mm)**, and **Opacity (%)**.
3. Pick a **Color**. Gray at 100 % matches the template wireframes.
4. Click "Add raster". Any existing raster in the presentation is replaced, so
only one raster is active at a time.
5. Click "Remove raster" when you are finished. This removes the raster from the
current slide, all layouts, and the slide master.
The hint below the controls shows the resulting cell size in millimetres and the
number of cells. A raster is limited to 600 cells.
**Warning:** Raster shapes are **included in slideshow, print, and export
output**. Remove the raster before presenting. Layout and master rasters are
background graphics and are not shown on slides that use **Hide Background
Graphics**; a full-slide picture on the slide can also cover them.
**Performance:** a layout/master raster is inherited by every slide that uses
it. On long presentations, prefer the **12 × 8** preset; a 24 × 16 raster adds
384 shapes to every inherited slide.
## Settings
### Slide Size
+5
View File
@@ -17,6 +17,7 @@ import DraftButtons from "./DraftButtons";
import ProgressBarButtons from "./ProgressBarButtons";
import AlignmentButtons from "./AlignmentButtons";
import GridGuidelineManager from "./GridGuidelineManager";
import RasterManager from "./RasterManager";
import Section from "./Section";
import {
Accordion,
@@ -231,6 +232,10 @@ const App: React.FC = () => {
<GridGuidelineManager />
</Section>
<Section title="Raster" value="raster">
<RasterManager />
</Section>
<Section title="Settings" value="settings">
<Field
label="Slide size"
+110
View File
@@ -0,0 +1,110 @@
/**
* @file ColorSwatches.tsx
* @description Shared colour picker for grids, guidelines, and rasters.
*/
import * as React from "react";
import { Button, makeStyles, Text, tokens } from "@fluentui/react-components";
import { CheckmarkRegular } from "@fluentui/react-icons";
export type SwatchColor = "blue" | "red" | "yellow" | "green" | "gray";
/** Colours written to the slide. */
export const SWATCH_VALUES: Record<SwatchColor, string> = {
blue: "#4472C4",
red: "#C00000",
yellow: "#FFC000",
green: "#70AD47",
gray: "#D9D9D9",
};
const SWATCH_LABELS: Record<SwatchColor, string> = {
blue: "Blue",
red: "Red",
yellow: "Yellow",
green: "Green",
gray: "Gray",
};
const SWATCH_ORDER: readonly SwatchColor[] = ["blue", "red", "yellow", "green", "gray"];
/** Choose a check colour that stays readable on every swatch. */
const getSwatchForeground = (color: SwatchColor): string =>
color === "yellow" || color === "green" || color === "gray" ? "#000000" : "#ffffff";
const useStyles = makeStyles({
row: {
display: "flex",
alignItems: "center",
gap: tokens.spacingHorizontalS,
},
label: {
minWidth: "48px",
color: tokens.colorNeutralForeground2,
},
group: {
display: "flex",
gap: tokens.spacingHorizontalXS,
},
button: {
width: "32px",
height: "32px",
minWidth: "32px",
padding: 0,
border: `1px solid ${tokens.colorNeutralStroke1}`,
borderRadius: tokens.borderRadiusMedium,
},
selected: {
border: `2px solid ${tokens.colorBrandForeground1}`,
},
});
export interface ColorSwatchesProps {
/** Visible group label, e.g. "Color" */
label: string;
value: SwatchColor;
onChange: (color: SwatchColor) => void;
}
/**
* A labelled group of colour swatches with a check mark on the selected value.
*/
export const ColorSwatches: React.FC<ColorSwatchesProps> = ({ label, value, onChange }) => {
const styles = useStyles();
const labelId = React.useId();
return (
<div className={styles.row}>
<Text id={labelId} size={200} className={styles.label}>
{label}
</Text>
<div className={styles.group} role="group" aria-labelledby={labelId}>
{SWATCH_ORDER.map((color) => {
const selected = color === value;
return (
<Button
key={color}
appearance="subtle"
className={`${styles.button} ${selected ? styles.selected : ""}`}
style={{
backgroundColor: SWATCH_VALUES[color],
color: getSwatchForeground(color),
width: "32px",
minWidth: "32px",
height: "32px",
padding: 0,
}}
onClick={() => onChange(color)}
title={`${SWATCH_LABELS[color]} color`}
aria-label={`${SWATCH_LABELS[color]} color`}
aria-pressed={selected}
icon={selected ? <CheckmarkRegular /> : undefined}
/>
);
})}
</div>
</div>
);
};
export default ColorSwatches;
+132 -204
View File
@@ -1,31 +1,30 @@
/**
* GridGuidelineManager Component
*
*
* This component provides functionality to create and manage grids and guidelines
* on PowerPoint slides. It allows users to add customizable grids with adjustable
* spacing, opacity, and color, as well as add individual guidelines with custom
* positioning and color.
*
*
* @module GridGuidelineManager
*/
import * as React from "react";
import {
import {
Button,
Field,
Input,
makeStyles,
Text,
ToggleButton,
tokens
tokens,
} from "@fluentui/react-components";
import {
CheckmarkRegular,
import {
DismissRegular,
AddRegular,
LineHorizontal3Regular,
SplitVerticalRegular,
GridDotsRegular
GridDotsRegular,
} from "@fluentui/react-icons";
import { useStatusContext } from "../context/StatusContext";
import { useSettings } from "../context/SettingsContext";
@@ -33,6 +32,7 @@ import { deleteShapesByPrefix, getErrorMessage } from "../types/office-types";
import { SHAPE_NAME_PREFIXES } from "../constants";
import { isCancellationRequested, resetCancellation } from "../services/cancellation";
import ConfirmButton from "./ConfirmButton";
import { ColorSwatches, SwatchColor, SWATCH_VALUES } from "./ColorSwatches";
/**
* Safety limits for user-provided grid and guideline values.
@@ -52,73 +52,35 @@ const GUIDE_PREFIX = SHAPE_NAME_PREFIXES.guide;
const clamp = (value: number, min: number, max: number): number =>
Math.min(max, Math.max(min, value));
/**
* Available colors for grids and guidelines
*/
type GridColor = "blue" | "red" | "yellow" | "green";
/**
* Direction options for guidelines
*/
type GuideDirection = "horizontal" | "vertical";
/**
* Color values mapping for the available grid and guideline colors
*/
const colorValues = {
blue: "#4472C4",
red: "#C00000",
yellow: "#FFC000",
green: "#70AD47"
};
/**
* Props for the ColorButton component
*/
interface ColorButtonProps {
/** The color this button represents */
color: GridColor;
/** The currently selected color */
selectedColor: GridColor;
/** Callback function when the color is clicked */
onClick: (color: GridColor) => void;
}
const useStyles = makeStyles({
root: {
display: "flex",
flexDirection: "column",
gap: tokens.spacingVerticalM
gap: tokens.spacingVerticalM,
},
hint: {
color: tokens.colorNeutralForeground3
color: tokens.colorNeutralForeground3,
},
field: {
maxWidth: "180px"
maxWidth: "180px",
},
controlRow: {
display: "flex",
alignItems: "center",
gap: tokens.spacingHorizontalS
gap: tokens.spacingHorizontalS,
},
controlLabel: {
minWidth: "48px",
color: tokens.colorNeutralForeground2
color: tokens.colorNeutralForeground2,
},
colorGroup: {
inlineGroup: {
display: "flex",
gap: tokens.spacingHorizontalXS
},
colorButton: {
width: "32px",
height: "32px",
minWidth: "32px",
padding: 0,
border: `1px solid ${tokens.colorNeutralStroke1}`,
borderRadius: tokens.borderRadiusMedium
},
colorButtonSelected: {
border: `2px solid ${tokens.colorBrandForeground1}`
gap: tokens.spacingHorizontalXS,
},
buttonGrid: {
display: "grid",
@@ -126,12 +88,12 @@ const useStyles = makeStyles({
gap: tokens.spacingHorizontalS,
width: "100%",
"@media (max-width: 360px)": {
gridTemplateColumns: "1fr"
}
gridTemplateColumns: "1fr",
},
},
gridButton: {
width: "100%",
minWidth: 0
minWidth: 0,
},
guidesContainer: {
display: "flex",
@@ -140,58 +102,20 @@ const useStyles = makeStyles({
paddingTop: tokens.spacingVerticalM,
borderTopWidth: "1px",
borderTopStyle: "solid",
borderTopColor: tokens.colorNeutralStroke3
}
borderTopColor: tokens.colorNeutralStroke3,
},
});
/**
* Returns a check colour with sufficient contrast for each swatch.
*/
const getSwatchForeground = (color: GridColor): string =>
color === "yellow" || color === "green" ? "#000000" : "#ffffff";
/**
* ColorButton component - Renders a color selection button
*
* @param props - Component props
* @returns React component
*/
const ColorButton: React.FC<ColorButtonProps> = ({ color, selectedColor, onClick }) => {
const styles = useStyles();
const label = color.charAt(0).toUpperCase() + color.slice(1);
const selected = color === selectedColor;
return (
<Button
appearance="subtle"
className={`${styles.colorButton} ${selected ? styles.colorButtonSelected : ''}`}
style={{
backgroundColor: colorValues[color],
color: getSwatchForeground(color),
width: "32px",
minWidth: "32px",
height: "32px",
padding: 0
}}
onClick={() => onClick(color)}
title={`${label} color`}
aria-label={`${label} color`}
aria-pressed={selected}
icon={selected ? <CheckmarkRegular /> : undefined}
/>
);
};
/**
* Custom hook for handling numeric input fields
*
*
* @param initialValue - The initial value for the input
* @returns A tuple containing the current value and a change handler function
*/
type NumericInputHandler = [
number,
(e: React.ChangeEvent<HTMLInputElement>) => void,
(value: number) => void
(value: number) => void,
];
const useNumericInputHandler = (initialValue: number): NumericInputHandler => {
@@ -214,33 +138,28 @@ const useNumericInputHandler = (initialValue: number): NumericInputHandler => {
/**
* GridGuidelineManager component - Provides UI and functionality for creating
* and managing grids and guidelines on PowerPoint slides
*
*
* @returns React component
*/
export const GridGuidelineManager: React.FC = () => {
const styles = useStyles();
const { slideSize } = useSettings();
const {
setStatusMessage,
setStatusType,
isProcessing,
setIsProcessing,
setProgress
} = useStatusContext();
const { setStatusMessage, setStatusType, isProcessing, setIsProcessing, setProgress } =
useStatusContext();
// Grid state
const [gridSpacing, handleGridSpacingChange, setGridSpacing] = useNumericInputHandler(50);
const [gridColor, setGridColor] = React.useState<GridColor>("blue");
const [gridColor, setGridColor] = React.useState<SwatchColor>("blue");
const [gridOpacity, handleGridOpacityChange, setGridOpacity] = useNumericInputHandler(30);
// Guidelines state
const [guidePosition, handleGuidePositionChange, setGuidePosition] = useNumericInputHandler(240);
const [guideDirection, setGuideDirection] = React.useState<GuideDirection>("horizontal");
const [guideColor, setGuideColor] = React.useState<GridColor>("red");
const [guideColor, setGuideColor] = React.useState<SwatchColor>("red");
/**
* Creates a line shape on the slide using a thin rectangle
*
*
* @param slide - The PowerPoint slide to add the shape to
* @param startX - Starting X coordinate
* @param startY - Starting Y coordinate
@@ -248,32 +167,29 @@ export const GridGuidelineManager: React.FC = () => {
* @param endY - Ending Y coordinate
* @returns The created shape object
*/
const createLineShape = React.useCallback((
slide: PowerPoint.Slide,
startX: number,
startY: number,
endX: number,
endY: number
) => {
// Create a line using alternative approach with a rectangle shape
const line = slide.shapes.addGeometricShape("Rectangle");
if (startX === endX) {
// Vertical line
line.left = startX;
line.top = startY;
line.height = endY - startY;
line.width = 1; // Make it 1pt wide
} else {
// Horizontal line
line.left = startX;
line.top = startY;
line.width = endX - startX;
line.height = 1; // Make it 1pt tall
}
return line;
}, []);
const createLineShape = React.useCallback(
(slide: PowerPoint.Slide, startX: number, startY: number, endX: number, endY: number) => {
// Create a line using alternative approach with a rectangle shape
const line = slide.shapes.addGeometricShape("Rectangle");
if (startX === endX) {
// Vertical line
line.left = startX;
line.top = startY;
line.height = endY - startY;
line.width = 1; // Make it 1pt wide
} else {
// Horizontal line
line.left = startX;
line.top = startY;
line.width = endX - startX;
line.height = 1; // Make it 1pt tall
}
return line;
},
[]
);
/**
* Creates a grid on the current slide based on the configured settings
@@ -320,11 +236,11 @@ export const GridGuidelineManager: React.FC = () => {
const selectedSlides = context.presentation.getSelectedSlides();
selectedSlides.load("items");
await context.sync();
if (selectedSlides.items.length === 0) {
throw new Error("No slide selected");
}
const currentSlide = selectedSlides.items[0];
// Remove any existing grid on this slide inside the same request context
@@ -346,50 +262,50 @@ export const GridGuidelineManager: React.FC = () => {
const totalLines = numHorizontalLines + numVerticalLines;
let queuedLines = 0;
// Create horizontal grid lines
for (let i = 1; i <= numHorizontalLines; i++) {
if (isCancellationRequested()) break;
const yPosition = i * spacing;
// Skip if we're at the edge of the slide
if (yPosition >= slideSize.height) continue;
// Create horizontal line
const line = createLineShape(currentSlide, 0, yPosition, slideSize.width, yPosition);
line.name = `${GRID_PREFIX}h_${i}`;
// Set line properties
line.fill.setSolidColor(colorValues[gridColor]);
line.fill.setSolidColor(SWATCH_VALUES[gridColor]);
line.lineFormat.weight = 0.75; // Thin line
line.lineFormat.visible = false; // No outline, just fill
// Set transparency (opacity is inverse of transparency)
line.fill.transparency = (100 - opacity) / 100;
queuedLines++;
setProgress({ current: queuedLines, total: totalLines });
}
// Create vertical grid lines
for (let i = 1; i <= numVerticalLines; i++) {
if (isCancellationRequested()) break;
const xPosition = i * spacing;
// Skip if we're at the edge of the slide
if (xPosition >= slideSize.width) continue;
// Create vertical line
const line = createLineShape(currentSlide, xPosition, 0, xPosition, slideSize.height);
line.name = `${GRID_PREFIX}v_${i}`;
// Set line properties
line.fill.setSolidColor(colorValues[gridColor]);
line.fill.setSolidColor(SWATCH_VALUES[gridColor]);
line.lineFormat.weight = 0.75; // Thin line
line.lineFormat.visible = false; // No outline, just fill
// Set transparency (opacity is inverse of transparency)
line.fill.transparency = (100 - opacity) / 100;
@@ -413,8 +329,20 @@ export const GridGuidelineManager: React.FC = () => {
setIsProcessing(false);
setProgress(null);
}
}, [createLineShape, gridColor, gridOpacity, gridSpacing, setGridOpacity, setGridSpacing, setIsProcessing, setProgress, setStatusMessage, setStatusType, slideSize]);
}, [
createLineShape,
gridColor,
gridOpacity,
gridSpacing,
setGridOpacity,
setGridSpacing,
setIsProcessing,
setProgress,
setStatusMessage,
setStatusType,
slideSize,
]);
/**
* Removes the grid from the current slide
*/
@@ -422,34 +350,34 @@ export const GridGuidelineManager: React.FC = () => {
resetCancellation();
setProgress(null);
setIsProcessing(true);
try {
await PowerPoint.run(async (context) => {
// Get the current slide using the selected slides collection
const selectedSlides = context.presentation.getSelectedSlides();
selectedSlides.load("items");
await context.sync();
if (selectedSlides.items.length === 0) {
throw new Error("No slide selected");
}
const currentSlide = selectedSlides.items[0];
// Load all shapes on this slide
currentSlide.shapes.load("items");
await context.sync();
// Load all shape names at once
for (const shape of currentSlide.shapes.items) {
shape.load("name");
}
await context.sync();
// Delete all grid shapes and commit the changes
const removedCount = deleteShapesByPrefix(currentSlide.shapes.items, GRID_PREFIX);
await context.sync();
if (removedCount > 0) {
setStatusMessage(`Removed grid from slide`);
setStatusType("success");
@@ -493,18 +421,17 @@ export const GridGuidelineManager: React.FC = () => {
const selectedSlides = context.presentation.getSelectedSlides();
selectedSlides.load("items");
await context.sync();
if (selectedSlides.items.length === 0) {
throw new Error("No slide selected");
}
const currentSlide = selectedSlides.items[0];
// Create a unique identifier for this guide
const timestamp = new Date().getTime();
const guideId = `${GUIDE_PREFIX}${guideDirection}_${timestamp}`;
// Add the guide line
let line: PowerPoint.Shape;
if (guideDirection === "horizontal") {
@@ -514,16 +441,16 @@ export const GridGuidelineManager: React.FC = () => {
// Create vertical guideline
line = createLineShape(currentSlide, position, 0, position, slideSize.height);
}
line.name = guideId;
// Set line properties
line.fill.setSolidColor(colorValues[guideColor]);
line.fill.setSolidColor(SWATCH_VALUES[guideColor]);
line.lineFormat.visible = false; // No outline, just fill
// We want solid lines for guidelines
line.fill.transparency = 0;
setStatusMessage(`Added ${guideDirection} guideline`);
setStatusType("success");
});
@@ -535,8 +462,19 @@ export const GridGuidelineManager: React.FC = () => {
setIsProcessing(false);
setProgress(null);
}
}, [createLineShape, guideColor, guideDirection, guidePosition, setGuidePosition, setIsProcessing, setProgress, setStatusMessage, setStatusType, slideSize]);
}, [
createLineShape,
guideColor,
guideDirection,
guidePosition,
setGuidePosition,
setIsProcessing,
setProgress,
setStatusMessage,
setStatusType,
slideSize,
]);
/**
* Removes all guidelines from the current slide
*/
@@ -550,27 +488,27 @@ export const GridGuidelineManager: React.FC = () => {
const selectedSlides = context.presentation.getSelectedSlides();
selectedSlides.load("items");
await context.sync();
if (selectedSlides.items.length === 0) {
throw new Error("No slide selected");
}
const currentSlide = selectedSlides.items[0];
// Load all shapes on this slide
currentSlide.shapes.load("items");
await context.sync();
// Load all shape names at once
for (const shape of currentSlide.shapes.items) {
shape.load("name");
}
await context.sync();
// Delete all guideline shapes and commit the changes
const removedCount = deleteShapesByPrefix(currentSlide.shapes.items, GUIDE_PREFIX);
await context.sync();
if (removedCount > 0) {
setStatusMessage(`Removed ${removedCount} guidelines`);
setStatusType("success");
@@ -591,7 +529,9 @@ export const GridGuidelineManager: React.FC = () => {
return (
<div className={styles.root}>
<Text size={400} weight="semibold">Grid</Text>
<Text size={400} weight="semibold">
Grid
</Text>
<Text size={200} className={styles.hint}>
Grid lines are slide shapes and appear in slideshows and exports.
</Text>
@@ -618,21 +558,13 @@ export const GridGuidelineManager: React.FC = () => {
/>
</Field>
<div className={styles.controlRow}>
<Text id="grid-color-label" size={200} className={styles.controlLabel}>Color</Text>
<div className={styles.colorGroup} role="group" aria-labelledby="grid-color-label">
<ColorButton color="blue" selectedColor={gridColor} onClick={setGridColor} />
<ColorButton color="red" selectedColor={gridColor} onClick={setGridColor} />
<ColorButton color="yellow" selectedColor={gridColor} onClick={setGridColor} />
<ColorButton color="green" selectedColor={gridColor} onClick={setGridColor} />
</div>
</div>
<ColorSwatches label="Color" value={gridColor} onChange={setGridColor} />
<div className={styles.buttonGrid}>
<Button
appearance="primary"
<Button
appearance="primary"
className={styles.gridButton}
onClick={createGrid}
onClick={createGrid}
icon={<GridDotsRegular />}
disabled={isProcessing}
title="Add grid"
@@ -656,7 +588,9 @@ export const GridGuidelineManager: React.FC = () => {
{/* Guidelines Section */}
<div className={styles.guidesContainer}>
<Text size={400} weight="semibold">Guidelines</Text>
<Text size={400} weight="semibold">
Guidelines
</Text>
<Field label="Position (pt)" className={styles.field}>
<Input
@@ -670,8 +604,10 @@ export const GridGuidelineManager: React.FC = () => {
</Field>
<div className={styles.controlRow}>
<Text id="guide-direction-label" size={200} className={styles.controlLabel}>Type</Text>
<div className={styles.colorGroup} role="group" aria-labelledby="guide-direction-label">
<Text id="guide-direction-label" size={200} className={styles.controlLabel}>
Type
</Text>
<div className={styles.inlineGroup} role="group" aria-labelledby="guide-direction-label">
<ToggleButton
size="small"
appearance="outline"
@@ -693,21 +629,13 @@ export const GridGuidelineManager: React.FC = () => {
</div>
</div>
<div className={styles.controlRow}>
<Text id="guide-color-label" size={200} className={styles.controlLabel}>Color</Text>
<div className={styles.colorGroup} role="group" aria-labelledby="guide-color-label">
<ColorButton color="blue" selectedColor={guideColor} onClick={setGuideColor} />
<ColorButton color="red" selectedColor={guideColor} onClick={setGuideColor} />
<ColorButton color="yellow" selectedColor={guideColor} onClick={setGuideColor} />
<ColorButton color="green" selectedColor={guideColor} onClick={setGuideColor} />
</div>
</div>
<ColorSwatches label="Color" value={guideColor} onChange={setGuideColor} />
<div className={styles.buttonGrid}>
<Button
appearance="primary"
<Button
appearance="primary"
className={styles.gridButton}
onClick={addGuideline}
onClick={addGuideline}
icon={<AddRegular />}
disabled={isProcessing}
title="Add guideline"
+361
View File
@@ -0,0 +1,361 @@
/**
* @file RasterManager.tsx
* @description Adds and removes a wireframe cell raster on the current slide.
*/
import * as React from "react";
import {
Button,
Dropdown,
Field,
Input,
makeStyles,
Option,
Text,
tokens,
} from "@fluentui/react-components";
import { DismissRegular, GridDotsRegular } from "@fluentui/react-icons";
import { useStatusContext } from "../context/StatusContext";
import { useSettings } from "../context/SettingsContext";
import { useCommonStyles } from "./commonStyles";
import { getErrorMessage } from "../types/office-types";
import {
RASTER_DEFAULT_GUTTER_MM,
RASTER_DEFAULT_OPACITY,
RASTER_PRESETS,
RASTER_SCOPE_LABELS,
RasterPresetId,
RasterScope,
} from "../constants";
import {
addRasterCells,
computeRasterLayout,
formatMillimeters,
getRasterTarget,
removeAllRasters,
} from "../services/raster";
import { isCancellationRequested, resetCancellation } from "../services/cancellation";
import { ColorSwatches, SwatchColor, SWATCH_VALUES } from "./ColorSwatches";
import ConfirmButton from "./ConfirmButton";
const useStyles = makeStyles({
root: {
display: "flex",
flexDirection: "column",
gap: tokens.spacingVerticalM,
},
control: {
width: "100%",
},
twoColumn: {
display: "grid",
gridTemplateColumns: "repeat(2, minmax(0, 1fr))",
gap: tokens.spacingHorizontalS,
"@media (max-width: 360px)": {
gridTemplateColumns: "1fr",
},
},
});
const parseInteger = (value: string): number => Number.parseInt(value, 10);
const parseDecimal = (value: string): number => Number.parseFloat(value);
/** PowerPoint shape coordinates use points. */
const MILLIMETERS_TO_POINTS = 72 / 25.4;
export const RasterManager: React.FC = () => {
const styles = useStyles();
const commonStyles = useCommonStyles();
const { slideSize } = useSettings();
const { setStatusMessage, setStatusType, isProcessing, setIsProcessing, setProgress } =
useStatusContext();
const [preset, setPreset] = React.useState<RasterPresetId>("coarse");
const [scope, setScope] = React.useState<RasterScope>("slide");
const [columnsInput, setColumnsInput] = React.useState("12");
const [rowsInput, setRowsInput] = React.useState("8");
const [gutterInput, setGutterInput] = React.useState(String(RASTER_DEFAULT_GUTTER_MM));
const [opacityInput, setOpacityInput] = React.useState(String(RASTER_DEFAULT_OPACITY));
const [color, setColor] = React.useState<SwatchColor>("gray");
const layoutResult = React.useMemo(
() =>
computeRasterLayout({
columns: parseInteger(columnsInput),
rows: parseInteger(rowsInput),
gutter: parseDecimal(gutterInput) * MILLIMETERS_TO_POINTS,
slideWidth: slideSize.width,
slideHeight: slideSize.height,
}),
[columnsInput, rowsInput, gutterInput, slideSize.height, slideSize.width]
);
const opacity = parseDecimal(opacityInput);
const opacityValid = Number.isFinite(opacity) && opacity >= 0 && opacity <= 100;
const layout = layoutResult.ok ? layoutResult.layout : null;
const canAdd = layout !== null && opacityValid;
const presetLabel =
preset === "custom"
? "Custom"
: (RASTER_PRESETS.find((item) => item.id === preset)?.label ?? "Custom");
const scopeHint =
scope === "slide"
? "Sits on top of the current slide's content."
: scope === "layout"
? "Background: appears on every slide using this layout."
: "Background: appears on every slide in the presentation.";
const scopeTarget =
scope === "slide"
? "the current slide"
: scope === "layout"
? "this slide's layout"
: "the slide master";
const hint = !layoutResult.ok
? layoutResult.error
: !opacityValid
? "Opacity must be between 0 and 100."
: `Cell size: ${formatMillimeters(layoutResult.layout.cellWidth)} × ${formatMillimeters(layoutResult.layout.cellHeight)} mm · ${layoutResult.layout.total} cells`;
const handlePreset = (nextPreset: RasterPresetId): void => {
setPreset(nextPreset);
if (nextPreset === "custom") return;
const selected = RASTER_PRESETS.find((item) => item.id === nextPreset);
if (!selected) return;
setColumnsInput(String(selected.columns));
setRowsInput(String(selected.rows));
setGutterInput(String(RASTER_DEFAULT_GUTTER_MM));
};
const updateGeometryNumber =
(setter: React.Dispatch<React.SetStateAction<string>>) =>
(event: React.ChangeEvent<HTMLInputElement>): void => {
setter(event.target.value);
setPreset("custom");
};
const updateOpacity = (event: React.ChangeEvent<HTMLInputElement>): void => {
setOpacityInput(event.target.value);
};
const addRasterToSlide = async (): Promise<void> => {
if (!layoutResult.ok) {
setStatusMessage(layoutResult.error);
setStatusType("warning");
return;
}
if (!opacityValid) {
setStatusMessage("Opacity must be between 0 and 100.");
setStatusType("warning");
return;
}
resetCancellation();
setProgress(null);
setIsProcessing(true);
try {
await PowerPoint.run(async (context) => {
const selectedSlides = context.presentation.getSelectedSlides();
selectedSlides.load("items");
await context.sync();
if (selectedSlides.items.length === 0) {
setStatusMessage("No slide selected.");
setStatusType("warning");
return;
}
const slide = selectedSlides.items[0];
const target = await getRasterTarget(context, slide, scope);
// Keep one raster in the presentation: clear the current slide, all
// layouts, and the slide master before adding the new one.
await removeAllRasters(context);
const result = await addRasterCells(
context,
target,
layoutResult.layout,
SWATCH_VALUES[color],
opacity,
(current, total) => setProgress({ current, total })
);
if (isCancellationRequested() || result.cancelled) {
setStatusMessage("Operation cancelled.");
setStatusType("warning");
return;
}
setStatusMessage(
`Added ${layoutResult.layout.columns} × ${layoutResult.layout.rows} raster (${result.created} cells) to ${scopeTarget}.`
);
setStatusType("success");
});
} catch (error: unknown) {
setStatusMessage(`Error: ${getErrorMessage(error)}`);
setStatusType("error");
console.error("Add raster error:", error);
} finally {
setIsProcessing(false);
setProgress(null);
}
};
const removeRasterFromSlide = async (): Promise<void> => {
resetCancellation();
setProgress(null);
setIsProcessing(true);
try {
await PowerPoint.run(async (context) => {
const result = await removeAllRasters(context);
if (result.removed > 0) {
setStatusMessage(`Removed ${result.removed} raster cells from the presentation.`);
setStatusType("success");
} else {
setStatusMessage("No raster found in the presentation.");
setStatusType("warning");
}
});
} catch (error: unknown) {
setStatusMessage(`Error: ${getErrorMessage(error)}`);
setStatusType("error");
console.error("Remove raster error:", error);
} finally {
setIsProcessing(false);
setProgress(null);
}
};
return (
<div className={styles.root}>
<Text size={200} className={commonStyles.hint}>
Adds a wireframe cell raster for object placement. Remove it before presenting.
</Text>
<Field label="Place on" hint={scopeHint}>
<Dropdown
className={styles.control}
value={RASTER_SCOPE_LABELS[scope]}
selectedOptions={[scope]}
onOptionSelect={(_, data) => {
if (data.optionValue) {
setScope(data.optionValue as RasterScope);
}
}}
>
<Option value="slide">{RASTER_SCOPE_LABELS.slide}</Option>
<Option value="layout">{RASTER_SCOPE_LABELS.layout}</Option>
<Option value="master">{RASTER_SCOPE_LABELS.master}</Option>
</Dropdown>
</Field>
<Field label="Preset">
<Dropdown
className={styles.control}
value={presetLabel}
selectedOptions={[preset]}
onOptionSelect={(_, data) => {
if (data.optionValue) {
handlePreset(data.optionValue as RasterPresetId);
}
}}
>
{RASTER_PRESETS.map((item) => (
<Option key={item.id} value={item.id}>
{item.label}
</Option>
))}
<Option value="custom">Custom</Option>
</Dropdown>
</Field>
<div className={styles.twoColumn}>
<Field label="Columns">
<Input
type="number"
min={1}
max={48}
value={columnsInput}
onChange={updateGeometryNumber(setColumnsInput)}
title="Number of raster columns"
/>
</Field>
<Field label="Rows">
<Input
type="number"
min={1}
max={32}
value={rowsInput}
onChange={updateGeometryNumber(setRowsInput)}
title="Number of raster rows"
/>
</Field>
</div>
<div className={styles.twoColumn}>
<Field label="Gutter (mm)">
<Input
type="number"
min={0}
step="0.1"
value={gutterInput}
onChange={updateGeometryNumber(setGutterInput)}
title="Space between raster cells in millimetres"
/>
</Field>
<Field label="Opacity (%)">
<Input
type="number"
min={0}
max={100}
value={opacityInput}
onChange={updateOpacity}
title="Raster cell opacity percentage"
/>
</Field>
</div>
<ColorSwatches label="Color" value={color} onChange={setColor} />
<Text size={200} className={commonStyles.hint}>
{hint}
</Text>
<div className={commonStyles.buttonGroup}>
<Button
appearance="primary"
icon={<GridDotsRegular />}
onClick={addRasterToSlide}
disabled={isProcessing || !canAdd}
title="Add raster"
>
Add raster
</Button>
<ConfirmButton
appearance="primary"
icon={<DismissRegular />}
onConfirm={removeRasterFromSlide}
disabled={isProcessing}
title="Remove raster"
confirmTitle="Remove raster?"
confirmMessage="This removes the raster from every slide, layout, and slide master in the presentation."
confirmLabel="Remove"
>
Remove raster
</ConfirmButton>
</div>
</div>
);
};
export default RasterManager;
+33
View File
@@ -31,4 +31,37 @@ export const SHAPE_NAME_PREFIXES = {
progressBar: "progress_bar_",
grid: "edison_grid_",
guide: "edison_guide_",
raster: "edison_raster_",
} as const;
/**
* Raster (wireframe cell grid) defaults.
*
* A 2 mm gutter reproduces the 12 × 8 and 24 × 16 wireframes from the
* design template at 16:9.
*/
export const RASTER_DEFAULT_GUTTER_MM = 2;
export const RASTER_DEFAULT_OPACITY = 30;
export const RASTER_MAX_CELLS = 600;
export type RasterPresetId = "coarse" | "fine" | "custom";
export type RasterScope = "slide" | "layout" | "master";
export const RASTER_SCOPE_LABELS: Record<RasterScope, string> = {
slide: "Current slide",
layout: "This layout (background)",
master: "Slide master (all slides)",
};
export interface RasterPreset {
id: Exclude<RasterPresetId, "custom">;
label: string;
columns: number;
rows: number;
}
export const RASTER_PRESETS: readonly RasterPreset[] = [
{ id: "coarse", label: "12 × 8", columns: 12, rows: 8 },
{ id: "fine", label: "24 × 16", columns: 24, rows: 16 },
];
+129
View File
@@ -0,0 +1,129 @@
import { describe, expect, it } from "vitest";
import { computeRasterLayout, formatMillimeters, type RasterLayout } from "./raster";
import { RASTER_DEFAULT_GUTTER_MM, RASTER_MAX_CELLS } from "../constants";
const GUTTER = (RASTER_DEFAULT_GUTTER_MM * 72) / 25.4;
const mm = (points: number): number => (points * 25.4) / 72;
/** Narrow the result or fail the test with the returned error. */
const layoutOf = (result: ReturnType<typeof computeRasterLayout>): RasterLayout => {
if (!result.ok) {
throw new Error(result.error);
}
return result.layout;
};
describe("computeRasterLayout", () => {
it("reproduces the 12 × 8 wireframe", () => {
const layout = layoutOf(
computeRasterLayout({
columns: 12,
rows: 8,
gutter: GUTTER,
slideWidth: 960,
slideHeight: 540,
})
);
expect(layout.total).toBe(96);
expect(mm(layout.cellWidth)).toBeCloseTo(26.39, 2);
expect(mm(layout.cellHeight)).toBeCloseTo(22.06, 2);
const last = layout.cells[layout.cells.length - 1];
expect(last.left + last.width).toBeCloseTo(960, 6);
expect(last.top + last.height).toBeCloseTo(540, 6);
});
it("reproduces the 24 × 16 wireframe", () => {
const layout = layoutOf(
computeRasterLayout({
columns: 24,
rows: 16,
gutter: GUTTER,
slideWidth: 960,
slideHeight: 540,
})
);
expect(layout.total).toBe(384);
// A round 2 mm gutter lands within 0.01 mm of the template's 12.20 mm.
expect(Math.abs(mm(layout.cellWidth) - 12.2)).toBeLessThan(0.01);
expect(mm(layout.cellHeight)).toBeCloseTo(10.03, 2);
const last = layout.cells[layout.cells.length - 1];
expect(last.left + last.width).toBeCloseTo(960, 6);
expect(last.top + last.height).toBeCloseTo(540, 6);
});
it("fills a 4:3 slide", () => {
const layout = layoutOf(
computeRasterLayout({
columns: 12,
rows: 8,
gutter: GUTTER,
slideWidth: 720,
slideHeight: 540,
})
);
const last = layout.cells[layout.cells.length - 1];
expect(last.left + last.width).toBeCloseTo(720, 6);
expect(last.top + last.height).toBeCloseTo(540, 6);
});
it("handles a single cell without a gutter", () => {
const layout = layoutOf(
computeRasterLayout({
columns: 1,
rows: 1,
gutter: 0,
slideWidth: 960,
slideHeight: 540,
})
);
expect(layout.cellWidth).toBe(960);
expect(layout.cellHeight).toBe(540);
expect(layout.cells).toHaveLength(1);
});
it("rejects invalid columns, rows, and gutters", () => {
const base = { columns: 12, rows: 8, gutter: GUTTER, slideWidth: 960, slideHeight: 540 };
expect(computeRasterLayout({ ...base, columns: 0 }).ok).toBe(false);
expect(computeRasterLayout({ ...base, rows: -1 }).ok).toBe(false);
expect(computeRasterLayout({ ...base, gutter: -1 }).ok).toBe(false);
});
it("rejects rasters over the cell limit", () => {
const result = computeRasterLayout({
columns: 30,
rows: 21,
gutter: 2,
slideWidth: 960,
slideHeight: 540,
});
expect(30 * 21).toBeGreaterThan(RASTER_MAX_CELLS);
expect(result.ok).toBe(false);
});
it("rejects a gutter that leaves no room for cells", () => {
const result = computeRasterLayout({
columns: 12,
rows: 8,
gutter: 100,
slideWidth: 960,
slideHeight: 540,
});
expect(result.ok).toBe(false);
});
});
describe("formatMillimeters", () => {
it("converts points to millimetres", () => {
expect(formatMillimeters(72)).toBe("25.40");
});
});
+275
View File
@@ -0,0 +1,275 @@
/* global PowerPoint */
/**
* @file raster.ts
* @description Wireframe cell-grid ("raster") geometry and PowerPoint operations.
*
* A raster is a columns × rows grid of rectangles that fills the current slide.
* It is used as a temporary placement aid, similar to grids and guidelines.
*/
import { RASTER_MAX_CELLS, SHAPE_NAME_PREFIXES, RasterScope } from "../constants";
import { deleteShapesByPrefix } from "../types/office-types";
import { isCancellationRequested } from "./cancellation";
export const RASTER_PREFIX = SHAPE_NAME_PREFIXES.raster;
/** Smallest allowed cell edge, in points. */
const MIN_CELL_SIZE = 1;
export interface RasterLayoutOptions {
columns: number;
rows: number;
/** Space between cells, in points. */
gutter: number;
/** Slide width in points. */
slideWidth: number;
/** Slide height in points. */
slideHeight: number;
}
export interface RasterCell {
column: number;
row: number;
left: number;
top: number;
width: number;
height: number;
}
export interface RasterLayout {
columns: number;
rows: number;
cellWidth: number;
cellHeight: number;
total: number;
cells: RasterCell[];
}
export type RasterLayoutResult = { ok: true; layout: RasterLayout } | { ok: false; error: string };
/**
* Converts points to millimetres for display.
*/
export const formatMillimeters = (points: number): string => ((points * 25.4) / 72).toFixed(2);
/**
* Computes the rectangles for a raster that fills the slide.
*
* Cells are evenly sized; the leftover space is distributed into the gutters.
*/
export function computeRasterLayout(options: RasterLayoutOptions): RasterLayoutResult {
const { columns, rows, gutter, slideWidth, slideHeight } = options;
if (!Number.isInteger(columns) || columns < 1) {
return { ok: false, error: "Columns must be at least 1." };
}
if (!Number.isInteger(rows) || rows < 1) {
return { ok: false, error: "Rows must be at least 1." };
}
if (!Number.isFinite(gutter) || gutter < 0) {
return { ok: false, error: "Gutter must be 0 or greater." };
}
if (
!Number.isFinite(slideWidth) ||
!Number.isFinite(slideHeight) ||
slideWidth <= 0 ||
slideHeight <= 0
) {
return { ok: false, error: "Slide size is not available." };
}
const total = columns * rows;
if (total > RASTER_MAX_CELLS) {
return {
ok: false,
error: `A ${columns} × ${rows} raster creates ${total} cells. The maximum is ${RASTER_MAX_CELLS}; reduce columns or rows.`,
};
}
const cellWidth = (slideWidth - (columns - 1) * gutter) / columns;
const cellHeight = (slideHeight - (rows - 1) * gutter) / rows;
if (cellWidth < MIN_CELL_SIZE || cellHeight < MIN_CELL_SIZE) {
return {
ok: false,
error: "The gutter is too large for this number of columns or rows.",
};
}
const cells: RasterCell[] = [];
for (let row = 0; row < rows; row++) {
for (let column = 0; column < columns; column++) {
cells.push({
column,
row,
left: column * (cellWidth + gutter),
top: row * (cellHeight + gutter),
width: cellWidth,
height: cellHeight,
});
}
}
return {
ok: true,
layout: { columns, rows, cellWidth, cellHeight, total, cells },
};
}
export interface AddRasterResult {
created: number;
cancelled: boolean;
}
/**
* Adds the raster cells to any shape collection (slide, layout, or master).
* Existing raster shapes should be removed by the caller before this runs.
*/
export async function addRasterCells(
context: PowerPoint.RequestContext,
shapes: PowerPoint.ShapeCollection,
layout: RasterLayout,
color: string,
opacity: number,
onProgress: (current: number, total: number) => void
): Promise<AddRasterResult> {
const clampedOpacity = Math.min(100, Math.max(0, opacity));
const transparency = (100 - clampedOpacity) / 100;
const created: PowerPoint.Shape[] = [];
let cancelled = false;
try {
for (const cell of layout.cells) {
if (isCancellationRequested()) {
cancelled = true;
break;
}
const shape = shapes.addGeometricShape("Rectangle", {
left: cell.left,
top: cell.top,
width: cell.width,
height: cell.height,
});
shape.name = `${RASTER_PREFIX}c${cell.column}_r${cell.row}`;
shape.fill.setSolidColor(color);
shape.fill.transparency = transparency;
shape.lineFormat.visible = false;
created.push(shape);
onProgress(created.length, layout.total);
}
} catch (error: unknown) {
// Do not leave a partial raster behind if the host rejects a shape.
for (const shape of created) {
shape.delete();
}
await context.sync();
throw error;
}
if (cancelled) {
// Leave no partial raster behind.
for (const shape of created) {
shape.delete();
}
await context.sync();
return { created: 0, cancelled: true };
}
await context.sync();
return { created: created.length, cancelled: false };
}
/**
* Resolves the shape collection for the requested raster scope.
*/
export async function getRasterTarget(
context: PowerPoint.RequestContext,
slide: PowerPoint.Slide,
scope: RasterScope
): Promise<PowerPoint.ShapeCollection> {
if (scope === "layout") {
slide.load("layout");
await context.sync();
return slide.layout.shapes;
}
if (scope === "master") {
slide.load("slideMaster");
await context.sync();
return slide.slideMaster.shapes;
}
return slide.shapes;
}
/**
* Loads every shape collection that can contain a raster: all slides, all
* layouts, and all slide masters. Names are loaded so callers can filter.
*/
async function loadRasterCollections(
context: PowerPoint.RequestContext
): Promise<PowerPoint.ShapeCollection[]> {
const slides = context.presentation.slides;
const masters = context.presentation.slideMasters;
slides.load("items");
masters.load("items");
await context.sync();
const collections: PowerPoint.ShapeCollection[] = [];
for (const slide of slides.items) {
collections.push(slide.shapes);
}
for (const master of masters.items) {
master.layouts.load("items");
collections.push(master.shapes);
}
await context.sync();
for (const master of masters.items) {
for (const layout of master.layouts.items) {
collections.push(layout.shapes);
}
}
for (const collection of collections) {
collection.load("items");
}
await context.sync();
for (const collection of collections) {
for (const shape of collection.items) {
shape.load("name");
}
}
await context.sync();
return collections;
}
/**
* Removes raster cells from every slide, layout, and slide master.
*
* The raster tool keeps one raster in the presentation, so cleanup is global
* regardless of the selected scope.
*/
export async function removeAllRasters(
context: PowerPoint.RequestContext
): Promise<{ removed: number }> {
const collections = await loadRasterCollections(context);
let removed = 0;
for (const collection of collections) {
removed += deleteShapesByPrefix(collection.items, RASTER_PREFIX);
}
await context.sync();
return { removed };
}