Fix alignment, progress bar, grid safety, and strict typing issues

- Load layout name before reading it in progress bar creation
- Load shape dimensions before aligning and align to slide edges/center
- Clamp grid spacing/opacity and guard zero spacing before deleting a grid
- Use hasText and text-capable shape checks with null-safe property matching
- Add info status style and remove dead imports
- Enable strict mode and skipLibCheck; add typecheck script
This commit is contained in:
schihei committed 2026-11-25 11:43:23 +01:00
1 parent 16491c00ce
commit 791cbc7b6c
13 files changed
+240 -152

No files matched your search

+1
View File
@@ -17,6 +17,7 @@
"dev-server": "webpack serve --mode development", "dev-server": "webpack serve --mode development",
"lint": "office-addin-lint check", "lint": "office-addin-lint check",
"lint:fix": "office-addin-lint fix", "lint:fix": "office-addin-lint fix",
"typecheck": "tsc --noEmit",
"prettier": "office-addin-lint prettier", "prettier": "office-addin-lint prettier",
"signin": "office-addin-dev-settings m365-account login", "signin": "office-addin-dev-settings m365-account login",
"signout": "office-addin-dev-settings m365-account logout", "signout": "office-addin-dev-settings m365-account logout",
+42 -38
View File
@@ -20,26 +20,19 @@ 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";
/** /**
* Configuration constants for alignment positions * Slide dimensions in points (16:9). Shapes are aligned to the slide edges
* and center, matching PowerPoint's "Align to Slide" behavior.
*/ */
const ALIGNMENT_CONFIG = { const SLIDE_WIDTH = 960;
// Horizontal alignment positions const SLIDE_HEIGHT = 540;
HORIZONTAL: {
LEFT: 81.1, /**
CENTER: 480, // Center point of slide * Warning message when no shapes are selected
RIGHT: 879.75 */
}, const NO_SELECTION_WARNING = "No shapes are selected. Please select shapes first.";
// Vertical alignment positions
VERTICAL: {
TOP: 136.75,
MIDDLE: 321, // Middle point of slide
BOTTOM: 505.25
},
// Warning message when no shapes are selected
NO_SELECTION_WARNING: "No shapes are selected. Please select shapes first."
};
/** /**
* Alignment types for horizontal and vertical alignment * Alignment types for horizontal and vertical alignment
@@ -89,11 +82,10 @@ export const AlignmentButtons: React.FC = () => {
* @param error - The error object * @param error - The error object
* @param operation - The operation being performed (for logging) * @param operation - The operation being performed (for logging)
*/ */
const handleError = (error: any, operation: string): void => { const handleError = (error: unknown, operation: string): void => {
setStatusMessage(`Error: ${error.message || "Unknown error occurred"}`); setStatusMessage(`Error: ${getErrorMessage(error)}`);
setStatusType("error"); setStatusType("error");
console.error(`${operation} error:`, error); console.error(`${operation} error:`, error);
setIsProcessing(false);
}; };
/** /**
@@ -112,22 +104,28 @@ export const AlignmentButtons: React.FC = () => {
// Check if shapes are selected // Check if shapes are selected
if (shapes.items.length === 0) { if (shapes.items.length === 0) {
setStatusMessage(ALIGNMENT_CONFIG.NO_SELECTION_WARNING); setStatusMessage(NO_SELECTION_WARNING);
setStatusType("warning"); setStatusType("warning");
return; return;
} }
// Shape widths are required to center shapes or align their right edges.
if (alignmentType !== "left") {
shapes.items.forEach((shape) => shape.load("width"));
await context.sync();
}
// Set alignment for all shapes at once based on alignment type // Set alignment for all shapes at once based on alignment type
shapes.items.forEach(shape => { shapes.items.forEach((shape) => {
switch (alignmentType) { switch (alignmentType) {
case 'left': case "left":
shape.left = ALIGNMENT_CONFIG.HORIZONTAL.LEFT; shape.left = 0;
break; break;
case 'center': case "center":
shape.left = ALIGNMENT_CONFIG.HORIZONTAL.CENTER - (shape.width / 2); shape.left = Math.max(0, (SLIDE_WIDTH - shape.width) / 2);
break; break;
case 'right': case "right":
shape.left = ALIGNMENT_CONFIG.HORIZONTAL.RIGHT - shape.width; shape.left = Math.max(0, SLIDE_WIDTH - shape.width);
break; break;
} }
}); });
@@ -138,7 +136,7 @@ export const AlignmentButtons: React.FC = () => {
setStatusMessage(`Objects aligned to ${alignmentType}.`); setStatusMessage(`Objects aligned to ${alignmentType}.`);
setStatusType("success"); setStatusType("success");
}); });
} catch (error) { } catch (error: unknown) {
handleError(error, `Align ${alignmentType}`); handleError(error, `Align ${alignmentType}`);
} finally { } finally {
setIsProcessing(false); setIsProcessing(false);
@@ -161,22 +159,28 @@ export const AlignmentButtons: React.FC = () => {
// Check if shapes are selected // Check if shapes are selected
if (shapes.items.length === 0) { if (shapes.items.length === 0) {
setStatusMessage(ALIGNMENT_CONFIG.NO_SELECTION_WARNING); setStatusMessage(NO_SELECTION_WARNING);
setStatusType("warning"); setStatusType("warning");
return; return;
} }
// Shape heights are required to center shapes or align their bottom edges.
if (alignmentType !== "top") {
shapes.items.forEach((shape) => shape.load("height"));
await context.sync();
}
// Set alignment for all shapes at once based on alignment type // Set alignment for all shapes at once based on alignment type
shapes.items.forEach(shape => { shapes.items.forEach((shape) => {
switch (alignmentType) { switch (alignmentType) {
case 'top': case "top":
shape.top = ALIGNMENT_CONFIG.VERTICAL.TOP; shape.top = 0;
break; break;
case 'middle': case "middle":
shape.top = ALIGNMENT_CONFIG.VERTICAL.MIDDLE - (shape.height / 2); shape.top = Math.max(0, (SLIDE_HEIGHT - shape.height) / 2);
break; break;
case 'bottom': case "bottom":
shape.top = ALIGNMENT_CONFIG.VERTICAL.BOTTOM - shape.height; shape.top = Math.max(0, SLIDE_HEIGHT - shape.height);
break; break;
} }
}); });
@@ -187,7 +191,7 @@ export const AlignmentButtons: React.FC = () => {
setStatusMessage(`Objects aligned to ${alignmentType}.`); setStatusMessage(`Objects aligned to ${alignmentType}.`);
setStatusType("success"); setStatusType("success");
}); });
} catch (error) { } catch (error: unknown) {
handleError(error, `Align ${alignmentType}`); handleError(error, `Align ${alignmentType}`);
} finally { } finally {
setIsProcessing(false); setIsProcessing(false);
+5 -1
View File
@@ -18,7 +18,7 @@ import ProgressBarButtons from "./ProgressBarButtons";
import AlignmentButtons from "./AlignmentButtons"; import AlignmentButtons from "./AlignmentButtons";
import GridGuidelineManager from "./GridGuidelineManager"; import GridGuidelineManager from "./GridGuidelineManager";
import Section from "./Section"; import Section from "./Section";
import { makeStyles, Text, tokens, Theme, Spinner } from "@fluentui/react-components"; import { makeStyles, Text, tokens, Spinner } from "@fluentui/react-components";
import { ShapeUnionRegular, SquareRegular, InfoRegular } from "@fluentui/react-icons"; import { ShapeUnionRegular, SquareRegular, InfoRegular } from "@fluentui/react-icons";
interface AppProps { interface AppProps {
@@ -68,6 +68,10 @@ const useStyles = makeStyles({
backgroundColor: "#f3f2f1", // Light gray background backgroundColor: "#f3f2f1", // Light gray background
transition: "all 0.3s ease", transition: "all 0.3s ease",
}, },
infoStatus: {
backgroundColor: "#EFF6FC", // Light blue background
color: "#004578", // Blue text
},
successStatus: { successStatus: {
backgroundColor: "#DFF6DD", // Light green background backgroundColor: "#DFF6DD", // Light green background
color: "#107C10", // Green text color: "#107C10", // Green text
@@ -15,6 +15,7 @@ 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";
/** /**
* Configuration constants for confidential markings * Configuration constants for confidential markings
@@ -93,11 +94,10 @@ export const ConfidentialButtons: React.FC = () => {
* @param error - The error object * @param error - The error object
* @param operation - The operation being performed (for logging) * @param operation - The operation being performed (for logging)
*/ */
const handleError = (error: any, operation: string): void => { const handleError = (error: unknown, operation: string): void => {
setStatusMessage(`Error: ${error.message || "Unknown error occurred"}`); setStatusMessage(`Error: ${getErrorMessage(error)}`);
setStatusType("error"); setStatusType("error");
console.error(`${operation} error:`, error); console.error(`${operation} error:`, error);
setIsProcessing(false);
}; };
/** /**
@@ -107,7 +107,7 @@ export const ConfidentialButtons: React.FC = () => {
* @param isAddOperation - Whether this was an add operation (true) or remove operation (false) * @param isAddOperation - Whether this was an add operation (true) or remove operation (false)
*/ */
const updateStatusFromResult = (result: ProcessingResult, isAddOperation: boolean): void => { const updateStatusFromResult = (result: ProcessingResult, isAddOperation: boolean): void => {
const { processedSlides, errorSlides, affectedCount } = result; const { errorSlides, affectedCount } = result;
if (affectedCount > 0) { if (affectedCount > 0) {
const action = isAddOperation ? "Added" : "Removed"; const action = isAddOperation ? "Added" : "Removed";
+3 -3
View File
@@ -16,6 +16,7 @@ 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";
/** /**
* Configuration constants for draft watermarks * Configuration constants for draft watermarks
@@ -101,11 +102,10 @@ export const DraftButtons: React.FC = () => {
* @param error - The error object * @param error - The error object
* @param operation - The operation being performed (for logging) * @param operation - The operation being performed (for logging)
*/ */
const handleError = (error: any, operation: string): void => { const handleError = (error: unknown, operation: string): void => {
setStatusMessage(`Error: ${error.message || "Unknown error occurred"}`); setStatusMessage(`Error: ${getErrorMessage(error)}`);
setStatusType("error"); setStatusType("error");
console.error(`${operation} error:`, error); console.error(`${operation} error:`, error);
setIsProcessing(false);
}; };
/** /**
@@ -26,6 +26,7 @@ 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";
/** /**
* Standard dimensions for PowerPoint slides in points * Standard dimensions for PowerPoint slides in points
@@ -33,6 +34,22 @@ import { useCommonStyles } from "./commonStyles";
const SLIDE_WIDTH = 960; // Width in points const SLIDE_WIDTH = 960; // Width in points
const SLIDE_HEIGHT = 540; // Height in points const SLIDE_HEIGHT = 540; // Height in points
/**
* Safety limits for user-provided grid and guideline values.
* A spacing of 0 would divide by zero and create an unbounded number of shapes.
*/
const GRID_SPACING_MIN = 4;
const GRID_SPACING_MAX = Math.min(SLIDE_WIDTH, SLIDE_HEIGHT);
const GRID_OPACITY_MIN = 0;
const GRID_OPACITY_MAX = 100;
const MAX_GRID_LINES = 600;
/**
* Restricts a number to the inclusive range [min, max]
*/
const clamp = (value: number, min: number, max: number): number =>
Math.min(max, Math.max(min, value));
/** /**
* Available colors for grids and guidelines * Available colors for grids and guidelines
*/ */
@@ -154,23 +171,27 @@ const ColorButton: React.FC<ColorButtonProps> = ({ color, selectedColor, onClick
* @param initialValue - The initial value for the input * @param initialValue - The initial value for the input
* @returns A tuple containing the current value and a change handler function * @returns A tuple containing the current value and a change handler function
*/ */
const useNumericInputHandler = ( type NumericInputHandler = [
initialValue: number number,
): [number, (e: React.ChangeEvent<HTMLInputElement>) => void] => { (e: React.ChangeEvent<HTMLInputElement>) => void,
(value: number) => void
];
const useNumericInputHandler = (initialValue: number): NumericInputHandler => {
const [value, setValue] = React.useState(initialValue); const [value, setValue] = React.useState(initialValue);
const handleChange = React.useCallback((e: React.ChangeEvent<HTMLInputElement>) => { const handleChange = React.useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value; const newValue = e.target.value;
const parsed = parseInt(newValue); const parsed = Number.parseInt(newValue, 10);
if (newValue === '') { if (newValue === "") {
setValue(0); setValue(0);
} else if (!isNaN(parsed)) { } else if (!Number.isNaN(parsed)) {
setValue(parsed); setValue(parsed);
} }
}, []); }, []);
return [value, handleChange]; return [value, handleChange, setValue];
}; };
/** /**
@@ -183,18 +204,18 @@ export const GridGuidelineManager: React.FC = () => {
const styles = useStyles(); const styles = useStyles();
const commonStyles = useCommonStyles(); const commonStyles = useCommonStyles();
const { const {
statusMessage, setStatusMessage, setStatusMessage,
statusType, setStatusType, setStatusType,
isProcessing, setIsProcessing isProcessing, setIsProcessing
} = useStatusContext(); } = useStatusContext();
// Grid state // Grid state
const [gridSpacing, handleGridSpacingChange] = useNumericInputHandler(50); const [gridSpacing, handleGridSpacingChange, setGridSpacing] = useNumericInputHandler(50);
const [gridColor, setGridColor] = React.useState<GridColor>("blue"); const [gridColor, setGridColor] = React.useState<GridColor>("blue");
const [gridOpacity, handleGridOpacityChange] = useNumericInputHandler(30); const [gridOpacity, handleGridOpacityChange, setGridOpacity] = useNumericInputHandler(30);
// Guidelines state // Guidelines state
const [guidePosition, handleGuidePositionChange] = useNumericInputHandler(240); const [guidePosition, handleGuidePositionChange, setGuidePosition] = useNumericInputHandler(240);
const [guideDirection, setGuideDirection] = React.useState<GuideDirection>("horizontal"); const [guideDirection, setGuideDirection] = React.useState<GuideDirection>("horizontal");
const [guideColor, setGuideColor] = React.useState<GridColor>("red"); const [guideColor, setGuideColor] = React.useState<GridColor>("red");
@@ -239,6 +260,36 @@ export const GridGuidelineManager: React.FC = () => {
* Creates a grid on the current slide based on the configured settings * Creates a grid on the current slide based on the configured settings
*/ */
const createGrid = React.useCallback(async () => { const createGrid = React.useCallback(async () => {
if (!Number.isFinite(gridSpacing) || !Number.isFinite(gridOpacity)) {
setStatusMessage("Please enter valid numeric values for spacing and opacity.");
setStatusType("warning");
return;
}
// A spacing of 0 (or less) would divide by zero or create no lines.
if (gridSpacing <= 0) {
setStatusMessage(`Grid spacing must be at least ${GRID_SPACING_MIN} pt.`);
setStatusType("warning");
return;
}
// Clamp user input before calculating line counts, and keep the inputs in sync.
const spacing = clamp(Math.round(gridSpacing), GRID_SPACING_MIN, GRID_SPACING_MAX);
const opacity = clamp(Math.round(gridOpacity), GRID_OPACITY_MIN, GRID_OPACITY_MAX);
if (spacing !== gridSpacing) setGridSpacing(spacing);
if (opacity !== gridOpacity) setGridOpacity(opacity);
// Validate before removing an existing grid so a bad value cannot leave the slide grid-less.
const numHorizontalLines = Math.floor(SLIDE_HEIGHT / spacing);
const numVerticalLines = Math.floor(SLIDE_WIDTH / spacing);
if (numHorizontalLines + numVerticalLines > MAX_GRID_LINES) {
setStatusMessage(
`Grid spacing of ${spacing} pt creates too many lines. Use a larger spacing value.`
);
setStatusType("warning");
return;
}
setIsProcessing(true); setIsProcessing(true);
try { try {
await PowerPoint.run(async (context) => { await PowerPoint.run(async (context) => {
@@ -256,13 +307,9 @@ export const GridGuidelineManager: React.FC = () => {
const currentSlide = selectedSlides.items[0]; const currentSlide = selectedSlides.items[0];
// Calculate number of lines needed
const numHorizontalLines = Math.floor(SLIDE_HEIGHT / gridSpacing);
const numVerticalLines = Math.floor(SLIDE_WIDTH / gridSpacing);
// 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 * gridSpacing; const yPosition = i * spacing;
// Skip if we're at the edge of the slide // Skip if we're at the edge of the slide
if (yPosition >= SLIDE_HEIGHT) continue; if (yPosition >= SLIDE_HEIGHT) continue;
@@ -277,12 +324,12 @@ export const GridGuidelineManager: React.FC = () => {
line.lineFormat.visible = false; // No outline, just fill line.lineFormat.visible = false; // No outline, just fill
// Set transparency (opacity is inverse of transparency) // Set transparency (opacity is inverse of transparency)
line.fill.transparency = (100 - gridOpacity) / 100; line.fill.transparency = (100 - opacity) / 100;
} }
// Create vertical grid lines // Create vertical grid lines
for (let i = 1; i <= numVerticalLines; i++) { for (let i = 1; i <= numVerticalLines; i++) {
const xPosition = i * gridSpacing; const xPosition = i * spacing;
// Skip if we're at the edge of the slide // Skip if we're at the edge of the slide
if (xPosition >= SLIDE_WIDTH) continue; if (xPosition >= SLIDE_WIDTH) continue;
@@ -297,20 +344,20 @@ export const GridGuidelineManager: React.FC = () => {
line.lineFormat.visible = false; // No outline, just fill line.lineFormat.visible = false; // No outline, just fill
// Set transparency (opacity is inverse of transparency) // Set transparency (opacity is inverse of transparency)
line.fill.transparency = (100 - gridOpacity) / 100; line.fill.transparency = (100 - opacity) / 100;
} }
setStatusMessage("Grid created on current slide"); setStatusMessage("Grid created on current slide");
setStatusType("success"); setStatusType("success");
}); });
} catch (error) { } catch (error: unknown) {
setStatusMessage(`Error: ${error.message}`); setStatusMessage(`Error: ${getErrorMessage(error)}`);
setStatusType("error"); setStatusType("error");
console.error("Create grid error:", error); console.error("Create grid error:", error);
} finally { } finally {
setIsProcessing(false); setIsProcessing(false);
} }
}, [createLineShape, gridColor, gridOpacity, gridSpacing, setIsProcessing, setStatusMessage, setStatusType]); }, [createLineShape, gridColor, gridOpacity, gridSpacing, setGridOpacity, setGridSpacing, setIsProcessing, setStatusMessage, setStatusType]);
/** /**
* Removes the grid from the current slide * Removes the grid from the current slide
@@ -370,9 +417,9 @@ export const GridGuidelineManager: React.FC = () => {
setStatusType("success"); setStatusType("success");
} }
}); });
} catch (error) { } catch (error: unknown) {
if (showStatus) { if (showStatus) {
setStatusMessage(`Error: ${error.message}`); setStatusMessage(`Error: ${getErrorMessage(error)}`);
setStatusType("error"); setStatusType("error");
} }
console.error("Remove grid error:", error); console.error("Remove grid error:", error);
@@ -387,6 +434,17 @@ export const GridGuidelineManager: React.FC = () => {
* Adds a guideline to the current slide based on the configured settings * Adds a guideline to the current slide based on the configured settings
*/ */
const addGuideline = React.useCallback(async () => { const addGuideline = React.useCallback(async () => {
if (!Number.isFinite(guidePosition)) {
setStatusMessage("Please enter a valid numeric position for the guideline.");
setStatusType("warning");
return;
}
// Keep the guideline inside the slide so it is visible and meaningful.
const maxPosition = guideDirection === "horizontal" ? SLIDE_HEIGHT : SLIDE_WIDTH;
const position = clamp(Math.round(guidePosition), 0, maxPosition);
if (position !== guidePosition) setGuidePosition(position);
setIsProcessing(true); setIsProcessing(true);
try { try {
await PowerPoint.run(async (context) => { await PowerPoint.run(async (context) => {
@@ -407,13 +465,13 @@ export const GridGuidelineManager: React.FC = () => {
const guideId = `${GUIDE_PREFIX}${guideDirection}_${timestamp}`; const guideId = `${GUIDE_PREFIX}${guideDirection}_${timestamp}`;
// Add the guide line // Add the guide line
let line; let line: PowerPoint.Shape;
if (guideDirection === "horizontal") { if (guideDirection === "horizontal") {
// Create horizontal guideline // Create horizontal guideline
line = createLineShape(currentSlide, 0, guidePosition, SLIDE_WIDTH, guidePosition); line = createLineShape(currentSlide, 0, position, SLIDE_WIDTH, position);
} else { } else {
// Create vertical guideline // Create vertical guideline
line = createLineShape(currentSlide, guidePosition, 0, guidePosition, SLIDE_HEIGHT); line = createLineShape(currentSlide, position, 0, position, SLIDE_HEIGHT);
} }
line.name = guideId; line.name = guideId;
@@ -428,14 +486,14 @@ export const GridGuidelineManager: React.FC = () => {
setStatusMessage(`Added ${guideDirection} guideline`); setStatusMessage(`Added ${guideDirection} guideline`);
setStatusType("success"); setStatusType("success");
}); });
} catch (error) { } catch (error: unknown) {
setStatusMessage(`Error: ${error.message}`); setStatusMessage(`Error: ${getErrorMessage(error)}`);
setStatusType("error"); setStatusType("error");
console.error("Add guideline error:", error); console.error("Add guideline error:", error);
} finally { } finally {
setIsProcessing(false); setIsProcessing(false);
} }
}, [createLineShape, guideColor, guideDirection, guidePosition, setIsProcessing, setStatusMessage, setStatusType]); }, [createLineShape, guideColor, guideDirection, guidePosition, setGuidePosition, setIsProcessing, setStatusMessage, setStatusType]);
/** /**
* Removes all guidelines from the current slide * Removes all guidelines from the current slide
@@ -488,8 +546,8 @@ export const GridGuidelineManager: React.FC = () => {
} }
setStatusType("success"); setStatusType("success");
}); });
} catch (error) { } catch (error: unknown) {
setStatusMessage(`Error: ${error.message}`); setStatusMessage(`Error: ${getErrorMessage(error)}`);
setStatusType("error"); setStatusType("error");
console.error("Remove guidelines error:", error); console.error("Remove guidelines error:", error);
} finally { } finally {
+6 -6
View File
@@ -10,11 +10,11 @@ import { TextBulletListRegular } from "@fluentui/react-icons";
import { useStatusContext } from "./App"; import { useStatusContext } from "./App";
import { useCommonStyles } from "./commonStyles"; import { useCommonStyles } from "./commonStyles";
import ActionButton from "./ActionButton"; import ActionButton from "./ActionButton";
import { getErrorMessage } 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; // Pixels from top of slide to consider a shape as a title
const STANDARD_SLIDE_WIDTH = 720; // Standard PowerPoint slide width const STANDARD_SLIDE_WIDTH = 960; // Standard widescreen PowerPoint slide width in points
// Title detection methods // Title detection methods
type TitleDetectionMethod = "auto" | "position" | "first" | "name"; type TitleDetectionMethod = "auto" | "position" | "first" | "name";
@@ -68,11 +68,11 @@ export const InsertTitles: React.FC = () => {
// Get the first selected shape // Get the first selected shape
const selectedShape = shapes.items[0]; const selectedShape = shapes.items[0];
// Check if the selected shape has a text frame // Check that the selected shape can hold editable text
selectedShape.load("textFrame"); selectedShape.load("type");
await context.sync(); await context.sync();
if (!selectedShape.textFrame) { if (!isTextCapableShape(selectedShape)) {
setStatusMessage("Please select a text box to insert slide titles."); setStatusMessage("Please select a text box to insert slide titles.");
setStatusType("warning"); setStatusType("warning");
return null; return null;
@@ -96,7 +96,7 @@ export const InsertTitles: React.FC = () => {
method: TitleDetectionMethod = "auto" method: TitleDetectionMethod = "auto"
): Promise<{ text: string } | null> => { ): Promise<{ text: string } | null> => {
try { try {
let titleCandidates: TitleCandidate[] = []; const titleCandidates: TitleCandidate[] = [];
// First pass: look for title shapes by name // First pass: look for title shapes by name
// This is the most reliable method if available // This is the most reliable method if available
+46 -58
View File
@@ -10,14 +10,7 @@ import { ColorRegular } from "@fluentui/react-icons";
import { useStatusContext } from "./App"; import { useStatusContext } from "./App";
import { useCommonStyles } from "./commonStyles"; import { useCommonStyles } from "./commonStyles";
import ActionButton from "./ActionButton"; import ActionButton from "./ActionButton";
import { getErrorMessage } from "../types/office-types"; import { getErrorMessage, isNotNullish, isTextCapableShape } from "../types/office-types";
// Property types that can be matched
enum PropertyType {
Line = "line",
Fill = "fill",
Text = "text"
}
// Shape property loading configuration // Shape property loading configuration
const SHAPE_PROPERTIES = { const SHAPE_PROPERTIES = {
@@ -29,9 +22,6 @@ const SHAPE_PROPERTIES = {
fill: [ fill: [
"fill/transparency", "fill/transparency",
"fill/foregroundColor" "fill/foregroundColor"
],
text: [
"textFrame"
] ]
}; };
@@ -80,11 +70,11 @@ export const MatchProperties: React.FC = () => {
sourceShape: PowerPoint.Shape, sourceShape: PowerPoint.Shape,
context: PowerPoint.RequestContext context: PowerPoint.RequestContext
): Promise<{ hasText: boolean }> => { ): Promise<{ hasText: boolean }> => {
// Load basic shape properties // Load basic shape properties and whether the shape actually contains text
const propertiesToLoad = [ const propertiesToLoad = [
...SHAPE_PROPERTIES.line, ...SHAPE_PROPERTIES.line,
...SHAPE_PROPERTIES.fill, ...SHAPE_PROPERTIES.fill,
...SHAPE_PROPERTIES.text "textFrame/hasText"
]; ];
sourceShape.load(propertiesToLoad); sourceShape.load(propertiesToLoad);
@@ -92,16 +82,11 @@ export const MatchProperties: React.FC = () => {
// Check if the shape has text and load text properties if it does // Check if the shape has text and load text properties if it does
let hasText = false; let hasText = false;
if (sourceShape.textFrame) { if (sourceShape.textFrame.hasText) {
sourceShape.textFrame.load("textRange");
await context.sync();
if (sourceShape.textFrame.textRange) {
sourceShape.textFrame.textRange.load(FONT_PROPERTIES); sourceShape.textFrame.textRange.load(FONT_PROPERTIES);
await context.sync(); await context.sync();
hasText = true; hasText = true;
} }
}
return { hasText }; return { hasText };
}; };
@@ -119,17 +104,9 @@ export const MatchProperties: React.FC = () => {
): Promise<void> => { ): Promise<void> => {
if (!hasText) return; if (!hasText) return;
// Batch 1: Load textFrame for all target shapes // Load the target shape types so text formatting is only applied to shapes that can hold text
for (let i = 1; i < shapes.items.length; i++) { for (let i = 1; i < shapes.items.length; i++) {
shapes.items[i].load("textFrame"); shapes.items[i].load("type");
}
await context.sync();
// Batch 2: For shapes that have textFrames, load their textRanges
for (let i = 1; i < shapes.items.length; i++) {
if (shapes.items[i].textFrame) {
shapes.items[i].textFrame.load("textRange");
}
} }
await context.sync(); await context.sync();
}; };
@@ -148,19 +125,19 @@ export const MatchProperties: React.FC = () => {
try { try {
// Line weight // Line weight
if (sourceShape.lineFormat.weight !== undefined) { if (isNotNullish(sourceShape.lineFormat.weight)) {
targetShape.lineFormat.weight = sourceShape.lineFormat.weight; targetShape.lineFormat.weight = sourceShape.lineFormat.weight;
propertiesApplied = true; propertiesApplied = true;
} }
// Line style // Line style
if (sourceShape.lineFormat.dashStyle !== undefined) { if (isNotNullish(sourceShape.lineFormat.dashStyle)) {
targetShape.lineFormat.dashStyle = sourceShape.lineFormat.dashStyle; targetShape.lineFormat.dashStyle = sourceShape.lineFormat.dashStyle;
propertiesApplied = true; propertiesApplied = true;
} }
// Line color // Line color
if (sourceShape.lineFormat.color !== undefined) { if (isNotNullish(sourceShape.lineFormat.color)) {
targetShape.lineFormat.color = sourceShape.lineFormat.color; targetShape.lineFormat.color = sourceShape.lineFormat.color;
propertiesApplied = true; propertiesApplied = true;
} }
@@ -185,13 +162,13 @@ export const MatchProperties: React.FC = () => {
try { try {
// Fill transparency // Fill transparency
if (sourceShape.fill.transparency !== undefined) { if (isNotNullish(sourceShape.fill.transparency)) {
targetShape.fill.transparency = sourceShape.fill.transparency; targetShape.fill.transparency = sourceShape.fill.transparency;
propertiesApplied = true; propertiesApplied = true;
} }
// Fill color // Fill color
if (sourceShape.fill.foregroundColor !== undefined) { if (isNotNullish(sourceShape.fill.foregroundColor)) {
targetShape.fill.foregroundColor = sourceShape.fill.foregroundColor; targetShape.fill.foregroundColor = sourceShape.fill.foregroundColor;
propertiesApplied = true; propertiesApplied = true;
} }
@@ -213,43 +190,52 @@ export const MatchProperties: React.FC = () => {
sourceShape: PowerPoint.Shape, sourceShape: PowerPoint.Shape,
targetShape: PowerPoint.Shape targetShape: PowerPoint.Shape
): boolean => { ): boolean => {
// Only copy text formatting when the source has text and the target can hold text.
if (!sourceShape.textFrame.hasText || !isTextCapableShape(targetShape)) {
return false;
}
let propertiesApplied = false;
try { try {
if (sourceShape.textFrame?.textRange && targetShape.textFrame?.textRange) {
const sourceFont = sourceShape.textFrame.textRange.font; const sourceFont = sourceShape.textFrame.textRange.font;
const targetFont = targetShape.textFrame.textRange.font; const targetFont = targetShape.textFrame.textRange.font;
// Apply font properties in batch // Apply font properties in batch
if (sourceFont.name !== undefined) { if (isNotNullish(sourceFont.name)) {
targetFont.name = sourceFont.name; targetFont.name = sourceFont.name;
propertiesApplied = true;
} }
if (sourceFont.size !== undefined) { if (isNotNullish(sourceFont.size)) {
targetFont.size = sourceFont.size; targetFont.size = sourceFont.size;
propertiesApplied = true;
} }
if (sourceFont.bold !== undefined) { if (isNotNullish(sourceFont.bold)) {
targetFont.bold = sourceFont.bold; targetFont.bold = sourceFont.bold;
propertiesApplied = true;
} }
if (sourceFont.italic !== undefined) { if (isNotNullish(sourceFont.italic)) {
targetFont.italic = sourceFont.italic; targetFont.italic = sourceFont.italic;
propertiesApplied = true;
} }
if (sourceFont.underline !== undefined) { if (isNotNullish(sourceFont.underline)) {
targetFont.underline = sourceFont.underline; targetFont.underline = sourceFont.underline;
propertiesApplied = true;
} }
if (sourceFont.color !== undefined) { if (isNotNullish(sourceFont.color)) {
targetFont.color = sourceFont.color; targetFont.color = sourceFont.color;
} propertiesApplied = true;
return true;
} }
} catch (err) { } catch (err) {
console.error("Error applying text format:", getErrorMessage(err)); console.error("Error applying text format:", getErrorMessage(err));
} }
return false; return propertiesApplied;
}; };
/** /**
@@ -279,29 +265,29 @@ export const MatchProperties: React.FC = () => {
// Apply properties to all target shapes // Apply properties to all target shapes
let successCount = 0; let successCount = 0;
let textStyleCount = 0; let textStyleCount = 0;
let lineAppliedToAny = false;
let fillAppliedToAny = false;
for (let i = 1; i < shapes.items.length; i++) { for (let i = 1; i < shapes.items.length; i++) {
const targetShape = shapes.items[i]; const targetShape = shapes.items[i];
let shapeUpdated = false;
// Apply different property types // Apply different property types
const lineApplied = applyLineProperties(sourceShape, targetShape); const lineApplied = applyLineProperties(sourceShape, targetShape);
const fillApplied = applyFillProperties(sourceShape, targetShape); const fillApplied = applyFillProperties(sourceShape, targetShape);
lineAppliedToAny = lineAppliedToAny || lineApplied;
fillAppliedToAny = fillAppliedToAny || fillApplied;
// Apply text properties if available // Apply text properties if available
let textApplied = false;
if (hasText) { if (hasText) {
const textApplied = applyTextProperties(sourceShape, targetShape); textApplied = applyTextProperties(sourceShape, targetShape);
if (textApplied) { if (textApplied) {
textStyleCount++; textStyleCount++;
} }
} }
// Count successful shape updates // Count successful shape updates
if (lineApplied || fillApplied) { if (lineApplied || fillApplied || textApplied) {
shapeUpdated = true;
}
if (shapeUpdated) {
successCount++; successCount++;
} }
} }
@@ -311,14 +297,16 @@ export const MatchProperties: React.FC = () => {
// Generate appropriate status message // Generate appropriate status message
if (successCount > 0) { if (successCount > 0) {
const propertyTypes = []; const propertyTypes: string[] = [];
// Build a detailed status message // Build a detailed status message based on what was actually applied
if (sourceShape.lineFormat) propertyTypes.push("line"); if (lineAppliedToAny) propertyTypes.push("line");
if (sourceShape.fill) propertyTypes.push("fill"); if (fillAppliedToAny) propertyTypes.push("fill");
if (propertyTypes.length === 0 && textStyleCount > 0) propertyTypes.push("text");
let message = `Applied ${propertyTypes.join(", ")} properties to ${successCount} shapes`; const appliedProperties = propertyTypes.length > 0 ? propertyTypes.join(", ") : "shape";
if (textStyleCount > 0) { let message = `Applied ${appliedProperties} properties to ${successCount} shapes`;
if (textStyleCount > 0 && (lineAppliedToAny || fillAppliedToAny)) {
message += ` (including text styling on ${textStyleCount})`; message += ` (including text styling on ${textStyleCount})`;
} }
+1 -1
View File
@@ -6,7 +6,7 @@
*/ */
import * as React from "react"; import * as React from "react";
import { ArrowFitInRegular, ArrowMaximizeRegular, ArrowMinimizeRegular } from "@fluentui/react-icons"; import { ArrowFitInRegular } from "@fluentui/react-icons";
import { useStatusContext } from "./App"; import { useStatusContext } from "./App";
import { useCommonStyles } from "./commonStyles"; import { useCommonStyles } from "./commonStyles";
import ActionButton from "./ActionButton"; import ActionButton from "./ActionButton";
@@ -16,6 +16,7 @@ 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";
// Constants for progress bar configuration // Constants for progress bar configuration
const PROGRESS_BAR_CONFIG = { const PROGRESS_BAR_CONFIG = {
@@ -60,8 +61,8 @@ export const ProgressBarButtons: React.FC = () => {
const styles = useStyles(); const styles = useStyles();
const commonStyles = useCommonStyles(); const commonStyles = useCommonStyles();
const { const {
statusMessage, setStatusMessage, setStatusMessage,
statusType, setStatusType, setStatusType,
isProcessing, setIsProcessing isProcessing, setIsProcessing
} = useStatusContext(); } = useStatusContext();
@@ -96,7 +97,7 @@ export const ProgressBarButtons: React.FC = () => {
// Load all slide layouts at once to reduce API calls // Load all slide layouts at once to reduce API calls
for (let i = 0; i < slideCount; i++) { for (let i = 0; i < slideCount; i++) {
slides.items[i].load("layout"); slides.items[i].load("layout/name");
} }
// Single sync to get all layouts // Single sync to get all layouts
@@ -158,8 +159,8 @@ export const ProgressBarButtons: React.FC = () => {
setStatusMessage("Added progress bar to slides."); setStatusMessage("Added progress bar to slides.");
setStatusType("success"); setStatusType("success");
}); });
} catch (error) { } catch (error: unknown) {
setStatusMessage(`Error: ${error.message}`); setStatusMessage(`Error: ${getErrorMessage(error)}`);
setStatusType("error"); setStatusType("error");
console.error("Add progress bar error:", error); console.error("Add progress bar error:", error);
} finally { } finally {
@@ -235,8 +236,8 @@ export const ProgressBarButtons: React.FC = () => {
} }
setStatusType("success"); setStatusType("success");
}); });
} catch (error) { } catch (error: unknown) {
setStatusMessage(`Error: ${error.message}`); setStatusMessage(`Error: ${getErrorMessage(error)}`);
setStatusType("error"); setStatusType("error");
console.error("Remove progress bar error:", error); console.error("Remove progress bar error:", error);
} finally { } finally {
+1 -1
View File
@@ -1,4 +1,4 @@
import { makeStyles, tokens } from "@fluentui/react-components"; import { makeStyles } from "@fluentui/react-components";
// Common styles used across multiple components // Common styles used across multiple components
export const useCommonStyles = makeStyles({ export const useCommonStyles = makeStyles({
+30
View File
@@ -1,3 +1,5 @@
/* global PowerPoint */
/** /**
* Type definitions for the Office JS API * Type definitions for the Office JS API
*/ */
@@ -26,6 +28,26 @@ export function getErrorMessage(error: unknown): string {
return String(error); return String(error);
} }
/**
* Narrows a value that is neither `undefined` nor `null`.
* Office.js returns `null` for properties that are unsupported or inconsistent.
*/
export function isNotNullish<T>(value: T | null | undefined): value is T {
return value !== undefined && value !== null;
}
/**
* Shape types that can contain editable text.
* `type` must be loaded before calling `isTextCapableShape`.
*/
const TEXT_CAPABLE_SHAPE_TYPES: ReadonlySet<string> = new Set([
"TextBox",
"Placeholder",
"GeometricShape",
"Callout",
"Freeform",
]);
/** /**
* Type-safe wrapper for PowerPoint API operations on shapes * Type-safe wrapper for PowerPoint API operations on shapes
*/ */
@@ -33,6 +55,14 @@ export function isPictureShape(shape: PowerPoint.Shape): boolean {
return shape.type === PowerPoint.ShapeType.image; return shape.type === PowerPoint.ShapeType.image;
} }
/**
* Returns true when the shape supports editable text rather than a picture,
* table, or another non-text shape. Requires the shape's `type` to be loaded.
*/
export function isTextCapableShape(shape: PowerPoint.Shape): boolean {
return TEXT_CAPABLE_SHAPE_TYPES.has(shape.type);
}
/** /**
* Type-safe wrapper for working with PowerPoint slides * Type-safe wrapper for working with PowerPoint slides
*/ */
+2
View File
@@ -12,7 +12,9 @@
"noUnusedParameters": true, "noUnusedParameters": true,
"outDir": "dist", "outDir": "dist",
"removeComments": false, "removeComments": false,
"skipLibCheck": true,
"sourceMap": true, "sourceMap": true,
"strict": true,
"target": "es5", "target": "es5",
"lib": [ "lib": [
"es7", "es7",