Starting Over with Ink

This commit is contained in:
2025-08-10 14:54:47 -05:00
parent f38eff12cd
commit ec6d49e37e
14 changed files with 3280 additions and 557 deletions

18
.babelrc Normal file
View File

@@ -0,0 +1,18 @@
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "16"
}
}
],
[
"@babel/preset-react",
{
"runtime": "classic"
}
]
]
}

View File

@@ -1,388 +0,0 @@
# Design Document
## Overview
The Shopify Price Updater TUI will be built as a Node.js terminal user interface that provides an interactive, menu-driven experience for all existing functionality. The design leverages the `blessed` library for robust terminal UI components and maintains complete integration with the existing service layer architecture. The TUI will serve as an alternative interface to the CLI while preserving all existing functionality and logging behavior.
## Architecture
### High-Level Architecture
```mermaid
graph TB
A[TUI Entry Point] --> B[TUI Application Controller]
B --> C[Screen Manager]
C --> D[Main Menu Screen]
C --> E[Configuration Screen]
C --> F[Operations Screen]
C --> G[Scheduling Screen]
C --> H[Logs Screen]
C --> I[Tag Analysis Screen]
B --> J[State Manager]
B --> K[Existing Services Layer]
K --> L[ProductService]
K --> M[ShopifyService]
K --> N[ProgressService]
K --> O[ScheduleService]
J --> P[Configuration State]
J --> Q[Operation State]
J --> R[UI State]
```
### Component Layers
1. **TUI Layer**: User interface components and screen management
2. **State Management Layer**: Application state and configuration management
3. **Integration Layer**: Bridges TUI with existing services
4. **Service Layer**: Existing business logic (unchanged)
## Components and Interfaces
### Core TUI Components
#### TUIApplication
```javascript
class TUIApplication {
constructor()
initialize()
run()
shutdown()
handleGlobalKeypress(key)
}
```
**Responsibilities:**
- Application lifecycle management
- Global keyboard shortcuts
- Screen routing and navigation
- Integration with existing services
#### ScreenManager
```javascript
class ScreenManager {
constructor(blessed, stateManager)
registerScreen(name, screenClass)
showScreen(name, params)
getCurrentScreen()
goBack()
showModal(content, options)
}
```
**Responsibilities:**
- Screen lifecycle management
- Navigation history
- Modal dialog management
- Screen transitions
#### StateManager
```javascript
class StateManager {
constructor()
getConfiguration()
updateConfiguration(key, value)
validateConfiguration()
saveConfiguration()
getOperationState()
updateOperationState(state)
subscribe(event, callback)
}
```
**Responsibilities:**
- Centralized state management
- Configuration persistence
- State change notifications
- Validation coordination
### Screen Components
#### MainMenuScreen
- **Purpose**: Primary navigation hub
- **Features**: Menu options, status indicators, quick actions
- **Navigation**: Routes to all other screens
#### ConfigurationScreen
- **Purpose**: Environment variable management
- **Features**: Form inputs, validation, API testing
- **Components**: Input fields, validation messages, save/cancel buttons
#### OperationsScreen
- **Purpose**: Price update and rollback execution
- **Features**: Operation selection, progress tracking, results display
- **Components**: Progress bars, product lists, error panels
#### SchedulingScreen
- **Purpose**: Scheduled operation management
- **Features**: Date/time picker, countdown display, cancellation
- **Components**: Calendar widget, time input, countdown timer
#### LogsScreen
- **Purpose**: Operation history and log viewing
- **Features**: Log filtering, search, pagination
- **Components**: Log list, search bar, filter controls
#### TagAnalysisScreen
- **Purpose**: Product tag debugging and analysis
- **Features**: Tag listing, product counts, sample display
- **Components**: Tag tree, product preview, statistics panel
### UI Component Library
#### Common Components
- **FormField**: Reusable input component with validation
- **ProgressBar**: Animated progress indicator
- **StatusBar**: Global status and connection indicator
- **ErrorPanel**: Error display with retry options
- **ConfirmDialog**: Modal confirmation dialogs
- **HelpOverlay**: Context-sensitive help system
## Data Models
### Configuration Model
```javascript
{
shopifyShopDomain: string,
shopifyAccessToken: string,
targetTag: string,
priceAdjustmentPercentage: number,
operationMode: 'update' | 'rollback',
isScheduled: boolean,
scheduledExecutionTime: Date,
isValid: boolean,
validationErrors: string[]
}
```
### Operation State Model
```javascript
{
currentOperation: 'idle' | 'fetching' | 'updating' | 'rollback' | 'scheduled',
progress: {
current: number,
total: number,
percentage: number,
currentProduct: string
},
results: {
totalProducts: number,
totalVariants: number,
successfulUpdates: number,
failedUpdates: number,
errors: Array
},
canCancel: boolean
}
```
### UI State Model
```javascript
{
currentScreen: string,
navigationHistory: string[],
modalStack: Array,
globalMessages: Array,
keyboardShortcuts: Object,
theme: Object
}
```
## Error Handling
### Error Categories
1. **Configuration Errors**: Invalid environment variables, API credentials
2. **Network Errors**: Shopify API connectivity issues
3. **Operation Errors**: Price update failures, validation errors
4. **UI Errors**: Screen rendering issues, input validation
### Error Handling Strategy
- **Graceful Degradation**: UI remains functional during errors
- **User-Friendly Messages**: Technical errors translated to user language
- **Recovery Options**: Retry mechanisms and alternative actions
- **Error Logging**: All errors logged to existing progress system
### Error Display Components
- **Inline Validation**: Real-time input validation feedback
- **Error Panels**: Dedicated error display areas
- **Toast Notifications**: Temporary error messages
- **Modal Dialogs**: Critical error handling
## Testing Strategy
### Unit Testing
- **Component Testing**: Individual screen and component functionality
- **State Management Testing**: Configuration and state transitions
- **Integration Testing**: TUI-to-service layer integration
- **Mock Testing**: Shopify API interactions
### Test Structure
```
tests/
├── tui/
│ ├── components/
│ │ ├── screens/
│ │ └── common/
│ ├── state/
│ └── integration/
└── fixtures/
└── tui-test-data.js
```
### Testing Approach
- **Blessed Testing**: Use blessed's testing utilities for UI components
- **State Testing**: Verify state transitions and persistence
- **Service Integration**: Ensure existing services work unchanged
- **User Journey Testing**: End-to-end workflow validation
## Implementation Details
### Technology Stack
- **UI Framework**: `blessed` - Mature, feature-rich terminal UI library
- **State Management**: Custom implementation using EventEmitter pattern
- **Configuration**: Extend existing environment.js configuration system
- **Logging**: Integrate with existing ProgressService for consistent logging
### Key Design Decisions
#### Choice of Blessed Library
- **Rationale**: Mature, well-documented, extensive widget library
- **Benefits**: Rich component set, event handling, layout management
- **Alternatives Considered**: Ink (React-based), terminal-kit, raw ANSI
#### State Management Pattern
- **Rationale**: Centralized state with event-driven updates
- **Benefits**: Predictable state changes, easy debugging, component isolation
- **Implementation**: Custom StateManager with EventEmitter for notifications
#### Service Integration Strategy
- **Rationale**: Preserve existing service layer without modifications
- **Benefits**: Maintains existing functionality, easier testing, reduced risk
- **Implementation**: TUI acts as alternative controller layer
### Screen Layout Design
#### Main Menu Layout
```
┌─ Shopify Price Updater TUI ─────────────────────────────────┐
│ Status: Connected ✓ | Config: Valid ✓ | Last Run: 2h ago │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. Configure Settings │
│ 2. Update Prices │
│ 3. Rollback Prices │
│ 4. Schedule Operation │
│ 5. View Logs │
│ 6. Analyze Tags │
│ 7. Help │
│ 8. Exit │
│ │
├─────────────────────────────────────────────────────────────┤
│ Press number key or use arrows + Enter | F1: Help | Q: Quit │
└─────────────────────────────────────────────────────────────┘
```
#### Operations Screen Layout
```
┌─ Price Update Operation ────────────────────────────────────┐
│ Target Tag: sale-items | Adjustment: +15% | Mode: Update │
├─────────────────────────────────────────────────────────────┤
│ Progress: [████████████████████████████████████████] 85% │
│ Products: 127/150 | Variants: 342/400 | Errors: 3 │
├─────────────────────────────────────────────────────────────┤
│ Current Product: "Premium Widget Set" │
│ Status: Updating variant prices... │
│ │
│ Recent Errors: │
│ • Product "Basic Kit": Invalid price format │
│ • Product "Deluxe Set": API rate limit (retrying...) │
│ │
├─────────────────────────────────────────────────────────────┤
│ ESC: Cancel (if safe) | F1: Help | Space: Pause/Resume │
└─────────────────────────────────────────────────────────────┘
```
### Keyboard Navigation Design
- **Global Shortcuts**: F1 (Help), ESC (Back/Cancel), Q (Quit)
- **Menu Navigation**: Arrow keys, Tab, Enter, Number keys
- **Form Navigation**: Tab/Shift+Tab, Enter (submit), ESC (cancel)
- **List Navigation**: Arrow keys, Page Up/Down, Home/End
### Theme and Styling
- **Color Scheme**: Terminal-friendly colors with fallbacks
- **Status Indicators**: Unicode symbols with text alternatives
- **Progress Indicators**: ASCII progress bars with percentage
- **Responsive Design**: Adapts to different terminal sizes
## Integration Points
### Existing Service Integration
- **ProductService**: Direct integration for all product operations
- **ShopifyService**: API connectivity and authentication
- **ProgressService**: Logging integration for audit trail
- **ScheduleService**: Scheduling functionality integration
### Configuration Integration
- **Environment Variables**: Read/write to existing .env system
- **Validation**: Use existing configuration validation logic
- **Persistence**: Maintain compatibility with CLI configuration
### Logging Integration
- **Progress.md**: Continue writing to existing log file
- **Console Output**: Maintain existing log format for compatibility
- **Error Tracking**: Use existing error categorization and handling
## Performance Considerations
### Memory Management
- **Screen Caching**: Cache frequently used screens
- **Event Cleanup**: Proper event listener cleanup on screen changes
- **Large Data Sets**: Pagination for large product lists and logs
### Responsiveness
- **Async Operations**: Non-blocking UI during API calls
- **Progress Feedback**: Real-time progress updates
- **Cancellation**: Safe operation cancellation where possible
### Terminal Compatibility
- **Size Adaptation**: Responsive layout for different terminal sizes
- **Color Support**: Graceful fallback for terminals without color
- **Unicode Support**: ASCII alternatives for Unicode characters

