selection also

This commit is contained in:
Reece Browne 2025-09-11 19:38:04 +01:00
parent 687ab39286
commit 93607937f6

View File

@ -1,11 +1,12 @@
import { useEffect } from 'react';
import { useSelectionCapability } from '@embedpdf/plugin-selection/react';
import { useEffect, useState } from 'react';
import { useSelectionCapability, SelectionRangeX } from '@embedpdf/plugin-selection/react';
/**
* Component that runs inside EmbedPDF context and exports selection controls globally
*/
export function SelectionControlsExporter() {
const { provides: selection } = useSelectionCapability();
const [hasSelection, setHasSelection] = useState(false);
useEffect(() => {
if (selection) {
@ -14,9 +15,37 @@ export function SelectionControlsExporter() {
copyToClipboard: () => selection.copyToClipboard(),
getSelectedText: () => selection.getSelectedText(),
getFormattedSelection: () => selection.getFormattedSelection(),
hasSelection: hasSelection,
};
// Listen for selection changes to track when text is selected
const unsubscribe = selection.onSelectionChange((sel: SelectionRangeX | null) => {
const hasText = !!sel;
setHasSelection(hasText);
// Update global state
if ((window as any).embedPdfSelection) {
(window as any).embedPdfSelection.hasSelection = hasText;
}
});
// Intercept Ctrl+C only when we have PDF text selected
const handleKeyDown = (event: KeyboardEvent) => {
if ((event.ctrlKey || event.metaKey) && event.key === 'c' && hasSelection) {
// Call EmbedPDF's copyToClipboard API
selection.copyToClipboard();
// Don't prevent default - let EmbedPDF handle the clipboard
}
};
// Add keyboard listener
document.addEventListener('keydown', handleKeyDown);
return () => {
unsubscribe?.();
document.removeEventListener('keydown', handleKeyDown);
};
}
}, [selection]);
}, [selection, hasSelection]);
return null; // This component doesn't render anything
}