Architecture Overview - Kyzael/BitCrafty GitHub Wiki

BitCrafty Architecture Overview

BitCrafty is a vanilla JavaScript web application built with modern ES6+ modules, event-driven architecture, and zero build dependencies. The application runs entirely client-side and emphasizes maintainability, testability, and performance.

๐Ÿ—๏ธ Core Architecture Principles

Event-Driven Communication

  • Decoupled Components: All components communicate via window.addEventListener() and window.dispatchEvent()
  • No Direct Function Calls: Components never directly call each other's methods
  • Custom Events: Rich event payload system for passing data between components
  • Loose Coupling: Easy to add, remove, or modify components without breaking others

Component-Based Modularity

  • Single Responsibility: Each component has one clear, focused purpose
  • Initialization Pattern: All components export an initialize() function
  • State Management: Centralized state via Zustand with component-specific helpers
  • Clean Interfaces: Components expose minimal, well-defined APIs

Testing-First Quality Assurance

  • Node.js Native Test Runner: Zero-dependency testing with node --test
  • Architectural Compliance: Tests verify component patterns and standards
  • Data Integrity: Comprehensive validation of JSON data relationships
  • CI/CD Integration: Automated testing via GitHub Actions

๐ŸŽจ Design Philosophy

Accessibility Principles

  • High contrast text and UI elements
  • Colorblind-safe profession color assignments
  • Keyboard navigation for all interactive elements

๐Ÿง  Modern State Management

  • Zustand for predictable state management
  • Normalized data structure with O(1) lookups
  • Async data loading with graceful error handling
  • Persistent queue state across sessions

๐Ÿ“Š Visualization Engine

  • vis-network for graph rendering
  • Custom node styling with profession-specific colors
  • Edge highlighting for input/output relationships
  • Performance optimizations for large datasets

๐Ÿ“ Project Structure & Organization

BitCrafty follows a strict modular architecture with clear separation of concerns:

BitCrafty/
โ”œโ”€โ”€ index.html                 # Application entry point (HTML)
โ”œโ”€โ”€ main.js                    # JavaScript application bootstrap
โ”œโ”€โ”€ package.json              # Project metadata and scripts
โ”œโ”€โ”€ style.css                 # Global styles and Monokai theme
โ”œโ”€โ”€ lib/                      # Shared utilities and patterns
โ”‚   โ”œโ”€โ”€ common.js             # Constants, DOM helpers, utilities
โ”‚   โ””โ”€โ”€ store-helpers.js      # Zustand store access patterns
โ”œโ”€โ”€ components/               # Feature-focused modules
โ”‚   โ”œโ”€โ”€ ui.js                 # Sidebar, search, item details
โ”‚   โ”œโ”€โ”€ graph.js              # Network visualization engine
โ”‚   โ”œโ”€โ”€ crafting.js           # Queue management, resource calculation
โ”‚   โ””โ”€โ”€ filters.js            # Profession and dependency filtering
โ”œโ”€โ”€ data/                     # Normalized JSON data files
โ”‚   โ”œโ”€โ”€ items.json            # Game items
โ”‚   โ”œโ”€โ”€ crafts.json           # Crafting recipes
โ”‚   โ”œโ”€โ”€ requirements.json     # Tool/profession requirements
โ”‚   โ””โ”€โ”€ metadata/             # Reference data
โ”‚       โ”œโ”€โ”€ professions.json  # Profession definitions with colors
โ”‚       โ”œโ”€โ”€ tools.json        # Available tools metadata
โ”‚       โ””โ”€โ”€ buildings.json    # Building definitions
โ”œโ”€โ”€ tests/                    # Comprehensive test suite
โ”‚   โ”œโ”€โ”€ components/           # Component unit tests
โ”‚   โ”œโ”€โ”€ lib/                  # Library unit tests
โ”‚   โ”œโ”€โ”€ data-validation.test.js # JSON data integrity validation
โ”‚   โ””โ”€โ”€ package.json          # Test-specific configuration
โ””โ”€โ”€ .github/workflows/        # CI/CD automation
    โ”œโ”€โ”€ unit-tests.yml        # Component/library testing
    โ””โ”€โ”€ data-validation.yml   # Data integrity validation

Key Organizational Principles

  • Initialization Order: main.js imports and initializes components in dependency order
  • Shared Libraries: Common utilities in lib/ prevent code duplication
  • Component Isolation: Each component in components/ is self-contained
  • Data Normalization: JSON files use consistent ID patterns and validation
  • Test Structure: Tests mirror source structure for easy maintenance
  • Zero Build Dependencies: Direct ES6 module imports, no bundling required

๏ฟฝ Data Structure & Management

BitCrafty uses a normalized, modular data architecture with globally unique namespaced IDs for all entities. This approach ensures data integrity, enables efficient lookups, and supports scalable development.

Data Organization

/data
  items.json              โ† Core game items (58 items)
  crafts.json             โ† All crafting recipes (38 crafts)
  requirements.json       โ† Tool/profession/building requirements (14 requirements)
  metadata/
    professions.json      โ† Profession definitions with colors (10 professions)
    tools.json            โ† Available tools metadata
    buildings.json        โ† Building definitions

ID Format Standard

All entities use the pattern: [entity-type]:[category]:[identifier]