View File

@@ -1,147 +0,0 @@
# Requirements Document
## Introduction
This document outlines the requirements for building a Terminal User Interface (TUI) for the Shopify Price Updater script. The TUI will provide an interactive, menu-driven interface that allows users to configure settings, execute operations, schedule price updates, and monitor progress without needing to use command-line arguments or edit environment files directly. The interface will make the tool more accessible to non-technical users while maintaining all existing functionality.
## Requirements
### Requirement 1
**User Story:** As a store owner, I want a visual terminal interface to interact with the price updater, so that I can easily access all features without memorizing command-line options.
#### Acceptance Criteria
1. WHEN the TUI is launched THEN the system SHALL display a main menu with clearly labeled options
2. WHEN a user navigates the interface THEN the system SHALL provide keyboard shortcuts and arrow key navigation
3. WHEN a user selects an option THEN the system SHALL provide immediate visual feedback
4. WHEN the interface is displayed THEN the system SHALL show the current configuration status
### Requirement 2
**User Story:** As a user, I want to configure all environment variables through the TUI, so that I don't need to manually edit .env files.
#### Acceptance Criteria
1. WHEN a user selects configuration settings THEN the system SHALL display all current environment variables
2. WHEN a user modifies a setting THEN the system SHALL validate the input before saving
3. WHEN configuration is saved THEN the system SHALL update the .env file automatically
4. WHEN invalid configuration is entered THEN the system SHALL display clear error messages
5. WHEN configuration is complete THEN the system SHALL test the Shopify API connection
### Requirement 3
**User Story:** As a user, I want to execute price update operations from the TUI, so that I can run operations with visual progress feedback.
#### Acceptance Criteria
1. WHEN a user selects price update THEN the system SHALL display current configuration summary
2. WHEN an operation starts THEN the system SHALL show real-time progress indicators
3. WHEN products are being processed THEN the system SHALL display current product information
4. WHEN an operation completes THEN the system SHALL show detailed results summary
5. WHEN errors occur THEN the system SHALL display them in a dedicated error panel
### Requirement 4
**User Story:** As a user, I want to execute rollback operations from the TUI, so that I can easily revert price changes with visual confirmation.
#### Acceptance Criteria
1. WHEN a user selects rollback THEN the system SHALL display eligible products for rollback
2. WHEN rollback starts THEN the system SHALL show progress with rollback-specific indicators
3. WHEN rollback completes THEN the system SHALL display rollback-specific results
4. WHEN no eligible products exist THEN the system SHALL clearly inform the user
### Requirement 5
**User Story:** As a user, I want to schedule price updates through the TUI, so that I can set up automated operations with a visual interface.
#### Acceptance Criteria
1. WHEN a user selects scheduling THEN the system SHALL provide date/time picker interface
2. WHEN a schedule is set THEN the system SHALL display countdown timer with cancellation option
3. WHEN scheduled time approaches THEN the system SHALL provide visual and audio notifications
4. WHEN a scheduled operation is cancelled THEN the system SHALL confirm cancellation clearly
5. WHEN scheduling is active THEN the system SHALL prevent conflicting operations
### Requirement 6
**User Story:** As a user, I want to view operation logs and history through the TUI, so that I can review past operations without opening external files.
#### Acceptance Criteria
1. WHEN a user selects log viewer THEN the system SHALL display recent operation history
2. WHEN logs are displayed THEN the system SHALL provide filtering and search capabilities
3. WHEN log entries are selected THEN the system SHALL show detailed operation information
4. WHEN logs are extensive THEN the system SHALL provide pagination controls
5. WHEN logs are updated THEN the system SHALL refresh the display automatically
### Requirement 7
**User Story:** As a user, I want to debug and analyze product tags through the TUI, so that I can troubleshoot issues without using separate scripts.
#### Acceptance Criteria
1. WHEN a user selects tag analysis THEN the system SHALL display available product tags
2. WHEN tags are analyzed THEN the system SHALL show product counts per tag
3. WHEN a tag is selected THEN the system SHALL display sample products with that tag
4. WHEN analysis completes THEN the system SHALL provide recommendations for target tags
### Requirement 8
**User Story:** As a user, I want real-time status monitoring in the TUI, so that I can see system health and operation progress at all times.
#### Acceptance Criteria
1. WHEN the TUI is active THEN the system SHALL display connection status to Shopify API
2. WHEN operations are running THEN the system SHALL show progress bars and completion percentages
3. WHEN errors occur THEN the system SHALL display error indicators in the status bar
4. WHEN system resources are constrained THEN the system SHALL show performance warnings
### Requirement 9
**User Story:** As a user, I want keyboard shortcuts and navigation aids in the TUI, so that I can efficiently operate the interface.
#### Acceptance Criteria
1. WHEN the interface is displayed THEN the system SHALL show available keyboard shortcuts
2. WHEN a user presses help key THEN the system SHALL display comprehensive help overlay
3. WHEN navigating menus THEN the system SHALL support arrow keys, tab, and enter
4. WHEN in any screen THEN the system SHALL provide consistent back/exit options
5. WHEN shortcuts are used THEN the system SHALL provide immediate response
### Requirement 10
**User Story:** As a user, I want the TUI to handle errors gracefully, so that the interface remains stable and informative during issues.
#### Acceptance Criteria
1. WHEN API errors occur THEN the system SHALL display user-friendly error messages
2. WHEN network issues happen THEN the system SHALL show retry options and status
3. WHEN configuration errors exist THEN the system SHALL guide users to corrections
4. WHEN unexpected errors occur THEN the system SHALL log details while maintaining interface stability
5. WHEN errors are resolved THEN the system SHALL automatically return to normal operation
### Requirement 11
**User Story:** As a user, I want the TUI to preserve my session and settings, so that I don't lose progress when switching between operations.
#### Acceptance Criteria
1. WHEN switching between screens THEN the system SHALL maintain current configuration state
2. WHEN operations are interrupted THEN the system SHALL preserve partial progress where possible
3. WHEN returning to previous screens THEN the system SHALL restore previous selections
4. WHEN the TUI is restarted THEN the system SHALL load the last saved configuration
5. WHEN session data exists THEN the system SHALL offer to resume previous operations
### Requirement 12
**User Story:** As a developer, I want the TUI to integrate seamlessly with existing codebase, so that maintenance and updates remain straightforward.
#### Acceptance Criteria
1. WHEN TUI is implemented THEN the system SHALL reuse existing service classes without modification
2. WHEN TUI operations run THEN the system SHALL generate the same logs as CLI operations
3. WHEN TUI is added THEN the system SHALL maintain backward compatibility with existing CLI interface
4. WHEN configuration changes THEN the system SHALL use the same validation logic as CLI version
5. WHEN TUI components are updated THEN the system SHALL follow existing code organization patterns

