Files
PriceUpdaterAppv2/docs/tui-guide.md

13 KiB

Terminal User Interface (TUI) Guide

Overview

The Shopify Price Updater includes a modern Terminal User Interface (TUI) built with Ink (React for CLI) that provides an interactive, user-friendly way to manage price updates. The TUI is optimized for cross-platform compatibility, with special attention to Windows terminal environments.

Getting Started

Launch the TUI

npm run tui

System Requirements

  • Node.js 16 or higher
  • Modern terminal with Unicode support
  • Recommended terminals:
    • Windows: Windows Terminal, PowerShell 7+
    • macOS: iTerm2, Terminal.app
    • Linux: GNOME Terminal, Konsole, Alacritty

Interface Overview

Main Menu

The main menu serves as the central navigation hub:

┌─ Shopify Price Updater ─────────────────────────┐
│                                                 │
│  ► Configuration                            [C] │
│    Operations                               [O] │
│    Scheduling                               [S] │
│    View Logs                                [L] │
│    Tag Analysis                             [T] │
│    Exit                                     [Q] │
│                                                 │
└─────────────────────────────────────────────────┘

Navigation:

  • Use arrow keys to navigate
  • Press Enter to select
  • Use keyboard shortcuts (letters in brackets)
  • Press 'q' or Escape to exit

Status Bar

The status bar displays real-time information:

● Connected | Store: your-store.myshopify.com | Progress: 45%

Indicators:

  • ● Connected: API connection status (green = connected, red = disconnected)
  • Store: Current Shopify store domain
  • Progress: Current operation progress percentage

Screen Components

Configuration Screen

Interactive form for managing environment settings:

┌─ Configuration ─────────────────────────────────┐
│                                                 │
│  Shopify Domain: [your-store.myshopify.com   ] │
│  Access Token:   [shpat_*********************] │
│  Target Tag:     [sale                       ] │
│  Price Adjust:   [10                         ]% │
│  Operation Mode: ► Update                       │
│                    Rollback                     │
│                                                 │
│  [Test Connection] [Save] [Cancel]              │
│                                                 │
└─────────────────────────────────────────────────┘

Features:

  • Real-time input validation
  • Secure token display (masked)
  • Connection testing
  • Configuration persistence

Operation Screen

Live progress tracking during price updates:

┌─ Price Update Operation ────────────────────────┐
│                                                 │
│  Target Tag: sale                               │
│  Operation: Update prices by +10%              │
│                                                 │
│  Progress: ████████████░░░░░░░░ 60% (15/25)     │
│                                                 │
│  Current Product: "Awesome T-Shirt"            │
│  Price: $19.99 → $21.99                        │
│                                                 │
│  ✅ Completed: 14                               │
│  ⚠️  Skipped: 1                                 │
│  ❌ Errors: 0                                   │
│                                                 │
└─────────────────────────────────────────────────┘

Features:

  • Real-time progress visualization
  • Current product information
  • Success/error counters
  • Detailed operation status

Scheduling Screen

Date/time picker for automated operations:

┌─ Schedule Operation ────────────────────────────┐
│                                                 │
│  Operation Type: ► Price Update                 │
│                    Price Rollback               │
│                                                 │
│  Schedule Date: [2024-12-25]                    │
│  Schedule Time: [10:30:00]                      │
│  Timezone:      [EST (-05:00)]                  │
│                                                 │
│  Countdown: 2 days, 14 hours, 23 minutes       │
│                                                 │
│  [Schedule] [Cancel Schedule] [Back]            │
│                                                 │
└─────────────────────────────────────────────────┘

Features:

  • Date/time picker interface
  • Timezone selection
  • Live countdown display
  • Schedule management

Log Viewer Screen

Paginated log display with search capabilities:

┌─ Log Viewer ────────────────────────────────────┐
│                                                 │
│  Search: [error                              ] 🔍│
│                                                 │
│  2024-01-15 10:30:15 | INFO  | Operation start │
│  2024-01-15 10:30:16 | INFO  | Found 25 prods  │
│  2024-01-15 10:30:17 | ERROR | API rate limit  │
│  2024-01-15 10:30:20 | INFO  | Retrying...     │
│  2024-01-15 10:30:21 | INFO  | Update success  │
│                                                 │
│  Page 1 of 5 | Showing 5 of 23 entries         │
│  [Previous] [Next] [Export] [Clear] [Back]     │
│                                                 │
└─────────────────────────────────────────────────┘

Features:

  • Real-time search and filtering
  • Pagination for large log files
  • Log level filtering (INFO, WARN, ERROR)
  • Export functionality

Tag Analysis Screen

Product tag statistics and recommendations:

┌─ Tag Analysis ──────────────────────────────────┐
│                                                 │
│  Available Tags:                                │
│                                                 │
│  ► sale          (25 products)                  │
│    clearance     (12 products)                  │
│    seasonal      (8 products)                   │
│    new-arrival   (15 products)                  │
│    featured      (6 products)                   │
│                                                 │
│  Sample Products for "sale":                    │
│  • Awesome T-Shirt ($19.99)                    │
│  • Cool Hoodie ($39.99)                        │
│  • Nice Jeans ($49.99)                         │
│                                                 │
│  [Analyze] [Refresh] [Back]                     │
│                                                 │
└─────────────────────────────────────────────────┘

