mirror of
https://github.com/Stirling-Tools/Stirling-PDF.git
synced 2025-09-18 01:19:24 +00:00
Rework navigation
This commit is contained in:
parent
83400dc6a7
commit
e59e73ceb0
@ -7,6 +7,7 @@ import { ToolWorkflowProvider } from "./contexts/ToolWorkflowContext";
|
||||
import { SidebarProvider } from "./contexts/SidebarContext";
|
||||
import ErrorBoundary from "./components/shared/ErrorBoundary";
|
||||
import HomePage from "./pages/HomePage";
|
||||
import { ScarfPixel } from "./components/ScarfPixel";
|
||||
|
||||
// Import global styles
|
||||
import "./styles/tailwind.css";
|
||||
@ -36,6 +37,7 @@ export default function App() {
|
||||
<ErrorBoundary>
|
||||
<FileContextProvider enableUrlSync={true} enablePersistence={true}>
|
||||
<NavigationProvider>
|
||||
<ScarfPixel />
|
||||
<FilesModalProvider>
|
||||
<ToolWorkflowProvider>
|
||||
<SidebarProvider>
|
||||
|
@ -1,32 +1,29 @@
|
||||
import { useLocation } from "react-router-dom";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useNavigationState } from "../contexts/NavigationContext";
|
||||
|
||||
export function ScarfPixel() {
|
||||
const location = useLocation();
|
||||
const { workbench, selectedTool } = useNavigationState();
|
||||
const lastUrlSent = useRef<string | null>(null); // helps with React 18 StrictMode in dev
|
||||
|
||||
useEffect(() => {
|
||||
// Force reload of the tracking pixel on route change
|
||||
// Get current pathname from browser location
|
||||
const pathname = window.location.pathname;
|
||||
|
||||
const url = 'https://static.scarf.sh/a.png?x-pxid=3c1d68de-8945-4e9f-873f-65320b6fabf7'
|
||||
+ '&path=' + encodeURIComponent(location.pathname)
|
||||
+ '&t=' + Date.now(); // cache-buster
|
||||
+ '&path=' + encodeURIComponent(pathname)
|
||||
+ '&t=' + Date.now(); // cache-buster
|
||||
|
||||
console.log("ScarfPixel: Navigation change", { workbench, selectedTool, pathname });
|
||||
|
||||
// + '&machineType=' + machineType
|
||||
// + '&appVersion=' + appVersion
|
||||
// + '&licenseType=' + license
|
||||
// + '&loginEnabled=' + loginEnabled;
|
||||
console.log("ScarfPixel: reload " + location.pathname );
|
||||
|
||||
if (lastUrlSent.current !== url) {
|
||||
if (lastUrlSent.current !== url) {
|
||||
lastUrlSent.current = url;
|
||||
const img = new Image();
|
||||
img.referrerPolicy = "no-referrer-when-downgrade"; // optional
|
||||
img.src = url;
|
||||
|
||||
console.log("ScarfPixel: Fire to... " + location.pathname , url);
|
||||
console.log("ScarfPixel: Fire to... " + pathname, url);
|
||||
}
|
||||
}, [location.pathname]);
|
||||
}, [workbench, selectedTool]); // Fire when navigation state changes
|
||||
|
||||
return null; // Nothing visible in UI
|
||||
}
|
||||
|
@ -411,9 +411,9 @@ const FileEditor = ({
|
||||
if (record) {
|
||||
// Set the file as selected in context and switch to viewer for preview
|
||||
setSelectedFiles([fileId]);
|
||||
navActions.setMode('viewer');
|
||||
navActions.setWorkbench('viewer');
|
||||
}
|
||||
}, [activeFileRecords, setSelectedFiles, navActions.setMode]);
|
||||
}, [activeFileRecords, setSelectedFiles, navActions.setWorkbench]);
|
||||
|
||||
const handleMergeFromHere = useCallback((fileId: string) => {
|
||||
const startIndex = activeFileRecords.findIndex(r => r.id === fileId);
|
||||
|
@ -6,13 +6,13 @@ import { useToolWorkflow } from '../../contexts/ToolWorkflowContext';
|
||||
import { useFileHandler } from '../../hooks/useFileHandler';
|
||||
import { useFileState, useFileActions } from '../../contexts/FileContext';
|
||||
import { useNavigationState, useNavigationActions } from '../../contexts/NavigationContext';
|
||||
import { useToolManagement } from '../../hooks/useToolManagement';
|
||||
|
||||
import TopControls from '../shared/TopControls';
|
||||
import FileEditor from '../fileEditor/FileEditor';
|
||||
import PageEditor from '../pageEditor/PageEditor';
|
||||
import PageEditorControls from '../pageEditor/PageEditorControls';
|
||||
import Viewer from '../viewer/Viewer';
|
||||
import ToolRenderer from '../tools/ToolRenderer';
|
||||
import LandingPage from '../shared/LandingPage';
|
||||
|
||||
// No props needed - component uses contexts directly
|
||||
@ -23,9 +23,9 @@ export default function Workbench() {
|
||||
// Use context-based hooks to eliminate all prop drilling
|
||||
const { state } = useFileState();
|
||||
const { actions } = useFileActions();
|
||||
const { currentMode: currentView } = useNavigationState();
|
||||
const { workbench: currentView } = useNavigationState();
|
||||
const { actions: navActions } = useNavigationActions();
|
||||
const setCurrentView = navActions.setMode;
|
||||
const setCurrentView = navActions.setWorkbench;
|
||||
const activeFiles = state.files.ids;
|
||||
const {
|
||||
previewFile,
|
||||
@ -36,7 +36,14 @@ export default function Workbench() {
|
||||
setSidebarsVisible
|
||||
} = useToolWorkflow();
|
||||
|
||||
const { selectedToolKey, selectedTool, handleToolSelect } = useToolWorkflow();
|
||||
const { handleToolSelect } = useToolWorkflow();
|
||||
|
||||
// Get navigation state - this is the source of truth
|
||||
const { selectedTool: selectedToolId } = useNavigationState();
|
||||
|
||||
// Get tool registry to look up selected tool
|
||||
const { toolRegistry } = useToolManagement();
|
||||
const selectedTool = selectedToolId ? toolRegistry[selectedToolId] : null;
|
||||
const { addToActiveFiles } = useFileHandler();
|
||||
|
||||
const handlePreviewClose = () => {
|
||||
@ -69,11 +76,11 @@ export default function Workbench() {
|
||||
case "fileEditor":
|
||||
return (
|
||||
<FileEditor
|
||||
toolMode={!!selectedToolKey}
|
||||
toolMode={!!selectedToolId}
|
||||
showUpload={true}
|
||||
showBulkActions={!selectedToolKey}
|
||||
showBulkActions={!selectedToolId}
|
||||
supportedExtensions={selectedTool?.supportedFormats || ["pdf"]}
|
||||
{...(!selectedToolKey && {
|
||||
{...(!selectedToolId && {
|
||||
onOpenPageEditor: (file) => {
|
||||
setCurrentView("pageEditor");
|
||||
},
|
||||
@ -127,14 +134,6 @@ export default function Workbench() {
|
||||
);
|
||||
|
||||
default:
|
||||
// Check if it's a tool view
|
||||
if (selectedToolKey && selectedTool) {
|
||||
return (
|
||||
<ToolRenderer
|
||||
selectedToolKey={selectedToolKey}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<LandingPage/>
|
||||
);
|
||||
@ -154,7 +153,7 @@ export default function Workbench() {
|
||||
<TopControls
|
||||
currentView={currentView}
|
||||
setCurrentView={setCurrentView}
|
||||
selectedToolKey={selectedToolKey}
|
||||
selectedToolKey={selectedToolId}
|
||||
/>
|
||||
|
||||
{/* Main content area */}
|
||||
|
@ -6,7 +6,6 @@ import {
|
||||
} from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useFileState, useFileActions, useCurrentFile, useFileSelection } from "../../contexts/FileContext";
|
||||
import { ModeType } from "../../contexts/NavigationContext";
|
||||
import { PDFDocument, PDFPage, PageEditorFunctions } from "../../types/pageEditor";
|
||||
import { ProcessedFile as EnhancedProcessedFile } from "../../types/processing";
|
||||
import { pdfExportService } from "../../services/pdfExportService";
|
||||
|
@ -25,7 +25,7 @@ export default function RightRail() {
|
||||
const [csvInput, setCsvInput] = useState<string>("");
|
||||
|
||||
// Navigation view
|
||||
const { currentMode: currentView } = useNavigationState();
|
||||
const { workbench: currentView } = useNavigationState();
|
||||
|
||||
// File state and selection
|
||||
const { state, selectors } = useFileState();
|
||||
|
@ -5,7 +5,7 @@ import rainbowStyles from '../../styles/rainbow.module.css';
|
||||
import VisibilityIcon from "@mui/icons-material/Visibility";
|
||||
import EditNoteIcon from "@mui/icons-material/EditNote";
|
||||
import FolderIcon from "@mui/icons-material/Folder";
|
||||
import { ModeType, isValidMode } from '../../contexts/NavigationContext';
|
||||
import { WorkbenchType, isValidWorkbench } from '../../types/navigation';
|
||||
import { Tooltip } from "./Tooltip";
|
||||
|
||||
const viewOptionStyle = {
|
||||
@ -19,7 +19,7 @@ const viewOptionStyle = {
|
||||
|
||||
|
||||
// Build view options showing text only for current view; others icon-only with tooltip
|
||||
const createViewOptions = (currentView: ModeType, switchingTo: ModeType | null) => [
|
||||
const createViewOptions = (currentView: WorkbenchType, switchingTo: WorkbenchType | null) => [
|
||||
{
|
||||
label: (
|
||||
<div style={viewOptionStyle as React.CSSProperties}>
|
||||
@ -70,8 +70,8 @@ const createViewOptions = (currentView: ModeType, switchingTo: ModeType | null)
|
||||
];
|
||||
|
||||
interface TopControlsProps {
|
||||
currentView: ModeType;
|
||||
setCurrentView: (view: ModeType) => void;
|
||||
currentView: WorkbenchType;
|
||||
setCurrentView: (view: WorkbenchType) => void;
|
||||
selectedToolKey?: string | null;
|
||||
}
|
||||
|
||||
@ -81,25 +81,25 @@ const TopControls = ({
|
||||
selectedToolKey,
|
||||
}: TopControlsProps) => {
|
||||
const { isRainbowMode } = useRainbowThemeContext();
|
||||
const [switchingTo, setSwitchingTo] = useState<ModeType | null>(null);
|
||||
const [switchingTo, setSwitchingTo] = useState<WorkbenchType | null>(null);
|
||||
|
||||
const isToolSelected = selectedToolKey !== null;
|
||||
|
||||
const handleViewChange = useCallback((view: string) => {
|
||||
if (!isValidMode(view)) {
|
||||
// Ignore invalid values defensively
|
||||
if (!isValidWorkbench(view)) {
|
||||
return;
|
||||
}
|
||||
const mode = view as ModeType;
|
||||
|
||||
const workbench = view;
|
||||
|
||||
// Show immediate feedback
|
||||
setSwitchingTo(mode as ModeType);
|
||||
setSwitchingTo(workbench);
|
||||
|
||||
// Defer the heavy view change to next frame so spinner can render
|
||||
requestAnimationFrame(() => {
|
||||
// Give the spinner one more frame to show
|
||||
requestAnimationFrame(() => {
|
||||
setCurrentView(mode as ModeType);
|
||||
setCurrentView(workbench);
|
||||
|
||||
// Clear the loading state after view change completes
|
||||
setTimeout(() => setSwitchingTo(null), 300);
|
||||
|
@ -1,6 +1,6 @@
|
||||
import React, { createContext, useContext, useReducer, useCallback } from 'react';
|
||||
import { useNavigationUrlSync } from '../hooks/useUrlSync';
|
||||
import { ModeType, isValidMode, getDefaultMode } from '../types/navigation';
|
||||
import { WorkbenchType, ToolId, getDefaultWorkbench } from '../types/navigation';
|
||||
import { useFlatToolRegistry } from '../data/useTranslatedToolRegistry';
|
||||
|
||||
/**
|
||||
* NavigationContext - Complete navigation management system
|
||||
@ -11,27 +11,38 @@ import { ModeType, isValidMode, getDefaultMode } from '../types/navigation';
|
||||
*/
|
||||
|
||||
// Navigation state
|
||||
interface NavigationState {
|
||||
currentMode: ModeType;
|
||||
interface NavigationContextState {
|
||||
workbench: WorkbenchType;
|
||||
selectedTool: ToolId | null;
|
||||
hasUnsavedChanges: boolean;
|
||||
pendingNavigation: (() => void) | null;
|
||||
showNavigationWarning: boolean;
|
||||
selectedToolKey: string | null; // Add tool selection to navigation state
|
||||
}
|
||||
|
||||
// Navigation actions
|
||||
type NavigationAction =
|
||||
| { type: 'SET_MODE'; payload: { mode: ModeType } }
|
||||
| { type: 'SET_WORKBENCH'; payload: { workbench: WorkbenchType } }
|
||||
| { type: 'SET_SELECTED_TOOL'; payload: { toolId: ToolId | null } }
|
||||
| { type: 'SET_TOOL_AND_WORKBENCH'; payload: { toolId: ToolId | null; workbench: WorkbenchType } }
|
||||
| { type: 'SET_UNSAVED_CHANGES'; payload: { hasChanges: boolean } }
|
||||
| { type: 'SET_PENDING_NAVIGATION'; payload: { navigationFn: (() => void) | null } }
|
||||
| { type: 'SHOW_NAVIGATION_WARNING'; payload: { show: boolean } }
|
||||
| { type: 'SET_SELECTED_TOOL'; payload: { toolKey: string | null } };
|
||||
| { type: 'SHOW_NAVIGATION_WARNING'; payload: { show: boolean } };
|
||||
|
||||
// Navigation reducer
|
||||
const navigationReducer = (state: NavigationState, action: NavigationAction): NavigationState => {
|
||||
const navigationReducer = (state: NavigationContextState, action: NavigationAction): NavigationContextState => {
|
||||
switch (action.type) {
|
||||
case 'SET_MODE':
|
||||
return { ...state, currentMode: action.payload.mode };
|
||||
case 'SET_WORKBENCH':
|
||||
return { ...state, workbench: action.payload.workbench };
|
||||
|
||||
case 'SET_SELECTED_TOOL':
|
||||
return { ...state, selectedTool: action.payload.toolId };
|
||||
|
||||
case 'SET_TOOL_AND_WORKBENCH':
|
||||
return {
|
||||
...state,
|
||||
selectedTool: action.payload.toolId,
|
||||
workbench: action.payload.workbench
|
||||
};
|
||||
|
||||
case 'SET_UNSAVED_CHANGES':
|
||||
return { ...state, hasUnsavedChanges: action.payload.hasChanges };
|
||||
@ -42,43 +53,41 @@ const navigationReducer = (state: NavigationState, action: NavigationAction): Na
|
||||
case 'SHOW_NAVIGATION_WARNING':
|
||||
return { ...state, showNavigationWarning: action.payload.show };
|
||||
|
||||
case 'SET_SELECTED_TOOL':
|
||||
return { ...state, selectedToolKey: action.payload.toolKey };
|
||||
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
};
|
||||
|
||||
// Initial state
|
||||
const initialState: NavigationState = {
|
||||
currentMode: getDefaultMode(),
|
||||
const initialState: NavigationContextState = {
|
||||
workbench: getDefaultWorkbench(),
|
||||
selectedTool: null,
|
||||
hasUnsavedChanges: false,
|
||||
pendingNavigation: null,
|
||||
showNavigationWarning: false,
|
||||
selectedToolKey: null
|
||||
showNavigationWarning: false
|
||||
};
|
||||
|
||||
// Navigation context actions interface
|
||||
export interface NavigationContextActions {
|
||||
setMode: (mode: ModeType) => void;
|
||||
setWorkbench: (workbench: WorkbenchType) => void;
|
||||
setSelectedTool: (toolId: ToolId | null) => void;
|
||||
setToolAndWorkbench: (toolId: ToolId | null, workbench: WorkbenchType) => void;
|
||||
setHasUnsavedChanges: (hasChanges: boolean) => void;
|
||||
showNavigationWarning: (show: boolean) => void;
|
||||
requestNavigation: (navigationFn: () => void) => void;
|
||||
confirmNavigation: () => void;
|
||||
cancelNavigation: () => void;
|
||||
selectTool: (toolKey: string) => void;
|
||||
clearToolSelection: () => void;
|
||||
handleToolSelect: (toolId: string) => void;
|
||||
}
|
||||
|
||||
// Split context values
|
||||
// Context state values
|
||||
export interface NavigationContextStateValue {
|
||||
currentMode: ModeType;
|
||||
workbench: WorkbenchType;
|
||||
selectedTool: ToolId | null;
|
||||
hasUnsavedChanges: boolean;
|
||||
pendingNavigation: (() => void) | null;
|
||||
showNavigationWarning: boolean;
|
||||
selectedToolKey: string | null;
|
||||
}
|
||||
|
||||
export interface NavigationContextActionsValue {
|
||||
@ -95,10 +104,19 @@ export const NavigationProvider: React.FC<{
|
||||
enableUrlSync?: boolean;
|
||||
}> = ({ children, enableUrlSync = true }) => {
|
||||
const [state, dispatch] = useReducer(navigationReducer, initialState);
|
||||
const toolRegistry = useFlatToolRegistry();
|
||||
|
||||
const actions: NavigationContextActions = {
|
||||
setMode: useCallback((mode: ModeType) => {
|
||||
dispatch({ type: 'SET_MODE', payload: { mode } });
|
||||
setWorkbench: useCallback((workbench: WorkbenchType) => {
|
||||
dispatch({ type: 'SET_WORKBENCH', payload: { workbench } });
|
||||
}, []),
|
||||
|
||||
setSelectedTool: useCallback((toolId: ToolId | null) => {
|
||||
dispatch({ type: 'SET_SELECTED_TOOL', payload: { toolId } });
|
||||
}, []),
|
||||
|
||||
setToolAndWorkbench: useCallback((toolId: ToolId | null, workbench: WorkbenchType) => {
|
||||
dispatch({ type: 'SET_TOOL_AND_WORKBENCH', payload: { toolId, workbench } });
|
||||
}, []),
|
||||
|
||||
setHasUnsavedChanges: useCallback((hasChanges: boolean) => {
|
||||
@ -110,77 +128,64 @@ export const NavigationProvider: React.FC<{
|
||||
}, []),
|
||||
|
||||
requestNavigation: useCallback((navigationFn: () => void) => {
|
||||
// If no unsaved changes, navigate immediately
|
||||
if (!state.hasUnsavedChanges) {
|
||||
navigationFn();
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, store the navigation and show warning
|
||||
dispatch({ type: 'SET_PENDING_NAVIGATION', payload: { navigationFn } });
|
||||
dispatch({ type: 'SHOW_NAVIGATION_WARNING', payload: { show: true } });
|
||||
}, [state.hasUnsavedChanges]),
|
||||
|
||||
confirmNavigation: useCallback(() => {
|
||||
// Execute pending navigation
|
||||
if (state.pendingNavigation) {
|
||||
state.pendingNavigation();
|
||||
}
|
||||
|
||||
// Clear navigation state
|
||||
dispatch({ type: 'SET_PENDING_NAVIGATION', payload: { navigationFn: null } });
|
||||
dispatch({ type: 'SHOW_NAVIGATION_WARNING', payload: { show: false } });
|
||||
}, [state.pendingNavigation]),
|
||||
|
||||
cancelNavigation: useCallback(() => {
|
||||
// Clear navigation without executing
|
||||
dispatch({ type: 'SET_PENDING_NAVIGATION', payload: { navigationFn: null } });
|
||||
dispatch({ type: 'SHOW_NAVIGATION_WARNING', payload: { show: false } });
|
||||
}, []),
|
||||
|
||||
selectTool: useCallback((toolKey: string) => {
|
||||
dispatch({ type: 'SET_SELECTED_TOOL', payload: { toolKey } });
|
||||
}, []),
|
||||
|
||||
clearToolSelection: useCallback(() => {
|
||||
dispatch({ type: 'SET_SELECTED_TOOL', payload: { toolKey: null } });
|
||||
dispatch({ type: 'SET_MODE', payload: { mode: getDefaultMode() } });
|
||||
dispatch({ type: 'SET_TOOL_AND_WORKBENCH', payload: { toolId: null, workbench: getDefaultWorkbench() } });
|
||||
}, []),
|
||||
|
||||
handleToolSelect: useCallback((toolId: string) => {
|
||||
// Handle special cases
|
||||
if (toolId === 'allTools') {
|
||||
dispatch({ type: 'SET_SELECTED_TOOL', payload: { toolKey: null } });
|
||||
dispatch({ type: 'SET_MODE', payload: { mode: getDefaultMode() } });
|
||||
dispatch({ type: 'SET_TOOL_AND_WORKBENCH', payload: { toolId: null, workbench: getDefaultWorkbench() } });
|
||||
return;
|
||||
}
|
||||
|
||||
// Special-case: if tool is a dedicated reader tool, enter reader mode
|
||||
if (toolId === 'read' || toolId === 'view-pdf') {
|
||||
dispatch({ type: 'SET_SELECTED_TOOL', payload: { toolKey: null } });
|
||||
dispatch({ type: 'SET_TOOL_AND_WORKBENCH', payload: { toolId: null, workbench: 'viewer' } });
|
||||
return;
|
||||
}
|
||||
|
||||
dispatch({ type: 'SET_SELECTED_TOOL', payload: { toolKey: toolId } });
|
||||
dispatch({ type: 'SET_MODE', payload: { mode: 'fileEditor' as ModeType } });
|
||||
}, [])
|
||||
// Look up the tool in the registry to get its proper workbench
|
||||
const tool = toolRegistry[toolId];
|
||||
const workbench = tool ? (tool.workbench || getDefaultWorkbench()) : getDefaultWorkbench();
|
||||
|
||||
dispatch({ type: 'SET_TOOL_AND_WORKBENCH', payload: { toolId, workbench } });
|
||||
}, [toolRegistry])
|
||||
};
|
||||
|
||||
const stateValue: NavigationContextStateValue = {
|
||||
currentMode: state.currentMode,
|
||||
workbench: state.workbench,
|
||||
selectedTool: state.selectedTool,
|
||||
hasUnsavedChanges: state.hasUnsavedChanges,
|
||||
pendingNavigation: state.pendingNavigation,
|
||||
showNavigationWarning: state.showNavigationWarning,
|
||||
selectedToolKey: state.selectedToolKey
|
||||
showNavigationWarning: state.showNavigationWarning
|
||||
};
|
||||
|
||||
const actionsValue: NavigationContextActionsValue = {
|
||||
actions
|
||||
};
|
||||
|
||||
// Enable URL synchronization
|
||||
useNavigationUrlSync(state.currentMode, actions.setMode, enableUrlSync);
|
||||
|
||||
return (
|
||||
<NavigationStateContext.Provider value={stateValue}>
|
||||
<NavigationActionsContext.Provider value={actionsValue}>
|
||||
@ -231,9 +236,6 @@ export const useNavigationGuard = () => {
|
||||
};
|
||||
};
|
||||
|
||||
// Re-export utility functions from types for backward compatibility
|
||||
export { isValidMode, getDefaultMode, type ModeType } from '../types/navigation';
|
||||
|
||||
// TODO: This will be expanded for URL-based routing system
|
||||
// - URL parsing utilities
|
||||
// - Route definitions
|
||||
|
@ -7,8 +7,8 @@ import React, { createContext, useContext, useReducer, useCallback, useMemo } fr
|
||||
import { useToolManagement } from '../hooks/useToolManagement';
|
||||
import { PageEditorFunctions } from '../types/pageEditor';
|
||||
import { ToolRegistryEntry } from '../data/toolsTaxonomy';
|
||||
import { useToolWorkflowUrlSync } from '../hooks/useUrlSync';
|
||||
import { useNavigationActions, useNavigationState } from './NavigationContext';
|
||||
import { useNavigationUrlSync } from '../hooks/useUrlSync';
|
||||
|
||||
// State interface
|
||||
interface ToolWorkflowState {
|
||||
@ -124,7 +124,7 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
|
||||
} = useToolManagement();
|
||||
|
||||
// Get selected tool from navigation context
|
||||
const selectedTool = getSelectedTool(navigationState.selectedToolKey);
|
||||
const selectedTool = getSelectedTool(navigationState.selectedTool);
|
||||
|
||||
// UI Action creators
|
||||
const setSidebarsVisible = useCallback((visible: boolean) => {
|
||||
@ -142,7 +142,7 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
|
||||
const setPreviewFile = useCallback((file: File | null) => {
|
||||
dispatch({ type: 'SET_PREVIEW_FILE', payload: file });
|
||||
if (file) {
|
||||
actions.setMode('viewer');
|
||||
actions.setWorkbench('viewer');
|
||||
}
|
||||
}, [actions]);
|
||||
|
||||
@ -172,7 +172,16 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
|
||||
|
||||
// Workflow actions (compound actions that coordinate multiple state changes)
|
||||
const handleToolSelect = useCallback((toolId: string) => {
|
||||
actions.handleToolSelect(toolId);
|
||||
// Set the selected tool and determine the appropriate workbench
|
||||
actions.setSelectedTool(toolId);
|
||||
|
||||
// Get the tool from registry to determine workbench
|
||||
const tool = getSelectedTool(toolId);
|
||||
if (tool && tool.workbench) {
|
||||
actions.setWorkbench(tool.workbench);
|
||||
} else {
|
||||
actions.setWorkbench('fileEditor'); // Default workbench
|
||||
}
|
||||
|
||||
// Clear search query when selecting a tool
|
||||
setSearchQuery('');
|
||||
@ -189,13 +198,13 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
|
||||
setLeftPanelView('toolContent');
|
||||
setReaderMode(false); // Disable read mode when selecting tools
|
||||
}
|
||||
}, [actions, setLeftPanelView, setReaderMode, setSearchQuery]);
|
||||
}, [actions, getSelectedTool, setLeftPanelView, setReaderMode, setSearchQuery]);
|
||||
|
||||
const handleBackToTools = useCallback(() => {
|
||||
setLeftPanelView('toolPicker');
|
||||
setReaderMode(false);
|
||||
actions.clearToolSelection();
|
||||
}, [setLeftPanelView, setReaderMode, actions]);
|
||||
actions.setSelectedTool(null);
|
||||
}, [setLeftPanelView, setReaderMode, actions.setSelectedTool]);
|
||||
|
||||
const handleReaderToggle = useCallback(() => {
|
||||
setReaderMode(true);
|
||||
@ -214,14 +223,23 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
|
||||
[state.sidebarsVisible, state.readerMode]
|
||||
);
|
||||
|
||||
// Enable URL synchronization for tool selection
|
||||
useToolWorkflowUrlSync(navigationState.selectedToolKey, actions.selectTool, actions.clearToolSelection, true);
|
||||
// URL sync for proper tool navigation
|
||||
useNavigationUrlSync(
|
||||
navigationState.workbench,
|
||||
navigationState.selectedTool,
|
||||
actions.setWorkbench,
|
||||
actions.setSelectedTool,
|
||||
handleToolSelect,
|
||||
() => actions.setSelectedTool(null),
|
||||
toolRegistry,
|
||||
true
|
||||
);
|
||||
|
||||
// Properly memoized context value
|
||||
const contextValue = useMemo((): ToolWorkflowContextValue => ({
|
||||
// State
|
||||
...state,
|
||||
selectedToolKey: navigationState.selectedToolKey,
|
||||
selectedToolKey: navigationState.selectedTool,
|
||||
selectedTool,
|
||||
toolRegistry,
|
||||
|
||||
@ -232,8 +250,8 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
|
||||
setPreviewFile,
|
||||
setPageEditorFunctions,
|
||||
setSearchQuery,
|
||||
selectTool: actions.selectTool,
|
||||
clearToolSelection: actions.clearToolSelection,
|
||||
selectTool: actions.setSelectedTool,
|
||||
clearToolSelection: () => actions.setSelectedTool(null),
|
||||
|
||||
// Tool Reset Actions
|
||||
registerToolReset,
|
||||
@ -249,7 +267,7 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
|
||||
isPanelVisible,
|
||||
}), [
|
||||
state,
|
||||
navigationState.selectedToolKey,
|
||||
navigationState.selectedTool,
|
||||
selectedTool,
|
||||
toolRegistry,
|
||||
setSidebarsVisible,
|
||||
@ -258,8 +276,7 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
|
||||
setPreviewFile,
|
||||
setPageEditorFunctions,
|
||||
setSearchQuery,
|
||||
actions.selectTool,
|
||||
actions.clearToolSelection,
|
||||
actions.setSelectedTool,
|
||||
registerToolReset,
|
||||
resetTool,
|
||||
handleToolSelect,
|
||||
|
@ -3,6 +3,7 @@ import React from 'react';
|
||||
import { ToolOperationHook, ToolOperationConfig } from '../hooks/tools/shared/useToolOperation';
|
||||
import { BaseToolProps } from '../types/tool';
|
||||
import { BaseParameters } from '../types/parameters';
|
||||
import { WorkbenchType } from '../types/navigation';
|
||||
|
||||
export enum SubcategoryId {
|
||||
SIGNING = 'signing',
|
||||
@ -28,7 +29,6 @@ export type ToolRegistryEntry = {
|
||||
icon: React.ReactNode;
|
||||
name: string;
|
||||
component: React.ComponentType<BaseToolProps> | null;
|
||||
view: 'sign' | 'security' | 'format' | 'extract' | 'view' | 'merge' | 'pageEditor' | 'convert' | 'redact' | 'split' | 'convert' | 'remove' | 'compress' | 'external';
|
||||
description: string;
|
||||
categoryId: ToolCategoryId;
|
||||
subcategoryId: SubcategoryId;
|
||||
@ -37,6 +37,10 @@ export type ToolRegistryEntry = {
|
||||
endpoints?: string[];
|
||||
link?: string;
|
||||
type?: string;
|
||||
// URL path for routing (e.g., '/split-pdfs', '/compress-pdf')
|
||||
urlPath?: string;
|
||||
// Workbench type for navigation
|
||||
workbench?: WorkbenchType;
|
||||
// Operation configuration for automation
|
||||
operationConfig?: ToolOperationConfig<any>;
|
||||
// Settings component for automation configuration
|
||||
@ -107,3 +111,30 @@ export const getAllApplicationEndpoints = (
|
||||
const convEp = extensionToEndpoint ? getConversionEndpoints(extensionToEndpoint) : [];
|
||||
return Array.from(new Set([...toolEp, ...convEp]));
|
||||
};
|
||||
|
||||
/**
|
||||
* Default workbench for tools that don't specify one
|
||||
* Returns null to trigger the default case in Workbench component (ToolRenderer)
|
||||
*/
|
||||
export const getDefaultToolWorkbench = (): WorkbenchType => 'fileEditor';
|
||||
|
||||
/**
|
||||
* Get workbench type for a tool
|
||||
*/
|
||||
export const getToolWorkbench = (tool: ToolRegistryEntry): WorkbenchType => {
|
||||
return tool.workbench || getDefaultToolWorkbench();
|
||||
};
|
||||
|
||||
/**
|
||||
* Get URL path for a tool
|
||||
*/
|
||||
export const getToolUrlPath = (toolId: string, tool: ToolRegistryEntry): string => {
|
||||
return tool.urlPath || `/${toolId.replace(/([A-Z])/g, '-$1').toLowerCase()}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if a tool ID exists in the registry
|
||||
*/
|
||||
export const isValidToolId = (toolId: string, registry: ToolRegistry): boolean => {
|
||||
return toolId in registry;
|
||||
};
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -45,16 +45,16 @@ const ALL_SUGGESTED_TOOLS: Omit<SuggestedTool, 'navigate'>[] = [
|
||||
|
||||
export function useSuggestedTools(): SuggestedTool[] {
|
||||
const { actions } = useNavigationActions();
|
||||
const { selectedToolKey } = useNavigationState();
|
||||
const { selectedTool } = useNavigationState();
|
||||
|
||||
return useMemo(() => {
|
||||
// Filter out the current tool
|
||||
const filteredTools = ALL_SUGGESTED_TOOLS.filter(tool => tool.id !== selectedToolKey);
|
||||
const filteredTools = ALL_SUGGESTED_TOOLS.filter(tool => tool.id !== selectedTool);
|
||||
|
||||
// Add navigation function to each tool
|
||||
return filteredTools.map(tool => ({
|
||||
...tool,
|
||||
navigate: () => actions.handleToolSelect(tool.id)
|
||||
navigate: () => actions.setSelectedTool(tool.id)
|
||||
}));
|
||||
}, [selectedToolKey, actions]);
|
||||
}, [selectedTool, actions]);
|
||||
}
|
||||
|
@ -1,123 +1,90 @@
|
||||
/**
|
||||
* URL synchronization hooks for tool routing
|
||||
* URL synchronization hooks for tool routing with registry support
|
||||
*/
|
||||
|
||||
import { useEffect, useCallback } from 'react';
|
||||
import { ModeType } from '../types/navigation';
|
||||
import { WorkbenchType, ToolId, ToolRoute } from '../types/navigation';
|
||||
import { parseToolRoute, updateToolRoute, clearToolRoute } from '../utils/urlRouting';
|
||||
import { ToolRegistry } from '../data/toolsTaxonomy';
|
||||
|
||||
/**
|
||||
* Hook to sync navigation mode with URL
|
||||
* Hook to sync workbench and tool with URL using registry
|
||||
*/
|
||||
export function useNavigationUrlSync(
|
||||
currentMode: ModeType,
|
||||
setMode: (mode: ModeType) => void,
|
||||
workbench: WorkbenchType,
|
||||
selectedTool: ToolId | null,
|
||||
setWorkbench: (workbench: WorkbenchType) => void,
|
||||
setSelectedTool: (toolId: ToolId | null) => void,
|
||||
handleToolSelect: (toolId: string) => void,
|
||||
clearToolSelection: () => void,
|
||||
registry: ToolRegistry,
|
||||
enableSync: boolean = true
|
||||
) {
|
||||
// Initialize mode from URL on mount
|
||||
// Initialize workbench and tool from URL on mount
|
||||
useEffect(() => {
|
||||
if (!enableSync) return;
|
||||
|
||||
const route = parseToolRoute();
|
||||
if (route.mode !== currentMode) {
|
||||
setMode(route.mode);
|
||||
const route = parseToolRoute(registry);
|
||||
if (route.toolId !== selectedTool) {
|
||||
if (route.toolId) {
|
||||
handleToolSelect(route.toolId);
|
||||
} else {
|
||||
clearToolSelection();
|
||||
}
|
||||
}
|
||||
}, []); // Only run on mount
|
||||
|
||||
// Update URL when mode changes
|
||||
// Update URL when tool or workbench changes
|
||||
useEffect(() => {
|
||||
if (!enableSync) return;
|
||||
|
||||
// Only update URL for actual tool modes, not internal UI modes
|
||||
// URL clearing is handled by useToolWorkflowUrlSync when selectedToolKey becomes null
|
||||
if (currentMode !== 'fileEditor' && currentMode !== 'pageEditor' && currentMode !== 'viewer') {
|
||||
updateToolRoute(currentMode, currentMode);
|
||||
if (selectedTool) {
|
||||
updateToolRoute(selectedTool, registry);
|
||||
} else {
|
||||
// Clear URL when no tool is selected
|
||||
clearToolRoute();
|
||||
}
|
||||
}, [currentMode, enableSync]);
|
||||
}, [selectedTool, registry, enableSync]);
|
||||
|
||||
// Handle browser back/forward navigation
|
||||
useEffect(() => {
|
||||
if (!enableSync) return;
|
||||
|
||||
const handlePopState = () => {
|
||||
const route = parseToolRoute();
|
||||
if (route.mode !== currentMode) {
|
||||
setMode(route.mode);
|
||||
const route = parseToolRoute(registry);
|
||||
if (route.toolId !== selectedTool) {
|
||||
if (route.toolId) {
|
||||
handleToolSelect(route.toolId);
|
||||
} else {
|
||||
clearToolSelection();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('popstate', handlePopState);
|
||||
return () => window.removeEventListener('popstate', handlePopState);
|
||||
}, [currentMode, setMode, enableSync]);
|
||||
}, [selectedTool, handleToolSelect, clearToolSelection, registry, enableSync]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to sync tool workflow with URL
|
||||
* Hook to programmatically navigate to tools with registry support
|
||||
*/
|
||||
export function useToolWorkflowUrlSync(
|
||||
selectedToolKey: string | null,
|
||||
selectTool: (toolKey: string) => void,
|
||||
clearTool: () => void,
|
||||
enableSync: boolean = true
|
||||
) {
|
||||
// Initialize tool from URL on mount
|
||||
useEffect(() => {
|
||||
if (!enableSync) return;
|
||||
|
||||
const route = parseToolRoute();
|
||||
if (route.toolKey && route.toolKey !== selectedToolKey) {
|
||||
selectTool(route.toolKey);
|
||||
} else if (!route.toolKey && selectedToolKey) {
|
||||
clearTool();
|
||||
}
|
||||
}, []); // Only run on mount
|
||||
|
||||
// Update URL when tool changes
|
||||
useEffect(() => {
|
||||
if (!enableSync) return;
|
||||
|
||||
if (selectedToolKey) {
|
||||
const route = parseToolRoute();
|
||||
if (route.toolKey !== selectedToolKey) {
|
||||
updateToolRoute(selectedToolKey as ModeType, selectedToolKey);
|
||||
}
|
||||
} else {
|
||||
// Clear URL when no tool is selected - always clear regardless of current URL
|
||||
clearToolRoute();
|
||||
}
|
||||
}, [selectedToolKey, enableSync]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to get current URL route information
|
||||
*/
|
||||
export function useCurrentRoute() {
|
||||
const getCurrentRoute = useCallback(() => {
|
||||
return parseToolRoute();
|
||||
}, []);
|
||||
|
||||
return getCurrentRoute;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to programmatically navigate to tools
|
||||
*/
|
||||
export function useToolNavigation() {
|
||||
const navigateToTool = useCallback((toolKey: string) => {
|
||||
updateToolRoute(toolKey as ModeType, toolKey);
|
||||
export function useToolNavigation(registry: ToolRegistry) {
|
||||
const navigateToTool = useCallback((toolId: ToolId) => {
|
||||
updateToolRoute(toolId, registry);
|
||||
|
||||
// Dispatch a custom event to notify other components
|
||||
window.dispatchEvent(new CustomEvent('toolNavigation', {
|
||||
detail: { toolKey }
|
||||
detail: { toolId }
|
||||
}));
|
||||
}, []);
|
||||
}, [registry]);
|
||||
|
||||
const navigateToHome = useCallback(() => {
|
||||
clearToolRoute();
|
||||
|
||||
// Dispatch a custom event to notify other components
|
||||
window.dispatchEvent(new CustomEvent('toolNavigation', {
|
||||
detail: { toolKey: null }
|
||||
detail: { toolId: null }
|
||||
}));
|
||||
}, []);
|
||||
|
||||
@ -126,3 +93,14 @@ export function useToolNavigation() {
|
||||
navigateToHome
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to get current URL route information with registry support
|
||||
*/
|
||||
export function useCurrentRoute(registry: ToolRegistry) {
|
||||
const getCurrentRoute = useCallback(() => {
|
||||
return parseToolRoute(registry);
|
||||
}, [registry]);
|
||||
|
||||
return getCurrentRoute;
|
||||
}
|
@ -8,7 +8,6 @@ import { BrowserRouter } from 'react-router-dom';
|
||||
import App from './App';
|
||||
import './i18n'; // Initialize i18next
|
||||
import { PostHogProvider } from 'posthog-js/react';
|
||||
import { ScarfPixel } from './components/ScarfPixel';
|
||||
|
||||
// Compute initial color scheme
|
||||
function getInitialScheme(): 'light' | 'dark' {
|
||||
@ -40,7 +39,6 @@ root.render(
|
||||
}}
|
||||
>
|
||||
<BrowserRouter>
|
||||
<ScarfPixel />
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</PostHogProvider>
|
||||
|
@ -2,7 +2,7 @@ import React, { useState, useMemo, useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useFileContext } from "../contexts/FileContext";
|
||||
import { useFileSelection } from "../contexts/FileContext";
|
||||
import { useNavigation } from "../contexts/NavigationContext";
|
||||
import { useNavigationActions } from "../contexts/NavigationContext";
|
||||
import { useToolWorkflow } from "../contexts/ToolWorkflowContext";
|
||||
|
||||
import { createToolFlow } from "../components/tools/shared/createToolFlow";
|
||||
@ -21,7 +21,7 @@ import { AUTOMATION_STEPS } from "../constants/automation";
|
||||
const Automate = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
|
||||
const { t } = useTranslation();
|
||||
const { selectedFiles } = useFileSelection();
|
||||
const { setMode } = useNavigation();
|
||||
const { actions } = useNavigationActions();
|
||||
const { registerToolReset } = useToolWorkflow();
|
||||
|
||||
const [currentStep, setCurrentStep] = useState<AutomationStep>(AUTOMATION_STEPS.SELECTION);
|
||||
@ -223,7 +223,7 @@ const Automate = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
|
||||
title: t('automate.reviewTitle', 'Automation Results'),
|
||||
onFileClick: (file: File) => {
|
||||
onPreviewFile?.(file);
|
||||
setMode('viewer');
|
||||
actions.setWorkbench('viewer');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
@ -43,7 +43,7 @@ const RemoveCertificateSign = ({ onPreviewFile, onComplete, onError }: BaseToolP
|
||||
const handleThumbnailClick = (file: File) => {
|
||||
onPreviewFile?.(file);
|
||||
sessionStorage.setItem("previousMode", "removeCertificateSign");
|
||||
actions.setMode("viewer");
|
||||
actions.setWorkbench("viewer");
|
||||
};
|
||||
|
||||
const handleSettingsReset = () => {
|
||||
|
@ -43,7 +43,7 @@ const Repair = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
|
||||
const handleThumbnailClick = (file: File) => {
|
||||
onPreviewFile?.(file);
|
||||
sessionStorage.setItem("previousMode", "repair");
|
||||
actions.setMode("viewer");
|
||||
actions.setWorkbench("viewer");
|
||||
};
|
||||
|
||||
const handleSettingsReset = () => {
|
||||
|
@ -43,7 +43,7 @@ const SingleLargePage = ({ onPreviewFile, onComplete, onError }: BaseToolProps)
|
||||
const handleThumbnailClick = (file: File) => {
|
||||
onPreviewFile?.(file);
|
||||
sessionStorage.setItem("previousMode", "single-large-page");
|
||||
actions.setMode("viewer");
|
||||
actions.setWorkbench("viewer");
|
||||
};
|
||||
|
||||
const handleSettingsReset = () => {
|
||||
|
@ -43,7 +43,7 @@ const UnlockPdfForms = ({ onPreviewFile, onComplete, onError }: BaseToolProps) =
|
||||
const handleThumbnailClick = (file: File) => {
|
||||
onPreviewFile?.(file);
|
||||
sessionStorage.setItem("previousMode", "unlockPdfForms");
|
||||
actions.setMode("viewer");
|
||||
actions.setWorkbench("viewer");
|
||||
};
|
||||
|
||||
const handleSettingsReset = () => {
|
||||
|
@ -1,42 +1,31 @@
|
||||
/**
|
||||
* Shared navigation types to avoid circular dependencies
|
||||
* Navigation types for workbench and tool separation
|
||||
*/
|
||||
|
||||
// Navigation mode types - complete list to match contexts
|
||||
export type ModeType =
|
||||
| 'viewer'
|
||||
| 'pageEditor'
|
||||
| 'fileEditor'
|
||||
| 'merge'
|
||||
| 'split'
|
||||
| 'compress'
|
||||
| 'ocr'
|
||||
| 'convert'
|
||||
| 'sanitize'
|
||||
| 'addPassword'
|
||||
| 'changePermissions'
|
||||
| 'addWatermark'
|
||||
| 'removePassword'
|
||||
| 'single-large-page'
|
||||
| 'repair'
|
||||
| 'unlockPdfForms'
|
||||
| 'removeCertificateSign';
|
||||
// Define workbench values once as source of truth
|
||||
const WORKBENCH_TYPES = ['viewer', 'pageEditor', 'fileEditor'] as const;
|
||||
|
||||
// Utility functions for mode handling
|
||||
export const isValidMode = (mode: string): mode is ModeType => {
|
||||
const validModes: ModeType[] = [
|
||||
'viewer', 'pageEditor', 'fileEditor', 'merge', 'split',
|
||||
'compress', 'ocr', 'convert', 'addPassword', 'changePermissions',
|
||||
'sanitize', 'addWatermark', 'removePassword', 'single-large-page',
|
||||
'repair', 'unlockPdfForms', 'removeCertificateSign'
|
||||
];
|
||||
return validModes.includes(mode as ModeType);
|
||||
// Workbench types - how the user interacts with content
|
||||
export type WorkbenchType = typeof WORKBENCH_TYPES[number];
|
||||
|
||||
// Tool identity - what PDF operation we're performing (derived from registry)
|
||||
export type ToolId = string;
|
||||
|
||||
// Navigation state
|
||||
export interface NavigationState {
|
||||
workbench: WorkbenchType;
|
||||
selectedTool: ToolId | null;
|
||||
}
|
||||
|
||||
export const getDefaultWorkbench = (): WorkbenchType => 'fileEditor';
|
||||
|
||||
// Type guard using the same source of truth - no duplication
|
||||
export const isValidWorkbench = (value: string): value is WorkbenchType => {
|
||||
return WORKBENCH_TYPES.includes(value as WorkbenchType);
|
||||
};
|
||||
|
||||
export const getDefaultMode = (): ModeType => 'fileEditor';
|
||||
|
||||
// Route parsing result
|
||||
export interface ToolRoute {
|
||||
mode: ModeType;
|
||||
toolKey: string | null;
|
||||
workbench: WorkbenchType;
|
||||
toolId: ToolId | null;
|
||||
}
|
@ -2,10 +2,11 @@
|
||||
* Navigation action interfaces to break circular dependencies
|
||||
*/
|
||||
|
||||
import { ModeType } from './navigation';
|
||||
import { WorkbenchType, ToolId } from './navigation';
|
||||
|
||||
export interface NavigationActions {
|
||||
setMode: (mode: ModeType) => void;
|
||||
setWorkbench: (workbench: WorkbenchType) => void;
|
||||
setSelectedTool: (toolId: ToolId | null) => void;
|
||||
setHasUnsavedChanges: (hasChanges: boolean) => void;
|
||||
showNavigationWarning: (show: boolean) => void;
|
||||
requestNavigation: (navigationFn: () => void) => void;
|
||||
@ -14,7 +15,8 @@ export interface NavigationActions {
|
||||
}
|
||||
|
||||
export interface NavigationState {
|
||||
currentMode: ModeType;
|
||||
workbench: WorkbenchType;
|
||||
selectedTool: ToolId | null;
|
||||
hasUnsavedChanges: boolean;
|
||||
pendingNavigation: (() => void) | null;
|
||||
showNavigationWarning: boolean;
|
||||
|
@ -1,119 +1,64 @@
|
||||
/**
|
||||
* URL routing utilities for tool navigation
|
||||
* Provides clean URL routing for the V2 tool system
|
||||
* URL routing utilities for tool navigation with registry support
|
||||
*/
|
||||
|
||||
import { ModeType, isValidMode as isValidModeType, getDefaultMode, ToolRoute } from '../types/navigation';
|
||||
import {
|
||||
ToolId,
|
||||
ToolRoute,
|
||||
getDefaultWorkbench
|
||||
} from '../types/navigation';
|
||||
import { ToolRegistry, getToolWorkbench, getToolUrlPath, isValidToolId } from '../data/toolsTaxonomy';
|
||||
|
||||
/**
|
||||
* Parse the current URL to extract tool routing information
|
||||
*/
|
||||
export function parseToolRoute(): ToolRoute {
|
||||
export function parseToolRoute(registry: ToolRegistry): ToolRoute {
|
||||
const path = window.location.pathname;
|
||||
const searchParams = new URLSearchParams(window.location.search);
|
||||
|
||||
// Extract tool from URL path (e.g., /split-pdf -> split)
|
||||
const toolMatch = path.match(/\/([a-zA-Z-]+)(?:-pdf)?$/);
|
||||
if (toolMatch) {
|
||||
const toolKey = toolMatch[1].toLowerCase();
|
||||
|
||||
// Map URL paths to tool keys and modes (excluding internal UI modes)
|
||||
const toolMappings: Record<string, { mode: ModeType; toolKey: string }> = {
|
||||
'split-pdfs': { mode: 'split', toolKey: 'split' },
|
||||
'split': { mode: 'split', toolKey: 'split' },
|
||||
'merge-pdfs': { mode: 'merge', toolKey: 'merge' },
|
||||
'compress-pdf': { mode: 'compress', toolKey: 'compress' },
|
||||
'convert': { mode: 'convert', toolKey: 'convert' },
|
||||
'convert-pdf': { mode: 'convert', toolKey: 'convert' },
|
||||
'file-to-pdf': { mode: 'convert', toolKey: 'convert' },
|
||||
'eml-to-pdf': { mode: 'convert', toolKey: 'convert' },
|
||||
'html-to-pdf': { mode: 'convert', toolKey: 'convert' },
|
||||
'markdown-to-pdf': { mode: 'convert', toolKey: 'convert' },
|
||||
'pdf-to-csv': { mode: 'convert', toolKey: 'convert' },
|
||||
'pdf-to-img': { mode: 'convert', toolKey: 'convert' },
|
||||
'pdf-to-markdown': { mode: 'convert', toolKey: 'convert' },
|
||||
'pdf-to-pdfa': { mode: 'convert', toolKey: 'convert' },
|
||||
'pdf-to-word': { mode: 'convert', toolKey: 'convert' },
|
||||
'pdf-to-xml': { mode: 'convert', toolKey: 'convert' },
|
||||
'add-password': { mode: 'addPassword', toolKey: 'addPassword' },
|
||||
'change-permissions': { mode: 'changePermissions', toolKey: 'changePermissions' },
|
||||
'sanitize-pdf': { mode: 'sanitize', toolKey: 'sanitize' },
|
||||
'ocr': { mode: 'ocr', toolKey: 'ocr' },
|
||||
'ocr-pdf': { mode: 'ocr', toolKey: 'ocr' },
|
||||
'add-watermark': { mode: 'addWatermark', toolKey: 'addWatermark' },
|
||||
'remove-password': { mode: 'removePassword', toolKey: 'removePassword' },
|
||||
'single-large-page': { mode: 'single-large-page', toolKey: 'single-large-page' },
|
||||
'repair': { mode: 'repair', toolKey: 'repair' },
|
||||
'unlock-pdf-forms': { mode: 'unlockPdfForms', toolKey: 'unlockPdfForms' },
|
||||
'remove-certificate-sign': { mode: 'removeCertificateSign', toolKey: 'removeCertificateSign' },
|
||||
'remove-cert-sign': { mode: 'removeCertificateSign', toolKey: 'removeCertificateSign' }
|
||||
};
|
||||
|
||||
const mapping = toolMappings[toolKey];
|
||||
if (mapping) {
|
||||
// Try to find tool by URL path
|
||||
for (const [toolId, tool] of Object.entries(registry)) {
|
||||
const toolUrlPath = getToolUrlPath(toolId, tool);
|
||||
if (path === toolUrlPath) {
|
||||
return {
|
||||
mode: mapping.mode,
|
||||
toolKey: mapping.toolKey
|
||||
workbench: getToolWorkbench(tool),
|
||||
toolId
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Check for query parameter fallback (e.g., ?tool=split)
|
||||
const toolParam = searchParams.get('tool');
|
||||
if (toolParam && isValidModeType(toolParam)) {
|
||||
if (toolParam && isValidToolId(toolParam, registry)) {
|
||||
const tool = registry[toolParam];
|
||||
return {
|
||||
mode: toolParam as ModeType,
|
||||
toolKey: toolParam
|
||||
workbench: getToolWorkbench(tool),
|
||||
toolId: toolParam
|
||||
};
|
||||
}
|
||||
|
||||
// Default to page editor for home page
|
||||
// Default to fileEditor workbench for home page
|
||||
return {
|
||||
mode: getDefaultMode(),
|
||||
toolKey: null
|
||||
workbench: getDefaultWorkbench(),
|
||||
toolId: null
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the URL to reflect the current tool selection
|
||||
* Internal UI modes (viewer, fileEditor, pageEditor) don't get URLs
|
||||
*/
|
||||
export function updateToolRoute(mode: ModeType, toolKey?: string): void {
|
||||
export function updateToolRoute(toolId: ToolId, registry: ToolRegistry): void {
|
||||
const currentPath = window.location.pathname;
|
||||
const searchParams = new URLSearchParams(window.location.search);
|
||||
|
||||
// Don't create URLs for internal UI modes
|
||||
if (mode === 'viewer' || mode === 'fileEditor' || mode === 'pageEditor') {
|
||||
// If we're switching to an internal mode, clear any existing tool URL
|
||||
if (currentPath !== '/') {
|
||||
clearToolRoute();
|
||||
}
|
||||
const tool = registry[toolId];
|
||||
if (!tool) {
|
||||
console.warn(`Tool ${toolId} not found in registry`);
|
||||
return;
|
||||
}
|
||||
|
||||
let newPath = '/';
|
||||
|
||||
// Map modes to URL paths (only for actual tools)
|
||||
if (toolKey) {
|
||||
const pathMappings: Record<string, string> = {
|
||||
'split': '/split-pdfs',
|
||||
'merge': '/merge-pdf',
|
||||
'compress': '/compress-pdf',
|
||||
'convert': '/convert-pdf',
|
||||
'addPassword': '/add-password-pdf',
|
||||
'changePermissions': '/change-permissions-pdf',
|
||||
'sanitize': '/sanitize-pdf',
|
||||
'ocr': '/ocr-pdf',
|
||||
'addWatermark': '/watermark',
|
||||
'removePassword': '/remove-password',
|
||||
'single-large-page': '/single-large-page',
|
||||
'repair': '/repair',
|
||||
'unlockPdfForms': '/unlock-pdf-forms',
|
||||
'removeCertificateSign': '/remove-certificate-sign'
|
||||
};
|
||||
|
||||
newPath = pathMappings[toolKey] || `/${toolKey}`;
|
||||
}
|
||||
const newPath = getToolUrlPath(toolId, tool);
|
||||
|
||||
// Remove tool query parameter since we're using path-based routing
|
||||
searchParams.delete('tool');
|
||||
@ -142,58 +87,25 @@ export function clearToolRoute(): void {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get clean tool name for display purposes
|
||||
* Get clean tool name for display purposes using registry
|
||||
*/
|
||||
export function getToolDisplayName(toolKey: string): string {
|
||||
const displayNames: Record<string, string> = {
|
||||
'split': 'Split PDF',
|
||||
'merge': 'Merge PDF',
|
||||
'compress': 'Compress PDF',
|
||||
'convert': 'Convert PDF',
|
||||
'addPassword': 'Add Password',
|
||||
'changePermissions': 'Change Permissions',
|
||||
'sanitize': 'Sanitize PDF',
|
||||
'ocr': 'OCR PDF'
|
||||
};
|
||||
|
||||
return displayNames[toolKey] || toolKey;
|
||||
export function getToolDisplayName(toolId: ToolId, registry: ToolRegistry): string {
|
||||
const tool = registry[toolId];
|
||||
return tool ? tool.name : toolId;
|
||||
}
|
||||
|
||||
// Note: isValidMode is now imported from types/navigation.ts
|
||||
|
||||
/**
|
||||
* Generate shareable URL for current tool state
|
||||
* Only generates URLs for actual tools, not internal UI modes
|
||||
* Generate shareable URL for current tool state using registry
|
||||
*/
|
||||
export function generateShareableUrl(mode: ModeType, toolKey?: string): string {
|
||||
export function generateShareableUrl(toolId: ToolId | null, registry: ToolRegistry): string {
|
||||
const baseUrl = window.location.origin;
|
||||
|
||||
// Don't generate URLs for internal UI modes
|
||||
if (mode === 'viewer' || mode === 'fileEditor' || mode === 'pageEditor') {
|
||||
if (!toolId || !registry[toolId]) {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
if (toolKey) {
|
||||
const pathMappings: Record<string, string> = {
|
||||
'split': '/split-pdf',
|
||||
'merge': '/merge-pdf',
|
||||
'compress': '/compress-pdf',
|
||||
'convert': '/convert-pdf',
|
||||
'addPassword': '/add-password-pdf',
|
||||
'changePermissions': '/change-permissions-pdf',
|
||||
'sanitize': '/sanitize-pdf',
|
||||
'ocr': '/ocr-pdf',
|
||||
'addWatermark': '/watermark',
|
||||
'removePassword': '/remove-password',
|
||||
'single-large-page': '/single-large-page',
|
||||
'repair': '/repair',
|
||||
'unlockPdfForms': '/unlock-pdf-forms',
|
||||
'removeCertificateSign': '/remove-certificate-sign'
|
||||
};
|
||||
const tool = registry[toolId];
|
||||
|
||||
const path = pathMappings[toolKey] || `/${toolKey}`;
|
||||
return `${baseUrl}${path}`;
|
||||
}
|
||||
|
||||
return baseUrl;
|
||||
const path = getToolUrlPath(toolId, tool);
|
||||
return `${baseUrl}${path}`;
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user