View File

@@ -0,0 +1,477 @@
# Design Document
## Overview
This design document outlines the replacement of the Blessed-based TUI with a Windows-compatible alternative using **Ink** (React for CLI) as the primary library choice. Ink provides excellent cross-platform support, modern React-based component architecture, and superior Windows compatibility compared to Blessed. The design maintains all existing functionality while improving performance, maintainability, and user experience across all platforms.
## Architecture
### Library Selection: Ink (React for CLI)
**Primary Choice: Ink v4.x**
- **Rationale**: Ink is built on React principles, providing a modern component-based architecture
- **Windows Compatibility**: Excellent support for Windows Terminal, Command Prompt, and PowerShell
- **Performance**: Uses React's reconciliation for efficient updates, reducing flicker
- **Ecosystem**: Large ecosystem of pre-built components and utilities
- **Maintenance**: Actively maintained by Vercel with strong community support
**Alternative Considerations**:
- **Blessed**: Current library with Windows issues (being replaced)
- **Terminal-kit**: Good Windows support but more complex API
- **Enquirer**: Limited to prompts, not full TUI applications
- **Neo-blessed**: Fork of Blessed with some improvements but still has Windows issues
### Component Architecture
```
TuiApplication (Root)
├── AppProvider (Context/State Management)
├── Router (Screen Management)
├── StatusBar (Global Status)
└── Screens/
├── MainMenuScreen
├── ConfigurationScreen
├── OperationScreen
├── SchedulingScreen
├── LogViewerScreen
└── TagAnalysisScreen
```
### State Management
Using React Context API with custom hooks for:
- Application state (current screen, navigation history)
- Configuration state (environment variables, settings)
- Operation state (progress, results, errors)
- UI state (focus, selections, modal states)
## Components and Interfaces
### Core Components
#### 1. TuiApplication (Root Component)
```javascript
const TuiApplication = () => {
return (
<AppProvider>
<Box flexDirection="column" height="100%">
<StatusBar />
<Router />
</Box>
</AppProvider>
);
};
```
#### 2. AppProvider (State Management)
```javascript
const AppProvider = ({ children }) => {
const [appState, setAppState] = useState({
currentScreen: "main-menu",
navigationHistory: [],
configuration: {},
operationState: null,
});
return (
<AppContext.Provider value={{ appState, setAppState }}>
{children}
</AppContext.Provider>
);
};
```
#### 3. Router (Screen Management)
```javascript
const Router = () => {
const { appState } = useContext(AppContext);
const screens = {
"main-menu": MainMenuScreen,
configuration: ConfigurationScreen,
operation: OperationScreen,
scheduling: SchedulingScreen,
logs: LogViewerScreen,
"tag-analysis": TagAnalysisScreen,
};
const CurrentScreen = screens[appState.currentScreen];
return <CurrentScreen />;
};
```
#### 4. StatusBar (Global Status Display)
```javascript
const StatusBar = () => {
const { connectionStatus, operationProgress } = useAppState();
return (
<Box borderStyle="single" paddingX={1}>
<Text color="green"> Connected</Text>
<Text> | </Text>
<Text>Progress: {operationProgress}%</Text>
</Box>
);
};
```
### Screen Components
#### MainMenuScreen
- Navigation menu with keyboard shortcuts
- Current configuration summary
- Quick action buttons
- Help information
#### ConfigurationScreen
- Environment variable editor
- Input validation with real-time feedback
- API connection testing
- Save/cancel operations
#### OperationScreen
- Operation type selection (update/rollback)
- Real-time progress display
- Product processing information
- Error handling and display
#### SchedulingScreen
- Date/time picker interface
- Schedule management
- Countdown display
- Cancellation controls
#### LogViewerScreen
- Paginated log display
- Search and filtering
- Log entry details
- Export functionality
#### TagAnalysisScreen
- Tag listing and statistics
- Product count per tag
- Sample product display
- Recommendations
### Reusable UI Components
#### ProgressBar
```javascript
const ProgressBar = ({ progress, label, color = "blue" }) => {
const width = 40;
const filled = Math.round((progress / 100) * width);
return (
<Box flexDirection="column">
<Text>{label}</Text>
<Box>
<Text color={color}>{"█".repeat(filled)}</Text>
<Text color="gray">{"░".repeat(width - filled)}</Text>
<Text> {progress}%</Text>
</Box>
</Box>
);
};
```
#### InputField
```javascript
const InputField = ({ label, value, onChange, validation, placeholder }) => {
const [isValid, setIsValid] = useState(true);
return (
<Box flexDirection="column" marginY={1}>
<Text>{label}:</Text>
<TextInput
value={value}
onChange={(val) => {
onChange(val);
setIsValid(validation ? validation(val) : true);
}}
placeholder={placeholder}
/>
{!isValid && <Text color="red">Invalid input</Text>}
</Box>
);
};
```
#### MenuList
```javascript
const MenuList = ({ items, selectedIndex, onSelect }) => {
return (
<Box flexDirection="column">
{items.map((item, index) => (
<Box key={index} paddingX={2}>
<Text color={index === selectedIndex ? "blue" : "white"}>
{index === selectedIndex ? "► " : " "}
{item.label}
</Text>
</Box>
))}
</Box>
);
};
```
## Data Models
### Application State
```javascript
interface AppState {
currentScreen: string;
navigationHistory: string[];
configuration: ConfigurationState;
operationState: OperationState | null;
uiState: UIState;
}
interface ConfigurationState {
shopifyDomain: string;
accessToken: string;
targetTag: string;
priceAdjustment: number;
operationMode: "update" | "rollback";
isValid: boolean;
lastTested: Date | null;
}
interface OperationState {
type: "update" | "rollback" | "scheduled";
status: "idle" | "running" | "completed" | "error";
progress: number;
currentProduct: string | null;
results: OperationResults | null;
errors: Error[];
}
interface UIState {
focusedComponent: string;
modalOpen: boolean;
selectedMenuIndex: number;
scrollPosition: number;
}
```
### Service Integration
```javascript
interface ServiceIntegration {
shopifyService: ShopifyService;
productService: ProductService;
progressService: ProgressService;
configService: ConfigurationService;
}
```
## Error Handling
### Error Categories
1. **Configuration Errors**: Invalid environment variables, API credentials
2. **Network Errors**: Connection failures, timeout issues
3. **API Errors**: Shopify API rate limits, authentication failures
4. **UI Errors**: Component rendering issues, state inconsistencies
5. **System Errors**: File system access, permission issues
### Error Display Strategy
```javascript
const ErrorBoundary = ({ children }) => {
const [error, setError] = useState(null);
if (error) {
return (
<Box
flexDirection="column"
padding={2}
borderStyle="single"
borderColor="red"
>
<Text color="red" bold>
Error Occurred
</Text>
<Text>{error.message}</Text>
<Text color="gray">Press 'r' to retry or 'q' to quit</Text>
</Box>
);
}
return children;
};
```
### Graceful Degradation
- Fallback to basic text display if advanced features fail
- Automatic retry mechanisms for network operations
- State persistence to recover from crashes
- Clear error messages with suggested actions
## Testing Strategy
### Component Testing
```javascript
// Example test using Ink's testing utilities
import { render } from "ink-testing-library";
import { MainMenuScreen } from "../screens/MainMenuScreen";
test("renders main menu with correct options", () => {
const { lastFrame } = render(<MainMenuScreen />);
expect(lastFrame()).toContain("Price Update Operations");
expect(lastFrame()).toContain("Configuration");
expect(lastFrame()).toContain("View Logs");
});
```
### Integration Testing
- Test service integration with mock services
- Verify state management across screen transitions
- Test keyboard navigation and input handling
- Validate error handling scenarios
### Cross-Platform Testing
- Automated testing on Windows, macOS, and Linux
- Terminal compatibility testing (Windows Terminal, Command Prompt, PowerShell)
- Unicode and color support verification
- Performance testing with large datasets
## Migration Strategy
### Phase 1: Setup and Core Infrastructure
1. Install Ink and related dependencies
2. Create basic application structure
3. Implement state management system
4. Set up routing and navigation
### Phase 2: Screen Implementation
1. Implement MainMenuScreen (simplest)
2. Create ConfigurationScreen with form handling
3. Build OperationScreen with progress display
4. Add remaining screens (Scheduling, Logs, TagAnalysis)
### Phase 3: Component Migration
1. Replace Blessed ProgressBar with Ink version
2. Migrate form components and input handling
3. Update navigation and keyboard shortcuts
4. Implement error handling and validation
### Phase 4: Testing and Refinement
1. Comprehensive testing on Windows systems
2. Performance optimization and bug fixes
3. Documentation updates
4. Legacy code cleanup
### Dependency Changes
```json
{
"dependencies": {
"ink": "^4.4.1",
"react": "^18.2.0",
"@ink/text-input": "^5.0.1",
"@ink/select-input": "^5.0.1",
"@ink/spinner": "^5.0.1"
},
"devDependencies": {
"ink-testing-library": "^3.0.0"
}
}
```
### File Structure Changes
```
src/
├── tui/
│ ├── components/
│ │ ├── common/
│ │ │ ├── ProgressBar.jsx
│ │ │ ├── InputField.jsx
│ │ │ ├── MenuList.jsx
│ │ │ └── ErrorBoundary.jsx
│ │ ├── screens/
│ │ │ ├── MainMenuScreen.jsx
│ │ │ ├── ConfigurationScreen.jsx
│ │ │ ├── OperationScreen.jsx
│ │ │ ├── SchedulingScreen.jsx
│ │ │ ├── LogViewerScreen.jsx
│ │ │ └── TagAnalysisScreen.jsx
│ │ └── providers/
│ │ ├── AppProvider.jsx
│ │ └── ServiceProvider.jsx
│ ├── hooks/
│ │ ├── useAppState.js
│ │ ├── useNavigation.js
│ │ └── useServices.js
│ ├── utils/
│ │ ├── keyboardHandlers.js
│ │ └── validation.js
│ └── TuiApplication.jsx
└── tui-entry.js (new entry point)
```
## Performance Considerations
### Rendering Optimization
- Use React.memo for expensive components
- Implement virtual scrolling for large lists
- Debounce rapid state updates
- Minimize re-renders with proper state structure
### Memory Management
- Clean up event listeners and timers
- Implement proper component unmounting
- Use weak references for large data structures
- Monitor memory usage during long operations
### Windows-Specific Optimizations
- Use Windows-compatible Unicode characters
- Optimize for Windows Terminal performance
- Handle Windows-specific keyboard events
- Ensure proper color rendering in different terminals
## Security Considerations
### Input Validation
- Sanitize all user inputs
- Validate configuration values
- Prevent injection attacks through input fields
- Secure handling of API credentials
### State Security
- Encrypt sensitive data in state
- Clear sensitive information on exit
- Prevent credential logging
- Secure temporary file handling
This design provides a robust foundation for replacing Blessed with Ink, ensuring excellent Windows compatibility while maintaining all existing functionality and improving the overall user experience.