Features:

  • Tag statistics and product counts
  • Sample product display
  • Tag recommendations
  • Real-time analysis

Component Architecture

Core Components

TuiApplication

Main application component that orchestrates the entire interface:

const TuiApplication = () => {
	return (
		<AppProvider>
			<Box flexDirection="column" height="100%">
				<StatusBar />
				<Router />
			</Box>
		</AppProvider>
	);
};

AppProvider

State management using React Context:

const AppProvider = ({ children }) => {
	const [appState, setAppState] = useState({
		currentScreen: "main-menu",
		configuration: {},
		operationState: null,
	});

	return (
		<AppContext.Provider value={{ appState, setAppState }}>
			{children}
		</AppContext.Provider>
	);
};

Reusable Components

ProgressBar

Visual progress indicator with customizable styling:

<ProgressBar progress={60} label="Processing products" color="blue" />

InputField

Form input with validation:

<InputField
	label="Target Tag"
	value={tag}
	onChange={setTag}
	validation={validateTag}
	placeholder="Enter product tag"
/>

MenuList

Keyboard-navigable menu:

<MenuList
	items={menuItems}
	selectedIndex={selectedIndex}
	onSelect={handleSelect}
/>

Custom Hooks

useAppState

Access and modify application state:

const { appState, setAppState } = useAppState();

useNavigation

Handle screen navigation:

const { navigateTo, goBack } = useNavigation();

useServices

Access service layer:

const { shopifyService, productService } = useServices();

Windows Compatibility

Optimizations

The TUI includes specific optimizations for Windows environments:

  • Unicode Support: Enhanced character rendering for Windows terminals
  • Color Compatibility: Fallback color schemes for older terminals
  • Keyboard Handling: Windows-specific key event processing
  • Performance: Optimized rendering for Windows Terminal

Supported Windows Terminals

  • Windows Terminal (recommended): Full feature support
  • PowerShell 7+: Good compatibility with modern features
  • Command Prompt: Basic functionality with graceful degradation
  • PowerShell 5.1: Limited color support, core features work

Troubleshooting Windows Issues

Unicode Characters Not Displaying

# Set console to UTF-8
chcp 65001
npm run tui

Colors Not Working

The TUI automatically detects color support and falls back to monochrome when needed.

Keyboard Issues

Ensure your terminal supports modern key sequences. Windows Terminal provides the best experience.

Performance Features

Memory Management

  • Component Memoization: React.memo for expensive components
  • Virtual Scrolling: Efficient handling of large lists
  • Cleanup: Automatic cleanup of event listeners and timers
  • Memory Monitoring: Built-in memory usage tracking

Rendering Optimization

  • Debounced Updates: Prevents excessive re-renders
  • Selective Updates: Only updates changed components
  • Efficient State: Optimized state structure for performance

Accessibility

Screen Reader Support

  • Semantic component structure
  • ARIA labels and descriptions
  • Keyboard-only navigation
  • Clear focus indicators

High Contrast Mode

  • Automatic detection of system preferences
  • Enhanced color contrast ratios
  • Alternative visual indicators

Keyboard Navigation

All functionality is accessible via keyboard:

  • Tab/Shift+Tab: Navigate between elements
  • Arrow Keys: Navigate lists and menus
  • Enter/Space: Activate buttons and selections
  • Escape: Cancel or go back
  • Ctrl+C: Exit application

Development Patterns

Component Structure

const MyComponent = ({ prop1, prop2 }) => {
	const [state, setState] = useState(initialState);
	const { appState } = useAppState();

	useEffect(() => {
		// Setup and cleanup
		return () => {
			// Cleanup
		};
	}, []);

	return <Box>{/* Component JSX */}</Box>;
};

Error Handling

const ErrorBoundary = ({ children }) => {
	const [error, setError] = useState(null);

	if (error) {
		return (
			<Box borderStyle="single" borderColor="red">
				<Text color="red">Error: {error.message}</Text>
				<Text>Press 'r' to retry or 'q' to quit</Text>
			</Box>
		);
	}

	return children;
};

Testing Components

import { render } from "ink-testing-library";
import MyComponent from "../MyComponent";

test("renders correctly", () => {
	const { lastFrame } = render(<MyComponent />);
	expect(lastFrame()).toContain("Expected text");
});

Best Practices

State Management

  • Use React Context for global state
  • Keep component state local when possible
  • Implement proper cleanup in useEffect

Performance

  • Use React.memo for expensive components
  • Implement virtual scrolling for large lists
  • Debounce rapid state updates

Error Handling

  • Implement error boundaries
  • Provide clear error messages
  • Include recovery mechanisms

Accessibility

  • Ensure keyboard navigation works
  • Provide clear focus indicators
  • Support screen readers

Migration from Blessed

The TUI was migrated from Blessed to Ink for better Windows compatibility:

Key Improvements

  • Better Windows Support: Native Windows terminal compatibility
  • Modern Architecture: React-based component system
  • Performance: Reduced flickering and improved rendering
  • Maintainability: Modern JavaScript patterns and testing

Breaking Changes

  • Component API changed from Blessed widgets to React components
  • Event handling updated to React patterns
  • State management moved to React Context

Migration Benefits

  • Improved cross-platform compatibility
  • Better development experience
  • Enhanced testing capabilities
  • Modern UI patterns and components