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
+498 -593

No files matched your search

+33 -2
View File
@@ -3,6 +3,7 @@ import { Button, ButtonProps } from "@fluentui/react-components";
import { useStatusContext } from "./App"; import { useStatusContext } from "./App";
import { useCommonStyles } from "./commonStyles"; import { useCommonStyles } from "./commonStyles";
import { getErrorMessage } from "../types/office-types"; import { getErrorMessage } from "../types/office-types";
import ConfirmButton from "./ConfirmButton";
export interface ActionButtonProps { export interface ActionButtonProps {
icon: ButtonProps["icon"]; icon: ButtonProps["icon"];
@@ -11,6 +12,12 @@ export interface ActionButtonProps {
title: string; title: string;
appearance?: "primary" | "secondary" | "outline" | "subtle"; appearance?: "primary" | "secondary" | "outline" | "subtle";
className?: string; 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, title,
appearance = "primary", appearance = "primary",
className = "", className = "",
confirmTitle,
confirmMessage,
confirmLabel,
}) => { }) => {
const styles = useCommonStyles(); const styles = useCommonStyles();
const { const {
@@ -48,13 +58,34 @@ 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 ( return (
<Button <Button
appearance={appearance} appearance={appearance}
className={`${styles.actionButton} ${className}`} className={buttonClassName}
onClick={handleClick} onClick={handleClick}
icon={icon} icon={icon}
disabled={disabled || isProcessing} disabled={isDisabled}
> >
{title} {title}
</Button> </Button>
+60 -84
View File
@@ -16,6 +16,7 @@ import {
import { useStatusContext } from "./App"; import { useStatusContext } from "./App";
import { useCommonStyles } from "./commonStyles"; import { useCommonStyles } from "./commonStyles";
import { getErrorMessage } from "../types/office-types"; import { getErrorMessage } from "../types/office-types";
import ConfirmButton from "./ConfirmButton";
/** /**
* Configuration constants for confidential markings * Configuration constants for confidential markings
@@ -172,61 +173,50 @@ export const ConfidentialButtons: React.FC = () => {
}; };
const { WIDTH, HEIGHT } = CONFIDENTIAL_CONFIG.SLIDE; const { WIDTH, HEIGHT } = CONFIDENTIAL_CONFIG.SLIDE;
const slideWidth = WIDTH; const positionFromTop = HEIGHT - CONFIDENTIAL_CONFIG.TEXT_BOX.POSITION_FROM_BOTTOM;
const slideHeight = HEIGHT;
// Process each slide // Load the shapes and names for every slide in two batches instead of two syncs per slide
for (let i = 0; i < slides.length; i++) { for (const slide of slides) {
try { slide.shapes.load("items");
const slide = slides[i]; }
const positionFromTop = slideHeight - CONFIDENTIAL_CONFIG.TEXT_BOX.POSITION_FROM_BOTTOM; await context.sync();
// Create the textbox spanning the full width of the slide const shapesBySlide: PowerPoint.Shape[][] = [];
const textBox = slide.shapes.addTextBox(""); for (const slide of slides) {
textBox.left = 0; // Start from left edge shapesBySlide.push(slide.shapes.items);
textBox.top = positionFromTop; for (const shape of slide.shapes.items) {
textBox.width = slideWidth; shape.load("name");
textBox.height = CONFIDENTIAL_CONFIG.TEXT_BOX.HEIGHT; }
}
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.name = CONFIDENTIAL_CONFIG.SHAPE_NAME;
textBox.textFrame.textRange.font.name = CONFIDENTIAL_CONFIG.FONT.NAME;
// Load textFrame and its properties in a single batch textBox.textFrame.textRange.font.size = CONFIDENTIAL_CONFIG.FONT.SIZE;
textBox.load("textFrame"); textBox.textFrame.textRange.font.color = CONFIDENTIAL_CONFIG.FONT.COLOR;
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"; textBox.textFrame.textRange.paragraphFormat.horizontalAlignment = "Center";
result.processedSlides++;
}
await context.sync(); await context.sync();
result.affectedCount++; result.affectedCount = slides.length;
} 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
}
}
return result; return result;
}; };
@@ -275,48 +265,31 @@ export const ConfidentialButtons: React.FC = () => {
affectedCount: 0 affectedCount: 0
}; };
// Process each slide // Load the shapes and names for every slide in two batches
for (let i = 0; i < slides.length; i++) { for (const slide of slides) {
try {
const slide = slides[i];
// Load all shapes on the slide
slide.shapes.load("items"); slide.shapes.load("items");
}
await context.sync(); await context.sync();
// Collect shapes to delete const allShapes: PowerPoint.Shape[] = [];
const shapesToDelete: PowerPoint.Shape[] = []; for (const slide of slides) {
for (const shape of slide.shapes.items) {
// 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"); shape.load("name");
allShapes.push(shape);
}
} }
// Wait for all shape names to load
await context.sync(); 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 // Delete all matching shapes in one batch
shapesToDelete.forEach(shape => shape.delete()); for (const shape of allShapes) {
result.affectedCount += shapesToDelete.length; if (shape.name === CONFIDENTIAL_CONFIG.SHAPE_NAME) {
shape.delete();
result.affectedCount++;
}
}
await context.sync(); await context.sync();
result.processedSlides++; result.processedSlides = slides.length;
} catch (slideError) {
console.error(`Error processing slide ${i+1}:`, slideError);
result.errorSlides++;
// Continue to the next slide
}
}
return result; return result;
}; };
@@ -333,16 +306,19 @@ export const ConfidentialButtons: React.FC = () => {
> >
Add Add
</Button> </Button>
<Button <ConfirmButton
appearance="primary" appearance="primary"
className={styles.confidentialButton} className={styles.confidentialButton}
onClick={removeConfidentialMarking} onConfirm={removeConfidentialMarking}
icon={<DismissRegular />} icon={<DismissRegular />}
disabled={isProcessing} disabled={isProcessing}
title="Remove Confidential" title="Remove Confidential"
confirmTitle="Remove confidential markings?"
confirmMessage="This removes the confidential marking from every slide in the presentation."
confirmLabel="Remove"
> >
Remove Remove
</Button> </ConfirmButton>
</div> </div>
</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;
+61 -85
View File
@@ -17,6 +17,7 @@ import {
import { useStatusContext } from "./App"; import { useStatusContext } from "./App";
import { useCommonStyles } from "./commonStyles"; import { useCommonStyles } from "./commonStyles";
import { getErrorMessage } from "../types/office-types"; import { getErrorMessage } from "../types/office-types";
import ConfirmButton from "./ConfirmButton";
/** /**
* Configuration constants for draft watermarks * Configuration constants for draft watermarks
@@ -183,62 +184,51 @@ export const DraftButtons: React.FC = () => {
affectedCount: 0 affectedCount: 0
}; };
// Process each slide master (usually there's just one) const { LEFT, TOP, WIDTH, HEIGHT } = DRAFT_CONFIG.TEXT_BOX;
for (let i = 0; i < masters.length; i++) {
try {
const master = masters[i];
// Create the textbox on the master slide // Load the shapes and names for every master in two batches instead of three syncs per master
const textBox = master.shapes.addTextBox(""); for (const master of masters) {
master.shapes.load("items");
}
await context.sync();
// Set position and size in a single batch const shapesByMaster: PowerPoint.Shape[][] = [];
textBox.left = DRAFT_CONFIG.TEXT_BOX.LEFT; for (const master of masters) {
textBox.top = DRAFT_CONFIG.TEXT_BOX.TOP; shapesByMaster.push(master.shapes.items);
textBox.width = DRAFT_CONFIG.TEXT_BOX.WIDTH; for (const shape of master.shapes.items) {
textBox.height = DRAFT_CONFIG.TEXT_BOX.HEIGHT; 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.name = DRAFT_CONFIG.SHAPE_NAME;
textBox.textFrame.textRange.font.name = DRAFT_CONFIG.FONT.NAME;
// Load textFrame to set text properties textBox.textFrame.textRange.font.size = DRAFT_CONFIG.FONT.SIZE;
textBox.load("textFrame"); textBox.textFrame.textRange.font.bold = true;
await context.sync(); textBox.textFrame.textRange.font.color = DRAFT_CONFIG.FONT.COLOR;
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"; textBox.textFrame.verticalAlignment = "MiddleCentered";
result.processedMasters++;
}
await context.sync(); await context.sync();
result.affectedCount++; result.affectedCount = masters.length;
} 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
}
}
return result; return result;
}; };
@@ -287,48 +277,31 @@ export const DraftButtons: React.FC = () => {
affectedCount: 0 affectedCount: 0
}; };
// Process each master slide // Load the shapes and names for every master in two batches
for (let i = 0; i < masters.length; i++) { for (const master of masters) {
try {
const master = masters[i];
// Load all shapes on the master slide
master.shapes.load("items"); master.shapes.load("items");
}
await context.sync(); await context.sync();
// Collect shapes to delete const allShapes: PowerPoint.Shape[] = [];
const shapesToDelete: PowerPoint.Shape[] = []; for (const master of masters) {
for (const shape of master.shapes.items) {
// 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"); shape.load("name");
allShapes.push(shape);
}
} }
// Wait for all shape names to load
await context.sync(); 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 // Delete all matching shapes in one batch
shapesToDelete.forEach(shape => shape.delete()); for (const shape of allShapes) {
result.affectedCount += shapesToDelete.length; if (shape.name === DRAFT_CONFIG.SHAPE_NAME) {
shape.delete();
result.affectedCount++;
}
}
await context.sync(); await context.sync();
result.processedMasters++; result.processedMasters = masters.length;
} catch (masterError) {
console.error(`Error processing master slide ${i+1}:`, masterError);
result.errorMasters++;
// Continue to the next master slide
}
}
return result; return result;
}; };
@@ -345,16 +318,19 @@ export const DraftButtons: React.FC = () => {
> >
Add Add
</Button> </Button>
<Button <ConfirmButton
appearance="primary" appearance="primary"
className={styles.draftButton} className={styles.draftButton}
onClick={removeDraftWatermark} onConfirm={removeDraftWatermark}
icon={<DismissRegular />} icon={<DismissRegular />}
disabled={isProcessing} disabled={isProcessing}
title="Remove Draft" title="Remove Draft"
confirmTitle="Remove draft watermarks?"
confirmMessage="This removes the DRAFT watermark from every slide master."
confirmLabel="Remove"
> >
Remove Remove
</Button> </ConfirmButton>
</div> </div>
</div> </div>
); );
@@ -26,7 +26,8 @@ import {
} from "@fluentui/react-icons"; } from "@fluentui/react-icons";
import { useStatusContext } from "./App"; import { useStatusContext } from "./App";
import { useCommonStyles } from "./commonStyles"; 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 * Standard dimensions for PowerPoint slides in points
@@ -293,9 +294,6 @@ export const GridGuidelineManager: React.FC = () => {
setIsProcessing(true); setIsProcessing(true);
try { try {
await PowerPoint.run(async (context) => { await PowerPoint.run(async (context) => {
// Remove any existing grid first
await removeGrid(false);
// Get the current slide using the selected slides collection // Get the current slide using the selected slides collection
const selectedSlides = context.presentation.getSelectedSlides(); const selectedSlides = context.presentation.getSelectedSlides();
selectedSlides.load("items"); selectedSlides.load("items");
@@ -307,6 +305,17 @@ export const GridGuidelineManager: React.FC = () => {
const currentSlide = selectedSlides.items[0]; 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 // Create horizontal grid lines
for (let i = 1; i <= numHorizontalLines; i++) { for (let i = 1; i <= numHorizontalLines; i++) {
const yPosition = i * spacing; const yPosition = i * spacing;
@@ -361,13 +370,9 @@ export const GridGuidelineManager: React.FC = () => {
/** /**
* Removes the grid from the current slide * Removes the grid from the current slide
*
* @param showStatus - Whether to show status messages (default: true)
*/ */
const removeGrid = React.useCallback(async (showStatus = true) => { const removeGrid = React.useCallback(async () => {
if (showStatus) {
setIsProcessing(true); setIsProcessing(true);
}
try { try {
await PowerPoint.run(async (context) => { await PowerPoint.run(async (context) => {
@@ -383,51 +388,34 @@ export const GridGuidelineManager: React.FC = () => {
const currentSlide = selectedSlides.items[0]; const currentSlide = selectedSlides.items[0];
// Load all shapes on this slide // Load all shapes on this slide
const shapes = currentSlide.shapes; currentSlide.shapes.load("items");
shapes.load("items");
await context.sync(); await context.sync();
// Load all shape names at once // Load all shape names at once
const allShapes = shapes.items; for (const shape of currentSlide.shapes.items) {
for (let i = 0; i < allShapes.length; i++) { shape.load("name");
allShapes[i].load("name");
} }
await context.sync(); await context.sync();
// Find shapes that are part of our grid and mark them for deletion // Delete all grid shapes and commit the changes
let removedCount = 0; const removedCount = deleteShapesByPrefix(currentSlide.shapes.items, GRID_PREFIX);
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
await context.sync(); await context.sync();
if (showStatus) {
if (removedCount > 0) { if (removedCount > 0) {
setStatusMessage(`Removed grid from slide`); setStatusMessage(`Removed grid from slide`);
setStatusType("success");
} else { } else {
setStatusMessage("No grid found to remove"); setStatusMessage("No grid found to remove");
} setStatusType("warning");
setStatusType("success");
} }
}); });
} catch (error: unknown) { } catch (error: unknown) {
if (showStatus) {
setStatusMessage(`Error: ${getErrorMessage(error)}`); setStatusMessage(`Error: ${getErrorMessage(error)}`);
setStatusType("error"); setStatusType("error");
}
console.error("Remove grid error:", error); console.error("Remove grid error:", error);
} finally { } finally {
if (showStatus) {
setIsProcessing(false); setIsProcessing(false);
} }
}
}, [setIsProcessing, setStatusMessage, setStatusType]); }, [setIsProcessing, setStatusMessage, setStatusType]);
/** /**
@@ -514,37 +502,26 @@ export const GridGuidelineManager: React.FC = () => {
const currentSlide = selectedSlides.items[0]; const currentSlide = selectedSlides.items[0];
// Load all shapes on this slide // Load all shapes on this slide
const shapes = currentSlide.shapes; currentSlide.shapes.load("items");
shapes.load("items");
await context.sync(); await context.sync();
// Load all shape names at once // Load all shape names at once
const allShapes = shapes.items; for (const shape of currentSlide.shapes.items) {
for (let i = 0; i < allShapes.length; i++) { shape.load("name");
allShapes[i].load("name");
} }
await context.sync(); await context.sync();
// Find shapes that are guidelines and mark them for deletion // Delete all guideline shapes and commit the changes
let removedCount = 0; const removedCount = deleteShapesByPrefix(currentSlide.shapes.items, GUIDE_PREFIX);
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
await context.sync(); await context.sync();
if (removedCount > 0) { if (removedCount > 0) {
setStatusMessage(`Removed ${removedCount} guidelines`); setStatusMessage(`Removed ${removedCount} guidelines`);
setStatusType("success");
} else { } else {
setStatusMessage("No guidelines found to remove"); setStatusMessage("No guidelines found to remove");
setStatusType("warning");
} }
setStatusType("success");
}); });
} catch (error: unknown) { } catch (error: unknown) {
setStatusMessage(`Error: ${getErrorMessage(error)}`); setStatusMessage(`Error: ${getErrorMessage(error)}`);
@@ -631,16 +608,19 @@ export const GridGuidelineManager: React.FC = () => {
> >
Add Add
</Button> </Button>
<Button <ConfirmButton
appearance="primary" appearance="primary"
className={styles.gridButton} className={styles.gridButton}
onClick={() => removeGrid(true)} onConfirm={removeGrid}
icon={<DismissRegular />} icon={<DismissRegular />}
disabled={isProcessing} disabled={isProcessing}
title="Remove Grid" title="Remove Grid"
confirmTitle="Remove the grid?"
confirmMessage="This removes the grid from the current slide."
confirmLabel="Remove"
> >
Remove Remove
</Button> </ConfirmButton>
</div> </div>
{/* Guidelines Section */} {/* Guidelines Section */}
@@ -722,16 +702,19 @@ export const GridGuidelineManager: React.FC = () => {
> >
Add Add
</Button> </Button>
<Button <ConfirmButton
appearance="primary" appearance="primary"
className={styles.gridButton} className={styles.gridButton}
onClick={removeGuidelines} onConfirm={removeGuidelines}
icon={<DismissRegular />} icon={<DismissRegular />}
disabled={isProcessing} disabled={isProcessing}
title="Remove All Guidelines" title="Remove All Guidelines"
confirmTitle="Remove all guidelines?"
confirmMessage="This removes every guideline from the current slide."
confirmLabel="Remove"
> >
Remove Remove
</Button> </ConfirmButton>
</div> </div>
</div> </div>
</div> </div>
+130 -248
View File
@@ -13,7 +13,7 @@ import ActionButton from "./ActionButton";
import { getErrorMessage, isTextCapableShape } from "../types/office-types"; import { getErrorMessage, isTextCapableShape } from "../types/office-types";
// Configuration constants // 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 const STANDARD_SLIDE_WIDTH = 960; // Standard widescreen PowerPoint slide width in points
// Title detection methods // Title detection methods
@@ -33,291 +33,159 @@ interface TitleCollectionResult {
// Title candidate with position and size information // Title candidate with position and size information
interface TitleCandidate { interface TitleCandidate {
name: string;
text: string; text: string;
top: number; top: number;
left: number; left: number;
width: number; width: number;
height: number; height: number;
fontSize?: number; fontSize: number;
isBold?: boolean; isBold: boolean;
} }
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 * Chooses the most likely title from the loaded text shapes on a slide.
* @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 ( const pickTitleText = (
shapes: PowerPoint.ShapeScopedCollection, candidates: TitleCandidate[],
context: PowerPoint.RequestContext method: TitleDetectionMethod
): Promise<PowerPoint.Shape | null> => { ): string | null => {
// Check if any shape is selected if (candidates.length === 0) {
if (shapes.items.length === 0) {
setStatusMessage("Please select a text box to insert slide titles.");
setStatusType("warning");
return null; return null;
} }
// Get the first selected shape // The first text shape in z-order
const selectedShape = shapes.items[0]; if (method === "first") {
return candidates[0].text;
// 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; // Shape names are the most reliable hint when present
};
/**
* 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") { if (method === "auto" || method === "name") {
for (let j = 0; j < shapes.items.length; j++) { const namedCandidate = candidates.find((candidate) => {
const shape = shapes.items[j]; const name = candidate.name.toLowerCase();
return name.includes("title") || name.includes("heading");
});
// Check if this shape has a name that indicates it's a title if (namedCandidate) {
shape.load("name,textFrame"); return namedCandidate.text;
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") { if (method === "name") {
return null; 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 // The first text shape near the top of the slide
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") { if (method === "position") {
return { text: shapeText }; const positionedCandidate = candidates.find(
(candidate) => candidate.top < TITLE_POSITION_THRESHOLD
);
return positionedCandidate ? positionedCandidate.text : null;
} }
// For auto method, add to candidates with priority score // Auto mode: rank the shapes nearest the top of the slide
const fontSize = shape.textFrame.textRange.font.size || 12; const topCandidates = candidates.filter(
const isBold = shape.textFrame.textRange.font.bold || false; (candidate) => candidate.top < TITLE_POSITION_THRESHOLD
);
titleCandidates.push({ if (topCandidates.length === 0) {
text: shapeText, return null;
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 topCandidates.sort((a, b) => a.top - b.top);
if (titleCandidates.length > 0) { const nearestCandidates = topCandidates.filter(
// First sort by vertical position (top-most first) (candidate) => candidate.top <= topCandidates[0].top + 50
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) { if (nearestCandidates.length > 1) {
// Sort by a combination of factors: nearestCandidates.sort((a, b) => {
// 1. How centered the shape is // Prefer shapes that are centered, use a larger font, are bold, and are wider
// 2. Font size (larger is better) const aCenterOffset = Math.abs(a.left + a.width / 2 - STANDARD_SLIDE_WIDTH / 2);
// 3. Bold text is preferred const bCenterOffset = Math.abs(b.left + b.width / 2 - STANDARD_SLIDE_WIDTH / 2);
// 4. Width (wider is better for titles) const aFontScore = a.fontSize * (a.isBold ? 1.5 : 1);
topCandidates.sort((a, b) => { const bFontScore = b.fontSize * (b.isBold ? 1.5 : 1);
// 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 aScore = aCenterOffset * 2 - aFontScore * 5 - a.width * 0.5;
const bScore = bCenterOffset * 2 - bFontScore * 5 - b.width * 0.5; const bScore = bCenterOffset * 2 - bFontScore * 5 - b.width * 0.5;
return aScore - bScore; return aScore - bScore;
}); });
} }
// Return the best candidate return nearestCandidates[0].text;
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 * Collects titles from all slides using three batched syncs instead of
* @param slides The collection of slides * multiple round-trips per shape.
* @param context The PowerPoint request context
* @param options Options for title collection
* @returns The collected titles and count
*/ */
const collectSlideTitles = async ( const collectSlideTitles = async (
slides: PowerPoint.SlideCollection, slides: PowerPoint.SlideCollection,
context: PowerPoint.RequestContext, context: PowerPoint.RequestContext,
options: TitleCollectionOptions = { options: TitleCollectionOptions
includeSlideNumbers: false,
detectionMethod: "auto"
}
): Promise<TitleCollectionResult> => { ): 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 titleText = "";
let titlesCollected = 0; let titlesCollected = 0;
try {
// Process each slide
for (let i = 0; i < slides.items.length; i++) { for (let i = 0; i < slides.items.length; i++) {
const slide = slides.items[i]; const candidates: TitleCandidate[] = [];
// Load shapes collection for (const shape of slides.items[i].shapes.items) {
slide.load("shapes"); if (!isTextCapableShape(shape) || !shape.textFrame.hasText) {
await context.sync(); continue;
}
const shapes = slide.shapes; const text = shape.textFrame.textRange.text;
shapes.load("items"); if (!text || text.trim() === "") {
await context.sync(); continue;
}
// Find the title shape on this slide candidates.push({
const titleShape = await findTitleShape( name: shape.name,
shapes, text: text.trim(),
context, top: shape.top,
i + 1, left: shape.left,
options.detectionMethod || "auto" width: shape.width,
); height: shape.height,
fontSize: shape.textFrame.textRange.font.size ?? 12,
isBold: shape.textFrame.textRange.font.bold ?? false
});
}
if (titleShape) { const title = pickTitleText(candidates, options.detectionMethod || "auto");
// Format the title text based on options if (title) {
const slideTitle = titleShape.text.trim();
const formattedTitle = options.includeSlideNumbers const formattedTitle = options.includeSlideNumbers
? `Slide ${i + 1}: ${slideTitle}` ? `Slide ${i + 1}: ${title}`
: slideTitle; : title;
// Add to our collection
titleText += `${formattedTitle}\n`; titleText += `${formattedTitle}\n`;
titlesCollected++; titlesCollected++;
} }
} }
} catch (error) {
console.error("Error collecting slide titles:", getErrorMessage(error));
}
return { titleText, titlesCollected }; 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 * Generates an appropriate status message based on the results
* @param titlesCollected The number of titles collected * @param titlesCollected The number of titles collected
@@ -339,53 +207,64 @@ export const InsertTitles: React.FC = () => {
return `Collected and inserted ${titlesCollected} slide titles.`; 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);
/** /**
* Main function to collect and insert slide titles * Main function to collect and insert slide titles
*/ */
const collectAndInsertTitles = async (): Promise<void> => { const collectAndInsertTitles = async (): Promise<void> => {
try { try {
await PowerPoint.run(async (context) => { await PowerPoint.run(async (context) => {
// Get the selected shapes // Get the selected shapes and all slides in one batch
const selectedShapes = context.presentation.getSelectedShapes(); 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; const slides = context.presentation.slides;
selectedShapes.load("items");
slides.load("items"); slides.load("items");
await context.sync(); await context.sync();
// Collect titles from all slides if (selectedShapes.items.length === 0) {
const { titleText, titlesCollected } = await collectSlideTitles( setStatusMessage("Please select a text box to insert slide titles.");
slides, setStatusType("warning");
context, return;
{
includeSlideNumbers: includeSlideNumbers,
detectionMethod: titleDetectionMethod
} }
);
// 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,
detectionMethod: titleDetectionMethod
});
// Insert titles if any were found // Insert titles if any were found
let insertSuccess = false; let insertSuccess = false;
if (titleText) { if (titleText) {
insertSuccess = await insertTitlesIntoShape(targetShape, titleText, context); targetShape.textFrame.textRange.text = titleText;
await context.sync();
insertSuccess = true;
} }
// Update status message // Update status message
const statusMessage = generateStatusMessage(titlesCollected, insertSuccess); setStatusMessage(generateStatusMessage(titlesCollected, insertSuccess));
setStatusMessage(statusMessage);
setStatusType( setStatusType(
titlesCollected === 0 ? "warning" : titlesCollected === 0 ? "warning" :
insertSuccess ? "success" : "error" insertSuccess ? "success" : "error"
); );
}); });
} catch (error) { } catch (error: unknown) {
console.error("Error in collectAndInsertTitles:", getErrorMessage(error)); console.error("Error in collectAndInsertTitles:", getErrorMessage(error));
setStatusMessage(`Error: ${getErrorMessage(error)}`); setStatusMessage(`Error: ${getErrorMessage(error)}`);
setStatusType("error"); setStatusType("error");
@@ -399,6 +278,9 @@ export const InsertTitles: React.FC = () => {
title="Insert Titles" title="Insert Titles"
icon={<TextBulletListRegular />} icon={<TextBulletListRegular />}
onClick={collectAndInsertTitles} 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>
<div style={{ marginTop: '10px', display: 'flex', justifyContent: 'flex-end' }}> <div style={{ marginTop: '10px', display: 'flex', justifyContent: 'flex-end' }}>
+65 -117
View File
@@ -16,7 +16,11 @@ import {
} from "@fluentui/react-icons"; } from "@fluentui/react-icons";
import { useStatusContext } from "./App"; import { useStatusContext } from "./App";
import { useCommonStyles } from "./commonStyles"; 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 // Constants for progress bar configuration
const PROGRESS_BAR_CONFIG = { const PROGRESS_BAR_CONFIG = {
@@ -26,20 +30,11 @@ const PROGRESS_BAR_CONFIG = {
// Progress bar appearance // Progress bar appearance
barHeight: 1, barHeight: 1,
distanceFromBottom: 28, distanceFromBottom: 28,
overlap: 0.5, // Small overlap to ensure no gaps between segments
// Colors // Colors
completedColor: "#205170", // Blue for progressed segments (RGB 32, 81, 112) completedColor: "#205170", // Blue for progressed segments (RGB 32, 81, 112)
pendingColor: "#F2F2F2" // Grey for segments not yet progressed (RGB 242, 242, 242) 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({ const useStyles = makeStyles({
buttonGrid: { buttonGrid: {
display: "grid", display: "grid",
@@ -67,96 +62,73 @@ export const ProgressBarButtons: React.FC = () => {
} = useStatusContext(); } = useStatusContext();
/** /**
* Adds a progress bar to the bottom of each slide in the presentation * Adds a progress bar to the bottom of every slide in the presentation.
* The progress bar shows the current position within the presentation * Each slide gets two rectangles: a full pending bar and the completed portion.
* with colored segments indicating progress
*/ */
const addProgressBar = async () => { const addProgressBar = async () => {
setIsProcessing(true); setIsProcessing(true);
const startTime = performance.now();
try { try {
await PowerPoint.run(async (context) => { await PowerPoint.run(async (context) => {
// Get all slides at once const slides = context.presentation.slides;
const presentation = context.presentation;
const slides = presentation.slides;
slides.load("items"); slides.load("items");
// Single sync to get all slides
await context.sync(); await context.sync();
if (slides.items.length === 0) { const slideCount = slides.items.length;
throw new Error("No slides in the presentation"); if (slideCount === 0) {
setStatusMessage("No slides found in the presentation.");
setStatusType("warning");
return;
} }
// Calculate dimensions based on slide count const { slideWidth, slideHeight, barHeight, distanceFromBottom } = PROGRESS_BAR_CONFIG;
const { slideWidth, slideHeight, barHeight, distanceFromBottom, overlap } = PROGRESS_BAR_CONFIG;
const slideCount = slides.items.length;
const segmentWidth = slideWidth / slideCount; const segmentWidth = slideWidth / slideCount;
const startY = slideHeight - distanceFromBottom; const startY = slideHeight - distanceFromBottom;
// Load all slide layouts at once to reduce API calls // Remove existing bars so repeated clicks replace instead of duplicate them
for (let i = 0; i < slideCount; i++) { for (const slide of slides.items) {
slides.items[i].load("layout/name"); slide.shapes.load("items");
} }
// Single sync to get all layouts
await context.sync(); await context.sync();
// Process each slide without unnecessary syncs const shapesBySlide: PowerPoint.Shape[][] = [];
for (let i = 0; i < slideCount; i++) { for (const slide of slides.items) {
const slide = slides.items[i]; for (const shape of slide.shapes.items) {
const layoutName = slide.layout.name; shape.load("name");
}
shapesBySlide.push(slide.shapes.items);
}
await context.sync();
// Check if this is a layout we want to add the progress bar to for (const shapes of shapesBySlide) {
const isCompatibleLayout = SUPPORTED_LAYOUTS.some(layout => deleteShapesByPrefix(shapes, PROGRESS_BAR_PREFIX);
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 // Two rectangles per slide: the full pending bar and the completed portion
segment.lineFormat.visible = false; 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`;
// Use shape name as identifier for later removal const completed = slide.shapes.addGeometricShape("Rectangle");
segment.name = "progress_bar_" + j; 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 // Single final sync to commit all changes
await context.sync(); await context.sync();
const endTime = performance.now(); setStatusMessage(`Added progress bar to ${slideCount} slides.`);
console.log(`Progress bar creation took ${endTime - startTime}ms`);
setStatusMessage("Added progress bar to slides.");
setStatusType("success"); setStatusType("success");
}); });
} catch (error: unknown) { } catch (error: unknown) {
@@ -174,67 +146,40 @@ export const ProgressBarButtons: React.FC = () => {
*/ */
const removeProgressBar = async () => { const removeProgressBar = async () => {
setIsProcessing(true); setIsProcessing(true);
const startTime = performance.now();
try { try {
await PowerPoint.run(async (context) => { await PowerPoint.run(async (context) => {
// Get all slides at once const slides = context.presentation.slides;
const presentation = context.presentation;
const slides = presentation.slides;
slides.load("items"); slides.load("items");
await context.sync(); await context.sync();
let removedCount = 0; // Load all shapes from all slides in a batch
const shapesToLoad = []; for (const slide of slides.items) {
slide.shapes.load("items");
// 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 });
} }
// Single sync to get all shapes
await context.sync(); await context.sync();
// Now load all shape names in a batch // Load all shape names in a batch
const allShapesWithNames = []; const allShapes: PowerPoint.Shape[] = [];
for (const slide of slides.items) {
for (const { slide, shapes } of shapesToLoad) { for (const shape of slide.shapes.items) {
for (let j = 0; j < shapes.items.length; j++) {
const shape = shapes.items[j];
shape.load("name"); shape.load("name");
allShapesWithNames.push({ slide, shape }); allShapes.push(shape);
} }
} }
// Single sync to get all shape names
await context.sync(); await context.sync();
// Filter shapes that are progress bars and delete them const removedCount = deleteShapesByPrefix(allShapes, PROGRESS_BAR_PREFIX);
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
await context.sync(); await context.sync();
const endTime = performance.now();
console.log(`Progress bar removal took ${endTime - startTime}ms`);
if (removedCount > 0) { if (removedCount > 0) {
setStatusMessage(`Removed progress bar from slides.`); setStatusMessage(`Removed progress bar from slides.`);
setStatusType("success");
} else { } else {
setStatusMessage("No progress bar found to remove."); setStatusMessage("No progress bar found to remove.");
setStatusType("warning");
} }
setStatusType("success");
}); });
} catch (error: unknown) { } catch (error: unknown) {
setStatusMessage(`Error: ${getErrorMessage(error)}`); setStatusMessage(`Error: ${getErrorMessage(error)}`);
@@ -258,16 +203,19 @@ export const ProgressBarButtons: React.FC = () => {
> >
Add Add
</Button> </Button>
<Button <ConfirmButton
appearance="primary" appearance="primary"
className={styles.progressButton} className={styles.progressButton}
onClick={removeProgressBar} onConfirm={removeProgressBar}
icon={<DismissRegular />} icon={<DismissRegular />}
disabled={isProcessing} disabled={isProcessing}
title="Remove Progress Bar" title="Remove Progress Bar"
confirmTitle="Remove progress bars?"
confirmMessage="This removes the progress bar from every slide in the presentation."
confirmLabel="Remove"
> >
Remove Remove
</Button> </ConfirmButton>
</div> </div>
</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 { export function selectShapesById(slide: PowerPoint.Slide, shapeIds: string[]): void {
slide.setSelectedShapes(shapeIds); 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;
}