Examples:

  • Items: item:farming:embergrain, item:tailoring:cloth-tarp
  • Crafts: craft:cooking:berry-pie, craft:forestry:wood-log
  • Requirements: requirement:tailoring:basic-loom, requirement:fishing:basic-tools
  • Professions: profession:tailoring, profession:cooking

Key Benefits

  • O(1) lookups using normalized Record<string, Entity> maps
  • Globally unique IDs prevent collisions and enable data merging
  • Human-readable identifiers for debugging and development
  • Graph-compatible IDs work seamlessly with vis-network
  • Validation-ready structure supports comprehensive data integrity testing

For complete data format specifications, see the Data Directory README

๐Ÿงช Testing Architecture

BitCrafty implements a comprehensive testing strategy using Node.js native test runner with zero external dependencies.

Test Categories

1. Unit Tests (Architecture Compliance)

  • Component Loading: Verify all components load without syntax errors
  • Export Validation: Ensure components export required initialize() function
  • Pattern Compliance: Validate event-driven communication usage
  • Dependency Checking: Verify proper imports from lib/common.js

2. Data Validation Tests

  • Reference Integrity: All entity IDs referenced in crafts/requirements exist
  • ID Format Validation: Entity IDs follow type:profession:identifier pattern
  • Profession Mapping: All professions exist in metadata
  • Orphaned Data Detection: Find unused requirements or broken references

Test Commands & Automation

npm test              # All tests (25 total: 24 unit + 1 data validation)
npm run test:unit     # Unit tests only (24 tests across 6 suites)
npm run validate      # Data validation only (with detailed tables)

GitHub Actions Integration

  • Unit Tests Workflow: Triggers on components/, lib/, or tests/ changes
  • Data Validation Workflow: Triggers on data/ or tests/ changes
  • Native Test Reporting: GitHub automatically displays Node.js test results
  • PR Blocking: All tests must pass before merge approval

Test Philosophy

Tests focus on architectural compliance and data integrity rather than implementation details, making them robust against refactoring while ensuring consistency with coding standards.

๐Ÿ”„ Component Communication Flow

BitCrafty uses a pure event-driven architecture with no direct component coupling:

Event Flow Patterns

  1. User Interaction โ†’ Component handles DOM event
  2. Component Logic โ†’ Updates Zustand store via helpers
  3. State Change โ†’ Component dispatches custom window event
  4. Other Components โ†’ Listen for relevant events and react
  5. UI Updates โ†’ Components update their DOM directly

Example: Item Selection Flow

// 1. User clicks item in UI component
ui.js: handleItemClick() โ†’ store.setSelectedItem()

// 2. UI dispatches selection event  
ui.js: window.dispatchEvent(new CustomEvent('item-selected', {detail: {itemId}}))

// 3. Graph component listens and reacts
graph.js: window.addEventListener('item-selected', highlightItemInGraph)

// 4. Crafting component listens and reacts  
crafting.js: window.addEventListener('item-selected', showCraftingOptions)

Benefits of Event-Driven Design

  • Zero Coupling: Components can be developed, tested, and modified independently
  • Easy Extension: New components just need to listen for relevant events
  • Debugging: Event flow is transparent and easily traceable
  • Testing: Components can be tested in isolation with mock events

๐Ÿ› ๏ธ Development Workflow

Getting Started

git clone https://github.com/Kyzael/BitCrafty.git
cd BitCrafty
npm start              # Starts Python web server on localhost:8000

Development Process

  1. Review Standards: Read .github/instructions/coding_standards.instructions.md
  2. Follow Patterns: Study existing component structure and event usage
  3. Test Changes: Run npm test after modifications
  4. Validate Data: Use npm run validate when modifying JSON files
  5. CI/CD: GitHub Actions automatically test PRs

Adding New Components

// components/new-feature.js
export function initialize() {
  // Setup event listeners
  window.addEventListener('relevant-event', handleEvent);
  
  // Initialize component state
  setupComponentUI();
}

function handleEvent(event) {
  // Process event, update store
  // Dispatch new events for other components
}

๐Ÿ”ง Technical Implementation Details

State Management Pattern

  • Single Store: Zustand provides centralized state with minimal boilerplate
  • Helper Functions: store-helpers.js provides component-specific data access
  • Reactive Updates: Components listen for state changes via events
  • Persistence: Critical state (like crafting queue) persists across sessions

Performance Optimizations

  • Normalized Data: O(1) entity lookups using Record<string, Entity> maps
  • Lazy Loading: Components initialize only when needed
  • Event Throttling: Prevent excessive UI updates during rapid interactions
  • Graph Optimization: vis-network configured for smooth rendering with large datasets

Browser Compatibility

  • ES6+ Modules: Requires modern browsers with native module support
  • No Transpilation: Direct browser execution without build steps
  • CDN Dependencies: Zustand and vis-network loaded from reliable CDNs
  • Fallback Handling: Graceful degradation for unsupported features

Security Considerations

  • Client-Side Only: No server communication, all data is static JSON
  • No User Data: Application doesn't collect or store personal information
  • Content Security: Minimal external dependencies reduce attack surface
  • HTTPS Deployment: Recommended for production deployments

๐Ÿ“š Related Documentation

This architecture enables rapid development, easy maintenance, and reliable testing while keeping the codebase simple and accessible to contributors of all skill levels.