View File

@@ -0,0 +1,151 @@
# Requirements Document
## Introduction
This document outlines the requirements for replacing the existing Blessed-based Terminal User Interface (TUI) with a Windows-compatible alternative. The current TUI implementation using the Blessed library has compatibility issues on Windows systems, requiring a migration to a more robust, cross-platform TUI library that provides better Windows support while maintaining all existing functionality and user experience expectations.
## Requirements
### Requirement 1
**User Story:** As a Windows user, I want a TUI that works reliably on my system, so that I can use the interactive interface without compatibility issues.
#### Acceptance Criteria
1. WHEN the TUI is launched on Windows THEN the system SHALL display correctly without rendering artifacts
2. WHEN using Windows Terminal or Command Prompt THEN the system SHALL handle keyboard input properly
3. WHEN the interface renders THEN the system SHALL display Unicode characters and colors correctly on Windows
4. WHEN resizing the terminal window THEN the system SHALL adapt the layout appropriately
5. WHEN using different Windows terminal emulators THEN the system SHALL maintain consistent behavior
### Requirement 2
**User Story:** As a developer, I want to replace Blessed with a better cross-platform TUI library, so that the application works consistently across all operating systems.
#### Acceptance Criteria
1. WHEN selecting a replacement library THEN the system SHALL prioritize Windows compatibility
2. WHEN the new library is integrated THEN the system SHALL maintain feature parity with the Blessed implementation
3. WHEN the library is chosen THEN the system SHALL have active maintenance and good documentation
4. WHEN implementing the replacement THEN the system SHALL support modern terminal features
5. WHEN the migration is complete THEN the system SHALL remove all Blessed dependencies
### Requirement 3
**User Story:** As a user, I want the same TUI functionality after the library replacement, so that my workflow remains unchanged.
#### Acceptance Criteria
1. WHEN the new TUI loads THEN the system SHALL display the same main menu structure
2. WHEN navigating the interface THEN the system SHALL support the same keyboard shortcuts
3. WHEN configuring settings THEN the system SHALL provide the same configuration options
4. WHEN running operations THEN the system SHALL show the same progress indicators
5. WHEN viewing logs THEN the system SHALL display the same information format
### Requirement 4
**User Story:** As a user, I want improved performance and responsiveness in the new TUI, so that the interface feels more fluid and responsive.
#### Acceptance Criteria
1. WHEN the TUI starts THEN the system SHALL load faster than the Blessed version
2. WHEN updating progress displays THEN the system SHALL render smoothly without flickering
3. WHEN handling large amounts of log data THEN the system SHALL maintain responsive scrolling
4. WHEN switching between screens THEN the system SHALL transition quickly
5. WHEN processing user input THEN the system SHALL respond immediately
### Requirement 5
**User Story:** As a developer, I want the new TUI implementation to follow modern JavaScript patterns, so that the code is maintainable and extensible.
#### Acceptance Criteria
1. WHEN implementing components THEN the system SHALL use ES6+ features and modern patterns
2. WHEN structuring the code THEN the system SHALL follow the existing project architecture
3. WHEN handling state THEN the system SHALL use clear state management patterns
4. WHEN implementing event handling THEN the system SHALL use consistent event patterns
5. WHEN writing tests THEN the system SHALL provide good test coverage for TUI components
### Requirement 6
**User Story:** As a user, I want enhanced visual feedback and better error handling in the new TUI, so that I have a clearer understanding of system status.
#### Acceptance Criteria
1. WHEN errors occur THEN the system SHALL display more informative error messages
2. WHEN operations are running THEN the system SHALL provide clearer progress visualization
3. WHEN configuration is invalid THEN the system SHALL highlight specific issues
4. WHEN API calls fail THEN the system SHALL show detailed connection status
5. WHEN the system is busy THEN the system SHALL provide appropriate loading indicators
### Requirement 7
**User Story:** As a developer, I want the migration to preserve all existing service integrations, so that business logic remains unchanged.
#### Acceptance Criteria
1. WHEN the new TUI is implemented THEN the system SHALL reuse existing ShopifyService without changes
2. WHEN operations run THEN the system SHALL use existing ProductService and ProgressService
3. WHEN configuration is managed THEN the system SHALL use existing environment configuration
4. WHEN logs are generated THEN the system SHALL maintain compatibility with existing log formats
5. WHEN the migration is complete THEN the system SHALL pass all existing integration tests
### Requirement 8
**User Story:** As a user, I want better accessibility features in the new TUI, so that the interface is more inclusive and easier to use.
#### Acceptance Criteria
1. WHEN using screen readers THEN the system SHALL provide appropriate text descriptions
2. WHEN using high contrast mode THEN the system SHALL adapt color schemes appropriately
3. WHEN using keyboard-only navigation THEN the system SHALL provide clear focus indicators
4. WHEN text is displayed THEN the system SHALL support different font sizes and terminal settings
5. WHEN colors are used THEN the system SHALL ensure sufficient contrast ratios
### Requirement 9
**User Story:** As a developer, I want comprehensive documentation for the new TUI library choice, so that future maintenance is straightforward.
#### Acceptance Criteria
1. WHEN the library is selected THEN the system SHALL document the selection rationale
2. WHEN implementation patterns are established THEN the system SHALL document coding conventions
3. WHEN components are created THEN the system SHALL include inline documentation
4. WHEN the migration is complete THEN the system SHALL update all relevant README files
5. WHEN troubleshooting guides are needed THEN the system SHALL provide Windows-specific guidance
### Requirement 10
**User Story:** As a user, I want the new TUI to handle terminal resizing and different screen sizes better, so that I can use it on various display configurations.
#### Acceptance Criteria
1. WHEN the terminal is resized THEN the system SHALL automatically adjust layout proportions
2. WHEN using small terminal windows THEN the system SHALL provide appropriate scrolling
3. WHEN using large displays THEN the system SHALL utilize available space effectively
4. WHEN switching between portrait and landscape orientations THEN the system SHALL adapt accordingly
5. WHEN minimum size requirements aren't met THEN the system SHALL display helpful guidance
### Requirement 11
**User Story:** As a developer, I want a smooth migration path from Blessed to the new library, so that the transition minimizes disruption.
#### Acceptance Criteria
1. WHEN planning the migration THEN the system SHALL identify all Blessed-specific code
2. WHEN implementing replacements THEN the system SHALL maintain API compatibility where possible
3. WHEN testing the migration THEN the system SHALL verify functionality on multiple Windows versions
4. WHEN deploying the changes THEN the system SHALL provide fallback options if issues arise
5. WHEN the migration is complete THEN the system SHALL clean up all legacy Blessed code
### Requirement 12
**User Story:** As a user, I want the new TUI to support modern terminal features, so that I can take advantage of enhanced terminal capabilities.
#### Acceptance Criteria
1. WHEN using modern terminals THEN the system SHALL support true color (24-bit) display
2. WHEN terminals support it THEN the system SHALL use enhanced Unicode characters
3. WHEN available THEN the system SHALL support mouse interaction for navigation
4. WHEN terminals provide it THEN the system SHALL use improved cursor positioning
5. WHEN modern features are unavailable THEN the system SHALL gracefully degrade functionality

