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()
andwindow.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/
, ortests/
changes - Data Validation Workflow: Triggers on
data/
ortests/
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
- User Interaction โ Component handles DOM event
- Component Logic โ Updates Zustand store via helpers
- State Change โ Component dispatches custom window event
- Other Components โ Listen for relevant events and react
- 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
- Review Standards: Read
.github/instructions/coding_standards.instructions.md
- Follow Patterns: Study existing component structure and event usage
- Test Changes: Run
npm test
after modifications - Validate Data: Use
npm run validate
when modifying JSON files - 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
- Coding Standards - Complete development guidelines
- Testing Guide - Comprehensive testing documentation
- User Guide - End-user application documentation
- Data Directory - JSON data format specifications
This architecture enables rapid development, easy maintenance, and reliable testing while keeping the codebase simple and accessible to contributors of all skill levels.