Batch slide operations, make adds idempotent, and add confirmations

- Replace per-slide sync loops in confidential, draft, progress bar, and grid operations
- Use addTextBox options and batch loads; remove the nested PowerPoint.run in grid creation
- Replace O(n^2) progress segments with two rectangles per slide and apply to all slides
- Rewrite Insert Titles with batched loads and a pure title ranking function
- Delete existing marks before adding so repeated clicks replace instead of duplicate
- Report a warning when there is nothing to remove
- Add ConfirmButton and confirmation support to ActionButton
This commit is contained in:
schihei committed 2026-11-25 11:51:04 +01:00
1 parent 791cbc7b6c
commit e57258afe9
8 files changed
+616 -711

No files matched your search

+34 -3
View File
@@ -3,6 +3,7 @@ import { Button, ButtonProps } from "@fluentui/react-components";
import { useStatusContext } from "./App";
import { useCommonStyles } from "./commonStyles";
import { getErrorMessage } from "../types/office-types";
import ConfirmButton from "./ConfirmButton";
export interface ActionButtonProps {
icon: ButtonProps["icon"];
@@ -11,6 +12,12 @@ export interface ActionButtonProps {
title: string;
appearance?: "primary" | "secondary" | "outline" | "subtle";
className?: string;
/** When set, asks for confirmation before running the action */
confirmTitle?: string;
/** Message shown in the confirmation dialog */
confirmMessage?: string;
/** Label for the confirm action */
confirmLabel?: string;
}
/**
@@ -23,6 +30,9 @@ export const ActionButton: React.FC<ActionButtonProps> = ({
title,
appearance = "primary",
className = "",
confirmTitle,
confirmMessage,
confirmLabel,
}) => {
const styles = useCommonStyles();
const {
@@ -48,17 +58,38 @@ export const ActionButton: React.FC<ActionButtonProps> = ({
}
};
const buttonClassName = `${styles.actionButton} ${className}`;
const isDisabled = disabled || isProcessing;
if (confirmMessage) {
return (
<ConfirmButton
title={title}
icon={icon}
appearance={appearance}
className={buttonClassName}
disabled={isDisabled}
confirmTitle={confirmTitle ?? title}
confirmMessage={confirmMessage}
confirmLabel={confirmLabel}
onConfirm={handleClick}
>
{title}
</ConfirmButton>
);
}
return (
<Button
appearance={appearance}
className={`${styles.actionButton} ${className}`}
className={buttonClassName}
onClick={handleClick}
icon={icon}
disabled={disabled || isProcessing}
disabled={isDisabled}
>
{title}
</Button>
);
};
export default ActionButton;
export default ActionButton;
+72 -96
View File
@@ -16,6 +16,7 @@ import {
import { useStatusContext } from "./App";
import { useCommonStyles } from "./commonStyles";
import { getErrorMessage } from "../types/office-types";
import ConfirmButton from "./ConfirmButton";
/**
* Configuration constants for confidential markings
@@ -172,61 +173,50 @@ export const ConfidentialButtons: React.FC = () => {
};
const { WIDTH, HEIGHT } = CONFIDENTIAL_CONFIG.SLIDE;
const slideWidth = WIDTH;
const slideHeight = HEIGHT;
const positionFromTop = HEIGHT - CONFIDENTIAL_CONFIG.TEXT_BOX.POSITION_FROM_BOTTOM;
// Process each slide
for (let i = 0; i < slides.length; i++) {
try {
const slide = slides[i];
const positionFromTop = slideHeight - CONFIDENTIAL_CONFIG.TEXT_BOX.POSITION_FROM_BOTTOM;
// Create the textbox spanning the full width of the slide
const textBox = slide.shapes.addTextBox("");
textBox.left = 0; // Start from left edge
textBox.top = positionFromTop;
textBox.width = slideWidth;
textBox.height = CONFIDENTIAL_CONFIG.TEXT_BOX.HEIGHT;
textBox.name = CONFIDENTIAL_CONFIG.SHAPE_NAME;
// Load textFrame and its properties in a single batch
textBox.load("textFrame");
await context.sync();
if (textBox.textFrame) {
// Load textRange and its properties
textBox.textFrame.load("textRange");
await context.sync();
// Set text and formatting in a single batch
textBox.textFrame.textRange.text = CONFIDENTIAL_CONFIG.TEXT;
textBox.textFrame.textRange.load("font,paragraphFormat");
await context.sync();
try {
// Apply font properties in a single batch
const font = textBox.textFrame.textRange.font;
font.name = CONFIDENTIAL_CONFIG.FONT.NAME;
font.size = CONFIDENTIAL_CONFIG.FONT.SIZE;
font.color = CONFIDENTIAL_CONFIG.FONT.COLOR;
textBox.textFrame.textRange.paragraphFormat.horizontalAlignment = "Center";
await context.sync();
result.affectedCount++;
} catch (fontError) {
console.error("Error setting font properties:", fontError);
// Continue with default font if custom font fails
}
}
result.processedSlides++;
} catch (slideError) {
console.error(`Error processing slide ${i+1}:`, slideError);
result.errorSlides++;
// Continue to the next slide
// Load the shapes and names for every slide in two batches instead of two syncs per slide
for (const slide of slides) {
slide.shapes.load("items");
}
await context.sync();
const shapesBySlide: PowerPoint.Shape[][] = [];
for (const slide of slides) {
shapesBySlide.push(slide.shapes.items);
for (const shape of slide.shapes.items) {
shape.load("name");
}
}
await context.sync();
// Replace any existing marking so repeated clicks do not duplicate it
for (const shapes of shapesBySlide) {
for (const shape of shapes) {
if (shape.name === CONFIDENTIAL_CONFIG.SHAPE_NAME) {
shape.delete();
}
}
}
// Create one marking per slide in a single batch
for (const slide of slides) {
const textBox = slide.shapes.addTextBox(CONFIDENTIAL_CONFIG.TEXT, {
left: 0,
top: positionFromTop,
width: WIDTH,
height: CONFIDENTIAL_CONFIG.TEXT_BOX.HEIGHT
});
textBox.name = CONFIDENTIAL_CONFIG.SHAPE_NAME;
textBox.textFrame.textRange.font.name = CONFIDENTIAL_CONFIG.FONT.NAME;
textBox.textFrame.textRange.font.size = CONFIDENTIAL_CONFIG.FONT.SIZE;
textBox.textFrame.textRange.font.color = CONFIDENTIAL_CONFIG.FONT.COLOR;
textBox.textFrame.textRange.paragraphFormat.horizontalAlignment = "Center";
result.processedSlides++;
}
await context.sync();
result.affectedCount = slides.length;
return result;
};
@@ -275,48 +265,31 @@ export const ConfidentialButtons: React.FC = () => {
affectedCount: 0
};
// Process each slide
for (let i = 0; i < slides.length; i++) {
try {
const slide = slides[i];
// Load all shapes on the slide
slide.shapes.load("items");
await context.sync();
// Collect shapes to delete
const shapesToDelete: PowerPoint.Shape[] = [];
// Find shapes with the confidential marking name
for (let j = 0; j < slide.shapes.items.length; j++) {
const shape = slide.shapes.items[j];
shape.load("name");
}
// Wait for all shape names to load
await context.sync();
// Now check names and collect shapes to delete
for (let j = 0; j < slide.shapes.items.length; j++) {
const shape = slide.shapes.items[j];
if (shape.name === CONFIDENTIAL_CONFIG.SHAPE_NAME) {
shapesToDelete.push(shape);
}
}
// Delete all matching shapes in one batch
shapesToDelete.forEach(shape => shape.delete());
result.affectedCount += shapesToDelete.length;
await context.sync();
result.processedSlides++;
} catch (slideError) {
console.error(`Error processing slide ${i+1}:`, slideError);
result.errorSlides++;
// Continue to the next slide
// Load the shapes and names for every slide in two batches
for (const slide of slides) {
slide.shapes.load("items");
}
await context.sync();
const allShapes: PowerPoint.Shape[] = [];
for (const slide of slides) {
for (const shape of slide.shapes.items) {
shape.load("name");
allShapes.push(shape);
}
}
await context.sync();
// Delete all matching shapes in one batch
for (const shape of allShapes) {
if (shape.name === CONFIDENTIAL_CONFIG.SHAPE_NAME) {
shape.delete();
result.affectedCount++;
}
}
await context.sync();
result.processedSlides = slides.length;
return result;
};
@@ -333,16 +306,19 @@ export const ConfidentialButtons: React.FC = () => {
>
Add
</Button>
<Button
appearance="primary"
<ConfirmButton
appearance="primary"
className={styles.confidentialButton}
onClick={removeConfidentialMarking}
onConfirm={removeConfidentialMarking}
icon={<DismissRegular />}
disabled={isProcessing}
title="Remove Confidential"
confirmTitle="Remove confidential markings?"
confirmMessage="This removes the confidential marking from every slide in the presentation."
confirmLabel="Remove"
>
Remove
</Button>
</ConfirmButton>
</div>
</div>
);
+91
View File
@@ -0,0 +1,91 @@
/**
* @file ConfirmButton.tsx
* @description Reusable button that asks for confirmation before running
* destructive actions such as removing marks or watermarks from a presentation.
*/
import * as React from "react";
import {
Button,
ButtonProps,
Dialog,
DialogActions,
DialogBody,
DialogContent,
DialogSurface,
DialogTitle,
} from "@fluentui/react-components";
export interface ConfirmButtonProps {
/** Tooltip and accessible label for the trigger button */
title: string;
icon: ButtonProps["icon"];
/** Visible label for the trigger button */
children: React.ReactNode;
/** Title shown in the confirmation dialog */
confirmTitle: string;
/** Explanation shown in the confirmation dialog */
confirmMessage: string;
/** Label for the confirm action */
confirmLabel?: string;
appearance?: ButtonProps["appearance"];
className?: string;
disabled?: boolean;
onConfirm: () => void | Promise<void>;
}
/**
* Button that opens a confirmation dialog before invoking `onConfirm`.
*/
export const ConfirmButton: React.FC<ConfirmButtonProps> = ({
title,
icon,
children,
confirmTitle,
confirmMessage,
confirmLabel = "Remove",
appearance = "primary",
className = "",
disabled = false,
onConfirm,
}) => {
const [isOpen, setIsOpen] = React.useState(false);
const handleConfirm = async (): Promise<void> => {
setIsOpen(false);
await onConfirm();
};
return (
<>
<Button
appearance={appearance}
className={className}
disabled={disabled}
icon={icon}
onClick={() => setIsOpen(true)}
title={title}
>
{children}
</Button>
<Dialog open={isOpen} onOpenChange={(_, data) => setIsOpen(data.open)}>
<DialogSurface>
<DialogBody>
<DialogTitle>{confirmTitle}</DialogTitle>
<DialogContent>{confirmMessage}</DialogContent>
<DialogActions>
<Button appearance="secondary" onClick={() => setIsOpen(false)}>
Cancel
</Button>
<Button appearance="primary" onClick={handleConfirm}>
{confirmLabel}
</Button>
</DialogActions>
</DialogBody>
</DialogSurface>
</Dialog>
</>
);
};
export default ConfirmButton;
+74 -98
View File
@@ -17,6 +17,7 @@ import {
import { useStatusContext } from "./App";
import { useCommonStyles } from "./commonStyles";
import { getErrorMessage } from "../types/office-types";
import ConfirmButton from "./ConfirmButton";
/**
* Configuration constants for draft watermarks
@@ -183,62 +184,51 @@ export const DraftButtons: React.FC = () => {
affectedCount: 0
};
// Process each slide master (usually there's just one)
for (let i = 0; i < masters.length; i++) {
try {
const master = masters[i];
// Create the textbox on the master slide
const textBox = master.shapes.addTextBox("");
// Set position and size in a single batch
textBox.left = DRAFT_CONFIG.TEXT_BOX.LEFT;
textBox.top = DRAFT_CONFIG.TEXT_BOX.TOP;
textBox.width = DRAFT_CONFIG.TEXT_BOX.WIDTH;
textBox.height = DRAFT_CONFIG.TEXT_BOX.HEIGHT;
textBox.name = DRAFT_CONFIG.SHAPE_NAME;
// Load textFrame to set text properties
textBox.load("textFrame");
await context.sync();
if (textBox.textFrame) {
// Load textRange to set text and properties
textBox.textFrame.load("textRange");
await context.sync();
// Set text and load font properties in a single batch
textBox.textFrame.textRange.text = DRAFT_CONFIG.TEXT;
textBox.textFrame.textRange.load("font,paragraphFormat");
await context.sync();
try {
// Apply all font properties in a single batch
const font = textBox.textFrame.textRange.font;
font.name = DRAFT_CONFIG.FONT.NAME;
font.size = DRAFT_CONFIG.FONT.SIZE;
font.bold = true;
font.color = DRAFT_CONFIG.FONT.COLOR;
// Set alignment
textBox.textFrame.verticalAlignment = "MiddleCentered";
await context.sync();
result.affectedCount++;
} catch (fontError) {
console.error("Error setting font properties:", fontError);
// Continue with default font if custom font fails
}
}
result.processedMasters++;
} catch (masterError) {
console.error(`Error processing master ${i+1}:`, masterError);
result.errorMasters++;
// Continue to the next master
const { LEFT, TOP, WIDTH, HEIGHT } = DRAFT_CONFIG.TEXT_BOX;
// Load the shapes and names for every master in two batches instead of three syncs per master
for (const master of masters) {
master.shapes.load("items");
}
await context.sync();
const shapesByMaster: PowerPoint.Shape[][] = [];
for (const master of masters) {
shapesByMaster.push(master.shapes.items);
for (const shape of master.shapes.items) {
shape.load("name");
}
}
await context.sync();
// Replace any existing watermark so repeated clicks do not duplicate it
for (const shapes of shapesByMaster) {
for (const shape of shapes) {
if (shape.name === DRAFT_CONFIG.SHAPE_NAME) {
shape.delete();
}
}
}
// Create one watermark per master in a single batch
for (const master of masters) {
const textBox = master.shapes.addTextBox(DRAFT_CONFIG.TEXT, {
left: LEFT,
top: TOP,
width: WIDTH,
height: HEIGHT
});
textBox.name = DRAFT_CONFIG.SHAPE_NAME;
textBox.textFrame.textRange.font.name = DRAFT_CONFIG.FONT.NAME;
textBox.textFrame.textRange.font.size = DRAFT_CONFIG.FONT.SIZE;
textBox.textFrame.textRange.font.bold = true;
textBox.textFrame.textRange.font.color = DRAFT_CONFIG.FONT.COLOR;
textBox.textFrame.verticalAlignment = "MiddleCentered";
result.processedMasters++;
}
await context.sync();
result.affectedCount = masters.length;
return result;
};
@@ -287,48 +277,31 @@ export const DraftButtons: React.FC = () => {
affectedCount: 0
};
// Process each master slide
for (let i = 0; i < masters.length; i++) {
try {
const master = masters[i];
// Load all shapes on the master slide
master.shapes.load("items");
await context.sync();
// Collect shapes to delete
const shapesToDelete: PowerPoint.Shape[] = [];
// Load all shape names in a single batch
for (let j = 0; j < master.shapes.items.length; j++) {
const shape = master.shapes.items[j];
shape.load("name");
}
// Wait for all shape names to load
await context.sync();
// Now check names and collect shapes to delete
for (let j = 0; j < master.shapes.items.length; j++) {
const shape = master.shapes.items[j];
if (shape.name === DRAFT_CONFIG.SHAPE_NAME) {
shapesToDelete.push(shape);
}
}
// Delete all matching shapes in one batch
shapesToDelete.forEach(shape => shape.delete());
result.affectedCount += shapesToDelete.length;
await context.sync();
result.processedMasters++;
} catch (masterError) {
console.error(`Error processing master slide ${i+1}:`, masterError);
result.errorMasters++;
// Continue to the next master slide
// Load the shapes and names for every master in two batches
for (const master of masters) {
master.shapes.load("items");
}
await context.sync();
const allShapes: PowerPoint.Shape[] = [];
for (const master of masters) {
for (const shape of master.shapes.items) {
shape.load("name");
allShapes.push(shape);
}
}
await context.sync();
// Delete all matching shapes in one batch
for (const shape of allShapes) {
if (shape.name === DRAFT_CONFIG.SHAPE_NAME) {
shape.delete();
result.affectedCount++;
}
}
await context.sync();
result.processedMasters = masters.length;
return result;
};
@@ -345,16 +318,19 @@ export const DraftButtons: React.FC = () => {
>
Add
</Button>
<Button
appearance="primary"
<ConfirmButton
appearance="primary"
className={styles.draftButton}
onClick={removeDraftWatermark}
onConfirm={removeDraftWatermark}
icon={<DismissRegular />}
disabled={isProcessing}
title="Remove Draft"
confirmTitle="Remove draft watermarks?"
confirmMessage="This removes the DRAFT watermark from every slide master."
confirmLabel="Remove"
>
Remove
</Button>
</ConfirmButton>
</div>
</div>
);
@@ -26,7 +26,8 @@ import {
} from "@fluentui/react-icons";
import { useStatusContext } from "./App";
import { useCommonStyles } from "./commonStyles";
import { getErrorMessage } from "../types/office-types";
import { deleteShapesByPrefix, getErrorMessage } from "../types/office-types";
import ConfirmButton from "./ConfirmButton";
/**
* Standard dimensions for PowerPoint slides in points
@@ -293,9 +294,6 @@ export const GridGuidelineManager: React.FC = () => {
setIsProcessing(true);
try {
await PowerPoint.run(async (context) => {
// Remove any existing grid first
await removeGrid(false);
// Get the current slide using the selected slides collection
const selectedSlides = context.presentation.getSelectedSlides();
selectedSlides.load("items");
@@ -306,6 +304,17 @@ export const GridGuidelineManager: React.FC = () => {
}
const currentSlide = selectedSlides.items[0];
// Remove any existing grid on this slide inside the same request context
currentSlide.shapes.load("items");
await context.sync();
for (const shape of currentSlide.shapes.items) {
shape.load("name");
}
await context.sync();
deleteShapesByPrefix(currentSlide.shapes.items, GRID_PREFIX);
// Create horizontal grid lines
for (let i = 1; i <= numHorizontalLines; i++) {
@@ -361,13 +370,9 @@ export const GridGuidelineManager: React.FC = () => {
/**
* Removes the grid from the current slide
*
* @param showStatus - Whether to show status messages (default: true)
*/
const removeGrid = React.useCallback(async (showStatus = true) => {
if (showStatus) {
setIsProcessing(true);
}
const removeGrid = React.useCallback(async () => {
setIsProcessing(true);
try {
await PowerPoint.run(async (context) => {
@@ -383,50 +388,33 @@ export const GridGuidelineManager: React.FC = () => {
const currentSlide = selectedSlides.items[0];
// Load all shapes on this slide
const shapes = currentSlide.shapes;
shapes.load("items");
currentSlide.shapes.load("items");
await context.sync();
// Load all shape names at once
const allShapes = shapes.items;
for (let i = 0; i < allShapes.length; i++) {
allShapes[i].load("name");
for (const shape of currentSlide.shapes.items) {
shape.load("name");
}
await context.sync();
// Find shapes that are part of our grid and mark them for deletion
let removedCount = 0;
for (let i = 0; i < allShapes.length; i++) {
const shape = allShapes[i];
// Check if this shape is part of our grid
if (shape.name && shape.name.startsWith(GRID_PREFIX)) {
shape.delete();
removedCount++;
}
}
// Single sync after all deletions
// Delete all grid shapes and commit the changes
const removedCount = deleteShapesByPrefix(currentSlide.shapes.items, GRID_PREFIX);
await context.sync();
if (showStatus) {
if (removedCount > 0) {
setStatusMessage(`Removed grid from slide`);
} else {
setStatusMessage("No grid found to remove");
}
if (removedCount > 0) {
setStatusMessage(`Removed grid from slide`);
setStatusType("success");
} else {
setStatusMessage("No grid found to remove");
setStatusType("warning");
}
});
} catch (error: unknown) {
if (showStatus) {
setStatusMessage(`Error: ${getErrorMessage(error)}`);
setStatusType("error");
}
setStatusMessage(`Error: ${getErrorMessage(error)}`);
setStatusType("error");
console.error("Remove grid error:", error);
} finally {
if (showStatus) {
setIsProcessing(false);
}
setIsProcessing(false);
}
}, [setIsProcessing, setStatusMessage, setStatusType]);
@@ -514,37 +502,26 @@ export const GridGuidelineManager: React.FC = () => {
const currentSlide = selectedSlides.items[0];
// Load all shapes on this slide
const shapes = currentSlide.shapes;
shapes.load("items");
currentSlide.shapes.load("items");
await context.sync();
// Load all shape names at once
const allShapes = shapes.items;
for (let i = 0; i < allShapes.length; i++) {
allShapes[i].load("name");
for (const shape of currentSlide.shapes.items) {
shape.load("name");
}
await context.sync();
// Find shapes that are guidelines and mark them for deletion
let removedCount = 0;
for (let i = 0; i < allShapes.length; i++) {
const shape = allShapes[i];
// Check if this shape is a guideline
if (shape.name && shape.name.startsWith(GUIDE_PREFIX)) {
shape.delete();
removedCount++;
}
}
// Single sync after all deletions
// 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");
} else {
setStatusMessage("No guidelines found to remove");
setStatusType("warning");
}
setStatusType("success");
});
} catch (error: unknown) {
setStatusMessage(`Error: ${getErrorMessage(error)}`);
@@ -631,16 +608,19 @@ export const GridGuidelineManager: React.FC = () => {
>
Add
</Button>
<Button
appearance="primary"
<ConfirmButton
appearance="primary"
className={styles.gridButton}
onClick={() => removeGrid(true)}
onConfirm={removeGrid}
icon={<DismissRegular />}
disabled={isProcessing}
title="Remove Grid"
confirmTitle="Remove the grid?"
confirmMessage="This removes the grid from the current slide."
confirmLabel="Remove"
>
Remove
</Button>
</ConfirmButton>
</div>
{/* Guidelines Section */}
@@ -722,16 +702,19 @@ export const GridGuidelineManager: React.FC = () => {
>
Add
</Button>
<Button
appearance="primary"
<ConfirmButton
appearance="primary"
className={styles.gridButton}
onClick={removeGuidelines}
onConfirm={removeGuidelines}
icon={<DismissRegular />}
disabled={isProcessing}
title="Remove All Guidelines"
confirmTitle="Remove all guidelines?"
confirmMessage="This removes every guideline from the current slide."
confirmLabel="Remove"
>
Remove
</Button>
</ConfirmButton>
</div>
</div>
</div>
+200 -318
View File
@@ -13,7 +13,7 @@ import ActionButton from "./ActionButton";
import { getErrorMessage, isTextCapableShape } from "../types/office-types";
// Configuration constants
const TITLE_POSITION_THRESHOLD = 95; // Pixels from top of slide to consider a shape as a title
const TITLE_POSITION_THRESHOLD = 95; // Points from the top of the slide to consider a shape as a title
const STANDARD_SLIDE_WIDTH = 960; // Standard widescreen PowerPoint slide width in points
// Title detection methods
@@ -33,359 +33,238 @@ interface TitleCollectionResult {
// Title candidate with position and size information
interface TitleCandidate {
name: string;
text: string;
top: number;
left: number;
width: number;
height: number;
fontSize?: number;
isBold?: boolean;
fontSize: number;
isBold: boolean;
}
/**
* Chooses the most likely title from the loaded text shapes on a slide.
*/
const pickTitleText = (
candidates: TitleCandidate[],
method: TitleDetectionMethod
): string | null => {
if (candidates.length === 0) {
return null;
}
// The first text shape in z-order
if (method === "first") {
return candidates[0].text;
}
// Shape names are the most reliable hint when present
if (method === "auto" || method === "name") {
const namedCandidate = candidates.find((candidate) => {
const name = candidate.name.toLowerCase();
return name.includes("title") || name.includes("heading");
});
if (namedCandidate) {
return namedCandidate.text;
}
if (method === "name") {
return null;
}
}
// The first text shape near the top of the slide
if (method === "position") {
const positionedCandidate = candidates.find(
(candidate) => candidate.top < TITLE_POSITION_THRESHOLD
);
return positionedCandidate ? positionedCandidate.text : null;
}
// Auto mode: rank the shapes nearest the top of the slide
const topCandidates = candidates.filter(
(candidate) => candidate.top < TITLE_POSITION_THRESHOLD
);
if (topCandidates.length === 0) {
return null;
}
topCandidates.sort((a, b) => a.top - b.top);
const nearestCandidates = topCandidates.filter(
(candidate) => candidate.top <= topCandidates[0].top + 50
);
if (nearestCandidates.length > 1) {
nearestCandidates.sort((a, b) => {
// Prefer shapes that are centered, use a larger font, are bold, and are wider
const aCenterOffset = Math.abs(a.left + a.width / 2 - STANDARD_SLIDE_WIDTH / 2);
const bCenterOffset = Math.abs(b.left + b.width / 2 - STANDARD_SLIDE_WIDTH / 2);
const aFontScore = a.fontSize * (a.isBold ? 1.5 : 1);
const bFontScore = b.fontSize * (b.isBold ? 1.5 : 1);
const aScore = aCenterOffset * 2 - aFontScore * 5 - a.width * 0.5;
const bScore = bCenterOffset * 2 - bFontScore * 5 - b.width * 0.5;
return aScore - bScore;
});
}
return nearestCandidates[0].text;
};
/**
* Collects titles from all slides using three batched syncs instead of
* multiple round-trips per shape.
*/
const collectSlideTitles = async (
slides: PowerPoint.SlideCollection,
context: PowerPoint.RequestContext,
options: TitleCollectionOptions
): Promise<TitleCollectionResult> => {
// Load the shape collections for every slide in a single batch
for (const slide of slides.items) {
slide.shapes.load("items");
}
await context.sync();
// Load geometry, type and text presence for every shape
for (const slide of slides.items) {
for (const shape of slide.shapes.items) {
shape.load(["name", "type", "top", "left", "width", "height", "textFrame/hasText"]);
}
}
await context.sync();
// Load text and font details only for shapes that can hold text and contain some
for (const slide of slides.items) {
for (const shape of slide.shapes.items) {
if (isTextCapableShape(shape) && shape.textFrame.hasText) {
shape.textFrame.textRange.load(["text", "font/size", "font/bold"]);
}
}
}
await context.sync();
let titleText = "";
let titlesCollected = 0;
for (let i = 0; i < slides.items.length; i++) {
const candidates: TitleCandidate[] = [];
for (const shape of slides.items[i].shapes.items) {
if (!isTextCapableShape(shape) || !shape.textFrame.hasText) {
continue;
}
const text = shape.textFrame.textRange.text;
if (!text || text.trim() === "") {
continue;
}
candidates.push({
name: shape.name,
text: text.trim(),
top: shape.top,
left: shape.left,
width: shape.width,
height: shape.height,
fontSize: shape.textFrame.textRange.font.size ?? 12,
isBold: shape.textFrame.textRange.font.bold ?? false
});
}
const title = pickTitleText(candidates, options.detectionMethod || "auto");
if (title) {
const formattedTitle = options.includeSlideNumbers
? `Slide ${i + 1}: ${title}`
: title;
titleText += `${formattedTitle}\n`;
titlesCollected++;
}
}
return { titleText, titlesCollected };
};
/**
* Generates an appropriate status message based on the results
* @param titlesCollected The number of titles collected
* @param insertSuccess Whether insertion was successful
* @returns The formatted status message
*/
const generateStatusMessage = (
titlesCollected: number,
insertSuccess: boolean
): string => {
if (titlesCollected === 0) {
return "No slide titles found to insert.";
}
if (!insertSuccess) {
return "Error inserting titles into the selected shape.";
}
return `Collected and inserted ${titlesCollected} slide titles.`;
};
export const InsertTitles: React.FC = () => {
const styles = useCommonStyles();
const { setStatusMessage, setStatusType } = useStatusContext();
const [titleDetectionMethod, setTitleDetectionMethod] = React.useState<TitleDetectionMethod>("auto");
const [includeSlideNumbers, setIncludeSlideNumbers] = React.useState<boolean>(false);
/**
* Validates that a text box is selected
* @param shapes The collection of selected shapes
* @param context The PowerPoint request context
* @returns The selected text box shape or null if validation fails
*/
const validateSelection = async (
shapes: PowerPoint.ShapeScopedCollection,
context: PowerPoint.RequestContext
): Promise<PowerPoint.Shape | null> => {
// Check if any shape is selected
if (shapes.items.length === 0) {
setStatusMessage("Please select a text box to insert slide titles.");
setStatusType("warning");
return null;
}
// Get the first selected shape
const selectedShape = shapes.items[0];
// Check that the selected shape can hold editable text
selectedShape.load("type");
await context.sync();
if (!isTextCapableShape(selectedShape)) {
setStatusMessage("Please select a text box to insert slide titles.");
setStatusType("warning");
return null;
}
return selectedShape;
};
/**
* Finds the title shape on a slide using multiple heuristics
* @param shapes The collection of shapes on a slide
* @param context The PowerPoint request context
* @param slideNumber The slide number (for logging)
* @param method The title detection method to use
* @returns The title shape text or null if not found
*/
const findTitleShape = async (
shapes: PowerPoint.ShapeCollection,
context: PowerPoint.RequestContext,
slideNumber: number,
method: TitleDetectionMethod = "auto"
): Promise<{ text: string } | null> => {
try {
const titleCandidates: TitleCandidate[] = [];
// First pass: look for title shapes by name
// This is the most reliable method if available
if (method === "auto" || method === "name") {
for (let j = 0; j < shapes.items.length; j++) {
const shape = shapes.items[j];
// Check if this shape has a name that indicates it's a title
shape.load("name,textFrame");
await context.sync();
// Check if this might be a title shape by name
if (shape.name &&
(shape.name.toLowerCase().includes("title") ||
shape.name.toLowerCase().includes("heading"))) {
if (shape.textFrame) {
shape.textFrame.load("textRange");
await context.sync();
if (shape.textFrame.textRange) {
shape.textFrame.textRange.load("text");
await context.sync();
const shapeText = shape.textFrame.textRange.text;
if (shapeText && shapeText.trim() !== "") {
return { text: shapeText };
}
}
}
}
}
}
// If we're only looking for title shapes by name and didn't find any, return null
if (method === "name") {
return null;
}
// Second pass: collect all text shapes based on the selected method
for (let j = 0; j < shapes.items.length; j++) {
const shape = shapes.items[j];
// Load basic properties for all shapes
shape.load("textFrame,top,left,width,height");
await context.sync();
if (shape.textFrame) {
shape.textFrame.load("textRange");
await context.sync();
if (shape.textFrame.textRange) {
shape.textFrame.textRange.load("text,font/size,font/bold");
await context.sync();
const shapeText = shape.textFrame.textRange.text;
if (shapeText && shapeText.trim() !== "") {
// For "first" method, return the first text shape we find
if (method === "first") {
return { text: shapeText };
}
// For position method or auto, check position
if (method === "position" || method === "auto") {
// Use position as a heuristic for identifying titles
if (shape.top < TITLE_POSITION_THRESHOLD) {
// For position-only method, return the first match
if (method === "position") {
return { text: shapeText };
}
// For auto method, add to candidates with priority score
const fontSize = shape.textFrame.textRange.font.size || 12;
const isBold = shape.textFrame.textRange.font.bold || false;
titleCandidates.push({
text: shapeText,
top: shape.top,
left: shape.left,
width: shape.width,
height: shape.height,
fontSize: fontSize,
isBold: isBold
});
}
}
}
}
}
}
// If we have candidates, sort them by position and size heuristics
if (titleCandidates.length > 0) {
// First sort by vertical position (top-most first)
titleCandidates.sort((a, b) => a.top - b.top);
// Then refine by other heuristics for the top candidates
// Only consider shapes that are close to the top
const topCandidates = titleCandidates.filter(
c => c.top <= titleCandidates[0].top + 50
);
if (topCandidates.length > 1) {
// Sort by a combination of factors:
// 1. How centered the shape is
// 2. Font size (larger is better)
// 3. Bold text is preferred
// 4. Width (wider is better for titles)
topCandidates.sort((a, b) => {
// Calculate how centered each shape is
const aCenterOffset = Math.abs((a.left + a.width/2) - (STANDARD_SLIDE_WIDTH/2));
const bCenterOffset = Math.abs((b.left + b.width/2) - (STANDARD_SLIDE_WIDTH/2));
// Calculate font score (size + bold bonus)
const aFontScore = (a.fontSize || 12) * (a.isBold ? 1.5 : 1);
const bFontScore = (b.fontSize || 12) * (b.isBold ? 1.5 : 1);
// Combine factors into a single score (lower is better)
// Weight factors by importance
const aScore = aCenterOffset * 2 - aFontScore * 5 - a.width * 0.5;
const bScore = bCenterOffset * 2 - bFontScore * 5 - b.width * 0.5;
return aScore - bScore;
});
}
// Return the best candidate
return { text: topCandidates[0].text };
}
} catch (error) {
console.error(`Error finding title on slide ${slideNumber}:`, getErrorMessage(error));
}
return null;
};
/**
* Collects titles from all slides in the presentation
* @param slides The collection of slides
* @param context The PowerPoint request context
* @param options Options for title collection
* @returns The collected titles and count
*/
const collectSlideTitles = async (
slides: PowerPoint.SlideCollection,
context: PowerPoint.RequestContext,
options: TitleCollectionOptions = {
includeSlideNumbers: false,
detectionMethod: "auto"
}
): Promise<TitleCollectionResult> => {
let titleText = "";
let titlesCollected = 0;
try {
// Process each slide
for (let i = 0; i < slides.items.length; i++) {
const slide = slides.items[i];
// Load shapes collection
slide.load("shapes");
await context.sync();
const shapes = slide.shapes;
shapes.load("items");
await context.sync();
// Find the title shape on this slide
const titleShape = await findTitleShape(
shapes,
context,
i + 1,
options.detectionMethod || "auto"
);
if (titleShape) {
// Format the title text based on options
const slideTitle = titleShape.text.trim();
const formattedTitle = options.includeSlideNumbers
? `Slide ${i + 1}: ${slideTitle}`
: slideTitle;
// Add to our collection
titleText += `${formattedTitle}\n`;
titlesCollected++;
}
}
} catch (error) {
console.error("Error collecting slide titles:", getErrorMessage(error));
}
return { titleText, titlesCollected };
};
/**
* Inserts collected titles into a shape
* @param shape The shape to insert titles into
* @param titleText The collected title text
* @param context The PowerPoint request context
* @returns True if insertion was successful
*/
const insertTitlesIntoShape = async (
shape: PowerPoint.Shape,
titleText: string,
context: PowerPoint.RequestContext
): Promise<boolean> => {
try {
// Make sure we have a textRange on the selected shape
shape.textFrame.load("textRange");
await context.sync();
shape.textFrame.textRange.text = titleText;
await context.sync();
return true;
} catch (error) {
console.error("Error inserting titles:", getErrorMessage(error));
return false;
}
};
/**
* Generates an appropriate status message based on the results
* @param titlesCollected The number of titles collected
* @param insertSuccess Whether insertion was successful
* @returns The formatted status message
*/
const generateStatusMessage = (
titlesCollected: number,
insertSuccess: boolean
): string => {
if (titlesCollected === 0) {
return "No slide titles found to insert.";
}
if (!insertSuccess) {
return "Error inserting titles into the selected shape.";
}
return `Collected and inserted ${titlesCollected} slide titles.`;
};
/**
* Main function to collect and insert slide titles
*/
const collectAndInsertTitles = async (): Promise<void> => {
try {
await PowerPoint.run(async (context) => {
// Get the selected shapes
// Get the selected shapes and all slides in one batch
const selectedShapes = context.presentation.getSelectedShapes();
selectedShapes.load("items");
await context.sync();
// Validate selection and get the target shape
const targetShape = await validateSelection(selectedShapes, context);
if (!targetShape) {
return;
}
// Get all slides in the presentation
const slides = context.presentation.slides;
selectedShapes.load("items");
slides.load("items");
await context.sync();
if (selectedShapes.items.length === 0) {
setStatusMessage("Please select a text box to insert slide titles.");
setStatusType("warning");
return;
}
// Check that the selected shape can hold editable text
const targetShape = selectedShapes.items[0];
targetShape.load("type");
await context.sync();
if (!isTextCapableShape(targetShape)) {
setStatusMessage("Please select a text box to insert slide titles.");
setStatusType("warning");
return;
}
// Collect titles from all slides
const { titleText, titlesCollected } = await collectSlideTitles(
slides,
context,
{
includeSlideNumbers: includeSlideNumbers,
detectionMethod: titleDetectionMethod
}
);
const { titleText, titlesCollected } = await collectSlideTitles(slides, context, {
includeSlideNumbers,
detectionMethod: titleDetectionMethod
});
// Insert titles if any were found
let insertSuccess = false;
if (titleText) {
insertSuccess = await insertTitlesIntoShape(targetShape, titleText, context);
targetShape.textFrame.textRange.text = titleText;
await context.sync();
insertSuccess = true;
}
// Update status message
const statusMessage = generateStatusMessage(titlesCollected, insertSuccess);
setStatusMessage(statusMessage);
setStatusMessage(generateStatusMessage(titlesCollected, insertSuccess));
setStatusType(
titlesCollected === 0 ? "warning" :
titlesCollected === 0 ? "warning" :
insertSuccess ? "success" : "error"
);
});
} catch (error) {
} catch (error: unknown) {
console.error("Error in collectAndInsertTitles:", getErrorMessage(error));
setStatusMessage(`Error: ${getErrorMessage(error)}`);
setStatusType("error");
@@ -399,6 +278,9 @@ export const InsertTitles: React.FC = () => {
title="Insert Titles"
icon={<TextBulletListRegular />}
onClick={collectAndInsertTitles}
confirmTitle="Replace text box contents?"
confirmMessage="This replaces all text in the selected text box with the titles collected from the presentation."
confirmLabel="Insert"
/>
</div>
<div style={{ marginTop: '10px', display: 'flex', justifyContent: 'flex-end' }}>
+78 -130
View File
@@ -16,7 +16,11 @@ import {
} from "@fluentui/react-icons";
import { useStatusContext } from "./App";
import { useCommonStyles } from "./commonStyles";
import { getErrorMessage } from "../types/office-types";
import { deleteShapesByPrefix, getErrorMessage } from "../types/office-types";
import ConfirmButton from "./ConfirmButton";
// Shape name prefix used to identify progress bar elements
const PROGRESS_BAR_PREFIX = "progress_bar_";
// Constants for progress bar configuration
const PROGRESS_BAR_CONFIG = {
@@ -26,20 +30,11 @@ const PROGRESS_BAR_CONFIG = {
// Progress bar appearance
barHeight: 1,
distanceFromBottom: 28,
overlap: 0.5, // Small overlap to ensure no gaps between segments
// Colors
completedColor: "#205170", // Blue for progressed segments (RGB 32, 81, 112)
pendingColor: "#F2F2F2" // Grey for segments not yet progressed (RGB 242, 242, 242)
};
// Layouts that should receive progress bars
const SUPPORTED_LAYOUTS = [
"Title",
"Content",
"Two Content",
"Blank"
];
const useStyles = makeStyles({
buttonGrid: {
display: "grid",
@@ -67,96 +62,73 @@ export const ProgressBarButtons: React.FC = () => {
} = useStatusContext();
/**
* Adds a progress bar to the bottom of each slide in the presentation
* The progress bar shows the current position within the presentation
* with colored segments indicating progress
* Adds a progress bar to the bottom of every slide in the presentation.
* Each slide gets two rectangles: a full pending bar and the completed portion.
*/
const addProgressBar = async () => {
setIsProcessing(true);
const startTime = performance.now();
try {
await PowerPoint.run(async (context) => {
// Get all slides at once
const presentation = context.presentation;
const slides = presentation.slides;
const slides = context.presentation.slides;
slides.load("items");
// Single sync to get all slides
await context.sync();
if (slides.items.length === 0) {
throw new Error("No slides in the presentation");
}
// Calculate dimensions based on slide count
const { slideWidth, slideHeight, barHeight, distanceFromBottom, overlap } = PROGRESS_BAR_CONFIG;
const slideCount = slides.items.length;
if (slideCount === 0) {
setStatusMessage("No slides found in the presentation.");
setStatusType("warning");
return;
}
const { slideWidth, slideHeight, barHeight, distanceFromBottom } = PROGRESS_BAR_CONFIG;
const segmentWidth = slideWidth / slideCount;
const startY = slideHeight - distanceFromBottom;
// Load all slide layouts at once to reduce API calls
for (let i = 0; i < slideCount; i++) {
slides.items[i].load("layout/name");
// Remove existing bars so repeated clicks replace instead of duplicate them
for (const slide of slides.items) {
slide.shapes.load("items");
}
// Single sync to get all layouts
await context.sync();
// Process each slide without unnecessary syncs
for (let i = 0; i < slideCount; i++) {
const slide = slides.items[i];
const layoutName = slide.layout.name;
// Check if this is a layout we want to add the progress bar to
const isCompatibleLayout = SUPPORTED_LAYOUTS.some(layout =>
layoutName.includes(layout)
);
if (isCompatibleLayout) {
// Create all segments for this slide in a batch
for (let j = 0; j < slideCount; j++) {
// Calculate segment position and dimensions
const startX = j * segmentWidth;
const endX = (j + 1) * segmentWidth;
// Create a rectangle with minimal height to simulate a line
const segment = slide.shapes.addGeometricShape("Rectangle");
// Set the rectangle's position to look like a line
segment.left = startX - (j > 0 ? overlap : 0);
segment.top = startY;
segment.width = (endX - startX) + (j > 0 ? overlap : 0) + (j < slideCount - 1 ? overlap : 0);
segment.height = barHeight;
// Set fill color based on progress
const isCompleted = j <= i;
segment.fill.setSolidColor(isCompleted ?
PROGRESS_BAR_CONFIG.completedColor :
PROGRESS_BAR_CONFIG.pendingColor
);
// Make the current slide indicator slightly more prominent
if (j == i) {
segment.width += 1;
}
// Remove the border/outline entirely
segment.lineFormat.visible = false;
// Use shape name as identifier for later removal
segment.name = "progress_bar_" + j;
}
const shapesBySlide: PowerPoint.Shape[][] = [];
for (const slide of slides.items) {
for (const shape of slide.shapes.items) {
shape.load("name");
}
shapesBySlide.push(slide.shapes.items);
}
await context.sync();
for (const shapes of shapesBySlide) {
deleteShapesByPrefix(shapes, PROGRESS_BAR_PREFIX);
}
// Two rectangles per slide: the full pending bar and the completed portion
slides.items.forEach((slide, index) => {
const pending = slide.shapes.addGeometricShape("Rectangle");
pending.left = 0;
pending.top = startY;
pending.width = slideWidth;
pending.height = barHeight;
pending.fill.setSolidColor(PROGRESS_BAR_CONFIG.pendingColor);
pending.lineFormat.visible = false;
pending.name = `${PROGRESS_BAR_PREFIX}pending`;
const completed = slide.shapes.addGeometricShape("Rectangle");
completed.left = 0;
completed.top = startY;
completed.width = (index + 1) * segmentWidth;
completed.height = barHeight;
completed.fill.setSolidColor(PROGRESS_BAR_CONFIG.completedColor);
completed.lineFormat.visible = false;
completed.name = `${PROGRESS_BAR_PREFIX}completed`;
});
// Single final sync to commit all changes
await context.sync();
const endTime = performance.now();
console.log(`Progress bar creation took ${endTime - startTime}ms`);
setStatusMessage("Added progress bar to slides.");
setStatusMessage(`Added progress bar to ${slideCount} slides.`);
setStatusType("success");
});
} catch (error: unknown) {
@@ -174,67 +146,40 @@ export const ProgressBarButtons: React.FC = () => {
*/
const removeProgressBar = async () => {
setIsProcessing(true);
const startTime = performance.now();
try {
await PowerPoint.run(async (context) => {
// Get all slides at once
const presentation = context.presentation;
const slides = presentation.slides;
const slides = context.presentation.slides;
slides.load("items");
await context.sync();
let removedCount = 0;
const shapesToLoad = [];
// First, load all shapes from all slides in a batch
for (let i = 0; i < slides.items.length; i++) {
const slide = slides.items[i];
const shapes = slide.shapes;
shapes.load("items");
shapesToLoad.push({ slide, shapes });
// Load all shapes from all slides in a batch
for (const slide of slides.items) {
slide.shapes.load("items");
}
// Single sync to get all shapes
await context.sync();
// Now load all shape names in a batch
const allShapesWithNames = [];
for (const { slide, shapes } of shapesToLoad) {
for (let j = 0; j < shapes.items.length; j++) {
const shape = shapes.items[j];
// Load all shape names in a batch
const allShapes: PowerPoint.Shape[] = [];
for (const slide of slides.items) {
for (const shape of slide.shapes.items) {
shape.load("name");
allShapesWithNames.push({ slide, shape });
allShapes.push(shape);
}
}
// Single sync to get all shape names
await context.sync();
// Filter shapes that are progress bars and delete them
const progressBarShapes = allShapesWithNames.filter(
({ shape }) => shape.name && shape.name.startsWith("progress_bar_")
);
// Delete all progress bar shapes
for (const { shape } of progressBarShapes) {
shape.delete();
removedCount++;
}
// Single final sync to commit all deletions
const removedCount = deleteShapesByPrefix(allShapes, PROGRESS_BAR_PREFIX);
await context.sync();
const endTime = performance.now();
console.log(`Progress bar removal took ${endTime - startTime}ms`);
if (removedCount > 0) {
setStatusMessage(`Removed progress bar from slides.`);
setStatusType("success");
} else {
setStatusMessage("No progress bar found to remove.");
setStatusType("warning");
}
setStatusType("success");
});
} catch (error: unknown) {
setStatusMessage(`Error: ${getErrorMessage(error)}`);
@@ -258,16 +203,19 @@ export const ProgressBarButtons: React.FC = () => {
>
Add
</Button>
<Button
appearance="primary"
<ConfirmButton
appearance="primary"
className={styles.progressButton}
onClick={removeProgressBar}
onConfirm={removeProgressBar}
icon={<DismissRegular />}
disabled={isProcessing}
title="Remove Progress Bar"
confirmTitle="Remove progress bars?"
confirmMessage="This removes the progress bar from every slide in the presentation."
confirmLabel="Remove"
>
Remove
</Button>
</ConfirmButton>
</div>
</div>
);
+18
View File
@@ -76,3 +76,21 @@ export function getFirstSelectedSlide(context: PowerPoint.RequestContext): Power
export function selectShapesById(slide: PowerPoint.Slide, shapeIds: string[]): void {
slide.setSelectedShapes(shapeIds);
}
/**
* Queues deletion of every shape whose name starts with `prefix`.
* The shapes' `name` properties must be loaded before calling this helper.
* @returns The number of shapes queued for deletion.
*/
export function deleteShapesByPrefix(shapes: PowerPoint.Shape[], prefix: string): number {
let removedCount = 0;
for (const shape of shapes) {
if (shape.name && shape.name.startsWith(prefix)) {
shape.delete();
removedCount++;
}
}
return removedCount;
}