View File

@@ -0,0 +1,268 @@
# Implementation Plan
- [ ] 1. Setup Ink infrastructure and remove Blessed dependencies
- Remove blessed dependency from package.json and install Ink dependencies
- Create new TUI entry point file that initializes Ink application
- Set up basic React component structure with JSX support
- _Requirements: 2.2, 2.5_
- [ ] 2. Implement core application structure and state management
- Create AppProvider component with React Context for global state management
- Implement Router component for screen navigation and history management
- Create useAppState and useNavigation custom hooks for state access
- Write unit tests for state management and navigation logic
- _Requirements: 5.1, 5.3, 7.1_
- [ ] 3. Build reusable UI components
- [ ] 3.1 Create ProgressBar component with Ink
- Replace Blessed ProgressBar with Ink-based implementation using Box and Text components
- Add support for different colors, labels, and progress indicators
- Write unit tests for ProgressBar component rendering and updates
- _Requirements: 3.1, 4.2, 6.2_
- [ ] 3.2 Implement InputField component with validation
- Create InputField component using Ink's TextInput with validation support
- Add real-time validation feedback and error message display
- Write unit tests for input validation and error handling
- _Requirements: 3.2, 6.3, 8.3_
- [ ] 3.3 Create MenuList component for navigation
- Implement MenuList component with keyboard navigation support
- Add selection highlighting and keyboard shortcut display
- Write unit tests for menu navigation and selection handling
- _Requirements: 1.2, 9.3, 9.4_
- [ ] 3.4 Build ErrorBoundary component for error handling
- Create ErrorBoundary component to catch and display React errors gracefully
- Implement error recovery mechanisms and user-friendly error messages
- Write unit tests for error boundary functionality
- _Requirements: 6.1, 10.4, 11.4_
- [ ] 4. Implement StatusBar component
- Create StatusBar component showing connection status and operation progress
- Integrate with existing services to display real-time system status
- Add support for different status indicators and colors
- Write unit tests for status display and updates
- _Requirements: 8.1, 8.2, 8.3_
- [ ] 5. Create MainMenuScreen component
- Implement MainMenuScreen as the primary navigation interface
- Add keyboard shortcuts and menu options matching existing TUI requirements
- Integrate with navigation system for screen transitions
- Write unit tests for menu functionality and navigation
- _Requirements: 1.1, 1.3, 3.1, 9.1_
- [ ] 6. Build ConfigurationScreen component
- [ ] 6.1 Create configuration form interface
- Implement ConfigurationScreen with form fields for all environment variables
- Add input validation and real-time feedback for configuration values
- Write unit tests for form validation and state management
- _Requirements: 2.1, 2.2, 2.4_
- [ ] 6.2 Implement configuration persistence
- Add functionality to save configuration changes to .env file
- Implement configuration loading and validation on screen load
- Write unit tests for configuration file operations
- _Requirements: 2.3, 7.4, 11.4_
- [ ] 6.3 Add API connection testing
- Integrate Shopify API connection testing within configuration screen
- Display connection status and error messages for failed connections
- Write unit tests for API connection testing functionality
- _Requirements: 2.5, 6.4, 8.1_
- [ ] 7. Implement OperationScreen component
- [ ] 7.1 Create operation selection interface
- Build OperationScreen with update/rollback operation selection
- Display current configuration summary before operation execution
- Write unit tests for operation selection and configuration display
- _Requirements: 3.1, 4.1, 7.2_
- [ ] 7.2 Add real-time progress display
- Implement real-time progress indicators using ProgressBar component
- Display current product information and processing status
- Write unit tests for progress display and updates
- _Requirements: 3.2, 3.3, 4.2, 8.2_
- [ ] 7.3 Integrate operation results display
- Add results summary display for completed operations
- Implement error display panel for operation failures
- Write unit tests for results display and error handling
- _Requirements: 3.4, 3.5, 4.3, 6.1_
- [ ] 8. Build SchedulingScreen component
- [ ] 8.1 Create scheduling interface
- Implement SchedulingScreen with date/time picker functionality
- Add schedule management and countdown timer display
- Write unit tests for scheduling interface and timer functionality
- _Requirements: 5.1, 5.2, 5.3_
- [ ] 8.2 Add schedule cancellation and notifications
- Implement schedule cancellation with confirmation dialog
- Add visual notifications for approaching scheduled operations
- Write unit tests for cancellation and notification systems
- _Requirements: 5.4, 5.5_
- [ ] 9. Create LogViewerScreen component
- [ ] 9.1 Implement log display with pagination
- Build LogViewerScreen with paginated log entry display
- Add scrolling support for large log files
- Write unit tests for log display and pagination
- _Requirements: 6.1, 6.4, 10.3_
- [ ] 9.2 Add log filtering and search functionality
- Implement search and filtering capabilities for log entries
- Add detailed view for selected log entries
- Write unit tests for search and filtering functionality
- _Requirements: 6.2, 6.3_
- [ ] 9.3 Integrate automatic log refresh
- Add automatic refresh functionality for active log monitoring
- Implement efficient update mechanisms to avoid performance issues
- Write unit tests for automatic refresh and performance
- _Requirements: 6.5, 4.3_
- [ ] 10. Build TagAnalysisScreen component
- [ ] 10.1 Create tag analysis interface
- Implement TagAnalysisScreen displaying available product tags and counts
- Add sample product display for selected tags
- Write unit tests for tag analysis display and selection
- _Requirements: 7.1, 7.2, 7.3_
- [ ] 10.2 Add tag recommendations
- Implement recommendation system for optimal target tags
- Display analysis results and suggestions to users
- Write unit tests for recommendation logic and display
- _Requirements: 7.4_
- [ ] 11. Implement keyboard navigation and shortcuts
- [ ] 11.1 Add global keyboard handlers
- Create keyboard event handlers for navigation and shortcuts
- Implement consistent back/exit functionality across all screens
- Write unit tests for keyboard navigation and event handling
- _Requirements: 9.1, 9.3, 9.4_
- [ ] 11.2 Create help system
- Implement help overlay displaying available shortcuts and navigation
- Add context-sensitive help for different screens
- Write unit tests for help system functionality
- _Requirements: 9.2, 9.5_
- [ ] 12. Integrate with existing services
- [ ] 12.1 Connect TUI to ShopifyService
- Integrate TUI components with existing ShopifyService for API operations
- Ensure all API calls use existing service methods without modification
- Write integration tests for service connectivity
- _Requirements: 7.1, 12.1_
- [ ] 12.2 Connect TUI to ProductService and ProgressService
- Integrate TUI with existing ProductService for product operations
- Connect ProgressService for logging and progress tracking
- Write integration tests for service integration
- _Requirements: 7.2, 12.2, 12.3_
- [ ] 12.3 Maintain CLI compatibility
- Ensure TUI implementation doesn't break existing CLI functionality
- Verify that both interfaces can coexist and use same configuration
- Write integration tests for CLI/TUI compatibility
- _Requirements: 12.3, 12.4_
- [ ] 13. Implement responsive layout and terminal handling
- [ ] 13.1 Add terminal resize handling
- Implement automatic layout adjustment for terminal resize events
- Add minimum size requirements and appropriate messaging
- Write unit tests for resize handling and layout adaptation
- _Requirements: 10.1, 10.2, 10.5_
- [ ] 13.2 Optimize for different screen sizes
- Implement responsive design for small and large terminal windows
- Add scrolling support where needed for content overflow
- Write unit tests for different screen size scenarios
- _Requirements: 10.2, 10.3, 10.4_
- [ ] 14. Add accessibility and modern terminal features
- [ ] 14.1 Implement accessibility features
- Add screen reader support and high contrast mode compatibility
- Implement clear focus indicators for keyboard navigation
- Write tests for accessibility features
- _Requirements: 8.1, 8.2, 8.3_
- [ ] 14.2 Add modern terminal feature support
- Implement true color support and enhanced Unicode character usage
- Add mouse interaction support where appropriate
- Write tests for modern terminal feature detection and usage
- _Requirements: 12.1, 12.2, 12.3_
- [ ] 15. Performance optimization and testing
- [ ] 15.1 Optimize rendering performance
- Implement React.memo for expensive components and virtual scrolling for large lists
- Add debouncing for rapid state updates and minimize unnecessary re-renders
- Write performance tests and benchmarks
- _Requirements: 4.1, 4.3, 4.4_
- [ ] 15.2 Add memory management
- Implement proper cleanup for event listeners and timers
- Add memory usage monitoring for long-running operations
- Write tests for memory leak detection and cleanup
- _Requirements: 4.2, 4.5_
- [ ] 16. Cross-platform testing and Windows optimization
- [ ] 16.1 Test Windows compatibility
- Run comprehensive tests on Windows Terminal, Command Prompt, and PowerShell
- Verify Unicode character rendering and color support on Windows
- Write Windows-specific integration tests
- _Requirements: 1.1, 1.2, 1.3, 1.4_
- [ ] 16.2 Optimize for Windows performance
- Implement Windows-specific optimizations for terminal rendering
- Add Windows-specific keyboard event handling
- Write performance tests specifically for Windows environments
- _Requirements: 1.5, 4.4_
- [ ] 17. Documentation and migration cleanup
- [ ] 17.1 Update documentation
- Update README files with new TUI library information and setup instructions
- Document new component architecture and development patterns
- Create troubleshooting guide for Windows-specific issues
- _Requirements: 9.1, 9.2, 9.4_
- [ ] 17.2 Clean up legacy Blessed code
- Remove all Blessed dependencies and related code files
- Clean up any remaining references to Blessed in documentation
- Verify complete migration through final testing
- _Requirements: 2.5, 11.5_

