Phase 3: - Declare PowerPointApi 1.5 and replace template manifest values - Remove the dead command pipeline and the tracked Babel/polyfill setup - Extract constants, status/settings contexts, PowerPoint services, and an error boundary - Build with ES2020 and strict TypeScript; hash production assets and drop prod source maps - Add Vitest tests, CI, LICENSE, Node 20 pinning, and prune unused dependencies - Correct the README, user guide, developer guide, and audit notes Phase 4: - Add a persisted 16:9/4:3 slide size setting used by all layout tools - Add dark mode with Office/system theme detection - Make sections collapsible and move to accessible Fluent controls - Announce status through aria-live and add semantic status icons - Add a progress counter with cooperative cancellation and a Stop button - Update the tracked dependency tree for the pruned packages
This commit is contained in:
1 parent
e57258afe9
commit
89989c04e9
6211 files changed
+7028
-274819
No files matched your search
@@ -1,8 +1,9 @@
|
||||
import * as React from "react";
|
||||
import { Button, ButtonProps } from "@fluentui/react-components";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useStatusContext } from "../context/StatusContext";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import { getErrorMessage } from "../types/office-types";
|
||||
import { resetCancellation } from "../services/cancellation";
|
||||
import ConfirmButton from "./ConfirmButton";
|
||||
|
||||
export interface ActionButtonProps {
|
||||
@@ -39,12 +40,15 @@ export const ActionButton: React.FC<ActionButtonProps> = ({
|
||||
setStatusMessage,
|
||||
setStatusType,
|
||||
isProcessing,
|
||||
setIsProcessing
|
||||
setIsProcessing,
|
||||
setProgress
|
||||
} = useStatusContext();
|
||||
|
||||
const handleClick = async () => {
|
||||
if (isProcessing) return;
|
||||
|
||||
resetCancellation();
|
||||
setProgress(null);
|
||||
setIsProcessing(true);
|
||||
try {
|
||||
await onClick();
|
||||
@@ -55,6 +59,7 @@ export const ActionButton: React.FC<ActionButtonProps> = ({
|
||||
console.error(`Error in ${title} action:`, error);
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
setProgress(null);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -18,16 +18,11 @@ import {
|
||||
TextboxAlignMiddleRegular,
|
||||
TextboxAlignBottomRegular
|
||||
} from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useStatusContext } from "../context/StatusContext";
|
||||
import { useSettings } from "../context/SettingsContext";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import { getErrorMessage } from "../types/office-types";
|
||||
|
||||
/**
|
||||
* Slide dimensions in points (16:9). Shapes are aligned to the slide edges
|
||||
* and center, matching PowerPoint's "Align to Slide" behavior.
|
||||
*/
|
||||
const SLIDE_WIDTH = 960;
|
||||
const SLIDE_HEIGHT = 540;
|
||||
import { resetCancellation } from "../services/cancellation";
|
||||
|
||||
/**
|
||||
* Warning message when no shapes are selected
|
||||
@@ -69,6 +64,7 @@ const useStyles = makeStyles({
|
||||
export const AlignmentButtons: React.FC = () => {
|
||||
const styles = useStyles();
|
||||
const commonStyles = useCommonStyles();
|
||||
const { slideSize } = useSettings();
|
||||
const {
|
||||
setStatusMessage,
|
||||
setStatusType,
|
||||
@@ -94,6 +90,7 @@ export const AlignmentButtons: React.FC = () => {
|
||||
* @param alignmentType - The type of horizontal alignment to apply
|
||||
*/
|
||||
const handleHorizontalAlignment = async (alignmentType: HorizontalAlignmentType): Promise<void> => {
|
||||
resetCancellation();
|
||||
setIsProcessing(true);
|
||||
try {
|
||||
await PowerPoint.run(async (context) => {
|
||||
@@ -122,10 +119,10 @@ export const AlignmentButtons: React.FC = () => {
|
||||
shape.left = 0;
|
||||
break;
|
||||
case "center":
|
||||
shape.left = Math.max(0, (SLIDE_WIDTH - shape.width) / 2);
|
||||
shape.left = Math.max(0, (slideSize.width - shape.width) / 2);
|
||||
break;
|
||||
case "right":
|
||||
shape.left = Math.max(0, SLIDE_WIDTH - shape.width);
|
||||
shape.left = Math.max(0, slideSize.width - shape.width);
|
||||
break;
|
||||
}
|
||||
});
|
||||
@@ -149,6 +146,7 @@ export const AlignmentButtons: React.FC = () => {
|
||||
* @param alignmentType - The type of vertical alignment to apply
|
||||
*/
|
||||
const handleVerticalAlignment = async (alignmentType: VerticalAlignmentType): Promise<void> => {
|
||||
resetCancellation();
|
||||
setIsProcessing(true);
|
||||
try {
|
||||
await PowerPoint.run(async (context) => {
|
||||
@@ -177,10 +175,10 @@ export const AlignmentButtons: React.FC = () => {
|
||||
shape.top = 0;
|
||||
break;
|
||||
case "middle":
|
||||
shape.top = Math.max(0, (SLIDE_HEIGHT - shape.height) / 2);
|
||||
shape.top = Math.max(0, (slideSize.height - shape.height) / 2);
|
||||
break;
|
||||
case "bottom":
|
||||
shape.top = Math.max(0, SLIDE_HEIGHT - shape.height);
|
||||
shape.top = Math.max(0, slideSize.height - shape.height);
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
+104
-67
@@ -2,7 +2,7 @@
|
||||
* @file App.tsx
|
||||
* @description Main application component for the PowerPoint toolbox add-in.
|
||||
* This component serves as the container for all tool components and provides
|
||||
* a context for status messages and processing state that can be used by child components.
|
||||
* status, processing, progress, and cancellation state to child components.
|
||||
*/
|
||||
|
||||
import * as React from "react";
|
||||
@@ -18,33 +18,31 @@ import ProgressBarButtons from "./ProgressBarButtons";
|
||||
import AlignmentButtons from "./AlignmentButtons";
|
||||
import GridGuidelineManager from "./GridGuidelineManager";
|
||||
import Section from "./Section";
|
||||
import { makeStyles, Text, tokens, Spinner } from "@fluentui/react-components";
|
||||
import { ShapeUnionRegular, SquareRegular, InfoRegular } from "@fluentui/react-icons";
|
||||
|
||||
interface AppProps {
|
||||
title: string;
|
||||
}
|
||||
|
||||
export type StatusType = "info" | "success" | "warning" | "error";
|
||||
|
||||
export interface StatusContextType {
|
||||
statusMessage: string;
|
||||
setStatusMessage: (message: string) => void;
|
||||
statusType: StatusType;
|
||||
setStatusType: (type: StatusType) => void;
|
||||
isProcessing: boolean;
|
||||
setIsProcessing: (processing: boolean) => void;
|
||||
}
|
||||
|
||||
export const StatusContext = React.createContext<StatusContextType | undefined>(undefined);
|
||||
|
||||
export const useStatusContext = () => {
|
||||
const context = React.useContext(StatusContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useStatusContext must be used within a StatusProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
import {
|
||||
Button,
|
||||
Dropdown,
|
||||
Field,
|
||||
makeStyles,
|
||||
Option,
|
||||
ProgressBar as FluentProgressBar,
|
||||
Spinner,
|
||||
Text,
|
||||
tokens
|
||||
} from "@fluentui/react-components";
|
||||
import {
|
||||
CheckmarkCircleRegular,
|
||||
ErrorCircleRegular,
|
||||
InfoRegular,
|
||||
WarningRegular
|
||||
} from "@fluentui/react-icons";
|
||||
import {
|
||||
OperationProgress,
|
||||
StatusContext,
|
||||
StatusType
|
||||
} from "../context/StatusContext";
|
||||
import { useSettings } from "../context/SettingsContext";
|
||||
import { requestCancellation } from "../services/cancellation";
|
||||
import { SlideSizePreset } from "../constants";
|
||||
|
||||
const useStyles = makeStyles({
|
||||
root: {
|
||||
@@ -58,63 +56,65 @@ const useStyles = makeStyles({
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
bottom: 0
|
||||
},
|
||||
statusContainer: {
|
||||
marginTop: "4px",
|
||||
padding: "8px 12px",
|
||||
fontSize: "13px",
|
||||
borderRadius: "6px",
|
||||
backgroundColor: "#f3f2f1", // Light gray background
|
||||
transition: "all 0.3s ease",
|
||||
backgroundColor: tokens.colorNeutralBackground3,
|
||||
transition: "all 0.3s ease"
|
||||
},
|
||||
infoStatus: {
|
||||
backgroundColor: "#EFF6FC", // Light blue background
|
||||
color: "#004578", // Blue text
|
||||
backgroundColor: tokens.colorBrandBackground2,
|
||||
color: tokens.colorBrandForeground2
|
||||
},
|
||||
successStatus: {
|
||||
backgroundColor: "#DFF6DD", // Light green background
|
||||
color: "#107C10", // Green text
|
||||
backgroundColor: tokens.colorPaletteGreenBackground1,
|
||||
color: tokens.colorPaletteGreenForeground1
|
||||
},
|
||||
warningStatus: {
|
||||
backgroundColor: "#FFF4CE", // Light yellow background
|
||||
color: "#797673", // Dark gray text
|
||||
backgroundColor: tokens.colorPaletteDarkOrangeBackground1,
|
||||
color: tokens.colorPaletteDarkOrangeForeground1
|
||||
},
|
||||
errorStatus: {
|
||||
backgroundColor: "#FDE7E9", // Light red background
|
||||
color: "#A80000", // Red text
|
||||
backgroundColor: tokens.colorPaletteRedBackground1,
|
||||
color: tokens.colorPaletteRedForeground1
|
||||
},
|
||||
statusIcon: {
|
||||
marginRight: "8px",
|
||||
marginRight: "8px"
|
||||
},
|
||||
statusText: {
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
alignItems: "center"
|
||||
},
|
||||
progressBar: {
|
||||
marginTop: "8px"
|
||||
},
|
||||
footer: {
|
||||
fontSize: "12px",
|
||||
color: tokens.colorNeutralForeground3,
|
||||
textAlign: "center",
|
||||
marginTop: "auto",
|
||||
padding: "8px 0",
|
||||
},
|
||||
padding: "8px 0"
|
||||
}
|
||||
});
|
||||
|
||||
const App: React.FC<AppProps> = () => {
|
||||
const SLIDE_SIZE_LABELS: Record<SlideSizePreset, string> = {
|
||||
widescreen: "Widescreen (16:9)",
|
||||
standard: "Standard (4:3)"
|
||||
};
|
||||
|
||||
const App: React.FC = () => {
|
||||
const styles = useStyles();
|
||||
const [theme, setTheme] = useState<string>("light");
|
||||
|
||||
const { slideSizePreset, setSlideSizePreset } = useSettings();
|
||||
|
||||
// Status state
|
||||
const [statusMessage, setStatusMessage] = useState("");
|
||||
const [statusType, setStatusType] = useState<StatusType>("info");
|
||||
const [isProcessing, setIsProcessing] = useState(false);
|
||||
|
||||
// Check if macOS is in dark mode (would need to be expanded in production)
|
||||
useEffect(() => {
|
||||
// In a real implementation, we would listen to Office theme changes
|
||||
const prefersDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
setTheme(prefersDarkMode ? "dark" : "light");
|
||||
}, []);
|
||||
const [progress, setProgress] = useState<OperationProgress | null>(null);
|
||||
|
||||
// Auto-clear success messages after 5 seconds
|
||||
useEffect(() => {
|
||||
@@ -132,13 +132,13 @@ const App: React.FC<AppProps> = () => {
|
||||
const getStatusIcon = () => {
|
||||
switch (statusType) {
|
||||
case "success":
|
||||
return <ShapeUnionRegular className={styles.statusIcon} />;
|
||||
return <CheckmarkCircleRegular className={styles.statusIcon} />;
|
||||
case "warning":
|
||||
return <SquareRegular className={styles.statusIcon} />;
|
||||
return <WarningRegular className={styles.statusIcon} />;
|
||||
case "error":
|
||||
return <InfoRegular className={styles.statusIcon} />;
|
||||
return <ErrorCircleRegular className={styles.statusIcon} />;
|
||||
default:
|
||||
return null;
|
||||
return <InfoRegular className={styles.statusIcon} />;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -149,9 +149,11 @@ const App: React.FC<AppProps> = () => {
|
||||
statusType,
|
||||
setStatusType,
|
||||
isProcessing,
|
||||
setIsProcessing
|
||||
setIsProcessing,
|
||||
progress,
|
||||
setProgress
|
||||
}}>
|
||||
<div className={styles.root} data-theme={theme}>
|
||||
<div className={styles.root}>
|
||||
<Section title="Content">
|
||||
<MatchProperties />
|
||||
<div style={{ marginTop: "8px" }}></div>
|
||||
@@ -179,32 +181,67 @@ const App: React.FC<AppProps> = () => {
|
||||
<Section title="Alignment">
|
||||
<AlignmentButtons />
|
||||
</Section>
|
||||
|
||||
|
||||
<Section title="Layout">
|
||||
<GridGuidelineManager />
|
||||
</Section>
|
||||
|
||||
|
||||
<Section title="Settings">
|
||||
<Field label="Slide size">
|
||||
<Dropdown
|
||||
value={SLIDE_SIZE_LABELS[slideSizePreset]}
|
||||
selectedOptions={[slideSizePreset]}
|
||||
onOptionSelect={(_, data) => {
|
||||
if (data.optionValue === "widescreen" || data.optionValue === "standard") {
|
||||
setSlideSizePreset(data.optionValue);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Option value="widescreen">{SLIDE_SIZE_LABELS.widescreen}</Option>
|
||||
<Option value="standard">{SLIDE_SIZE_LABELS.standard}</Option>
|
||||
</Dropdown>
|
||||
</Field>
|
||||
</Section>
|
||||
|
||||
{/* Status message area at the bottom */}
|
||||
{isProcessing && (
|
||||
<div className={styles.statusContainer}>
|
||||
<div className={styles.statusContainer} role="status" aria-live="polite">
|
||||
<div className={styles.statusText}>
|
||||
<Spinner size="tiny" style={{ marginRight: "8px" }} />
|
||||
Processing...
|
||||
{progress ? `Processing ${progress.current} / ${progress.total}...` : "Processing..."}
|
||||
</div>
|
||||
{progress && progress.total > 0 && (
|
||||
<FluentProgressBar
|
||||
className={styles.progressBar}
|
||||
value={progress.current / progress.total}
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
size="small"
|
||||
appearance="subtle"
|
||||
style={{ marginTop: "4px" }}
|
||||
onClick={requestCancellation}
|
||||
>
|
||||
Stop
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
{!isProcessing && statusMessage && (
|
||||
<div className={`${styles.statusContainer} ${styles[`${statusType}Status`]}`}>
|
||||
<div
|
||||
className={`${styles.statusContainer} ${styles[`${statusType}Status`]}`}
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
>
|
||||
<div className={styles.statusText}>
|
||||
{getStatusIcon()}
|
||||
{statusMessage}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
<div className={styles.footer}>
|
||||
<Text size={100}>Edison • v1.2.0-dev</Text>
|
||||
<Text size={100}>Edison • v{__APP_VERSION__}</Text>
|
||||
</div>
|
||||
</div>
|
||||
</StatusContext.Provider>
|
||||
|
||||
@@ -13,9 +13,13 @@ import {
|
||||
ShieldLockRegular,
|
||||
DismissRegular
|
||||
} from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useStatusContext } from "../context/StatusContext";
|
||||
import { useSettings } from "../context/SettingsContext";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import { getErrorMessage } from "../types/office-types";
|
||||
import { MARKER_NAMES } from "../constants";
|
||||
import { addMarkerToCollections, removeMarkerFromCollections } from "../services/markers";
|
||||
import { isCancellationRequested, resetCancellation } from "../services/cancellation";
|
||||
import ConfirmButton from "./ConfirmButton";
|
||||
|
||||
/**
|
||||
@@ -24,19 +28,12 @@ import ConfirmButton from "./ConfirmButton";
|
||||
const CONFIDENTIAL_CONFIG = {
|
||||
// Marking text that appears on slides
|
||||
TEXT: "– Confidential –",
|
||||
// Shape name used to identify confidential markings
|
||||
SHAPE_NAME: "ConfidentialMarking",
|
||||
// Font configuration
|
||||
FONT: {
|
||||
NAME: "Inter",
|
||||
SIZE: 8,
|
||||
COLOR: "#DA1335" // RGB(218, 19, 53)
|
||||
},
|
||||
// Default slide dimensions in points (if we can't get actual dimensions)
|
||||
SLIDE: {
|
||||
WIDTH: 960, // 10 inches * 72 points
|
||||
HEIGHT: 540, // 7.5 inches * 72 points
|
||||
},
|
||||
// Text box configuration
|
||||
TEXT_BOX: {
|
||||
HEIGHT: 25,
|
||||
@@ -82,11 +79,13 @@ interface ProcessingResult {
|
||||
export const ConfidentialButtons: React.FC = () => {
|
||||
const styles = useStyles();
|
||||
const commonStyles = useCommonStyles();
|
||||
const { slideSize } = useSettings();
|
||||
const {
|
||||
setStatusMessage,
|
||||
setStatusType,
|
||||
isProcessing,
|
||||
setIsProcessing
|
||||
setIsProcessing,
|
||||
setProgress
|
||||
} = useStatusContext();
|
||||
|
||||
/**
|
||||
@@ -131,6 +130,8 @@ export const ConfidentialButtons: React.FC = () => {
|
||||
* Adds confidential markings to all slides in the presentation
|
||||
*/
|
||||
const addConfidentialMarking = async (): Promise<void> => {
|
||||
resetCancellation();
|
||||
setProgress(null);
|
||||
setIsProcessing(true);
|
||||
try {
|
||||
await PowerPoint.run(async (context) => {
|
||||
@@ -146,12 +147,18 @@ export const ConfidentialButtons: React.FC = () => {
|
||||
}
|
||||
|
||||
const result = await processAddMarkings(context, slides.items);
|
||||
if (isCancellationRequested()) {
|
||||
setStatusMessage("Operation cancelled.");
|
||||
setStatusType("warning");
|
||||
return;
|
||||
}
|
||||
updateStatusFromResult(result, true);
|
||||
});
|
||||
} catch (error) {
|
||||
} catch (error: unknown) {
|
||||
handleError(error, "Add confidential");
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
setProgress(null);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -166,64 +173,42 @@ export const ConfidentialButtons: React.FC = () => {
|
||||
context: PowerPoint.RequestContext,
|
||||
slides: PowerPoint.Slide[]
|
||||
): Promise<ProcessingResult> => {
|
||||
const result: ProcessingResult = {
|
||||
processedSlides: 0,
|
||||
const positionFromTop = slideSize.height - CONFIDENTIAL_CONFIG.TEXT_BOX.POSITION_FROM_BOTTOM;
|
||||
const result = await addMarkerToCollections(
|
||||
context,
|
||||
slides.map((slide) => slide.shapes),
|
||||
{
|
||||
name: MARKER_NAMES.confidential,
|
||||
text: CONFIDENTIAL_CONFIG.TEXT,
|
||||
font: {
|
||||
name: CONFIDENTIAL_CONFIG.FONT.NAME,
|
||||
size: CONFIDENTIAL_CONFIG.FONT.SIZE,
|
||||
color: CONFIDENTIAL_CONFIG.FONT.COLOR
|
||||
},
|
||||
box: {
|
||||
left: 0,
|
||||
top: positionFromTop,
|
||||
width: slideSize.width,
|
||||
height: CONFIDENTIAL_CONFIG.TEXT_BOX.HEIGHT
|
||||
},
|
||||
horizontalAlignment: PowerPoint.ParagraphHorizontalAlignment.center
|
||||
},
|
||||
(current, total) => setProgress({ current, total })
|
||||
);
|
||||
|
||||
return {
|
||||
processedSlides: slides.length,
|
||||
errorSlides: 0,
|
||||
affectedCount: 0
|
||||
affectedCount: result.affected
|
||||
};
|
||||
|
||||
const { WIDTH, HEIGHT } = CONFIDENTIAL_CONFIG.SLIDE;
|
||||
const positionFromTop = HEIGHT - CONFIDENTIAL_CONFIG.TEXT_BOX.POSITION_FROM_BOTTOM;
|
||||
|
||||
// Load the shapes and names for every slide in two batches instead of two syncs per slide
|
||||
for (const slide of slides) {
|
||||
slide.shapes.load("items");
|
||||
}
|
||||
await context.sync();
|
||||
|
||||
const shapesBySlide: PowerPoint.Shape[][] = [];
|
||||
for (const slide of slides) {
|
||||
shapesBySlide.push(slide.shapes.items);
|
||||
for (const shape of slide.shapes.items) {
|
||||
shape.load("name");
|
||||
}
|
||||
}
|
||||
await context.sync();
|
||||
|
||||
// Replace any existing marking so repeated clicks do not duplicate it
|
||||
for (const shapes of shapesBySlide) {
|
||||
for (const shape of shapes) {
|
||||
if (shape.name === CONFIDENTIAL_CONFIG.SHAPE_NAME) {
|
||||
shape.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create one marking per slide in a single batch
|
||||
for (const slide of slides) {
|
||||
const textBox = slide.shapes.addTextBox(CONFIDENTIAL_CONFIG.TEXT, {
|
||||
left: 0,
|
||||
top: positionFromTop,
|
||||
width: WIDTH,
|
||||
height: CONFIDENTIAL_CONFIG.TEXT_BOX.HEIGHT
|
||||
});
|
||||
textBox.name = CONFIDENTIAL_CONFIG.SHAPE_NAME;
|
||||
textBox.textFrame.textRange.font.name = CONFIDENTIAL_CONFIG.FONT.NAME;
|
||||
textBox.textFrame.textRange.font.size = CONFIDENTIAL_CONFIG.FONT.SIZE;
|
||||
textBox.textFrame.textRange.font.color = CONFIDENTIAL_CONFIG.FONT.COLOR;
|
||||
textBox.textFrame.textRange.paragraphFormat.horizontalAlignment = "Center";
|
||||
result.processedSlides++;
|
||||
}
|
||||
|
||||
await context.sync();
|
||||
result.affectedCount = slides.length;
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* Removes confidential markings from all slides in the presentation
|
||||
*/
|
||||
const removeConfidentialMarking = async (): Promise<void> => {
|
||||
resetCancellation();
|
||||
setProgress(null);
|
||||
setIsProcessing(true);
|
||||
try {
|
||||
await PowerPoint.run(async (context) => {
|
||||
@@ -239,12 +224,18 @@ export const ConfidentialButtons: React.FC = () => {
|
||||
}
|
||||
|
||||
const result = await processRemoveMarkings(context, slides.items);
|
||||
if (isCancellationRequested()) {
|
||||
setStatusMessage("Operation cancelled.");
|
||||
setStatusType("warning");
|
||||
return;
|
||||
}
|
||||
updateStatusFromResult(result, false);
|
||||
});
|
||||
} catch (error) {
|
||||
} catch (error: unknown) {
|
||||
handleError(error, "Remove confidential");
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
setProgress(null);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -259,38 +250,17 @@ export const ConfidentialButtons: React.FC = () => {
|
||||
context: PowerPoint.RequestContext,
|
||||
slides: PowerPoint.Slide[]
|
||||
): Promise<ProcessingResult> => {
|
||||
const result: ProcessingResult = {
|
||||
processedSlides: 0,
|
||||
const result = await removeMarkerFromCollections(
|
||||
context,
|
||||
slides.map((slide) => slide.shapes),
|
||||
MARKER_NAMES.confidential
|
||||
);
|
||||
|
||||
return {
|
||||
processedSlides: slides.length,
|
||||
errorSlides: 0,
|
||||
affectedCount: 0
|
||||
affectedCount: result.affected
|
||||
};
|
||||
|
||||
// Load the shapes and names for every slide in two batches
|
||||
for (const slide of slides) {
|
||||
slide.shapes.load("items");
|
||||
}
|
||||
await context.sync();
|
||||
|
||||
const allShapes: PowerPoint.Shape[] = [];
|
||||
for (const slide of slides) {
|
||||
for (const shape of slide.shapes.items) {
|
||||
shape.load("name");
|
||||
allShapes.push(shape);
|
||||
}
|
||||
}
|
||||
await context.sync();
|
||||
|
||||
// Delete all matching shapes in one batch
|
||||
for (const shape of allShapes) {
|
||||
if (shape.name === CONFIDENTIAL_CONFIG.SHAPE_NAME) {
|
||||
shape.delete();
|
||||
result.affectedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
await context.sync();
|
||||
result.processedSlides = slides.length;
|
||||
return result;
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -14,17 +14,18 @@ import {
|
||||
Edit24Regular,
|
||||
DismissRegular
|
||||
} from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useStatusContext } from "../context/StatusContext";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import { getErrorMessage } from "../types/office-types";
|
||||
import { MARKER_NAMES } from "../constants";
|
||||
import { addMarkerToCollections, removeMarkerFromCollections } from "../services/markers";
|
||||
import { isCancellationRequested, resetCancellation } from "../services/cancellation";
|
||||
import ConfirmButton from "./ConfirmButton";
|
||||
|
||||
/**
|
||||
* Configuration constants for draft watermarks
|
||||
*/
|
||||
const DRAFT_CONFIG = {
|
||||
// Shape name used to identify draft watermarks
|
||||
SHAPE_NAME: "DraftWatermark",
|
||||
// Font configuration
|
||||
FONT: {
|
||||
NAME: "Inter",
|
||||
@@ -94,7 +95,8 @@ export const DraftButtons: React.FC = () => {
|
||||
setStatusMessage,
|
||||
setStatusType,
|
||||
isProcessing,
|
||||
setIsProcessing
|
||||
setIsProcessing,
|
||||
setProgress
|
||||
} = useStatusContext();
|
||||
|
||||
/**
|
||||
@@ -143,6 +145,8 @@ export const DraftButtons: React.FC = () => {
|
||||
* Adds draft watermarks to all master slides in the presentation
|
||||
*/
|
||||
const addDraftWatermark = async (): Promise<void> => {
|
||||
resetCancellation();
|
||||
setProgress(null);
|
||||
setIsProcessing(true);
|
||||
try {
|
||||
await PowerPoint.run(async (context) => {
|
||||
@@ -158,12 +162,18 @@ export const DraftButtons: React.FC = () => {
|
||||
}
|
||||
|
||||
const result = await processAddWatermarks(context, masters.items);
|
||||
if (isCancellationRequested()) {
|
||||
setStatusMessage("Operation cancelled.");
|
||||
setStatusType("warning");
|
||||
return;
|
||||
}
|
||||
updateStatusFromResult(result, true);
|
||||
});
|
||||
} catch (error) {
|
||||
} catch (error: unknown) {
|
||||
handleError(error, "Add draft watermark");
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
setProgress(null);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -178,64 +188,39 @@ export const DraftButtons: React.FC = () => {
|
||||
context: PowerPoint.RequestContext,
|
||||
masters: PowerPoint.SlideMaster[]
|
||||
): Promise<ProcessingResult> => {
|
||||
const result: ProcessingResult = {
|
||||
processedMasters: 0,
|
||||
errorMasters: 0,
|
||||
affectedCount: 0
|
||||
};
|
||||
|
||||
const { LEFT, TOP, WIDTH, HEIGHT } = DRAFT_CONFIG.TEXT_BOX;
|
||||
|
||||
// Load the shapes and names for every master in two batches instead of three syncs per master
|
||||
for (const master of masters) {
|
||||
master.shapes.load("items");
|
||||
}
|
||||
await context.sync();
|
||||
const result = await addMarkerToCollections(
|
||||
context,
|
||||
masters.map((master) => master.shapes),
|
||||
{
|
||||
name: MARKER_NAMES.draft,
|
||||
text: DRAFT_CONFIG.TEXT,
|
||||
font: {
|
||||
name: DRAFT_CONFIG.FONT.NAME,
|
||||
size: DRAFT_CONFIG.FONT.SIZE,
|
||||
color: DRAFT_CONFIG.FONT.COLOR,
|
||||
bold: true
|
||||
},
|
||||
box: { left: LEFT, top: TOP, width: WIDTH, height: HEIGHT },
|
||||
verticalAlignment: PowerPoint.TextVerticalAlignment.middleCentered
|
||||
},
|
||||
(current, total) => setProgress({ current, total })
|
||||
);
|
||||
|
||||
const shapesByMaster: PowerPoint.Shape[][] = [];
|
||||
for (const master of masters) {
|
||||
shapesByMaster.push(master.shapes.items);
|
||||
for (const shape of master.shapes.items) {
|
||||
shape.load("name");
|
||||
}
|
||||
}
|
||||
await context.sync();
|
||||
|
||||
// Replace any existing watermark so repeated clicks do not duplicate it
|
||||
for (const shapes of shapesByMaster) {
|
||||
for (const shape of shapes) {
|
||||
if (shape.name === DRAFT_CONFIG.SHAPE_NAME) {
|
||||
shape.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create one watermark per master in a single batch
|
||||
for (const master of masters) {
|
||||
const textBox = master.shapes.addTextBox(DRAFT_CONFIG.TEXT, {
|
||||
left: LEFT,
|
||||
top: TOP,
|
||||
width: WIDTH,
|
||||
height: HEIGHT
|
||||
});
|
||||
textBox.name = DRAFT_CONFIG.SHAPE_NAME;
|
||||
textBox.textFrame.textRange.font.name = DRAFT_CONFIG.FONT.NAME;
|
||||
textBox.textFrame.textRange.font.size = DRAFT_CONFIG.FONT.SIZE;
|
||||
textBox.textFrame.textRange.font.bold = true;
|
||||
textBox.textFrame.textRange.font.color = DRAFT_CONFIG.FONT.COLOR;
|
||||
textBox.textFrame.verticalAlignment = "MiddleCentered";
|
||||
result.processedMasters++;
|
||||
}
|
||||
|
||||
await context.sync();
|
||||
result.affectedCount = masters.length;
|
||||
return result;
|
||||
return {
|
||||
processedMasters: masters.length,
|
||||
errorMasters: 0,
|
||||
affectedCount: result.affected
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Removes draft watermarks from all master slides in the presentation
|
||||
*/
|
||||
const removeDraftWatermark = async (): Promise<void> => {
|
||||
resetCancellation();
|
||||
setProgress(null);
|
||||
setIsProcessing(true);
|
||||
try {
|
||||
await PowerPoint.run(async (context) => {
|
||||
@@ -251,12 +236,18 @@ export const DraftButtons: React.FC = () => {
|
||||
}
|
||||
|
||||
const result = await processRemoveWatermarks(context, masters.items);
|
||||
if (isCancellationRequested()) {
|
||||
setStatusMessage("Operation cancelled.");
|
||||
setStatusType("warning");
|
||||
return;
|
||||
}
|
||||
updateStatusFromResult(result, false);
|
||||
});
|
||||
} catch (error) {
|
||||
} catch (error: unknown) {
|
||||
handleError(error, "Remove draft watermark");
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
setProgress(null);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -271,38 +262,17 @@ export const DraftButtons: React.FC = () => {
|
||||
context: PowerPoint.RequestContext,
|
||||
masters: PowerPoint.SlideMaster[]
|
||||
): Promise<ProcessingResult> => {
|
||||
const result: ProcessingResult = {
|
||||
processedMasters: 0,
|
||||
const result = await removeMarkerFromCollections(
|
||||
context,
|
||||
masters.map((master) => master.shapes),
|
||||
MARKER_NAMES.draft
|
||||
);
|
||||
|
||||
return {
|
||||
processedMasters: masters.length,
|
||||
errorMasters: 0,
|
||||
affectedCount: 0
|
||||
affectedCount: result.affected
|
||||
};
|
||||
|
||||
// Load the shapes and names for every master in two batches
|
||||
for (const master of masters) {
|
||||
master.shapes.load("items");
|
||||
}
|
||||
await context.sync();
|
||||
|
||||
const allShapes: PowerPoint.Shape[] = [];
|
||||
for (const master of masters) {
|
||||
for (const shape of master.shapes.items) {
|
||||
shape.load("name");
|
||||
allShapes.push(shape);
|
||||
}
|
||||
}
|
||||
await context.sync();
|
||||
|
||||
// Delete all matching shapes in one batch
|
||||
for (const shape of allShapes) {
|
||||
if (shape.name === DRAFT_CONFIG.SHAPE_NAME) {
|
||||
shape.delete();
|
||||
result.affectedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
await context.sync();
|
||||
result.processedMasters = masters.length;
|
||||
return result;
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* @file ErrorBoundary.tsx
|
||||
* @description Catches render errors so the task pane never shows a blank page.
|
||||
*/
|
||||
|
||||
import * as React from "react";
|
||||
import { getErrorMessage } from "../types/office-types";
|
||||
|
||||
interface ErrorBoundaryProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
interface ErrorBoundaryState {
|
||||
hasError: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
|
||||
state: ErrorBoundaryState = { hasError: false, message: "" };
|
||||
|
||||
static getDerivedStateFromError(error: unknown): ErrorBoundaryState {
|
||||
return { hasError: true, message: getErrorMessage(error) };
|
||||
}
|
||||
|
||||
componentDidCatch(error: unknown, info: React.ErrorInfo): void {
|
||||
console.error("Task pane render error:", error, info.componentStack);
|
||||
}
|
||||
|
||||
render(): React.ReactNode {
|
||||
if (this.state.hasError) {
|
||||
return (
|
||||
<div role="alert" style={{ padding: "16px", fontFamily: "inherit" }}>
|
||||
<h2 style={{ marginTop: 0, fontSize: "16px" }}>Edison could not load</h2>
|
||||
<p style={{ fontSize: "13px" }}>{this.state.message || "An unexpected error occurred."}</p>
|
||||
<button type="button" onClick={() => window.location.reload()}>
|
||||
Reload task pane
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
export default ErrorBoundary;
|
||||
@@ -12,6 +12,8 @@
|
||||
import * as React from "react";
|
||||
import {
|
||||
Button,
|
||||
Field,
|
||||
Input,
|
||||
makeStyles,
|
||||
Label,
|
||||
ToggleButton,
|
||||
@@ -24,27 +26,26 @@ import {
|
||||
SplitVerticalRegular,
|
||||
GridDotsRegular
|
||||
} from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useStatusContext } from "../context/StatusContext";
|
||||
import { useSettings } from "../context/SettingsContext";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import { deleteShapesByPrefix, getErrorMessage } from "../types/office-types";
|
||||
import { SHAPE_NAME_PREFIXES } from "../constants";
|
||||
import { isCancellationRequested, resetCancellation } from "../services/cancellation";
|
||||
import ConfirmButton from "./ConfirmButton";
|
||||
|
||||
/**
|
||||
* Standard dimensions for PowerPoint slides in points
|
||||
*/
|
||||
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;
|
||||
|
||||
const GRID_PREFIX = SHAPE_NAME_PREFIXES.grid;
|
||||
const GUIDE_PREFIX = SHAPE_NAME_PREFIXES.guide;
|
||||
|
||||
/**
|
||||
* Restricts a number to the inclusive range [min, max]
|
||||
*/
|
||||
@@ -61,12 +62,6 @@ type GridColor = "blue" | "red" | "yellow" | "green";
|
||||
*/
|
||||
type GuideDirection = "horizontal" | "vertical";
|
||||
|
||||
/**
|
||||
* Prefixes used for naming shapes to identify them later
|
||||
*/
|
||||
const GRID_PREFIX = "edison_grid_";
|
||||
const GUIDE_PREFIX = "edison_guide_";
|
||||
|
||||
/**
|
||||
* Color values mapping for the available grid and guideline colors
|
||||
*/
|
||||
@@ -162,6 +157,8 @@ const ColorButton: React.FC<ColorButtonProps> = ({ color, selectedColor, onClick
|
||||
style={{ backgroundColor: colorValues[color] }}
|
||||
onClick={() => onClick(color)}
|
||||
title={color.charAt(0).toUpperCase() + color.slice(1)}
|
||||
aria-label={`${color.charAt(0).toUpperCase() + color.slice(1)} color`}
|
||||
aria-pressed={color === selectedColor}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -204,10 +201,13 @@ const useNumericInputHandler = (initialValue: number): NumericInputHandler => {
|
||||
export const GridGuidelineManager: React.FC = () => {
|
||||
const styles = useStyles();
|
||||
const commonStyles = useCommonStyles();
|
||||
const { slideSize } = useSettings();
|
||||
const {
|
||||
setStatusMessage,
|
||||
setStatusType,
|
||||
isProcessing, setIsProcessing
|
||||
isProcessing,
|
||||
setIsProcessing,
|
||||
setProgress
|
||||
} = useStatusContext();
|
||||
|
||||
// Grid state
|
||||
@@ -261,6 +261,9 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
* Creates a grid on the current slide based on the configured settings
|
||||
*/
|
||||
const createGrid = React.useCallback(async () => {
|
||||
resetCancellation();
|
||||
setProgress(null);
|
||||
|
||||
if (!Number.isFinite(gridSpacing) || !Number.isFinite(gridOpacity)) {
|
||||
setStatusMessage("Please enter valid numeric values for spacing and opacity.");
|
||||
setStatusType("warning");
|
||||
@@ -275,14 +278,15 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
}
|
||||
|
||||
// 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 maxSpacing = Math.min(slideSize.width, slideSize.height);
|
||||
const spacing = clamp(Math.round(gridSpacing), GRID_SPACING_MIN, maxSpacing);
|
||||
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);
|
||||
const numHorizontalLines = Math.floor(slideSize.height / spacing);
|
||||
const numVerticalLines = Math.floor(slideSize.width / spacing);
|
||||
if (numHorizontalLines + numVerticalLines > MAX_GRID_LINES) {
|
||||
setStatusMessage(
|
||||
`Grid spacing of ${spacing} pt creates too many lines. Use a larger spacing value.`
|
||||
@@ -314,17 +318,28 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
}
|
||||
await context.sync();
|
||||
|
||||
if (isCancellationRequested()) {
|
||||
setStatusMessage("Operation cancelled.");
|
||||
setStatusType("warning");
|
||||
return;
|
||||
}
|
||||
|
||||
deleteShapesByPrefix(currentSlide.shapes.items, GRID_PREFIX);
|
||||
|
||||
const totalLines = numHorizontalLines + numVerticalLines;
|
||||
let queuedLines = 0;
|
||||
|
||||
// Create horizontal grid lines
|
||||
for (let i = 1; i <= numHorizontalLines; i++) {
|
||||
if (isCancellationRequested()) break;
|
||||
|
||||
const yPosition = i * spacing;
|
||||
|
||||
// Skip if we're at the edge of the slide
|
||||
if (yPosition >= SLIDE_HEIGHT) continue;
|
||||
if (yPosition >= slideSize.height) continue;
|
||||
|
||||
// Create horizontal line
|
||||
const line = createLineShape(currentSlide, 0, yPosition, SLIDE_WIDTH, yPosition);
|
||||
const line = createLineShape(currentSlide, 0, yPosition, slideSize.width, yPosition);
|
||||
line.name = `${GRID_PREFIX}h_${i}`;
|
||||
|
||||
// Set line properties
|
||||
@@ -334,17 +349,22 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
|
||||
// Set transparency (opacity is inverse of transparency)
|
||||
line.fill.transparency = (100 - opacity) / 100;
|
||||
|
||||
queuedLines++;
|
||||
setProgress({ current: queuedLines, total: totalLines });
|
||||
}
|
||||
|
||||
// Create vertical grid lines
|
||||
for (let i = 1; i <= numVerticalLines; i++) {
|
||||
if (isCancellationRequested()) break;
|
||||
|
||||
const xPosition = i * spacing;
|
||||
|
||||
// Skip if we're at the edge of the slide
|
||||
if (xPosition >= SLIDE_WIDTH) continue;
|
||||
if (xPosition >= slideSize.width) continue;
|
||||
|
||||
// Create vertical line
|
||||
const line = createLineShape(currentSlide, xPosition, 0, xPosition, SLIDE_HEIGHT);
|
||||
const line = createLineShape(currentSlide, xPosition, 0, xPosition, slideSize.height);
|
||||
line.name = `${GRID_PREFIX}v_${i}`;
|
||||
|
||||
// Set line properties
|
||||
@@ -354,10 +374,18 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
|
||||
// Set transparency (opacity is inverse of transparency)
|
||||
line.fill.transparency = (100 - opacity) / 100;
|
||||
|
||||
queuedLines++;
|
||||
setProgress({ current: queuedLines, total: totalLines });
|
||||
}
|
||||
|
||||
if (isCancellationRequested()) {
|
||||
setStatusMessage("Operation cancelled.");
|
||||
setStatusType("warning");
|
||||
} else {
|
||||
setStatusMessage("Grid created on current slide");
|
||||
setStatusType("success");
|
||||
}
|
||||
|
||||
setStatusMessage("Grid created on current slide");
|
||||
setStatusType("success");
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
setStatusMessage(`Error: ${getErrorMessage(error)}`);
|
||||
@@ -365,13 +393,16 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
console.error("Create grid error:", error);
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
setProgress(null);
|
||||
}
|
||||
}, [createLineShape, gridColor, gridOpacity, gridSpacing, setGridOpacity, setGridSpacing, setIsProcessing, setStatusMessage, setStatusType]);
|
||||
}, [createLineShape, gridColor, gridOpacity, gridSpacing, setGridOpacity, setGridSpacing, setIsProcessing, setProgress, setStatusMessage, setStatusType, slideSize]);
|
||||
|
||||
/**
|
||||
* Removes the grid from the current slide
|
||||
*/
|
||||
const removeGrid = React.useCallback(async () => {
|
||||
resetCancellation();
|
||||
setProgress(null);
|
||||
setIsProcessing(true);
|
||||
|
||||
try {
|
||||
@@ -415,13 +446,17 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
console.error("Remove grid error:", error);
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
setProgress(null);
|
||||
}
|
||||
}, [setIsProcessing, setStatusMessage, setStatusType]);
|
||||
}, [setIsProcessing, setProgress, setStatusMessage, setStatusType]);
|
||||
|
||||
/**
|
||||
* Adds a guideline to the current slide based on the configured settings
|
||||
*/
|
||||
const addGuideline = React.useCallback(async () => {
|
||||
resetCancellation();
|
||||
setProgress(null);
|
||||
|
||||
if (!Number.isFinite(guidePosition)) {
|
||||
setStatusMessage("Please enter a valid numeric position for the guideline.");
|
||||
setStatusType("warning");
|
||||
@@ -429,7 +464,7 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
}
|
||||
|
||||
// Keep the guideline inside the slide so it is visible and meaningful.
|
||||
const maxPosition = guideDirection === "horizontal" ? SLIDE_HEIGHT : SLIDE_WIDTH;
|
||||
const maxPosition = guideDirection === "horizontal" ? slideSize.height : slideSize.width;
|
||||
const position = clamp(Math.round(guidePosition), 0, maxPosition);
|
||||
if (position !== guidePosition) setGuidePosition(position);
|
||||
|
||||
@@ -456,10 +491,10 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
let line: PowerPoint.Shape;
|
||||
if (guideDirection === "horizontal") {
|
||||
// Create horizontal guideline
|
||||
line = createLineShape(currentSlide, 0, position, SLIDE_WIDTH, position);
|
||||
line = createLineShape(currentSlide, 0, position, slideSize.width, position);
|
||||
} else {
|
||||
// Create vertical guideline
|
||||
line = createLineShape(currentSlide, position, 0, position, SLIDE_HEIGHT);
|
||||
line = createLineShape(currentSlide, position, 0, position, slideSize.height);
|
||||
}
|
||||
|
||||
line.name = guideId;
|
||||
@@ -480,13 +515,16 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
console.error("Add guideline error:", error);
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
setProgress(null);
|
||||
}
|
||||
}, [createLineShape, guideColor, guideDirection, guidePosition, setGuidePosition, setIsProcessing, setStatusMessage, setStatusType]);
|
||||
}, [createLineShape, guideColor, guideDirection, guidePosition, setGuidePosition, setIsProcessing, setProgress, setStatusMessage, setStatusType, slideSize]);
|
||||
|
||||
/**
|
||||
* Removes all guidelines from the current slide
|
||||
*/
|
||||
const removeGuidelines = React.useCallback(async () => {
|
||||
resetCancellation();
|
||||
setProgress(null);
|
||||
setIsProcessing(true);
|
||||
try {
|
||||
await PowerPoint.run(async (context) => {
|
||||
@@ -529,8 +567,9 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
console.error("Remove guidelines error:", error);
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
setProgress(null);
|
||||
}
|
||||
}, [setIsProcessing, setStatusMessage, setStatusType]);
|
||||
}, [setIsProcessing, setProgress, setStatusMessage, setStatusType]);
|
||||
|
||||
return (
|
||||
<div className={commonStyles.container} style={{ maxHeight: "400px", overflowY: "auto" }}>
|
||||
@@ -543,49 +582,29 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
Grid
|
||||
</Label>
|
||||
|
||||
<div className={styles.controlRow}>
|
||||
<Label className={styles.controlLabel}>Spacing</Label>
|
||||
<div style={{ width: "80px", flex: "none" }}>
|
||||
<input
|
||||
type="text"
|
||||
value={gridSpacing}
|
||||
onChange={handleGridSpacingChange}
|
||||
onClick={(e) => (e.target as HTMLInputElement).select()}
|
||||
title="Grid Spacing"
|
||||
placeholder="Grid Spacing"
|
||||
aria-label="Grid Spacing"
|
||||
style={{
|
||||
width: "100%",
|
||||
padding: "5px 8px",
|
||||
border: "1px solid #d1d1d1",
|
||||
borderRadius: "4px",
|
||||
fontSize: "14px"
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Field label="Spacing" style={{ marginBottom: "8px" }}>
|
||||
<Input
|
||||
type="number"
|
||||
value={String(gridSpacing)}
|
||||
onChange={handleGridSpacingChange}
|
||||
min={GRID_SPACING_MIN}
|
||||
max={Math.min(slideSize.width, slideSize.height)}
|
||||
title="Grid spacing in points"
|
||||
style={{ width: "100px" }}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<div className={styles.controlRow}>
|
||||
<Label className={styles.controlLabel}>Opacity</Label>
|
||||
<div style={{ width: "80px", flex: "none" }}>
|
||||
<input
|
||||
type="text"
|
||||
value={gridOpacity}
|
||||
onChange={handleGridOpacityChange}
|
||||
onClick={(e) => (e.target as HTMLInputElement).select()}
|
||||
title="Grid Opacity"
|
||||
placeholder="Grid Opacity"
|
||||
aria-label="Grid Opacity"
|
||||
style={{
|
||||
width: "100%",
|
||||
padding: "5px 8px",
|
||||
border: "1px solid #d1d1d1",
|
||||
borderRadius: "4px",
|
||||
fontSize: "14px"
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Field label="Opacity" style={{ marginBottom: "8px" }}>
|
||||
<Input
|
||||
type="number"
|
||||
value={String(gridOpacity)}
|
||||
onChange={handleGridOpacityChange}
|
||||
min={GRID_OPACITY_MIN}
|
||||
max={GRID_OPACITY_MAX}
|
||||
title="Grid opacity percentage"
|
||||
style={{ width: "100px" }}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<div className={styles.controlRow}>
|
||||
<Label className={styles.controlLabel}>Color</Label>
|
||||
@@ -633,27 +652,17 @@ export const GridGuidelineManager: React.FC = () => {
|
||||
Guidelines
|
||||
</Label>
|
||||
|
||||
<div className={styles.controlRow}>
|
||||
<Label className={styles.controlLabel}>Position</Label>
|
||||
<div style={{ width: "80px", flex: "none" }}>
|
||||
<input
|
||||
type="text"
|
||||
value={guidePosition}
|
||||
onChange={handleGuidePositionChange}
|
||||
onClick={(e) => (e.target as HTMLInputElement).select()}
|
||||
title="Guide Position"
|
||||
placeholder="Guide Position"
|
||||
aria-label="Guide Position"
|
||||
style={{
|
||||
width: "100%",
|
||||
padding: "5px 8px",
|
||||
border: "1px solid #d1d1d1",
|
||||
borderRadius: "4px",
|
||||
fontSize: "14px"
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Field label="Position" style={{ marginBottom: "8px" }}>
|
||||
<Input
|
||||
type="number"
|
||||
value={String(guidePosition)}
|
||||
onChange={handleGuidePositionChange}
|
||||
min={0}
|
||||
max={guideDirection === "horizontal" ? slideSize.height : slideSize.width}
|
||||
title="Guideline position in points"
|
||||
style={{ width: "100px" }}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<div className={styles.controlRow}>
|
||||
<Label className={styles.controlLabel}>Type</Label>
|
||||
|
||||
@@ -1,222 +1,42 @@
|
||||
/**
|
||||
* @file InsertTitles.tsx
|
||||
* @description Component that provides functionality to collect and insert slide titles
|
||||
* from all slides in a PowerPoint presentation into a selected text box. This allows users
|
||||
* to quickly generate a table of contents or agenda slide with all presentation titles.
|
||||
* @description Collects slide titles from all slides and inserts them into a
|
||||
* selected text box, producing a table of contents or agenda slide.
|
||||
*/
|
||||
|
||||
import * as React from "react";
|
||||
import { Dropdown, Field, Option } from "@fluentui/react-components";
|
||||
import { TextBulletListRegular } from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useStatusContext } from "../context/StatusContext";
|
||||
import { useSettings } from "../context/SettingsContext";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import ActionButton from "./ActionButton";
|
||||
import { getErrorMessage, isTextCapableShape } from "../types/office-types";
|
||||
import { collectSlideTitles, TitleDetectionMethod } from "../services/titles";
|
||||
import { isCancellationRequested, resetCancellation } from "../services/cancellation";
|
||||
|
||||
// Configuration constants
|
||||
const TITLE_POSITION_THRESHOLD = 95; // Points from the top of the slide to consider a shape as a title
|
||||
const STANDARD_SLIDE_WIDTH = 960; // Standard widescreen PowerPoint slide width in points
|
||||
|
||||
// Title detection methods
|
||||
type TitleDetectionMethod = "auto" | "position" | "first" | "name";
|
||||
|
||||
// Title collection options
|
||||
interface TitleCollectionOptions {
|
||||
includeSlideNumbers: boolean;
|
||||
detectionMethod?: TitleDetectionMethod;
|
||||
}
|
||||
|
||||
// Title collection result
|
||||
interface TitleCollectionResult {
|
||||
titleText: string;
|
||||
titlesCollected: number;
|
||||
}
|
||||
|
||||
// Title candidate with position and size information
|
||||
interface TitleCandidate {
|
||||
name: string;
|
||||
text: string;
|
||||
top: number;
|
||||
left: number;
|
||||
width: number;
|
||||
height: number;
|
||||
fontSize: number;
|
||||
isBold: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Chooses the most likely title from the loaded text shapes on a slide.
|
||||
*/
|
||||
const pickTitleText = (
|
||||
candidates: TitleCandidate[],
|
||||
method: TitleDetectionMethod
|
||||
): string | null => {
|
||||
if (candidates.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// The first text shape in z-order
|
||||
if (method === "first") {
|
||||
return candidates[0].text;
|
||||
}
|
||||
|
||||
// Shape names are the most reliable hint when present
|
||||
if (method === "auto" || method === "name") {
|
||||
const namedCandidate = candidates.find((candidate) => {
|
||||
const name = candidate.name.toLowerCase();
|
||||
return name.includes("title") || name.includes("heading");
|
||||
});
|
||||
|
||||
if (namedCandidate) {
|
||||
return namedCandidate.text;
|
||||
}
|
||||
|
||||
if (method === "name") {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// The first text shape near the top of the slide
|
||||
if (method === "position") {
|
||||
const positionedCandidate = candidates.find(
|
||||
(candidate) => candidate.top < TITLE_POSITION_THRESHOLD
|
||||
);
|
||||
return positionedCandidate ? positionedCandidate.text : null;
|
||||
}
|
||||
|
||||
// Auto mode: rank the shapes nearest the top of the slide
|
||||
const topCandidates = candidates.filter(
|
||||
(candidate) => candidate.top < TITLE_POSITION_THRESHOLD
|
||||
);
|
||||
if (topCandidates.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
topCandidates.sort((a, b) => a.top - b.top);
|
||||
const nearestCandidates = topCandidates.filter(
|
||||
(candidate) => candidate.top <= topCandidates[0].top + 50
|
||||
);
|
||||
|
||||
if (nearestCandidates.length > 1) {
|
||||
nearestCandidates.sort((a, b) => {
|
||||
// Prefer shapes that are centered, use a larger font, are bold, and are wider
|
||||
const aCenterOffset = Math.abs(a.left + a.width / 2 - STANDARD_SLIDE_WIDTH / 2);
|
||||
const bCenterOffset = Math.abs(b.left + b.width / 2 - STANDARD_SLIDE_WIDTH / 2);
|
||||
const aFontScore = a.fontSize * (a.isBold ? 1.5 : 1);
|
||||
const bFontScore = b.fontSize * (b.isBold ? 1.5 : 1);
|
||||
const aScore = aCenterOffset * 2 - aFontScore * 5 - a.width * 0.5;
|
||||
const bScore = bCenterOffset * 2 - bFontScore * 5 - b.width * 0.5;
|
||||
return aScore - bScore;
|
||||
});
|
||||
}
|
||||
|
||||
return nearestCandidates[0].text;
|
||||
};
|
||||
|
||||
/**
|
||||
* Collects titles from all slides using three batched syncs instead of
|
||||
* multiple round-trips per shape.
|
||||
*/
|
||||
const collectSlideTitles = async (
|
||||
slides: PowerPoint.SlideCollection,
|
||||
context: PowerPoint.RequestContext,
|
||||
options: TitleCollectionOptions
|
||||
): Promise<TitleCollectionResult> => {
|
||||
// Load the shape collections for every slide in a single batch
|
||||
for (const slide of slides.items) {
|
||||
slide.shapes.load("items");
|
||||
}
|
||||
await context.sync();
|
||||
|
||||
// Load geometry, type and text presence for every shape
|
||||
for (const slide of slides.items) {
|
||||
for (const shape of slide.shapes.items) {
|
||||
shape.load(["name", "type", "top", "left", "width", "height", "textFrame/hasText"]);
|
||||
}
|
||||
}
|
||||
await context.sync();
|
||||
|
||||
// Load text and font details only for shapes that can hold text and contain some
|
||||
for (const slide of slides.items) {
|
||||
for (const shape of slide.shapes.items) {
|
||||
if (isTextCapableShape(shape) && shape.textFrame.hasText) {
|
||||
shape.textFrame.textRange.load(["text", "font/size", "font/bold"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
await context.sync();
|
||||
|
||||
let titleText = "";
|
||||
let titlesCollected = 0;
|
||||
|
||||
for (let i = 0; i < slides.items.length; i++) {
|
||||
const candidates: TitleCandidate[] = [];
|
||||
|
||||
for (const shape of slides.items[i].shapes.items) {
|
||||
if (!isTextCapableShape(shape) || !shape.textFrame.hasText) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const text = shape.textFrame.textRange.text;
|
||||
if (!text || text.trim() === "") {
|
||||
continue;
|
||||
}
|
||||
|
||||
candidates.push({
|
||||
name: shape.name,
|
||||
text: text.trim(),
|
||||
top: shape.top,
|
||||
left: shape.left,
|
||||
width: shape.width,
|
||||
height: shape.height,
|
||||
fontSize: shape.textFrame.textRange.font.size ?? 12,
|
||||
isBold: shape.textFrame.textRange.font.bold ?? false
|
||||
});
|
||||
}
|
||||
|
||||
const title = pickTitleText(candidates, options.detectionMethod || "auto");
|
||||
if (title) {
|
||||
const formattedTitle = options.includeSlideNumbers
|
||||
? `Slide ${i + 1}: ${title}`
|
||||
: title;
|
||||
titleText += `${formattedTitle}\n`;
|
||||
titlesCollected++;
|
||||
}
|
||||
}
|
||||
|
||||
return { titleText, titlesCollected };
|
||||
};
|
||||
|
||||
/**
|
||||
* Generates an appropriate status message based on the results
|
||||
* @param titlesCollected The number of titles collected
|
||||
* @param insertSuccess Whether insertion was successful
|
||||
* @returns The formatted status message
|
||||
*/
|
||||
const generateStatusMessage = (
|
||||
titlesCollected: number,
|
||||
insertSuccess: boolean
|
||||
): string => {
|
||||
if (titlesCollected === 0) {
|
||||
return "No slide titles found to insert.";
|
||||
}
|
||||
|
||||
if (!insertSuccess) {
|
||||
return "Error inserting titles into the selected shape.";
|
||||
}
|
||||
|
||||
return `Collected and inserted ${titlesCollected} slide titles.`;
|
||||
const DETECTION_LABELS: Record<TitleDetectionMethod, string> = {
|
||||
auto: "Auto-detect titles",
|
||||
name: "Title shapes by name",
|
||||
position: "Position-based detection",
|
||||
first: "First text on slide"
|
||||
};
|
||||
|
||||
export const InsertTitles: React.FC = () => {
|
||||
const styles = useCommonStyles();
|
||||
const { setStatusMessage, setStatusType } = useStatusContext();
|
||||
const [titleDetectionMethod, setTitleDetectionMethod] = React.useState<TitleDetectionMethod>("auto");
|
||||
const { slideSize } = useSettings();
|
||||
const { setStatusMessage, setStatusType, setIsProcessing, setProgress } = useStatusContext();
|
||||
const [titleDetectionMethod, setTitleDetectionMethod] =
|
||||
React.useState<TitleDetectionMethod>("auto");
|
||||
const [includeSlideNumbers, setIncludeSlideNumbers] = React.useState<boolean>(false);
|
||||
|
||||
/**
|
||||
* Main function to collect and insert slide titles
|
||||
*/
|
||||
const collectAndInsertTitles = async (): Promise<void> => {
|
||||
resetCancellation();
|
||||
setProgress(null);
|
||||
|
||||
try {
|
||||
await PowerPoint.run(async (context) => {
|
||||
// Get the selected shapes and all slides in one batch
|
||||
@@ -244,10 +64,19 @@ export const InsertTitles: React.FC = () => {
|
||||
}
|
||||
|
||||
// Collect titles from all slides
|
||||
const { titleText, titlesCollected } = await collectSlideTitles(slides, context, {
|
||||
includeSlideNumbers,
|
||||
detectionMethod: titleDetectionMethod
|
||||
});
|
||||
const { titleText, titlesCollected, cancelled } = await collectSlideTitles(
|
||||
slides,
|
||||
context,
|
||||
{ includeSlideNumbers, detectionMethod: titleDetectionMethod },
|
||||
slideSize.width,
|
||||
(current, total) => setProgress({ current, total })
|
||||
);
|
||||
|
||||
if (cancelled || isCancellationRequested()) {
|
||||
setStatusMessage("Operation cancelled.");
|
||||
setStatusType("warning");
|
||||
return;
|
||||
}
|
||||
|
||||
// Insert titles if any were found
|
||||
let insertSuccess = false;
|
||||
@@ -257,17 +86,24 @@ export const InsertTitles: React.FC = () => {
|
||||
insertSuccess = true;
|
||||
}
|
||||
|
||||
// Update status message
|
||||
setStatusMessage(generateStatusMessage(titlesCollected, insertSuccess));
|
||||
setStatusType(
|
||||
titlesCollected === 0 ? "warning" :
|
||||
insertSuccess ? "success" : "error"
|
||||
);
|
||||
if (titlesCollected === 0) {
|
||||
setStatusMessage("No slide titles found to insert.");
|
||||
setStatusType("warning");
|
||||
} else if (!insertSuccess) {
|
||||
setStatusMessage("Error inserting titles into the selected shape.");
|
||||
setStatusType("error");
|
||||
} else {
|
||||
setStatusMessage(`Collected and inserted ${titlesCollected} slide titles.`);
|
||||
setStatusType("success");
|
||||
}
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
console.error("Error in collectAndInsertTitles:", getErrorMessage(error));
|
||||
setStatusMessage(`Error: ${getErrorMessage(error)}`);
|
||||
setStatusType("error");
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
setProgress(null);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -283,32 +119,37 @@ export const InsertTitles: React.FC = () => {
|
||||
confirmLabel="Insert"
|
||||
/>
|
||||
</div>
|
||||
<div style={{ marginTop: '10px', display: 'flex', justifyContent: 'flex-end' }}>
|
||||
<select
|
||||
value={titleDetectionMethod}
|
||||
onChange={(e) => setTitleDetectionMethod(e.target.value as TitleDetectionMethod)}
|
||||
style={{ width: '75%' }}
|
||||
aria-label="Title detection method"
|
||||
title="Select title detection method"
|
||||
|
||||
<Field label="Title detection">
|
||||
<Dropdown
|
||||
value={DETECTION_LABELS[titleDetectionMethod]}
|
||||
selectedOptions={[titleDetectionMethod]}
|
||||
onOptionSelect={(_, data) => {
|
||||
if (data.optionValue) {
|
||||
setTitleDetectionMethod(data.optionValue as TitleDetectionMethod);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="auto">Auto-detect titles</option>
|
||||
<option value="name">Title shapes by name</option>
|
||||
<option value="position">Position-based detection</option>
|
||||
<option value="first">First text on slide</option>
|
||||
</select>
|
||||
</div>
|
||||
<div style={{ marginTop: '10px', display: 'flex', justifyContent: 'flex-end' }}>
|
||||
<select
|
||||
value={includeSlideNumbers ? "yes" : "no"}
|
||||
onChange={(e) => setIncludeSlideNumbers(e.target.value === "yes")}
|
||||
style={{ width: '75%' }}
|
||||
aria-label="Include slide numbers"
|
||||
title="Include slide numbers in output"
|
||||
{(Object.keys(DETECTION_LABELS) as TitleDetectionMethod[]).map((method) => (
|
||||
<Option key={method} value={method}>
|
||||
{DETECTION_LABELS[method]}
|
||||
</Option>
|
||||
))}
|
||||
</Dropdown>
|
||||
</Field>
|
||||
|
||||
<Field label="Slide numbers">
|
||||
<Dropdown
|
||||
value={includeSlideNumbers ? "Include slide numbers" : "Exclude slide numbers"}
|
||||
selectedOptions={[includeSlideNumbers ? "yes" : "no"]}
|
||||
onOptionSelect={(_, data) => {
|
||||
setIncludeSlideNumbers(data.optionValue === "yes");
|
||||
}}
|
||||
>
|
||||
<option value="no">Exclude slide numbers</option>
|
||||
<option value="yes">Include slide numbers</option>
|
||||
</select>
|
||||
</div>
|
||||
<Option value="no">Exclude slide numbers</Option>
|
||||
<Option value="yes">Include slide numbers</Option>
|
||||
</Dropdown>
|
||||
</Field>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
import * as React from "react";
|
||||
import { ColorRegular } from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useStatusContext } from "../context/StatusContext";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import ActionButton from "./ActionButton";
|
||||
import { getErrorMessage, isNotNullish, isTextCapableShape } from "../types/office-types";
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
import * as React from "react";
|
||||
import { ArrowFitInRegular } from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useStatusContext } from "../context/StatusContext";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import ActionButton from "./ActionButton";
|
||||
import { getErrorMessage } from "../types/office-types";
|
||||
|
||||
@@ -14,27 +14,17 @@ import {
|
||||
GaugeRegular,
|
||||
DismissRegular
|
||||
} from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useStatusContext } from "../context/StatusContext";
|
||||
import { useSettings } from "../context/SettingsContext";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import { deleteShapesByPrefix, getErrorMessage } from "../types/office-types";
|
||||
import { getErrorMessage } from "../types/office-types";
|
||||
import { isCancellationRequested, resetCancellation } from "../services/cancellation";
|
||||
import {
|
||||
addProgressBar as addProgressBarToSlides,
|
||||
removeProgressBar as removeProgressBars
|
||||
} from "../services/progressBar";
|
||||
import ConfirmButton from "./ConfirmButton";
|
||||
|
||||
// Shape name prefix used to identify progress bar elements
|
||||
const PROGRESS_BAR_PREFIX = "progress_bar_";
|
||||
|
||||
// Constants for progress bar configuration
|
||||
const PROGRESS_BAR_CONFIG = {
|
||||
// Standard PowerPoint slide dimensions in points
|
||||
slideWidth: 960,
|
||||
slideHeight: 540,
|
||||
// Progress bar appearance
|
||||
barHeight: 1,
|
||||
distanceFromBottom: 28,
|
||||
// Colors
|
||||
completedColor: "#205170", // Blue for progressed segments (RGB 32, 81, 112)
|
||||
pendingColor: "#F2F2F2" // Grey for segments not yet progressed (RGB 242, 242, 242)
|
||||
};
|
||||
|
||||
const useStyles = makeStyles({
|
||||
buttonGrid: {
|
||||
display: "grid",
|
||||
@@ -55,10 +45,13 @@ const useStyles = makeStyles({
|
||||
export const ProgressBarButtons: React.FC = () => {
|
||||
const styles = useStyles();
|
||||
const commonStyles = useCommonStyles();
|
||||
const { slideSize } = useSettings();
|
||||
const {
|
||||
setStatusMessage,
|
||||
setStatusType,
|
||||
isProcessing, setIsProcessing
|
||||
isProcessing,
|
||||
setIsProcessing,
|
||||
setProgress
|
||||
} = useStatusContext();
|
||||
|
||||
/**
|
||||
@@ -66,69 +59,31 @@ export const ProgressBarButtons: React.FC = () => {
|
||||
* Each slide gets two rectangles: a full pending bar and the completed portion.
|
||||
*/
|
||||
const addProgressBar = async () => {
|
||||
resetCancellation();
|
||||
setProgress(null);
|
||||
setIsProcessing(true);
|
||||
|
||||
try {
|
||||
await PowerPoint.run(async (context) => {
|
||||
const slides = context.presentation.slides;
|
||||
slides.load("items");
|
||||
await context.sync();
|
||||
const result = await addProgressBarToSlides(
|
||||
context,
|
||||
slideSize,
|
||||
(current, total) => setProgress({ current, total })
|
||||
);
|
||||
|
||||
const slideCount = slides.items.length;
|
||||
if (slideCount === 0) {
|
||||
if (isCancellationRequested() || result.cancelled) {
|
||||
setStatusMessage("Operation cancelled.");
|
||||
setStatusType("warning");
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.slideCount === 0) {
|
||||
setStatusMessage("No slides found in the presentation.");
|
||||
setStatusType("warning");
|
||||
return;
|
||||
}
|
||||
|
||||
const { slideWidth, slideHeight, barHeight, distanceFromBottom } = PROGRESS_BAR_CONFIG;
|
||||
const segmentWidth = slideWidth / slideCount;
|
||||
const startY = slideHeight - distanceFromBottom;
|
||||
|
||||
// Remove existing bars so repeated clicks replace instead of duplicate them
|
||||
for (const slide of slides.items) {
|
||||
slide.shapes.load("items");
|
||||
}
|
||||
await context.sync();
|
||||
|
||||
const shapesBySlide: PowerPoint.Shape[][] = [];
|
||||
for (const slide of slides.items) {
|
||||
for (const shape of slide.shapes.items) {
|
||||
shape.load("name");
|
||||
}
|
||||
shapesBySlide.push(slide.shapes.items);
|
||||
}
|
||||
await context.sync();
|
||||
|
||||
for (const shapes of shapesBySlide) {
|
||||
deleteShapesByPrefix(shapes, PROGRESS_BAR_PREFIX);
|
||||
}
|
||||
|
||||
// Two rectangles per slide: the full pending bar and the completed portion
|
||||
slides.items.forEach((slide, index) => {
|
||||
const pending = slide.shapes.addGeometricShape("Rectangle");
|
||||
pending.left = 0;
|
||||
pending.top = startY;
|
||||
pending.width = slideWidth;
|
||||
pending.height = barHeight;
|
||||
pending.fill.setSolidColor(PROGRESS_BAR_CONFIG.pendingColor);
|
||||
pending.lineFormat.visible = false;
|
||||
pending.name = `${PROGRESS_BAR_PREFIX}pending`;
|
||||
|
||||
const completed = slide.shapes.addGeometricShape("Rectangle");
|
||||
completed.left = 0;
|
||||
completed.top = startY;
|
||||
completed.width = (index + 1) * segmentWidth;
|
||||
completed.height = barHeight;
|
||||
completed.fill.setSolidColor(PROGRESS_BAR_CONFIG.completedColor);
|
||||
completed.lineFormat.visible = false;
|
||||
completed.name = `${PROGRESS_BAR_PREFIX}completed`;
|
||||
});
|
||||
|
||||
// Single final sync to commit all changes
|
||||
await context.sync();
|
||||
|
||||
setStatusMessage(`Added progress bar to ${slideCount} slides.`);
|
||||
setStatusMessage(`Added progress bar to ${result.slideCount} slides.`);
|
||||
setStatusType("success");
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
@@ -137,6 +92,7 @@ export const ProgressBarButtons: React.FC = () => {
|
||||
console.error("Add progress bar error:", error);
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
setProgress(null);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -145,35 +101,21 @@ export const ProgressBarButtons: React.FC = () => {
|
||||
* Identifies progress bar elements by their name prefix "progress_bar_"
|
||||
*/
|
||||
const removeProgressBar = async () => {
|
||||
resetCancellation();
|
||||
setProgress(null);
|
||||
setIsProcessing(true);
|
||||
|
||||
try {
|
||||
await PowerPoint.run(async (context) => {
|
||||
const slides = context.presentation.slides;
|
||||
slides.load("items");
|
||||
await context.sync();
|
||||
const result = await removeProgressBars(context);
|
||||
|
||||
// Load all shapes from all slides in a batch
|
||||
for (const slide of slides.items) {
|
||||
slide.shapes.load("items");
|
||||
if (isCancellationRequested() || result.cancelled) {
|
||||
setStatusMessage("Operation cancelled.");
|
||||
setStatusType("warning");
|
||||
return;
|
||||
}
|
||||
await context.sync();
|
||||
|
||||
// Load all shape names in a batch
|
||||
const allShapes: PowerPoint.Shape[] = [];
|
||||
for (const slide of slides.items) {
|
||||
for (const shape of slide.shapes.items) {
|
||||
shape.load("name");
|
||||
allShapes.push(shape);
|
||||
}
|
||||
}
|
||||
await context.sync();
|
||||
|
||||
const removedCount = deleteShapesByPrefix(allShapes, PROGRESS_BAR_PREFIX);
|
||||
|
||||
await context.sync();
|
||||
|
||||
if (removedCount > 0) {
|
||||
if (result.removed > 0) {
|
||||
setStatusMessage(`Removed progress bar from slides.`);
|
||||
setStatusType("success");
|
||||
} else {
|
||||
@@ -187,6 +129,7 @@ export const ProgressBarButtons: React.FC = () => {
|
||||
console.error("Remove progress bar error:", error);
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
setProgress(null);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
import * as React from "react";
|
||||
import { CircleRegular } from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useStatusContext } from "../context/StatusContext";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import ActionButton from "./ActionButton";
|
||||
import { getErrorMessage, isPictureShape, getFirstSelectedSlide, selectShapesById } from "../types/office-types";
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import * as React from "react";
|
||||
import { Subtitle1, makeStyles, tokens } from "@fluentui/react-components";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionHeader,
|
||||
AccordionItem,
|
||||
AccordionPanel,
|
||||
makeStyles,
|
||||
tokens
|
||||
} from "@fluentui/react-components";
|
||||
|
||||
interface SectionProps {
|
||||
title: string;
|
||||
@@ -15,30 +22,35 @@ const useStyles = makeStyles({
|
||||
boxShadow: "0 1px 2px rgba(0, 0, 0, 0.06)",
|
||||
transition: "all 0.2s ease",
|
||||
":hover": {
|
||||
boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
|
||||
},
|
||||
boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)"
|
||||
}
|
||||
},
|
||||
accordion: {
|
||||
width: "100%"
|
||||
},
|
||||
sectionTitle: {
|
||||
marginBottom: "12px",
|
||||
fontWeight: tokens.fontWeightSemibold,
|
||||
color: tokens.colorBrandForeground1,
|
||||
},
|
||||
fontSize: tokens.fontSizeBase400
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Reusable section component with consistent styling
|
||||
* Collapsible section used to group related tools.
|
||||
*/
|
||||
export const Section: React.FC<SectionProps> = ({ title, children }) => {
|
||||
const styles = useStyles();
|
||||
|
||||
return (
|
||||
<div className={styles.section}>
|
||||
<Subtitle1 block className={styles.sectionTitle}>
|
||||
{title}
|
||||
</Subtitle1>
|
||||
{children}
|
||||
<Accordion collapsible defaultOpenItems={[title]} className={styles.accordion}>
|
||||
<AccordionItem value={title}>
|
||||
<AccordionHeader className={styles.sectionTitle}>{title}</AccordionHeader>
|
||||
<AccordionPanel>{children}</AccordionPanel>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Section;
|
||||
export default Section;
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
import * as React from "react";
|
||||
import { ArrowSwapRegular } from "@fluentui/react-icons";
|
||||
import { useStatusContext } from "./App";
|
||||
import { useStatusContext } from "../context/StatusContext";
|
||||
import { useCommonStyles } from "./commonStyles";
|
||||
import ActionButton from "./ActionButton";
|
||||
import { getErrorMessage } from "../types/office-types";
|
||||
|
||||
Reference in new issue
Block a user