TagSpaces is an offline, open source, document manager with tagging support
feat: support opening the file picker dialog from extensions
Ilian Sapundshieve3351b59d582
diff --git a/src/renderer/components/EntryContainer.tsx b/src/renderer/components/EntryContainer.tsxindex 6013401b2..23ff4a46a 100644--- a/src/renderer/components/EntryContainer.tsx+++ b/src/renderer/components/EntryContainer.tsx@@ -23,6 +23,7 @@ import EntryContainerTitle from '-/components/EntryContainerTitle';import { ErrorBoundary } from '-/components/ErrorBoundary';import FileView from '-/components/FileView';import { Splitter } from '-/components/Splitter';+import { useFilePickerDialogContext } from '-/components/dialogs/hooks/useFilePickerDialogContext';import { useResolveConflictContext } from '-/components/dialogs/hooks/useResolveConflictContext';import { TabNames } from '-/hooks/EntryPropsTabsContextProvider';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';@@ -76,6 +77,7 @@ function EntryContainer() {const { saveDescription, isEditMode, setEditMode, closeOpenedEntries } =useFilePropertiesContext();const { findLocation } = useCurrentLocationContext();+ const { openFilePickerDialog } = useFilePickerDialogContext();const { saveFileOpen } = useResolveConflictContext();const { setThumbnailImageChange } = useIOActionsContext();const { saveBinaryFilePromise } = usePlatformFacadeContext();@@ -382,6 +384,57 @@ function EntryContainer() {setFileChanged(true);break;}+ case 'requestFilePicker': {+ const opts = data.options || {};+ const sep = cLocation?.getDirSeparator?.() || '/';+ const sourceLocationId =+ opts.sourceLocationId ?? openedEntry?.locationID;+ const sourceDir =+ opts.sourceDir ??+ (openedEntry?.path+ ? openedEntry.isFile+ ? extractContainingDirectoryPath(openedEntry.path, sep)+ : openedEntry.path+ : undefined);++ const reply = (payload: Record<string, unknown>) => {+ fileViewer.current?.contentWindow?.postMessage(+ { eventID: data.eventID, ...payload },+ '*',+ );+ };++ openFilePickerDialog({+ mode: opts.mode ?? 'any',+ title: opts.title,+ // Least-privilege default: open scoped to the current entry's+ // location. The user can still switch locations manually.+ initialLocationId: sourceLocationId,+ sourceLocationId,+ sourceDir,+ // Optional: extension can prefill an editable Link-text field+ // (e.g. with the user's currently-selected text in the editor).+ showLabelField: opts.showLabelField === true,+ initialLabel:+ typeof opts.initialLabel === 'string'+ ? opts.initialLabel+ : undefined,+ onSelect: (entry, link, linkType, label) => {+ reply({+ link,+ linkType,+ label,+ name: entry.name,+ path: entry.path,+ locationId: entry.locationID,+ isFile: entry.isFile,+ extension: entry.extension,+ });+ },+ onCancel: () => reply({ cancelled: true }),+ });+ break;+ }default:console.log('Not recognized messaging command: ' + JSON.stringify(data),diff --git a/src/renderer/components/dialogs/FilePickerDialog.tsx b/src/renderer/components/dialogs/FilePickerDialog.tsxindex 806091c93..f898c33ae 100644--- a/src/renderer/components/dialogs/FilePickerDialog.tsx+++ b/src/renderer/components/dialogs/FilePickerDialog.tsx@@ -83,6 +83,10 @@ export interface FilePickerDialogProps {linkType: FilePickerLinkType,label: string,) => void;+ /** Fired exactly once when the dialog closes without a confirmed selection+ * (X / Cancel / Esc / backdrop). Mutually exclusive with onSelect for any+ * single open cycle. */+ onCancel?: () => void;}function modeAccepts(entry: TS.FileSystemEntry, mode: FilePickerMode): boolean {@@ -106,6 +110,7 @@ function FilePickerDialog(props: FilePickerDialogProps) {showLabelField,initialLabel,onSelect,+ onCancel,} = props;const { locations, findLocation } = useCurrentLocationContext();@@ -147,6 +152,9 @@ function FilePickerDialog(props: FilePickerDialogProps) {// the user switches to a different entry — but only as long as the label// still matches the previous entry's name (i.e. they haven't customized).const prevEntryNameRef = useRef<string>('');+ // True once `handleConfirm` has fired `onSelect` this open cycle. Used to+ // suppress the `onCancel` callback when closing after a successful pick.+ const selectionMadeRef = useRef<boolean>(false);// Reset all transient state on each fresh open of the dialog so reuse from a// keepMounted context provider doesn't show stale selection between opens.@@ -162,6 +170,7 @@ function FilePickerDialog(props: FilePickerDialogProps) {setLinkLabel(initialLabel || '');userEditedLabelRef.current = !!initialLabel;prevEntryNameRef.current = '';+ selectionMadeRef.current = false;}// eslint-disable-next-line react-hooks/exhaustive-deps}, [open]);@@ -288,14 +297,25 @@ function FilePickerDialog(props: FilePickerDialogProps) {}const finalLabel =(linkLabel && linkLabel.trim()) || selectedEntry.name || '';+ selectionMadeRef.current = true;onSelect(selectedEntry, link, canUseRelative ? linkType : 'ts', finalLabel);onClose();}+ // Single funnel for all close paths (X / Cancel / Esc / backdrop). If we+ // got here without `handleConfirm` flipping the ref, the user dismissed+ // without picking — fire onCancel exactly once.+ function handleClose() {+ if (!selectionMadeRef.current) {+ onCancel?.();+ }+ onClose();+ }+return (<Dialogopen={open}- onClose={onClose}+ onClose={handleClose}keepMountedscroll="paper"aria-labelledby="fpd-title"@@ -316,7 +336,7 @@ function FilePickerDialog(props: FilePickerDialogProps) {</Typography>}closeButtonTestId="closeFilePickerTID"- onClose={onClose}+ onClose={handleClose}/><DialogContent sx={{ overflowX: 'hidden', overflowY: 'auto' }}>{open && targetLocation && (@@ -434,7 +454,7 @@ function FilePickerDialog(props: FilePickerDialogProps) {<Box />)}<Stack direction="row" spacing={1}>- <TsButton data-tid="closeFilePickerDialog" onClick={onClose}>+ <TsButton data-tid="closeFilePickerDialog" onClick={handleClose}>{t('core:cancel')}</TsButton><TsButtondiff --git a/src/renderer/components/dialogs/hooks/FilePickerDialogContextProvider.tsx b/src/renderer/components/dialogs/hooks/FilePickerDialogContextProvider.tsxindex a0149945d..fa5803434 100644--- a/src/renderer/components/dialogs/hooks/FilePickerDialogContextProvider.tsx+++ b/src/renderer/components/dialogs/hooks/FilePickerDialogContextProvider.tsx@@ -17,20 +17,24 @@*//**- * Extension postMessage protocol for requesting a file picker (spec only —- * the host-side router that translates these messages into- * `openFilePickerDialog` calls is a follow-up).+ * Extension postMessage protocol for requesting a file picker. Implemented+ * by the host-side router in `EntryContainer.handleMessage`.** Request (extension → host):* {* command: 'requestFilePicker',- * eventID: string,+ * eventID: string, // must match the iframe's eventID* options?: {- * mode?: 'file' | 'folder' | 'any',- * allowedExtensions?: string[],- * title?: string,- * sourceLocationId?: string,- * sourceDir?: string,+ * mode?: 'file' | 'folder' | 'any', // default 'any'+ * allowedExtensions?: string[], // accepted but currently ignored (TODO)+ * title?: string, // optional dialog title override+ * sourceLocationId?: string, // optional; defaults to openedEntry.locationID+ * sourceDir?: string, // optional; defaults to the openedEntry's+ * // containing folder (file) or itself (folder)+ * showLabelField?: boolean, // when true, the dialog renders an editable+ * // "Link text" field; returned in response.label+ * initialLabel?: string, // default value for the Link-text field+ * // (e.g. the user's current editor selection)* },* }*@@ -40,12 +44,21 @@* cancelled?: true, // mutually exclusive with the rest* link?: 'ts://...' | '../foo.md',* linkType?: 'ts' | 'relative',+ * label?: string, // user-edited link text (when showLabelField)* name?: string,* path?: string, // absolute path inside the location* locationId?: string,* isFile?: boolean,* extension?: string,* }+ *+ * Constraints:+ * - Only one outstanding `requestFilePicker` per iframe. Sending a second+ * before the first resolves silently replaces it — no `cancelled` reply+ * will arrive for the abandoned request.+ * - The host defaults `initialLocationId` to the current entry's location+ * (least-privilege). The user can switch locations manually inside the+ * dialog; the eventual response carries the picked entry's `locationId`.*/import LoadingLazy from '-/components/LoadingLazy';@@ -72,6 +85,12 @@ export interface FilePickerDialogOpenOptions {linkType: FilePickerLinkType,label: string,) => void;+ /** Fired exactly once when the dialog closes without a confirmed selection+ * (X / Cancel / Esc / backdrop). Mutually exclusive with onSelect for any+ * single open cycle. Required for callers that need a definitive "the user+ * walked away" signal — e.g. the extension postMessage router has to reply+ * with `{ cancelled: true }` so the requesting extension stops waiting. */+ onCancel?: () => void;}type FilePickerDialogContextData = {@@ -154,6 +173,9 @@ export const FilePickerDialogContextProvider = ({// Read from the ref so callers can pass freshly-closed-over handlers.options.current?.onSelect(entry, link, linkType, label);}}+ onCancel={() => {+ options.current?.onCancel?.();+ }}/>{children}</FilePickerDialogContext.Provider>