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:
1 parent
16491c00ce
commit
791cbc7b6c
13 files changed
+271
-183
No files matched your search
@@ -17,6 +17,7 @@
|
||||
"dev-server": "webpack serve --mode development",
|
||||
"lint": "office-addin-lint check",
|
||||
"lint:fix": "office-addin-lint fix",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"prettier": "office-addin-lint prettier",
|
||||
"signin": "office-addin-dev-settings m365-account login",
|
||||
"signout": "office-addin-dev-settings m365-account logout",
|
||||
|
||||
@@ -20,26 +20,19 @@ import {
|
||||
} from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
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 = {
|
||||
// Horizontal alignment positions
|
||||
HORIZONTAL: {
|
||||
LEFT: 81.1,
|
||||
CENTER: 480, // Center point of slide
|
||||
RIGHT: 879.75
|
||||
},
|
||||
// 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."
|
||||
};
|
||||
const SLIDE_WIDTH = 960;
|
||||
const SLIDE_HEIGHT = 540;
|
||||
|
||||
/**
|
||||
* Warning message when no shapes are selected
|
||||
*/
|
||||
const NO_SELECTION_WARNING = "No shapes are selected. Please select shapes first.";
|
||||
|
||||
/**
|
||||
* Alignment types for horizontal and vertical alignment
|
||||
@@ -89,11 +82,10 @@ export const AlignmentButtons: React.FC = () => {
|
||||
* @param error - The error object
|
||||
* @param operation - The operation being performed (for logging)
|
||||
*/
|
||||
const handleError = (error: any, operation: string): void => {
|
||||
setStatusMessage(`Error: ${error.message || "Unknown error occurred"}`);
|
||||
const handleError = (error: unknown, operation: string): void => {
|
||||
setStatusMessage(`Error: ${getErrorMessage(error)}`);
|
||||
setStatusType("error");
|
||||
console.error(`${operation} error:`, error);
|
||||
setIsProcessing(false);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -112,33 +104,39 @@ export const AlignmentButtons: React.FC = () => {
|
||||
|
||||
// Check if shapes are selected
|
||||
if (shapes.items.length === 0) {
|
||||
setStatusMessage(ALIGNMENT_CONFIG.NO_SELECTION_WARNING);
|
||||
setStatusMessage(NO_SELECTION_WARNING);
|
||||
setStatusType("warning");
|
||||
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
|
||||
shapes.items.forEach(shape => {
|
||||
shapes.items.forEach((shape) => {
|
||||
switch (alignmentType) {
|
||||
case 'left':
|
||||
shape.left = ALIGNMENT_CONFIG.HORIZONTAL.LEFT;
|
||||
case "left":
|
||||
shape.left = 0;
|
||||
break;
|
||||
case 'center':
|
||||
shape.left = ALIGNMENT_CONFIG.HORIZONTAL.CENTER - (shape.width / 2);
|
||||
case "center":
|
||||
shape.left = Math.max(0, (SLIDE_WIDTH - shape.width) / 2);
|
||||
break;
|
||||
case 'right':
|
||||
shape.left = ALIGNMENT_CONFIG.HORIZONTAL.RIGHT - shape.width;
|
||||
case "right":
|
||||
shape.left = Math.max(0, SLIDE_WIDTH - shape.width);
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// Single sync after all updates
|
||||
await context.sync();
|
||||
|
||||
|
||||
setStatusMessage(`Objects aligned to ${alignmentType}.`);
|
||||
setStatusType("success");
|
||||
});
|
||||
} catch (error) {
|
||||
} catch (error: unknown) {
|
||||
handleError(error, `Align ${alignmentType}`);
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
@@ -161,33 +159,39 @@ export const AlignmentButtons: React.FC = () => {
|
||||
|
||||
// Check if shapes are selected
|
||||
if (shapes.items.length === 0) {
|
||||
setStatusMessage(ALIGNMENT_CONFIG.NO_SELECTION_WARNING);
|
||||
setStatusMessage(NO_SELECTION_WARNING);
|
||||
setStatusType("warning");
|
||||
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
|
||||
shapes.items.forEach(shape => {
|
||||
shapes.items.forEach((shape) => {
|
||||
switch (alignmentType) {
|
||||
case 'top':
|
||||
shape.top = ALIGNMENT_CONFIG.VERTICAL.TOP;
|
||||
case "top":
|
||||
shape.top = 0;
|
||||
break;
|
||||
case 'middle':
|
||||
shape.top = ALIGNMENT_CONFIG.VERTICAL.MIDDLE - (shape.height / 2);
|
||||
case "middle":
|
||||
shape.top = Math.max(0, (SLIDE_HEIGHT - shape.height) / 2);
|
||||
break;
|
||||
case 'bottom':
|
||||
shape.top = ALIGNMENT_CONFIG.VERTICAL.BOTTOM - shape.height;
|
||||
case "bottom":
|
||||
shape.top = Math.max(0, SLIDE_HEIGHT - shape.height);
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// Single sync after all updates
|
||||
await context.sync();
|
||||
|
||||
|
||||
setStatusMessage(`Objects aligned to ${alignmentType}.`);
|
||||
setStatusType("success");
|
||||
});
|
||||
} catch (error) {
|
||||
} catch (error: unknown) {
|
||||
handleError(error, `Align ${alignmentType}`);
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
|
||||
@@ -18,7 +18,7 @@ import ProgressBarButtons from "./ProgressBarButtons";
|
||||
import AlignmentButtons from "./AlignmentButtons";
|
||||
import GridGuidelineManager from "./GridGuidelineManager";
|
||||
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";
|
||||
|
||||
interface AppProps {
|
||||
@@ -68,6 +68,10 @@ const useStyles = makeStyles({
|
||||
backgroundColor: "#f3f2f1", // Light gray background
|
||||
transition: "all 0.3s ease",
|
||||
},
|
||||
infoStatus: {
|
||||
backgroundColor: "#EFF6FC", // Light blue background
|
||||
color: "#004578", // Blue text
|
||||
},
|
||||
successStatus: {
|
||||
backgroundColor: "#DFF6DD", // Light green background
|
||||
color: "#107C10", // Green text
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
} from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import { getErrorMessage } from "../types/office-types";
|
||||
|
||||
/**
|
||||
* Configuration constants for confidential markings
|
||||
@@ -93,11 +94,10 @@ export const ConfidentialButtons: React.FC = () => {
|
||||
* @param error - The error object
|
||||
* @param operation - The operation being performed (for logging)
|
||||
*/
|
||||
const handleError = (error: any, operation: string): void => {
|
||||
setStatusMessage(`Error: ${error.message || "Unknown error occurred"}`);
|
||||
const handleError = (error: unknown, operation: string): void => {
|
||||
setStatusMessage(`Error: ${getErrorMessage(error)}`);
|
||||
setStatusType("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)
|
||||
*/
|
||||
const updateStatusFromResult = (result: ProcessingResult, isAddOperation: boolean): void => {
|
||||
const { processedSlides, errorSlides, affectedCount } = result;
|
||||
const { errorSlides, affectedCount } = result;
|
||||
|
||||
if (affectedCount > 0) {
|
||||
const action = isAddOperation ? "Added" : "Removed";
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import { getErrorMessage } from "../types/office-types";
|
||||
|
||||
/**
|
||||
* Configuration constants for draft watermarks
|
||||
@@ -101,11 +102,10 @@ export const DraftButtons: React.FC = () => {
|
||||
* @param error - The error object
|
||||
* @param operation - The operation being performed (for logging)
|
||||
*/
|
||||
const handleError = (error: any, operation: string): void => {
|
||||
setStatusMessage(`Error: ${error.message || "Unknown error occurred"}`);
|
||||
const handleError = (error: unknown, operation: string): void => {
|
||||
setStatusMessage(`Error: ${getErrorMessage(error)}`);
|
||||
setStatusType("error");
|
||||
console.error(`${operation} error:`, error);
|
||||
setIsProcessing(false);
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
} from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import { getErrorMessage } from "../types/office-types";
|
||||
|
||||
/**
|
||||
* Standard dimensions for PowerPoint slides in points
|
||||
@@ -33,6 +34,22 @@ import { useCommonStyles } from "./commonStyles";
|
||||
const SLIDE_WIDTH = 960; // Width 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
|
||||
*/
|
||||
@@ -154,23 +171,27 @@ const ColorButton: React.FC<ColorButtonProps> = ({ color, selectedColor, onClick
|
||||
* @param initialValue - The initial value for the input
|
||||
* @returns A tuple containing the current value and a change handler function
|
||||
*/
|
||||
const useNumericInputHandler = (
|
||||
initialValue: number
|
||||
): [number, (e: React.ChangeEvent<HTMLInputElement>) => void] => {
|
||||
type NumericInputHandler = [
|
||||
number,
|
||||
(e: React.ChangeEvent<HTMLInputElement>) => void,
|
||||
(value: number) => void
|
||||
];
|
||||
|
||||
const useNumericInputHandler = (initialValue: number): NumericInputHandler => {
|
||||
const [value, setValue] = React.useState(initialValue);
|
||||
|
||||
|
||||
const handleChange = React.useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newValue = e.target.value;
|
||||
const parsed = parseInt(newValue);
|
||||
|
||||
if (newValue === '') {
|
||||
const parsed = Number.parseInt(newValue, 10);
|
||||
|
||||
if (newValue === "") {
|
||||
setValue(0);
|
||||
} else if (!isNaN(parsed)) {
|
||||
} else if (!Number.isNaN(parsed)) {
|
||||
setValue(parsed);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return [value, handleChange];
|
||||
|
||||
return [value, handleChange, setValue];
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -183,18 +204,18 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
const styles = useStyles();
|
||||
const commonStyles = useCommonStyles();
|
||||
const {
|
||||
statusMessage, setStatusMessage,
|
||||
statusType, setStatusType,
|
||||
setStatusMessage,
|
||||
setStatusType,
|
||||
isProcessing, setIsProcessing
|
||||
} = useStatusContext();
|
||||
|
||||
// Grid state
|
||||
const [gridSpacing, handleGridSpacingChange] = useNumericInputHandler(50);
|
||||
const [gridSpacing, handleGridSpacingChange, setGridSpacing] = useNumericInputHandler(50);
|
||||
const [gridColor, setGridColor] = React.useState<GridColor>("blue");
|
||||
const [gridOpacity, handleGridOpacityChange] = useNumericInputHandler(30);
|
||||
const [gridOpacity, handleGridOpacityChange, setGridOpacity] = useNumericInputHandler(30);
|
||||
|
||||
// Guidelines state
|
||||
const [guidePosition, handleGuidePositionChange] = useNumericInputHandler(240);
|
||||
const [guidePosition, handleGuidePositionChange, setGuidePosition] = useNumericInputHandler(240);
|
||||
const [guideDirection, setGuideDirection] = React.useState<GuideDirection>("horizontal");
|
||||
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
|
||||
*/
|
||||
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);
|
||||
try {
|
||||
await PowerPoint.run(async (context) => {
|
||||
@@ -256,13 +307,9 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
|
||||
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
|
||||
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
|
||||
if (yPosition >= SLIDE_HEIGHT) continue;
|
||||
@@ -277,12 +324,12 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
line.lineFormat.visible = false; // No outline, just fill
|
||||
|
||||
// Set transparency (opacity is inverse of transparency)
|
||||
line.fill.transparency = (100 - gridOpacity) / 100;
|
||||
line.fill.transparency = (100 - opacity) / 100;
|
||||
}
|
||||
|
||||
// Create vertical grid lines
|
||||
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
|
||||
if (xPosition >= SLIDE_WIDTH) continue;
|
||||
@@ -297,20 +344,20 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
line.lineFormat.visible = false; // No outline, just fill
|
||||
|
||||
// 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");
|
||||
setStatusType("success");
|
||||
});
|
||||
} catch (error) {
|
||||
setStatusMessage(`Error: ${error.message}`);
|
||||
} catch (error: unknown) {
|
||||
setStatusMessage(`Error: ${getErrorMessage(error)}`);
|
||||
setStatusType("error");
|
||||
console.error("Create grid error:", error);
|
||||
} finally {
|
||||
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
|
||||
@@ -370,9 +417,9 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
setStatusType("success");
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
} catch (error: unknown) {
|
||||
if (showStatus) {
|
||||
setStatusMessage(`Error: ${error.message}`);
|
||||
setStatusMessage(`Error: ${getErrorMessage(error)}`);
|
||||
setStatusType("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
|
||||
*/
|
||||
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);
|
||||
try {
|
||||
await PowerPoint.run(async (context) => {
|
||||
@@ -407,13 +465,13 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
const guideId = `${GUIDE_PREFIX}${guideDirection}_${timestamp}`;
|
||||
|
||||
// Add the guide line
|
||||
let line;
|
||||
let line: PowerPoint.Shape;
|
||||
if (guideDirection === "horizontal") {
|
||||
// Create horizontal guideline
|
||||
line = createLineShape(currentSlide, 0, guidePosition, SLIDE_WIDTH, guidePosition);
|
||||
line = createLineShape(currentSlide, 0, position, SLIDE_WIDTH, position);
|
||||
} else {
|
||||
// Create vertical guideline
|
||||
line = createLineShape(currentSlide, guidePosition, 0, guidePosition, SLIDE_HEIGHT);
|
||||
line = createLineShape(currentSlide, position, 0, position, SLIDE_HEIGHT);
|
||||
}
|
||||
|
||||
line.name = guideId;
|
||||
@@ -428,14 +486,14 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
setStatusMessage(`Added ${guideDirection} guideline`);
|
||||
setStatusType("success");
|
||||
});
|
||||
} catch (error) {
|
||||
setStatusMessage(`Error: ${error.message}`);
|
||||
} catch (error: unknown) {
|
||||
setStatusMessage(`Error: ${getErrorMessage(error)}`);
|
||||
setStatusType("error");
|
||||
console.error("Add guideline error:", error);
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
}
|
||||
}, [createLineShape, guideColor, guideDirection, guidePosition, setIsProcessing, setStatusMessage, setStatusType]);
|
||||
}, [createLineShape, guideColor, guideDirection, guidePosition, setGuidePosition, setIsProcessing, setStatusMessage, setStatusType]);
|
||||
|
||||
/**
|
||||
* Removes all guidelines from the current slide
|
||||
@@ -488,8 +546,8 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
}
|
||||
setStatusType("success");
|
||||
});
|
||||
} catch (error) {
|
||||
setStatusMessage(`Error: ${error.message}`);
|
||||
} catch (error: unknown) {
|
||||
setStatusMessage(`Error: ${getErrorMessage(error)}`);
|
||||
setStatusType("error");
|
||||
console.error("Remove guidelines error:", error);
|
||||
} finally {
|
||||
|
||||
@@ -10,11 +10,11 @@ import { TextBulletListRegular } from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import ActionButton from "./ActionButton";
|
||||
import { getErrorMessage } from "../types/office-types";
|
||||
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 STANDARD_SLIDE_WIDTH = 720; // Standard PowerPoint slide width
|
||||
const STANDARD_SLIDE_WIDTH = 960; // Standard widescreen PowerPoint slide width in points
|
||||
|
||||
// Title detection methods
|
||||
type TitleDetectionMethod = "auto" | "position" | "first" | "name";
|
||||
@@ -68,11 +68,11 @@ export const InsertTitles: React.FC = () => {
|
||||
// Get the first selected shape
|
||||
const selectedShape = shapes.items[0];
|
||||
|
||||
// Check if the selected shape has a text frame
|
||||
selectedShape.load("textFrame");
|
||||
// Check that the selected shape can hold editable text
|
||||
selectedShape.load("type");
|
||||
await context.sync();
|
||||
|
||||
if (!selectedShape.textFrame) {
|
||||
if (!isTextCapableShape(selectedShape)) {
|
||||
setStatusMessage("Please select a text box to insert slide titles.");
|
||||
setStatusType("warning");
|
||||
return null;
|
||||
@@ -96,7 +96,7 @@ export const InsertTitles: React.FC = () => {
|
||||
method: TitleDetectionMethod = "auto"
|
||||
): Promise<{ text: string } | null> => {
|
||||
try {
|
||||
let titleCandidates: TitleCandidate[] = [];
|
||||
const titleCandidates: TitleCandidate[] = [];
|
||||
|
||||
// First pass: look for title shapes by name
|
||||
// This is the most reliable method if available
|
||||
|
||||
@@ -10,14 +10,7 @@ import { ColorRegular } from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import ActionButton from "./ActionButton";
|
||||
import { getErrorMessage } from "../types/office-types";
|
||||
|
||||
// Property types that can be matched
|
||||
enum PropertyType {
|
||||
Line = "line",
|
||||
Fill = "fill",
|
||||
Text = "text"
|
||||
}
|
||||
import { getErrorMessage, isNotNullish, isTextCapableShape } from "../types/office-types";
|
||||
|
||||
// Shape property loading configuration
|
||||
const SHAPE_PROPERTIES = {
|
||||
@@ -29,9 +22,6 @@ const SHAPE_PROPERTIES = {
|
||||
fill: [
|
||||
"fill/transparency",
|
||||
"fill/foregroundColor"
|
||||
],
|
||||
text: [
|
||||
"textFrame"
|
||||
]
|
||||
};
|
||||
|
||||
@@ -80,11 +70,11 @@ export const MatchProperties: React.FC = () => {
|
||||
sourceShape: PowerPoint.Shape,
|
||||
context: PowerPoint.RequestContext
|
||||
): Promise<{ hasText: boolean }> => {
|
||||
// Load basic shape properties
|
||||
// Load basic shape properties and whether the shape actually contains text
|
||||
const propertiesToLoad = [
|
||||
...SHAPE_PROPERTIES.line,
|
||||
...SHAPE_PROPERTIES.fill,
|
||||
...SHAPE_PROPERTIES.text
|
||||
"textFrame/hasText"
|
||||
];
|
||||
|
||||
sourceShape.load(propertiesToLoad);
|
||||
@@ -92,15 +82,10 @@ export const MatchProperties: React.FC = () => {
|
||||
|
||||
// Check if the shape has text and load text properties if it does
|
||||
let hasText = false;
|
||||
if (sourceShape.textFrame) {
|
||||
sourceShape.textFrame.load("textRange");
|
||||
if (sourceShape.textFrame.hasText) {
|
||||
sourceShape.textFrame.textRange.load(FONT_PROPERTIES);
|
||||
await context.sync();
|
||||
|
||||
if (sourceShape.textFrame.textRange) {
|
||||
sourceShape.textFrame.textRange.load(FONT_PROPERTIES);
|
||||
await context.sync();
|
||||
hasText = true;
|
||||
}
|
||||
hasText = true;
|
||||
}
|
||||
|
||||
return { hasText };
|
||||
@@ -119,17 +104,9 @@ export const MatchProperties: React.FC = () => {
|
||||
): Promise<void> => {
|
||||
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++) {
|
||||
shapes.items[i].load("textFrame");
|
||||
}
|
||||
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");
|
||||
}
|
||||
shapes.items[i].load("type");
|
||||
}
|
||||
await context.sync();
|
||||
};
|
||||
@@ -148,19 +125,19 @@ export const MatchProperties: React.FC = () => {
|
||||
|
||||
try {
|
||||
// Line weight
|
||||
if (sourceShape.lineFormat.weight !== undefined) {
|
||||
if (isNotNullish(sourceShape.lineFormat.weight)) {
|
||||
targetShape.lineFormat.weight = sourceShape.lineFormat.weight;
|
||||
propertiesApplied = true;
|
||||
}
|
||||
|
||||
// Line style
|
||||
if (sourceShape.lineFormat.dashStyle !== undefined) {
|
||||
if (isNotNullish(sourceShape.lineFormat.dashStyle)) {
|
||||
targetShape.lineFormat.dashStyle = sourceShape.lineFormat.dashStyle;
|
||||
propertiesApplied = true;
|
||||
}
|
||||
|
||||
// Line color
|
||||
if (sourceShape.lineFormat.color !== undefined) {
|
||||
if (isNotNullish(sourceShape.lineFormat.color)) {
|
||||
targetShape.lineFormat.color = sourceShape.lineFormat.color;
|
||||
propertiesApplied = true;
|
||||
}
|
||||
@@ -185,13 +162,13 @@ export const MatchProperties: React.FC = () => {
|
||||
|
||||
try {
|
||||
// Fill transparency
|
||||
if (sourceShape.fill.transparency !== undefined) {
|
||||
if (isNotNullish(sourceShape.fill.transparency)) {
|
||||
targetShape.fill.transparency = sourceShape.fill.transparency;
|
||||
propertiesApplied = true;
|
||||
}
|
||||
|
||||
// Fill color
|
||||
if (sourceShape.fill.foregroundColor !== undefined) {
|
||||
if (isNotNullish(sourceShape.fill.foregroundColor)) {
|
||||
targetShape.fill.foregroundColor = sourceShape.fill.foregroundColor;
|
||||
propertiesApplied = true;
|
||||
}
|
||||
@@ -213,43 +190,52 @@ export const MatchProperties: React.FC = () => {
|
||||
sourceShape: PowerPoint.Shape,
|
||||
targetShape: PowerPoint.Shape
|
||||
): 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 {
|
||||
if (sourceShape.textFrame?.textRange && targetShape.textFrame?.textRange) {
|
||||
const sourceFont = sourceShape.textFrame.textRange.font;
|
||||
const targetFont = targetShape.textFrame.textRange.font;
|
||||
|
||||
// Apply font properties in batch
|
||||
if (sourceFont.name !== undefined) {
|
||||
targetFont.name = sourceFont.name;
|
||||
}
|
||||
|
||||
if (sourceFont.size !== undefined) {
|
||||
targetFont.size = sourceFont.size;
|
||||
}
|
||||
|
||||
if (sourceFont.bold !== undefined) {
|
||||
targetFont.bold = sourceFont.bold;
|
||||
}
|
||||
|
||||
if (sourceFont.italic !== undefined) {
|
||||
targetFont.italic = sourceFont.italic;
|
||||
}
|
||||
|
||||
if (sourceFont.underline !== undefined) {
|
||||
targetFont.underline = sourceFont.underline;
|
||||
}
|
||||
|
||||
if (sourceFont.color !== undefined) {
|
||||
targetFont.color = sourceFont.color;
|
||||
}
|
||||
|
||||
return true;
|
||||
const sourceFont = sourceShape.textFrame.textRange.font;
|
||||
const targetFont = targetShape.textFrame.textRange.font;
|
||||
|
||||
// Apply font properties in batch
|
||||
if (isNotNullish(sourceFont.name)) {
|
||||
targetFont.name = sourceFont.name;
|
||||
propertiesApplied = true;
|
||||
}
|
||||
|
||||
if (isNotNullish(sourceFont.size)) {
|
||||
targetFont.size = sourceFont.size;
|
||||
propertiesApplied = true;
|
||||
}
|
||||
|
||||
if (isNotNullish(sourceFont.bold)) {
|
||||
targetFont.bold = sourceFont.bold;
|
||||
propertiesApplied = true;
|
||||
}
|
||||
|
||||
if (isNotNullish(sourceFont.italic)) {
|
||||
targetFont.italic = sourceFont.italic;
|
||||
propertiesApplied = true;
|
||||
}
|
||||
|
||||
if (isNotNullish(sourceFont.underline)) {
|
||||
targetFont.underline = sourceFont.underline;
|
||||
propertiesApplied = true;
|
||||
}
|
||||
|
||||
if (isNotNullish(sourceFont.color)) {
|
||||
targetFont.color = sourceFont.color;
|
||||
propertiesApplied = true;
|
||||
}
|
||||
} catch (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
|
||||
let successCount = 0;
|
||||
let textStyleCount = 0;
|
||||
let lineAppliedToAny = false;
|
||||
let fillAppliedToAny = false;
|
||||
|
||||
for (let i = 1; i < shapes.items.length; i++) {
|
||||
const targetShape = shapes.items[i];
|
||||
let shapeUpdated = false;
|
||||
|
||||
// Apply different property types
|
||||
const lineApplied = applyLineProperties(sourceShape, targetShape);
|
||||
const fillApplied = applyFillProperties(sourceShape, targetShape);
|
||||
lineAppliedToAny = lineAppliedToAny || lineApplied;
|
||||
fillAppliedToAny = fillAppliedToAny || fillApplied;
|
||||
|
||||
// Apply text properties if available
|
||||
let textApplied = false;
|
||||
if (hasText) {
|
||||
const textApplied = applyTextProperties(sourceShape, targetShape);
|
||||
textApplied = applyTextProperties(sourceShape, targetShape);
|
||||
if (textApplied) {
|
||||
textStyleCount++;
|
||||
}
|
||||
}
|
||||
|
||||
// Count successful shape updates
|
||||
if (lineApplied || fillApplied) {
|
||||
shapeUpdated = true;
|
||||
}
|
||||
|
||||
if (shapeUpdated) {
|
||||
if (lineApplied || fillApplied || textApplied) {
|
||||
successCount++;
|
||||
}
|
||||
}
|
||||
@@ -311,14 +297,16 @@ export const MatchProperties: React.FC = () => {
|
||||
|
||||
// Generate appropriate status message
|
||||
if (successCount > 0) {
|
||||
const propertyTypes = [];
|
||||
const propertyTypes: string[] = [];
|
||||
|
||||
// Build a detailed status message
|
||||
if (sourceShape.lineFormat) propertyTypes.push("line");
|
||||
if (sourceShape.fill) propertyTypes.push("fill");
|
||||
// Build a detailed status message based on what was actually applied
|
||||
if (lineAppliedToAny) propertyTypes.push("line");
|
||||
if (fillAppliedToAny) propertyTypes.push("fill");
|
||||
if (propertyTypes.length === 0 && textStyleCount > 0) propertyTypes.push("text");
|
||||
|
||||
let message = `Applied ${propertyTypes.join(", ")} properties to ${successCount} shapes`;
|
||||
if (textStyleCount > 0) {
|
||||
const appliedProperties = propertyTypes.length > 0 ? propertyTypes.join(", ") : "shape";
|
||||
let message = `Applied ${appliedProperties} properties to ${successCount} shapes`;
|
||||
if (textStyleCount > 0 && (lineAppliedToAny || fillAppliedToAny)) {
|
||||
message += ` (including text styling on ${textStyleCount})`;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
|
||||
import * as React from "react";
|
||||
import { ArrowFitInRegular, ArrowMaximizeRegular, ArrowMinimizeRegular } from "@fluentui/react-icons";
|
||||
import { ArrowFitInRegular } from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import ActionButton from "./ActionButton";
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import { getErrorMessage } from "../types/office-types";
|
||||
|
||||
// Constants for progress bar configuration
|
||||
const PROGRESS_BAR_CONFIG = {
|
||||
@@ -60,8 +61,8 @@ export const ProgressBarButtons: React.FC = () => {
|
||||
const styles = useStyles();
|
||||
const commonStyles = useCommonStyles();
|
||||
const {
|
||||
statusMessage, setStatusMessage,
|
||||
statusType, setStatusType,
|
||||
setStatusMessage,
|
||||
setStatusType,
|
||||
isProcessing, setIsProcessing
|
||||
} = useStatusContext();
|
||||
|
||||
@@ -96,7 +97,7 @@ export const ProgressBarButtons: React.FC = () => {
|
||||
|
||||
// Load all slide layouts at once to reduce API calls
|
||||
for (let i = 0; i < slideCount; i++) {
|
||||
slides.items[i].load("layout");
|
||||
slides.items[i].load("layout/name");
|
||||
}
|
||||
|
||||
// Single sync to get all layouts
|
||||
@@ -158,8 +159,8 @@ export const ProgressBarButtons: React.FC = () => {
|
||||
setStatusMessage("Added progress bar to slides.");
|
||||
setStatusType("success");
|
||||
});
|
||||
} catch (error) {
|
||||
setStatusMessage(`Error: ${error.message}`);
|
||||
} catch (error: unknown) {
|
||||
setStatusMessage(`Error: ${getErrorMessage(error)}`);
|
||||
setStatusType("error");
|
||||
console.error("Add progress bar error:", error);
|
||||
} finally {
|
||||
@@ -235,8 +236,8 @@ export const ProgressBarButtons: React.FC = () => {
|
||||
}
|
||||
setStatusType("success");
|
||||
});
|
||||
} catch (error) {
|
||||
setStatusMessage(`Error: ${error.message}`);
|
||||
} catch (error: unknown) {
|
||||
setStatusMessage(`Error: ${getErrorMessage(error)}`);
|
||||
setStatusType("error");
|
||||
console.error("Remove progress bar error:", error);
|
||||
} finally {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { makeStyles, tokens } from "@fluentui/react-components";
|
||||
import { makeStyles } from "@fluentui/react-components";
|
||||
|
||||
// Common styles used across multiple components
|
||||
export const useCommonStyles = makeStyles({
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
/* 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
@@ -33,6 +55,14 @@ export function isPictureShape(shape: PowerPoint.Shape): boolean {
|
||||
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
|
||||
*/
|
||||
@@ -45,4 +75,4 @@ export function getFirstSelectedSlide(context: PowerPoint.RequestContext): Power
|
||||
*/
|
||||
export function selectShapesById(slide: PowerPoint.Slide, shapeIds: string[]): void {
|
||||
slide.setSelectedShapes(shapeIds);
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,9 @@
|
||||
"noUnusedParameters": true,
|
||||
"outDir": "dist",
|
||||
"removeComments": false,
|
||||
"skipLibCheck": true,
|
||||
"sourceMap": true,
|
||||
"strict": true,
|
||||
"target": "es5",
|
||||
"lib": [
|
||||
"es7",
|
||||
|
||||
Reference in new issue
Block a user