mirror of
https://github.com/jhbruhn/respira.git
synced 2026-01-27 02:13:41 +00:00
feature: Implement Zustand state management
- Add zustand dependency for modern state management - Create three separate stores for better code organization: - useMachineStore: Machine connection, status, and operations - usePatternStore: Pattern data, offset, and upload state - useUIStore: Pyodide and UI-specific state - Migrate App.tsx from useBrotherMachine hook to Zustand stores - Use useShallow for optimized multi-value selections - Implement dynamic polling intervals based on machine state - Add ESLint ignore for .vite build directory Benefits: - Better separation of concerns with logical store divisions - Improved performance through selector-based subscriptions - Cleaner code replacing 445-line hook with maintainable stores - Full TypeScript support with proper typing 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
b7d64887cb
commit
e015c587bd
7 changed files with 877 additions and 113 deletions
|
|
@ -6,7 +6,7 @@ import tseslint from 'typescript-eslint'
|
|||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
globalIgnores(['dist', '.vite']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
|
|
|
|||
31
package-lock.json
generated
31
package-lock.json
generated
|
|
@ -20,7 +20,8 @@
|
|||
"react-dom": "^19.2.0",
|
||||
"react-konva": "^19.2.1",
|
||||
"tailwindcss": "^4.1.17",
|
||||
"update-electron-app": "^3.1.2"
|
||||
"update-electron-app": "^3.1.2",
|
||||
"zustand": "^5.0.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@electron-forge/cli": "^7.10.2",
|
||||
|
|
@ -15253,6 +15254,34 @@
|
|||
"peerDependencies": {
|
||||
"zod": "^3.25.0 || ^4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/zustand": {
|
||||
"version": "5.0.9",
|
||||
"resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.9.tgz",
|
||||
"integrity": "sha512-ALBtUj0AfjJt3uNRQoL1tL2tMvj6Gp/6e39dnfT6uzpelGru8v1tPOGBzayOWbPJvujM8JojDk3E1LxeFisBNg==",
|
||||
"engines": {
|
||||
"node": ">=12.20.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": ">=18.0.0",
|
||||
"immer": ">=9.0.6",
|
||||
"react": ">=18.0.0",
|
||||
"use-sync-external-store": ">=1.2.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
},
|
||||
"immer": {
|
||||
"optional": true
|
||||
},
|
||||
"react": {
|
||||
"optional": true
|
||||
},
|
||||
"use-sync-external-store": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,7 +30,8 @@
|
|||
"react-dom": "^19.2.0",
|
||||
"react-konva": "^19.2.1",
|
||||
"tailwindcss": "^4.1.17",
|
||||
"update-electron-app": "^3.1.2"
|
||||
"update-electron-app": "^3.1.2",
|
||||
"zustand": "^5.0.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@electron-forge/cli": "^7.10.2",
|
||||
|
|
|
|||
283
src/App.tsx
283
src/App.tsx
|
|
@ -1,5 +1,8 @@
|
|||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useBrotherMachine } from './hooks/useBrotherMachine';
|
||||
import { useEffect, useCallback, useRef } from 'react';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
import { useMachineStore } from './stores/useMachineStore';
|
||||
import { usePatternStore } from './stores/usePatternStore';
|
||||
import { useUIStore } from './stores/useUIStore';
|
||||
import { FileUpload } from './components/FileUpload';
|
||||
import { PatternCanvas } from './components/PatternCanvas';
|
||||
import { ProgressMonitor } from './components/ProgressMonitor';
|
||||
|
|
@ -7,37 +10,112 @@ import { WorkflowStepper } from './components/WorkflowStepper';
|
|||
import { PatternSummaryCard } from './components/PatternSummaryCard';
|
||||
import { BluetoothDevicePicker } from './components/BluetoothDevicePicker';
|
||||
import type { PesPatternData } from './utils/pystitchConverter';
|
||||
import { pyodideLoader } from './utils/pyodideLoader';
|
||||
import { hasError, getErrorDetails } from './utils/errorCodeHelpers';
|
||||
import { canDeletePattern, getStateVisualInfo } from './utils/machineStateHelpers';
|
||||
import { CheckCircleIcon, BoltIcon, PauseCircleIcon, ExclamationTriangleIcon, ArrowPathIcon, XMarkIcon, InformationCircleIcon } from '@heroicons/react/24/solid';
|
||||
import './App.css';
|
||||
|
||||
function App() {
|
||||
const machine = useBrotherMachine();
|
||||
const [pesData, setPesData] = useState<PesPatternData | null>(null);
|
||||
const [pyodideReady, setPyodideReady] = useState(false);
|
||||
const [pyodideError, setPyodideError] = useState<string | null>(null);
|
||||
const [patternOffset, setPatternOffset] = useState<{ x: number; y: number }>({ x: 0, y: 0 });
|
||||
const [patternUploaded, setPatternUploaded] = useState(false);
|
||||
const [currentFileName, setCurrentFileName] = useState<string>(''); // Track current pattern filename
|
||||
const [showErrorPopover, setShowErrorPopover] = useState(false);
|
||||
// Machine store
|
||||
const {
|
||||
isConnected,
|
||||
machineInfo,
|
||||
machineStatus,
|
||||
machineStatusName,
|
||||
machineError,
|
||||
patternInfo,
|
||||
sewingProgress,
|
||||
uploadProgress,
|
||||
error: machineErrorMessage,
|
||||
isPairingError,
|
||||
isCommunicating: isPolling,
|
||||
isUploading,
|
||||
isDeleting,
|
||||
resumeAvailable,
|
||||
resumeFileName,
|
||||
resumedPattern,
|
||||
connect,
|
||||
disconnect,
|
||||
uploadPattern,
|
||||
startMaskTrace,
|
||||
startSewing,
|
||||
resumeSewing,
|
||||
deletePattern,
|
||||
} = useMachineStore(
|
||||
useShallow((state) => ({
|
||||
isConnected: state.isConnected,
|
||||
machineInfo: state.machineInfo,
|
||||
machineStatus: state.machineStatus,
|
||||
machineStatusName: state.machineStatusName,
|
||||
machineError: state.machineError,
|
||||
patternInfo: state.patternInfo,
|
||||
sewingProgress: state.sewingProgress,
|
||||
uploadProgress: state.uploadProgress,
|
||||
error: state.error,
|
||||
isPairingError: state.isPairingError,
|
||||
isCommunicating: state.isCommunicating,
|
||||
isUploading: state.isUploading,
|
||||
isDeleting: state.isDeleting,
|
||||
resumeAvailable: state.resumeAvailable,
|
||||
resumeFileName: state.resumeFileName,
|
||||
resumedPattern: state.resumedPattern,
|
||||
connect: state.connect,
|
||||
disconnect: state.disconnect,
|
||||
uploadPattern: state.uploadPattern,
|
||||
startMaskTrace: state.startMaskTrace,
|
||||
startSewing: state.startSewing,
|
||||
resumeSewing: state.resumeSewing,
|
||||
deletePattern: state.deletePattern,
|
||||
}))
|
||||
);
|
||||
|
||||
// Pattern store
|
||||
const {
|
||||
pesData,
|
||||
currentFileName,
|
||||
patternOffset,
|
||||
patternUploaded,
|
||||
setPattern,
|
||||
setPatternOffset,
|
||||
setPatternUploaded,
|
||||
clearPattern,
|
||||
} = usePatternStore(
|
||||
useShallow((state) => ({
|
||||
pesData: state.pesData,
|
||||
currentFileName: state.currentFileName,
|
||||
patternOffset: state.patternOffset,
|
||||
patternUploaded: state.patternUploaded,
|
||||
setPattern: state.setPattern,
|
||||
setPatternOffset: state.setPatternOffset,
|
||||
setPatternUploaded: state.setPatternUploaded,
|
||||
clearPattern: state.clearPattern,
|
||||
}))
|
||||
);
|
||||
|
||||
// UI store
|
||||
const {
|
||||
pyodideReady,
|
||||
pyodideError,
|
||||
showErrorPopover,
|
||||
initializePyodide,
|
||||
setErrorPopover,
|
||||
} = useUIStore(
|
||||
useShallow((state) => ({
|
||||
pyodideReady: state.pyodideReady,
|
||||
pyodideError: state.pyodideError,
|
||||
showErrorPopover: state.showErrorPopover,
|
||||
initializePyodide: state.initializePyodide,
|
||||
setErrorPopover: state.setErrorPopover,
|
||||
}))
|
||||
);
|
||||
|
||||
const errorPopoverRef = useRef<HTMLDivElement>(null);
|
||||
const errorButtonRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
// Initialize Pyodide on mount
|
||||
useEffect(() => {
|
||||
pyodideLoader
|
||||
.initialize()
|
||||
.then(() => {
|
||||
setPyodideReady(true);
|
||||
console.log('[App] Pyodide initialized successfully');
|
||||
})
|
||||
.catch((err) => {
|
||||
setPyodideError(err instanceof Error ? err.message : 'Failed to initialize Python environment');
|
||||
console.error('[App] Failed to initialize Pyodide:', err);
|
||||
});
|
||||
}, []);
|
||||
initializePyodide();
|
||||
}, [initializePyodide]);
|
||||
|
||||
// Close error popover when clicking outside
|
||||
useEffect(() => {
|
||||
|
|
@ -48,7 +126,7 @@ function App() {
|
|||
errorButtonRef.current &&
|
||||
!errorButtonRef.current.contains(event.target as Node)
|
||||
) {
|
||||
setShowErrorPopover(false);
|
||||
setErrorPopover(false);
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -56,54 +134,39 @@ function App() {
|
|||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}
|
||||
}, [showErrorPopover]);
|
||||
}, [showErrorPopover, setErrorPopover]);
|
||||
|
||||
// Auto-load cached pattern when available
|
||||
const resumedPattern = machine.resumedPattern;
|
||||
const resumeFileName = machine.resumeFileName;
|
||||
|
||||
if (resumedPattern && !pesData) {
|
||||
console.log('[App] Loading resumed pattern:', resumeFileName, 'Offset:', resumedPattern.patternOffset);
|
||||
setPesData(resumedPattern.pesData);
|
||||
setPattern(resumedPattern.pesData, resumeFileName || '');
|
||||
// Restore the cached pattern offset
|
||||
if (resumedPattern.patternOffset) {
|
||||
setPatternOffset(resumedPattern.patternOffset);
|
||||
}
|
||||
// Preserve the filename from cache
|
||||
if (resumeFileName) {
|
||||
setCurrentFileName(resumeFileName);
|
||||
setPatternOffset(resumedPattern.patternOffset.x, resumedPattern.patternOffset.y);
|
||||
}
|
||||
}
|
||||
|
||||
const handlePatternLoaded = useCallback((data: PesPatternData, fileName: string) => {
|
||||
setPesData(data);
|
||||
setCurrentFileName(fileName);
|
||||
// Reset pattern offset when new pattern is loaded
|
||||
setPatternOffset({ x: 0, y: 0 });
|
||||
setPatternUploaded(false);
|
||||
}, []);
|
||||
setPattern(data, fileName);
|
||||
}, [setPattern]);
|
||||
|
||||
const handlePatternOffsetChange = useCallback((offsetX: number, offsetY: number) => {
|
||||
setPatternOffset({ x: offsetX, y: offsetY });
|
||||
console.log('[App] Pattern offset changed:', { x: offsetX, y: offsetY });
|
||||
}, []);
|
||||
setPatternOffset(offsetX, offsetY);
|
||||
}, [setPatternOffset]);
|
||||
|
||||
const handleUpload = useCallback(async (penData: Uint8Array, pesData: PesPatternData, fileName: string, patternOffset?: { x: number; y: number }) => {
|
||||
await machine.uploadPattern(penData, pesData, fileName, patternOffset);
|
||||
await uploadPattern(penData, pesData, fileName, patternOffset);
|
||||
setPatternUploaded(true);
|
||||
}, [machine]);
|
||||
}, [uploadPattern, setPatternUploaded]);
|
||||
|
||||
const handleDeletePattern = useCallback(async () => {
|
||||
await machine.deletePattern();
|
||||
setPatternUploaded(false);
|
||||
// NOTE: We intentionally DON'T clear setPesData(null) here
|
||||
await deletePattern();
|
||||
clearPattern();
|
||||
// NOTE: We intentionally DON'T clear pesData in the pattern store
|
||||
// so the pattern remains visible in the canvas for re-editing and re-uploading
|
||||
}, [machine]);
|
||||
}, [deletePattern, clearPattern]);
|
||||
|
||||
// Track pattern uploaded state based on machine status
|
||||
const isConnected = machine.isConnected;
|
||||
const patternInfo = machine.patternInfo;
|
||||
|
||||
if (!isConnected) {
|
||||
if (patternUploaded) {
|
||||
setPatternUploaded(false);
|
||||
|
|
@ -117,7 +180,7 @@ function App() {
|
|||
}
|
||||
|
||||
// Get state visual info for header status badge
|
||||
const stateVisual = getStateVisualInfo(machine.machineStatus);
|
||||
const stateVisual = getStateVisualInfo(machineStatus);
|
||||
const stateIcons = {
|
||||
ready: CheckCircleIcon,
|
||||
active: BoltIcon,
|
||||
|
|
@ -134,40 +197,40 @@ function App() {
|
|||
<div className="grid grid-cols-1 lg:grid-cols-[280px_1fr] gap-4 lg:gap-8 items-center">
|
||||
{/* Machine Connection Status - Responsive width column */}
|
||||
<div className="flex items-center gap-3 w-full lg:w-[280px]">
|
||||
<div className="w-2.5 h-2.5 bg-green-400 rounded-full animate-pulse shadow-lg shadow-green-400/50" style={{ visibility: machine.isConnected ? 'visible' : 'hidden' }}></div>
|
||||
<div className="w-2.5 h-2.5 bg-gray-400 rounded-full -ml-2.5" style={{ visibility: !machine.isConnected ? 'visible' : 'hidden' }}></div>
|
||||
<div className="w-2.5 h-2.5 bg-green-400 rounded-full animate-pulse shadow-lg shadow-green-400/50" style={{ visibility: isConnected ? 'visible' : 'hidden' }}></div>
|
||||
<div className="w-2.5 h-2.5 bg-gray-400 rounded-full -ml-2.5" style={{ visibility: !isConnected ? 'visible' : 'hidden' }}></div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<h1 className="text-lg lg:text-xl font-bold text-white leading-tight">Respira</h1>
|
||||
{machine.isConnected && machine.machineInfo?.serialNumber && (
|
||||
{isConnected && machineInfo?.serialNumber && (
|
||||
<span
|
||||
className="text-xs text-blue-200 cursor-help"
|
||||
title={`Serial: ${machine.machineInfo.serialNumber}${
|
||||
machine.machineInfo.macAddress
|
||||
? `\nMAC: ${machine.machineInfo.macAddress}`
|
||||
title={`Serial: ${machineInfo.serialNumber}${
|
||||
machineInfo.macAddress
|
||||
? `\nMAC: ${machineInfo.macAddress}`
|
||||
: ''
|
||||
}${
|
||||
machine.machineInfo.totalCount !== undefined
|
||||
? `\nTotal stitches: ${machine.machineInfo.totalCount.toLocaleString()}`
|
||||
machineInfo.totalCount !== undefined
|
||||
? `\nTotal stitches: ${machineInfo.totalCount.toLocaleString()}`
|
||||
: ''
|
||||
}${
|
||||
machine.machineInfo.serviceCount !== undefined
|
||||
? `\nStitches since service: ${machine.machineInfo.serviceCount.toLocaleString()}`
|
||||
machineInfo.serviceCount !== undefined
|
||||
? `\nStitches since service: ${machineInfo.serviceCount.toLocaleString()}`
|
||||
: ''
|
||||
}`}
|
||||
>
|
||||
• {machine.machineInfo.serialNumber}
|
||||
• {machineInfo.serialNumber}
|
||||
</span>
|
||||
)}
|
||||
{machine.isPolling && (
|
||||
{isPolling && (
|
||||
<ArrowPathIcon className="w-3.5 h-3.5 text-blue-200 animate-spin" title="Auto-refreshing status" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-1 min-h-[32px]">
|
||||
{machine.isConnected ? (
|
||||
{isConnected ? (
|
||||
<>
|
||||
<button
|
||||
onClick={machine.disconnect}
|
||||
onClick={disconnect}
|
||||
className="inline-flex items-center gap-1.5 px-2.5 py-1.5 sm:py-1 rounded text-sm font-medium bg-white/10 hover:bg-red-600 text-blue-100 hover:text-white border border-white/20 hover:border-red-600 cursor-pointer transition-all flex-shrink-0"
|
||||
title="Disconnect from machine"
|
||||
aria-label="Disconnect from machine"
|
||||
|
|
@ -177,7 +240,7 @@ function App() {
|
|||
</button>
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-1.5 sm:py-1 rounded text-sm font-semibold bg-white/20 text-white border border-white/30 flex-shrink-0">
|
||||
<StatusIcon className="w-3 h-3" />
|
||||
{machine.machineStatusName}
|
||||
{machineStatusName}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
|
|
@ -188,23 +251,23 @@ function App() {
|
|||
<div className="relative">
|
||||
<button
|
||||
ref={errorButtonRef}
|
||||
onClick={() => setShowErrorPopover(!showErrorPopover)}
|
||||
onClick={() => setErrorPopover(!showErrorPopover)}
|
||||
className={`inline-flex items-center gap-1.5 px-2.5 py-1.5 sm:py-1 rounded text-sm font-medium bg-red-500/90 hover:bg-red-600 text-white border border-red-400 transition-all flex-shrink-0 ${
|
||||
(machine.error || pyodideError)
|
||||
(machineErrorMessage || pyodideError)
|
||||
? 'cursor-pointer animate-pulse hover:animate-none'
|
||||
: 'invisible pointer-events-none'
|
||||
}`}
|
||||
title="Click to view error details"
|
||||
aria-label="View error details"
|
||||
disabled={!(machine.error || pyodideError)}
|
||||
disabled={!(machineErrorMessage || pyodideError)}
|
||||
>
|
||||
<ExclamationTriangleIcon className="w-3.5 h-3.5 flex-shrink-0" />
|
||||
<span>
|
||||
{(() => {
|
||||
if (pyodideError) return 'Python Error';
|
||||
if (machine.isPairingError) return 'Pairing Required';
|
||||
if (isPairingError) return 'Pairing Required';
|
||||
|
||||
const errorMsg = machine.error || '';
|
||||
const errorMsg = machineErrorMessage || '';
|
||||
|
||||
// Categorize by error message content
|
||||
if (errorMsg.toLowerCase().includes('bluetooth') || errorMsg.toLowerCase().includes('connection')) {
|
||||
|
|
@ -216,7 +279,7 @@ function App() {
|
|||
if (errorMsg.toLowerCase().includes('pattern')) {
|
||||
return 'Pattern Error';
|
||||
}
|
||||
if (machine.machineError !== undefined) {
|
||||
if (machineError !== undefined) {
|
||||
return `Machine Error`;
|
||||
}
|
||||
|
||||
|
|
@ -227,7 +290,7 @@ function App() {
|
|||
</button>
|
||||
|
||||
{/* Error popover */}
|
||||
{showErrorPopover && (machine.error || pyodideError) && (
|
||||
{showErrorPopover && (machineErrorMessage || pyodideError) && (
|
||||
<div
|
||||
ref={errorPopoverRef}
|
||||
className="absolute top-full mt-2 left-0 w-[600px] z-50 animate-fadeIn"
|
||||
|
|
@ -235,10 +298,10 @@ function App() {
|
|||
aria-label="Error details"
|
||||
>
|
||||
{(() => {
|
||||
const errorDetails = getErrorDetails(machine.machineError);
|
||||
const isPairingError = machine.isPairingError;
|
||||
const errorMsg = pyodideError || machine.error || '';
|
||||
const isInfo = isPairingError || errorDetails?.isInformational;
|
||||
const errorDetails = getErrorDetails(machineError);
|
||||
const isPairingErr = isPairingError;
|
||||
const errorMsg = pyodideError || machineErrorMessage || '';
|
||||
const isInfo = isPairingErr || errorDetails?.isInformational;
|
||||
|
||||
const bgColor = isInfo
|
||||
? 'bg-blue-50 dark:bg-blue-900/95 border-blue-600 dark:border-blue-500'
|
||||
|
|
@ -261,7 +324,7 @@ function App() {
|
|||
: 'text-red-700 dark:text-red-300';
|
||||
|
||||
const Icon = isInfo ? InformationCircleIcon : ExclamationTriangleIcon;
|
||||
const title = errorDetails?.title || (isPairingError ? 'Pairing Required' : 'Error');
|
||||
const title = errorDetails?.title || (isPairingErr ? 'Pairing Required' : 'Error');
|
||||
|
||||
return (
|
||||
<div className={`${bgColor} border-l-4 p-4 rounded-lg shadow-xl backdrop-blur-sm`}>
|
||||
|
|
@ -286,9 +349,9 @@ function App() {
|
|||
</ol>
|
||||
</>
|
||||
)}
|
||||
{machine.machineError !== undefined && !errorDetails?.isInformational && (
|
||||
{machineError !== undefined && !errorDetails?.isInformational && (
|
||||
<p className={`text-xs ${descColor} mt-3 font-mono`}>
|
||||
Error Code: 0x{machine.machineError.toString(16).toUpperCase().padStart(2, '0')}
|
||||
Error Code: 0x{machineError.toString(16).toUpperCase().padStart(2, '0')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -306,13 +369,13 @@ function App() {
|
|||
{/* Workflow Stepper - Flexible width column */}
|
||||
<div>
|
||||
<WorkflowStepper
|
||||
machineStatus={machine.machineStatus}
|
||||
isConnected={machine.isConnected}
|
||||
machineStatus={machineStatus}
|
||||
isConnected={isConnected}
|
||||
hasPattern={pesData !== null}
|
||||
patternUploaded={patternUploaded}
|
||||
hasError={hasError(machine.machineError)}
|
||||
errorMessage={machine.error || undefined}
|
||||
errorCode={machine.machineError}
|
||||
hasError={hasError(machineError)}
|
||||
errorMessage={machineErrorMessage || undefined}
|
||||
errorCode={machineError}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -323,7 +386,7 @@ function App() {
|
|||
{/* Left Column - Controls */}
|
||||
<div className="flex flex-col gap-4 md:gap-5 lg:gap-6 lg:overflow-hidden">
|
||||
{/* Connect Button - Show when disconnected */}
|
||||
{!machine.isConnected && (
|
||||
{!isConnected && (
|
||||
<div className="bg-white dark:bg-gray-800 p-4 rounded-lg shadow-md border-l-4 border-gray-400 dark:border-gray-600">
|
||||
<div className="flex items-start gap-3 mb-3">
|
||||
<div className="w-6 h-6 text-gray-600 dark:text-gray-400 flex-shrink-0 mt-0.5">
|
||||
|
|
@ -337,7 +400,7 @@ function App() {
|
|||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={machine.connect}
|
||||
onClick={connect}
|
||||
className="w-full flex items-center justify-center gap-2 px-3 py-2.5 sm:py-2 bg-blue-600 dark:bg-blue-700 text-white rounded font-semibold text-sm hover:bg-blue-700 dark:hover:bg-blue-600 active:bg-blue-800 dark:active:bg-blue-500 transition-colors cursor-pointer"
|
||||
>
|
||||
Connect to Machine
|
||||
|
|
@ -346,49 +409,49 @@ function App() {
|
|||
)}
|
||||
|
||||
{/* Pattern File - Show during upload stage (before pattern is uploaded) */}
|
||||
{machine.isConnected && !patternUploaded && (
|
||||
{isConnected && !patternUploaded && (
|
||||
<FileUpload
|
||||
isConnected={machine.isConnected}
|
||||
machineStatus={machine.machineStatus}
|
||||
uploadProgress={machine.uploadProgress}
|
||||
isConnected={isConnected}
|
||||
machineStatus={machineStatus}
|
||||
uploadProgress={uploadProgress}
|
||||
onPatternLoaded={handlePatternLoaded}
|
||||
onUpload={handleUpload}
|
||||
pyodideReady={pyodideReady}
|
||||
patternOffset={patternOffset}
|
||||
patternUploaded={patternUploaded}
|
||||
resumeAvailable={machine.resumeAvailable}
|
||||
resumeFileName={machine.resumeFileName}
|
||||
resumeAvailable={resumeAvailable}
|
||||
resumeFileName={resumeFileName}
|
||||
pesData={pesData}
|
||||
currentFileName={currentFileName}
|
||||
isUploading={machine.isUploading}
|
||||
machineInfo={machine.machineInfo}
|
||||
isUploading={isUploading}
|
||||
machineInfo={machineInfo}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Compact Pattern Summary - Show after upload (during sewing stages) */}
|
||||
{machine.isConnected && patternUploaded && pesData && (
|
||||
{isConnected && patternUploaded && pesData && (
|
||||
<PatternSummaryCard
|
||||
pesData={pesData}
|
||||
fileName={currentFileName}
|
||||
onDeletePattern={handleDeletePattern}
|
||||
canDelete={canDeletePattern(machine.machineStatus)}
|
||||
isDeleting={machine.isDeleting}
|
||||
canDelete={canDeletePattern(machineStatus)}
|
||||
isDeleting={isDeleting}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Progress Monitor - Show when pattern is uploaded */}
|
||||
{machine.isConnected && patternUploaded && (
|
||||
{isConnected && patternUploaded && (
|
||||
<div className="lg:flex-1 lg:min-h-0">
|
||||
<ProgressMonitor
|
||||
machineStatus={machine.machineStatus}
|
||||
patternInfo={machine.patternInfo}
|
||||
sewingProgress={machine.sewingProgress}
|
||||
machineStatus={machineStatus}
|
||||
patternInfo={patternInfo}
|
||||
sewingProgress={sewingProgress}
|
||||
pesData={pesData}
|
||||
onStartMaskTrace={machine.startMaskTrace}
|
||||
onStartSewing={machine.startSewing}
|
||||
onResumeSewing={machine.resumeSewing}
|
||||
onStartMaskTrace={startMaskTrace}
|
||||
onStartSewing={startSewing}
|
||||
onResumeSewing={resumeSewing}
|
||||
onDeletePattern={handleDeletePattern}
|
||||
isDeleting={machine.isDeleting}
|
||||
isDeleting={isDeleting}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -399,12 +462,12 @@ function App() {
|
|||
{pesData ? (
|
||||
<PatternCanvas
|
||||
pesData={pesData}
|
||||
sewingProgress={machine.sewingProgress}
|
||||
machineInfo={machine.machineInfo}
|
||||
sewingProgress={sewingProgress}
|
||||
machineInfo={machineInfo}
|
||||
initialPatternOffset={patternOffset}
|
||||
onPatternOffsetChange={handlePatternOffsetChange}
|
||||
patternUploaded={patternUploaded}
|
||||
isUploading={machine.uploadProgress > 0 && machine.uploadProgress < 100}
|
||||
isUploading={uploadProgress > 0 && uploadProgress < 100}
|
||||
/>
|
||||
) : (
|
||||
<div className="lg:h-full bg-white dark:bg-gray-800 p-6 rounded-lg shadow-md animate-fadeIn flex flex-col">
|
||||
|
|
|
|||
554
src/stores/useMachineStore.ts
Normal file
554
src/stores/useMachineStore.ts
Normal file
|
|
@ -0,0 +1,554 @@
|
|||
import { create } from 'zustand';
|
||||
import { BrotherPP1Service, BluetoothPairingError } from '../services/BrotherPP1Service';
|
||||
import type {
|
||||
MachineInfo,
|
||||
PatternInfo,
|
||||
SewingProgress,
|
||||
} from '../types/machine';
|
||||
import { MachineStatus, MachineStatusNames } from '../types/machine';
|
||||
import { SewingMachineError } from '../utils/errorCodeHelpers';
|
||||
import { uuidToString } from '../services/PatternCacheService';
|
||||
import { createStorageService } from '../platform';
|
||||
import type { IStorageService } from '../platform/interfaces/IStorageService';
|
||||
import type { PesPatternData } from '../utils/pystitchConverter';
|
||||
|
||||
interface MachineState {
|
||||
// Service instances
|
||||
service: BrotherPP1Service;
|
||||
storageService: IStorageService;
|
||||
|
||||
// Connection state
|
||||
isConnected: boolean;
|
||||
machineInfo: MachineInfo | null;
|
||||
|
||||
// Machine status
|
||||
machineStatus: MachineStatus;
|
||||
machineStatusName: string;
|
||||
machineError: number;
|
||||
|
||||
// Pattern state
|
||||
patternInfo: PatternInfo | null;
|
||||
sewingProgress: SewingProgress | null;
|
||||
|
||||
// Upload state
|
||||
uploadProgress: number;
|
||||
isUploading: boolean;
|
||||
|
||||
// Resume state
|
||||
resumeAvailable: boolean;
|
||||
resumeFileName: string | null;
|
||||
resumedPattern: { pesData: PesPatternData; patternOffset?: { x: number; y: number } } | null;
|
||||
|
||||
// Error state
|
||||
error: string | null;
|
||||
isPairingError: boolean;
|
||||
|
||||
// Communication state
|
||||
isCommunicating: boolean;
|
||||
isDeleting: boolean;
|
||||
|
||||
// Polling control
|
||||
pollIntervalId: NodeJS.Timeout | null;
|
||||
serviceCountIntervalId: NodeJS.Timeout | null;
|
||||
|
||||
// Actions
|
||||
connect: () => Promise<void>;
|
||||
disconnect: () => Promise<void>;
|
||||
refreshStatus: () => Promise<void>;
|
||||
refreshPatternInfo: () => Promise<void>;
|
||||
refreshProgress: () => Promise<void>;
|
||||
refreshServiceCount: () => Promise<void>;
|
||||
uploadPattern: (
|
||||
penData: Uint8Array,
|
||||
pesData: PesPatternData,
|
||||
fileName: string,
|
||||
patternOffset?: { x: number; y: number }
|
||||
) => Promise<void>;
|
||||
startMaskTrace: () => Promise<void>;
|
||||
startSewing: () => Promise<void>;
|
||||
resumeSewing: () => Promise<void>;
|
||||
deletePattern: () => Promise<void>;
|
||||
checkResume: () => Promise<PesPatternData | null>;
|
||||
loadCachedPattern: () => Promise<{ pesData: PesPatternData; patternOffset?: { x: number; y: number } } | null>;
|
||||
|
||||
// Internal methods
|
||||
_setupSubscriptions: () => void;
|
||||
_startPolling: () => void;
|
||||
_stopPolling: () => void;
|
||||
}
|
||||
|
||||
export const useMachineStore = create<MachineState>((set, get) => ({
|
||||
// Initial state
|
||||
service: new BrotherPP1Service(),
|
||||
storageService: createStorageService(),
|
||||
isConnected: false,
|
||||
machineInfo: null,
|
||||
machineStatus: MachineStatus.None,
|
||||
machineStatusName: MachineStatusNames[MachineStatus.None] || 'Unknown',
|
||||
machineError: SewingMachineError.None,
|
||||
patternInfo: null,
|
||||
sewingProgress: null,
|
||||
uploadProgress: 0,
|
||||
isUploading: false,
|
||||
resumeAvailable: false,
|
||||
resumeFileName: null,
|
||||
resumedPattern: null,
|
||||
error: null,
|
||||
isPairingError: false,
|
||||
isCommunicating: false,
|
||||
isDeleting: false,
|
||||
pollIntervalId: null,
|
||||
serviceCountIntervalId: null,
|
||||
|
||||
// Check for resumable pattern
|
||||
checkResume: async (): Promise<PesPatternData | null> => {
|
||||
try {
|
||||
const { service, storageService } = get();
|
||||
console.log('[Resume] Checking for cached pattern...');
|
||||
|
||||
const machineUuid = await service.getPatternUUID();
|
||||
console.log(
|
||||
'[Resume] Machine UUID:',
|
||||
machineUuid ? uuidToString(machineUuid) : 'none',
|
||||
);
|
||||
|
||||
if (!machineUuid) {
|
||||
console.log('[Resume] No pattern loaded on machine');
|
||||
set({ resumeAvailable: false, resumeFileName: null });
|
||||
return null;
|
||||
}
|
||||
|
||||
const uuidStr = uuidToString(machineUuid);
|
||||
const cached = await storageService.getPatternByUUID(uuidStr);
|
||||
|
||||
if (cached) {
|
||||
console.log('[Resume] Pattern found in cache:', cached.fileName, 'Offset:', cached.patternOffset);
|
||||
console.log('[Resume] Auto-loading cached pattern...');
|
||||
set({
|
||||
resumeAvailable: true,
|
||||
resumeFileName: cached.fileName,
|
||||
resumedPattern: { pesData: cached.pesData, patternOffset: cached.patternOffset },
|
||||
});
|
||||
|
||||
// Fetch pattern info from machine
|
||||
try {
|
||||
const info = await service.getPatternInfo();
|
||||
set({ patternInfo: info });
|
||||
console.log('[Resume] Pattern info loaded from machine');
|
||||
} catch (err) {
|
||||
console.error('[Resume] Failed to load pattern info:', err);
|
||||
}
|
||||
|
||||
return cached.pesData;
|
||||
} else {
|
||||
console.log('[Resume] Pattern on machine not found in cache');
|
||||
set({ resumeAvailable: false, resumeFileName: null });
|
||||
return null;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[Resume] Failed to check resume:', err);
|
||||
set({ resumeAvailable: false, resumeFileName: null });
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
// Connect to machine
|
||||
connect: async () => {
|
||||
try {
|
||||
const { service, checkResume } = get();
|
||||
set({ error: null, isPairingError: false });
|
||||
|
||||
await service.connect();
|
||||
set({ isConnected: true });
|
||||
|
||||
// Fetch initial machine info and status
|
||||
const info = await service.getMachineInfo();
|
||||
const state = await service.getMachineState();
|
||||
|
||||
set({
|
||||
machineInfo: info,
|
||||
machineStatus: state.status,
|
||||
machineStatusName: MachineStatusNames[state.status] || 'Unknown',
|
||||
machineError: state.error,
|
||||
});
|
||||
|
||||
// Check for resume possibility
|
||||
await checkResume();
|
||||
|
||||
// Start polling
|
||||
get()._startPolling();
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
const isPairing = err instanceof BluetoothPairingError;
|
||||
set({
|
||||
isPairingError: isPairing,
|
||||
error: err instanceof Error ? err.message : 'Failed to connect',
|
||||
isConnected: false,
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// Disconnect from machine
|
||||
disconnect: async () => {
|
||||
try {
|
||||
const { service, _stopPolling } = get();
|
||||
_stopPolling();
|
||||
|
||||
await service.disconnect();
|
||||
set({
|
||||
isConnected: false,
|
||||
machineInfo: null,
|
||||
machineStatus: MachineStatus.None,
|
||||
machineStatusName: MachineStatusNames[MachineStatus.None] || 'Unknown',
|
||||
patternInfo: null,
|
||||
sewingProgress: null,
|
||||
error: null,
|
||||
machineError: SewingMachineError.None,
|
||||
});
|
||||
} catch (err) {
|
||||
set({
|
||||
error: err instanceof Error ? err.message : 'Failed to disconnect',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// Refresh machine status
|
||||
refreshStatus: async () => {
|
||||
const { isConnected, service } = get();
|
||||
if (!isConnected) return;
|
||||
|
||||
try {
|
||||
const state = await service.getMachineState();
|
||||
set({
|
||||
machineStatus: state.status,
|
||||
machineStatusName: MachineStatusNames[state.status] || 'Unknown',
|
||||
machineError: state.error,
|
||||
});
|
||||
} catch (err) {
|
||||
set({
|
||||
error: err instanceof Error ? err.message : 'Failed to get status',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// Refresh pattern info
|
||||
refreshPatternInfo: async () => {
|
||||
const { isConnected, service } = get();
|
||||
if (!isConnected) return;
|
||||
|
||||
try {
|
||||
const info = await service.getPatternInfo();
|
||||
set({ patternInfo: info });
|
||||
} catch (err) {
|
||||
set({
|
||||
error: err instanceof Error ? err.message : 'Failed to get pattern info',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// Refresh sewing progress
|
||||
refreshProgress: async () => {
|
||||
const { isConnected, service } = get();
|
||||
if (!isConnected) return;
|
||||
|
||||
try {
|
||||
const progress = await service.getSewingProgress();
|
||||
set({ sewingProgress: progress });
|
||||
} catch (err) {
|
||||
set({
|
||||
error: err instanceof Error ? err.message : 'Failed to get progress',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// Refresh service count
|
||||
refreshServiceCount: async () => {
|
||||
const { isConnected, machineInfo, service } = get();
|
||||
if (!isConnected || !machineInfo) return;
|
||||
|
||||
try {
|
||||
const counts = await service.getServiceCount();
|
||||
set({
|
||||
machineInfo: {
|
||||
...machineInfo,
|
||||
serviceCount: counts.serviceCount,
|
||||
totalCount: counts.totalCount,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('Failed to get service count:', err);
|
||||
}
|
||||
},
|
||||
|
||||
// Upload pattern to machine
|
||||
uploadPattern: async (
|
||||
penData: Uint8Array,
|
||||
pesData: PesPatternData,
|
||||
fileName: string,
|
||||
patternOffset?: { x: number; y: number }
|
||||
) => {
|
||||
const { isConnected, service, storageService, refreshStatus, refreshPatternInfo } = get();
|
||||
if (!isConnected) {
|
||||
set({ error: 'Not connected to machine' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
set({ error: null, uploadProgress: 0, isUploading: true });
|
||||
|
||||
const uuid = await service.uploadPattern(
|
||||
penData,
|
||||
(progress) => {
|
||||
set({ uploadProgress: progress });
|
||||
},
|
||||
pesData.bounds,
|
||||
patternOffset,
|
||||
);
|
||||
|
||||
set({ uploadProgress: 100 });
|
||||
|
||||
// Cache the pattern with its UUID and offset
|
||||
const uuidStr = uuidToString(uuid);
|
||||
storageService.savePattern(uuidStr, pesData, fileName, patternOffset);
|
||||
console.log('[Cache] Saved pattern:', fileName, 'with UUID:', uuidStr, 'Offset:', patternOffset);
|
||||
|
||||
// Clear resume state since we just uploaded
|
||||
set({
|
||||
resumeAvailable: false,
|
||||
resumeFileName: null,
|
||||
});
|
||||
|
||||
// Refresh status and pattern info after upload
|
||||
await refreshStatus();
|
||||
await refreshPatternInfo();
|
||||
} catch (err) {
|
||||
set({
|
||||
error: err instanceof Error ? err.message : 'Failed to upload pattern',
|
||||
});
|
||||
} finally {
|
||||
set({ isUploading: false });
|
||||
}
|
||||
},
|
||||
|
||||
// Start mask trace
|
||||
startMaskTrace: async () => {
|
||||
const { isConnected, service, refreshStatus } = get();
|
||||
if (!isConnected) return;
|
||||
|
||||
try {
|
||||
set({ error: null });
|
||||
await service.startMaskTrace();
|
||||
await refreshStatus();
|
||||
} catch (err) {
|
||||
set({
|
||||
error: err instanceof Error ? err.message : 'Failed to start mask trace',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// Start sewing
|
||||
startSewing: async () => {
|
||||
const { isConnected, service, refreshStatus } = get();
|
||||
if (!isConnected) return;
|
||||
|
||||
try {
|
||||
set({ error: null });
|
||||
await service.startSewing();
|
||||
await refreshStatus();
|
||||
} catch (err) {
|
||||
set({
|
||||
error: err instanceof Error ? err.message : 'Failed to start sewing',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// Resume sewing
|
||||
resumeSewing: async () => {
|
||||
const { isConnected, service, refreshStatus } = get();
|
||||
if (!isConnected) return;
|
||||
|
||||
try {
|
||||
set({ error: null });
|
||||
await service.resumeSewing();
|
||||
await refreshStatus();
|
||||
} catch (err) {
|
||||
set({
|
||||
error: err instanceof Error ? err.message : 'Failed to resume sewing',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// Delete pattern from machine
|
||||
deletePattern: async () => {
|
||||
const { isConnected, service, storageService, refreshStatus } = get();
|
||||
if (!isConnected) return;
|
||||
|
||||
try {
|
||||
set({ error: null, isDeleting: true });
|
||||
|
||||
// Delete pattern from cache to prevent auto-resume
|
||||
try {
|
||||
const machineUuid = await service.getPatternUUID();
|
||||
if (machineUuid) {
|
||||
const uuidStr = uuidToString(machineUuid);
|
||||
await storageService.deletePattern(uuidStr);
|
||||
console.log('[Cache] Deleted pattern with UUID:', uuidStr);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[Cache] Failed to get UUID for cache deletion:', err);
|
||||
}
|
||||
|
||||
await service.deletePattern();
|
||||
|
||||
// Clear machine-related state
|
||||
set({
|
||||
patternInfo: null,
|
||||
sewingProgress: null,
|
||||
uploadProgress: 0,
|
||||
resumeAvailable: false,
|
||||
resumeFileName: null,
|
||||
});
|
||||
|
||||
await refreshStatus();
|
||||
} catch (err) {
|
||||
set({
|
||||
error: err instanceof Error ? err.message : 'Failed to delete pattern',
|
||||
});
|
||||
} finally {
|
||||
set({ isDeleting: false });
|
||||
}
|
||||
},
|
||||
|
||||
// Load cached pattern
|
||||
loadCachedPattern: async (): Promise<{ pesData: PesPatternData; patternOffset?: { x: number; y: number } } | null> => {
|
||||
const { resumeAvailable, service, storageService, refreshPatternInfo } = get();
|
||||
if (!resumeAvailable) return null;
|
||||
|
||||
try {
|
||||
const machineUuid = await service.getPatternUUID();
|
||||
if (!machineUuid) return null;
|
||||
|
||||
const uuidStr = uuidToString(machineUuid);
|
||||
const cached = await storageService.getPatternByUUID(uuidStr);
|
||||
|
||||
if (cached) {
|
||||
console.log('[Resume] Loading cached pattern:', cached.fileName, 'Offset:', cached.patternOffset);
|
||||
await refreshPatternInfo();
|
||||
return { pesData: cached.pesData, patternOffset: cached.patternOffset };
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (err) {
|
||||
set({
|
||||
error: err instanceof Error ? err.message : 'Failed to load cached pattern',
|
||||
});
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
// Setup service subscriptions
|
||||
_setupSubscriptions: () => {
|
||||
const { service } = get();
|
||||
|
||||
// Subscribe to communication state changes
|
||||
service.onCommunicationChange((isCommunicating) => {
|
||||
set({ isCommunicating });
|
||||
});
|
||||
|
||||
// Subscribe to disconnect events
|
||||
service.onDisconnect(() => {
|
||||
console.log('[useMachineStore] Device disconnected');
|
||||
get()._stopPolling();
|
||||
set({
|
||||
isConnected: false,
|
||||
machineInfo: null,
|
||||
machineStatus: MachineStatus.None,
|
||||
machineStatusName: MachineStatusNames[MachineStatus.None] || 'Unknown',
|
||||
machineError: SewingMachineError.None,
|
||||
patternInfo: null,
|
||||
sewingProgress: null,
|
||||
error: 'Device disconnected',
|
||||
isPairingError: false,
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
// Start polling for status updates
|
||||
_startPolling: () => {
|
||||
const { _stopPolling, refreshStatus, refreshProgress, refreshServiceCount } = get();
|
||||
|
||||
// Stop any existing polling
|
||||
_stopPolling();
|
||||
|
||||
// Function to determine polling interval based on machine status
|
||||
const getPollInterval = () => {
|
||||
const status = get().machineStatus;
|
||||
|
||||
// Fast polling for active states
|
||||
if (
|
||||
status === MachineStatus.SEWING ||
|
||||
status === MachineStatus.MASK_TRACING ||
|
||||
status === MachineStatus.SEWING_DATA_RECEIVE
|
||||
) {
|
||||
return 500;
|
||||
} else if (
|
||||
status === MachineStatus.COLOR_CHANGE_WAIT ||
|
||||
status === MachineStatus.MASK_TRACE_LOCK_WAIT ||
|
||||
status === MachineStatus.SEWING_WAIT
|
||||
) {
|
||||
return 1000;
|
||||
}
|
||||
return 2000; // Default for idle states
|
||||
};
|
||||
|
||||
// Main polling function
|
||||
const poll = async () => {
|
||||
await refreshStatus();
|
||||
|
||||
// Refresh progress during sewing
|
||||
if (get().machineStatus === MachineStatus.SEWING) {
|
||||
await refreshProgress();
|
||||
}
|
||||
|
||||
// Schedule next poll with updated interval
|
||||
const newInterval = getPollInterval();
|
||||
const pollIntervalId = setTimeout(poll, newInterval);
|
||||
set({ pollIntervalId });
|
||||
};
|
||||
|
||||
// Start polling
|
||||
const initialInterval = getPollInterval();
|
||||
const pollIntervalId = setTimeout(poll, initialInterval);
|
||||
|
||||
// Service count polling (every 10 seconds)
|
||||
const serviceCountIntervalId = setInterval(refreshServiceCount, 10000);
|
||||
|
||||
set({ pollIntervalId, serviceCountIntervalId });
|
||||
},
|
||||
|
||||
// Stop polling
|
||||
_stopPolling: () => {
|
||||
const { pollIntervalId, serviceCountIntervalId } = get();
|
||||
|
||||
if (pollIntervalId) {
|
||||
clearTimeout(pollIntervalId);
|
||||
set({ pollIntervalId: null });
|
||||
}
|
||||
|
||||
if (serviceCountIntervalId) {
|
||||
clearInterval(serviceCountIntervalId);
|
||||
set({ serviceCountIntervalId: null });
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
// Initialize subscriptions when store is created
|
||||
useMachineStore.getState()._setupSubscriptions();
|
||||
|
||||
// Selector hooks for common use cases
|
||||
export const useIsConnected = () => useMachineStore((state) => state.isConnected);
|
||||
export const useMachineInfo = () => useMachineStore((state) => state.machineInfo);
|
||||
export const useMachineStatus = () => useMachineStore((state) => state.machineStatus);
|
||||
export const useMachineError = () => useMachineStore((state) => state.machineError);
|
||||
export const usePatternInfo = () => useMachineStore((state) => state.patternInfo);
|
||||
export const useSewingProgress = () => useMachineStore((state) => state.sewingProgress);
|
||||
66
src/stores/usePatternStore.ts
Normal file
66
src/stores/usePatternStore.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import { create } from 'zustand';
|
||||
import type { PesPatternData } from '../utils/pystitchConverter';
|
||||
|
||||
interface PatternState {
|
||||
// Pattern data
|
||||
pesData: PesPatternData | null;
|
||||
currentFileName: string;
|
||||
patternOffset: { x: number; y: number };
|
||||
patternUploaded: boolean;
|
||||
|
||||
// Actions
|
||||
setPattern: (data: PesPatternData, fileName: string) => void;
|
||||
setPatternOffset: (x: number, y: number) => void;
|
||||
setPatternUploaded: (uploaded: boolean) => void;
|
||||
clearPattern: () => void;
|
||||
resetPatternOffset: () => void;
|
||||
}
|
||||
|
||||
export const usePatternStore = create<PatternState>((set) => ({
|
||||
// Initial state
|
||||
pesData: null,
|
||||
currentFileName: '',
|
||||
patternOffset: { x: 0, y: 0 },
|
||||
patternUploaded: false,
|
||||
|
||||
// Set pattern data and filename
|
||||
setPattern: (data: PesPatternData, fileName: string) => {
|
||||
set({
|
||||
pesData: data,
|
||||
currentFileName: fileName,
|
||||
patternOffset: { x: 0, y: 0 }, // Reset offset when new pattern is loaded
|
||||
patternUploaded: false,
|
||||
});
|
||||
},
|
||||
|
||||
// Update pattern offset
|
||||
setPatternOffset: (x: number, y: number) => {
|
||||
set({ patternOffset: { x, y } });
|
||||
console.log('[PatternStore] Pattern offset changed:', { x, y });
|
||||
},
|
||||
|
||||
// Mark pattern as uploaded/not uploaded
|
||||
setPatternUploaded: (uploaded: boolean) => {
|
||||
set({ patternUploaded: uploaded });
|
||||
},
|
||||
|
||||
// Clear pattern (but keep data visible for re-editing)
|
||||
clearPattern: () => {
|
||||
set({
|
||||
patternUploaded: false,
|
||||
// Note: We intentionally DON'T clear pesData or currentFileName
|
||||
// so the pattern remains visible in the canvas for re-editing
|
||||
});
|
||||
},
|
||||
|
||||
// Reset pattern offset to default
|
||||
resetPatternOffset: () => {
|
||||
set({ patternOffset: { x: 0, y: 0 } });
|
||||
},
|
||||
}));
|
||||
|
||||
// Selector hooks for common use cases
|
||||
export const usePesData = () => usePatternStore((state) => state.pesData);
|
||||
export const usePatternFileName = () => usePatternStore((state) => state.currentFileName);
|
||||
export const usePatternOffset = () => usePatternStore((state) => state.patternOffset);
|
||||
export const usePatternUploaded = () => usePatternStore((state) => state.patternUploaded);
|
||||
51
src/stores/useUIStore.ts
Normal file
51
src/stores/useUIStore.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { create } from 'zustand';
|
||||
import { pyodideLoader } from '../utils/pyodideLoader';
|
||||
|
||||
interface UIState {
|
||||
// Pyodide state
|
||||
pyodideReady: boolean;
|
||||
pyodideError: string | null;
|
||||
|
||||
// UI state
|
||||
showErrorPopover: boolean;
|
||||
|
||||
// Actions
|
||||
initializePyodide: () => Promise<void>;
|
||||
toggleErrorPopover: () => void;
|
||||
setErrorPopover: (show: boolean) => void;
|
||||
}
|
||||
|
||||
export const useUIStore = create<UIState>((set) => ({
|
||||
// Initial state
|
||||
pyodideReady: false,
|
||||
pyodideError: null,
|
||||
showErrorPopover: false,
|
||||
|
||||
// Initialize Pyodide
|
||||
initializePyodide: async () => {
|
||||
try {
|
||||
await pyodideLoader.initialize();
|
||||
set({ pyodideReady: true });
|
||||
console.log('[UIStore] Pyodide initialized successfully');
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to initialize Python environment';
|
||||
set({ pyodideError: errorMessage });
|
||||
console.error('[UIStore] Failed to initialize Pyodide:', err);
|
||||
}
|
||||
},
|
||||
|
||||
// Toggle error popover visibility
|
||||
toggleErrorPopover: () => {
|
||||
set((state) => ({ showErrorPopover: !state.showErrorPopover }));
|
||||
},
|
||||
|
||||
// Set error popover visibility
|
||||
setErrorPopover: (show: boolean) => {
|
||||
set({ showErrorPopover: show });
|
||||
},
|
||||
}));
|
||||
|
||||
// Selector hooks for common use cases
|
||||
export const usePyodideReady = () => useUIStore((state) => state.pyodideReady);
|
||||
export const usePyodideError = () => useUIStore((state) => state.pyodideError);
|
||||
export const useErrorPopover = () => useUIStore((state) => state.showErrorPopover);
|
||||
Loading…
Reference in a new issue