2042
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -5,6 +5,7 @@
"main": "src/index.js",
"scripts": {
"start": "node src/index.js",
"tui": "node src/tui-entry.js",
"update": "set OPERATION_MODE=update && node src/index.js",
"rollback": "set OPERATION_MODE=rollback && node src/index.js",
"schedule-update": "set OPERATION_MODE=update && node src/index.js",
@@ -23,10 +24,18 @@
"dependencies": {
"@shopify/shopify-api": "^7.7.0",
"dotenv": "^16.3.1",
"node-fetch": "^3.3.2"
"node-fetch": "^3.3.2",
"ink": "^3.2.0",
"react": "^17.0.2",
"ink-text-input": "^4.0.3",
"ink-select-input": "^4.2.2",
"ink-spinner": "^4.0.3"
},
"devDependencies": {
"jest": "^29.7.0"
"jest": "^29.7.0",
"ink-testing-library": "^2.1.0",
"@babel/preset-react": "^7.22.0",
"@babel/preset-env": "^7.22.0"
},
"engines": {
"node": ">=16.0.0"

44
src/tui-entry.js Normal file
View File

@@ -0,0 +1,44 @@
#!/usr/bin/env node
/**
* TUI Entry Point
* Initializes the Ink-based Terminal User Interface
* Requirements: 2.2, 2.5
*/
const React = require("react");
const { render } = require("ink");
const TuiApplication = require("./tui/TuiApplication.jsx");
// Initialize the TUI application
const main = () => {
try {
// Render the main TUI application
const { waitUntilExit } = render(React.createElement(TuiApplication));
// Wait for the application to exit
return waitUntilExit();
} catch (error) {
console.error("Failed to start TUI application:", error);
process.exit(1);
}
};
// Handle process signals gracefully
process.on("SIGINT", () => {
process.exit(0);
});
process.on("SIGTERM", () => {
process.exit(0);
});
// Start the application
if (require.main === module) {
main().catch((error) => {
console.error("TUI application error:", error);
process.exit(1);
});
}
module.exports = main;

View File

@@ -0,0 +1,25 @@
const React = require("react");
const { Box, Text } = require("ink");
const AppProvider = require("./providers/AppProvider");
const Router = require("./components/Router");
const StatusBar = require("./components/StatusBar");
/**
* Main TUI Application Component
* Root component that sets up the application structure
* Requirements: 2.2, 2.5
*/
const TuiApplication = () => {
return React.createElement(
AppProvider,
null,
React.createElement(
Box,
{ flexDirection: "column", height: "100%" },
React.createElement(StatusBar),
React.createElement(Router)
)
);
};
module.exports = TuiApplication;

View File

@@ -0,0 +1,71 @@
const React = require("react");
const { Box, Text } = require("ink");
const { useAppState } = require("../providers/AppProvider");
// Import screen components (will be created in later tasks)
// const MainMenuScreen = require('./screens/MainMenuScreen');
// const ConfigurationScreen = require('./screens/ConfigurationScreen');
// const OperationScreen = require('./screens/OperationScreen');
// const SchedulingScreen = require('./screens/SchedulingScreen');
// const LogViewerScreen = require('./screens/LogViewerScreen');
// const TagAnalysisScreen = require('./screens/TagAnalysisScreen');
/**
* Router Component
* Manages screen navigation and renders the current screen
* Requirements: 5.1, 5.3, 7.1
*/
const Router = () => {
const { appState } = useAppState();
// Temporary placeholder screens until actual screens are implemented
const screens = {
"main-menu": () =>
React.createElement(
Box,
{ padding: 2 },
React.createElement(Text, null, "Main Menu Screen - Coming Soon")
),
configuration: () =>
React.createElement(
Box,
{ padding: 2 },
React.createElement(Text, null, "Configuration Screen - Coming Soon")
),
operation: () =>
React.createElement(
Box,
{ padding: 2 },
React.createElement(Text, null, "Operation Screen - Coming Soon")
),
scheduling: () =>
React.createElement(
Box,
{ padding: 2 },
React.createElement(Text, null, "Scheduling Screen - Coming Soon")
),
logs: () =>
React.createElement(
Box,
{ padding: 2 },
React.createElement(Text, null, "Log Viewer Screen - Coming Soon")
),
"tag-analysis": () =>
React.createElement(
Box,
{ padding: 2 },
React.createElement(Text, null, "Tag Analysis Screen - Coming Soon")
),
};
// Get the current screen component
const CurrentScreen = screens[appState.currentScreen] || screens["main-menu"];
return React.createElement(
Box,
{ flexGrow: 1 },
React.createElement(CurrentScreen)
);
};
module.exports = Router;

View File

@@ -0,0 +1,56 @@
const React = require("react");
const { Box, Text } = require("ink");
const { useAppState } = require("../providers/AppProvider");
/**
* StatusBar Component
* Displays global status information at the top of the application
* Requirements: 8.1, 8.2, 8.3
*/
const StatusBar = () => {
const { appState } = useAppState();
// Get connection status (placeholder for now)
const connectionStatus = "Connected"; // Will be dynamic later
const connectionColor = "green";
// Get operation progress
const operationProgress = appState.operationState?.progress || 0;
// Get current screen name for display
const screenNames = {
"main-menu": "Main Menu",
configuration: "Configuration",
operation: "Operation",
scheduling: "Scheduling",
logs: "Logs",
"tag-analysis": "Tag Analysis",
};
const currentScreenName = screenNames[appState.currentScreen] || "Unknown";
return React.createElement(
Box,
{
borderStyle: "single",
paddingX: 1,
justifyContent: "space-between",
},
React.createElement(
Box,
null,
React.createElement(Text, { color: connectionColor }, "● "),
React.createElement(Text, null, connectionStatus),
React.createElement(Text, null, " | "),
React.createElement(Text, null, `Screen: ${currentScreenName}`)
),
React.createElement(
Box,
null,
appState.operationState &&
React.createElement(Text, null, `Progress: ${operationProgress}%`)
)
);
};
module.exports = StatusBar;

View File

@@ -0,0 +1,137 @@
const React = require("react");
const { useState, createContext, useContext } = React;
/**
* Application Context for global state management
* Requirements: 5.1, 5.3, 7.1
*/
const AppContext = createContext();
/**
* Initial application state
*/
const initialState = {
currentScreen: "main-menu",
navigationHistory: [],
configuration: {
shopifyDomain: "",
accessToken: "",
targetTag: "",
priceAdjustment: 0,
operationMode: "update",
isValid: false,
lastTested: null,
},
operationState: null,
uiState: {
focusedComponent: "menu",
modalOpen: false,
selectedMenuIndex: 0,
scrollPosition: 0,
},
};
/**
* AppProvider Component
* Provides global state management using React Context
*/
const AppProvider = ({ children }) => {
const [appState, setAppState] = useState(initialState);
/**
* Navigate to a new screen
*/
const navigateTo = (screen) => {
setAppState((prevState) => ({
...prevState,
navigationHistory: [
...prevState.navigationHistory,
prevState.currentScreen,
],
currentScreen: screen,
}));
};
/**
* Navigate back to previous screen
*/
const navigateBack = () => {
setAppState((prevState) => {
const history = [...prevState.navigationHistory];
const previousScreen = history.pop() || "main-menu";
return {
...prevState,
currentScreen: previousScreen,
navigationHistory: history,
};
});
};
/**
* Update configuration
*/
const updateConfiguration = (updates) => {
setAppState((prevState) => ({
...prevState,
configuration: {
...prevState.configuration,
...updates,
},
}));
};
/**
* Update operation state
*/
const updateOperationState = (operationState) => {
setAppState((prevState) => ({
...prevState,
operationState,
}));
};
/**
* Update UI state
*/
const updateUIState = (updates) => {
setAppState((prevState) => ({
...prevState,
uiState: {
...prevState.uiState,
...updates,
},
}));
};
const contextValue = {
appState,
setAppState,
navigateTo,
navigateBack,
updateConfiguration,
updateOperationState,
updateUIState,
};
return React.createElement(
AppContext.Provider,
{ value: contextValue },
children
);
};
/**
* Custom hook to use app context
*/
const useAppState = () => {
const context = useContext(AppContext);
if (!context) {
throw new Error("useAppState must be used within an AppProvider");
}
return context;
};
module.exports = AppProvider;
module.exports.useAppState = useAppState;
module.exports.AppContext = AppContext;