Calculator Application - Full Development Context & Implementation Log
Main calculator interface with modern design and responsive layout
History modal showing past calculations with reuse and delete functionality
1. AI Assistant Profile & Philosophy
Core Personality & Approach
I operate as a pragmatic software engineering consultant with expert-level insight into modern programming trends, tooling ecosystems, and language paradigms. My approach is rooted in best practices, avoiding unnecessary reinvention unless solving a defined and complex problem. I advocate for widely adopted methodologies, including object-oriented programming, modular architecture, and minimalistic framework usage.
Development Philosophy
My workflow is guided by a focus on productivity, performance, clarity, and structured environments. I maintain a disciplined, minimalist approach to development, where perfectionism and attention to detail guide every facet of implementation.
- Strict Separation of Concerns: The backend serves as the single source of truth, typically via API services. Frontend stacks are chosen for adaptability and cross-platform capabilities, not for trend conformity. Redundant technologies are avoided unless they enable native integration or platform flexibility.
- Lean, Purposeful Implementations: Over-engineering is discouraged. The developer experience is treated as equally important to the technical output, emphasizing clean, readable code and predictable architecture.
- Code as Documentation: Code comments are excluded unless explicitly required. The code itself must be self-explanatory through clear naming, concise functions, and logical structure.
Technical & Quality Standards
- Open Source & Privacy: I promote open-source ecosystems with an emphasis on user data privacy and secure networking practices. Freemium third-party services are rejected unless they solve time-critical problems without introducing long-term constraints.
- Tooling Skepticism: High-overhead tools like Docker CE or hosted CI/CD providers (e.g., GitHub Actions) are viewed with skepticism for solo workflows due to their complexity and scalability issues.
- Structural Discipline: Architectural and functional components are alphabetically sorted unless logic mandates a procedural order. Functions are concise, pure when possible, and free from hidden side effects. Naming conventions are descriptive, scoped, and minimalistic.
- Stylistic Consistency: Four spaces are used for indentation. Strict formatting and linting are enforced using tools like Black and Prettier.
2. Developer Environment & Languages (AI Assistant: Added Context)
System Environment
- Operating System: Ubuntu 24.04.2
- IDE: Visual Studio Code only
- Development Approach: Terminal (bash) and CLI-first
- Environment Isolation: Always use virtual environments for Python (
venv
) and equivalent sandboxing for other languages.
3. Project Vision & Architecture
Project Overview
The goal is to build a robust, cross-platform calculator application with a backend-as-single-source-of-truth architecture. This ensures calculation consistency across web, iOS, and Android platforms while maintaining a lean, maintainable codebase. The application is a SvelteKit-based calculator frontend with a professional UI/UX, full backend integration, and a hybrid offline-first architecture.
Key Architectural Decisions
Backend-First Philosophy
A single FastAPI endpoint (POST /calculate
) handles all mathematical operations. This stateless design ensures that one calculation engine serves all platforms, making bug fixes and feature additions (like a future scientific calculator) instantly available to every client. This approach avoids the massive overhead of building, testing, and maintaining separate calculation engines for Swift, Kotlin, and JavaScript.
The Hybrid "Offline-First" Solution
A purely frontend implementation works offline but sacrifices the cross-platform consistency and precision our backend provides. A purely backend approach is robust but fails without an internet connection.
The solution is a hybrid "offline-first" architecture:
- Prioritize Backend API: The app always attempts to call the high-precision Python backend first.
- Graceful Fallback: If the API call fails (e.g., no internet), the app seamlessly falls back to a basic JavaScript calculation engine built into the frontend.
- Clear UI Feedback: The UI uses a lightning bolt icon (⚡) to indicate when it is operating in offline mode, making the user aware of the precision trade-off.
This hybrid model delivers the best of both worlds: the calculator is always functional (resilience) and provides mathematically exact answers whenever possible (reliability).
Precision is Mandatory
All backend calculations use Python's decimal.Decimal
module for exact arithmetic. Standard floating-point math is unacceptable due to its inherent precision limitations (e.g., 0.1 + 0.2
not equaling 0.3
). This guarantees accuracy and builds a trustworthy application from the start.
Client-Side History Management
To enhance privacy and simplify the architecture, calculation history is managed on the client side using localStorage
. The backend remains completely stateless, as it never stores user data. This eliminates syncing complexity and the need for a database. The workflow is simple: the frontend sends an expression to the backend, receives the result, and saves the completed calculation to local storage.
A string token array
(e.g., ["5", "+", "3", "*", "2"]
) is the standard data format for all API requests. This delegates all parsing and type conversion to the backend, reinforcing its role as the single source of truth and preventing mixed-type errors.
The Power of a Stateless Backend
The backend is stateless, meaning each calculation is an independent, transient event. The server uses CPU, not memory, for the lightning-fast PEMDAS parsing and Decimal arithmetic. This architecture is not a bottleneck; it is the solution to scaling. For high-traffic scenarios, the system scales horizontally by adding more small, identical instances of the application behind a load balancer.
4. Design System Architecture
The frontend is built on a formal design system to ensure long-term visual consistency across the web and future native platforms.
Design Tokens System
A central JSON file (./design-system-tokens.json
) defines the entire visual language, including colors, typography, spacing, radii, and shadows.
- For the Web: A script (
scripts/generate-css-tokens.js
) automatically transforms these tokens into CSS variables for use in the SvelteKit application. This can be run with npm run tokens
.
- For Native Apps: In the future, the same JSON file will be consumed by the native build processes to generate platform-specific styling resources (e.g.,
UIColor
definitions in Swift, color resources in Android XML).
This approach abstracts the design language from any specific platform, ensuring that a change to the primary color in tokens.json
propagates everywhere consistently.
5. Implementation & Features (Production Ready)
- Implementation Status: Complete and Production Ready ✅
- Version: 1.0.0 - Web App Release
Backend Implementation (Complete)
- Location:
/backend/app/
- Core Logic: A
calculator.py
file contains the Decimal-based calculation engine with full PEMDAS support. main.py
serves the FastAPI application.
- API Contract: A
POST /calculate
endpoint accepts a string token array and returns either a {"result": "..."}
or an {"error": "..."}
.
- Validated Features: The backend is fully tested for PEMDAS compliance, division-by-zero errors, decimal precision, and invalid input rejection.
Frontend Implementation (Complete)
Core Architecture & Setup
- Framework: SvelteKit with a Vite development server.
- Build System: Vite provides hot module replacement for a fast development loop. NPM is used for package management.
Calculator Core Features
- Input Management: A 12-digit input limit prevents overflow. Long expressions are truncated for readability (e.g.,
… + 9 + 9
).
- Mathematical Operations: Includes basic arithmetic, PEMDAS compliance via the backend, and a JavaScript-based fallback engine for offline use.
- Number Formatting: Features live comma formatting as users type, handles large numbers with K/M/B/T notation, and correctly preserves decimal places.
User Interface & Design
- Button System: Uses the Lucide SVG icon library. Buttons have a static, real-calculator feel with no hover animations, except for light gray hovers on number buttons for enhanced contrast.
- Color Coding: A clear visual hierarchy is established with distinct colors for numbers (white), operators (blue), clear all (red), clear entry (orange), equals (green), and menu (gray).
- Layout: A modern, responsive 4x5 grid layout with a
400px
fixed width. It features a glassmorphism effect over a purple gradient background.
History Management System
- History Modal: A professional, dark-themed modal allows users to view, clear, reuse, or delete past calculations.
- Local Storage: The browser's
localStorage
provides persistent, device-specific history for up to 50 entries, with automatic cleanup of old items.
Backend Integration & Hybrid Mode
- Seamless Switching: The app automatically detects backend availability and switches between online (high-precision) and offline (standard-precision) modes with a sub-5-second timeout.
- Visual Indicators: The UI header displays the current connection status, with a lightning bolt icon (⚡) indicating offline mode.
Advanced UI/UX & Accessibility
- Accessibility: Full keyboard support, descriptive tooltips on all icon buttons, proper ARIA labels, and WCAG-compliant color contrast ratios are implemented.
- Dual-Line Display: Shows both the current expression and the input value, with smart truncation for long expressions.
Error Handling & Edge Cases
- Input Validation: A 12-digit limit prevents buffer overflow, and the system gracefully handles malformed expressions and division-by-zero errors from the backend.
- UI Stability: The calculator's fixed dimensions and text overflow management prevent layout breaks. State recovery mechanisms ensure a stable user experience.
- Component Structure: The frontend is organized into logical Svelte components:
Calculator
, Display
, Button
, IconButton
, and History
.
- Scripts: Includes
npm run dev
, npm run build
, npm run preview
, and the custom npm run tokens
.
- Backend Management: Use
cd backend && ./backend.sh
to manage the backend server.
- Utility Functions: Helper functions for number formatting, input validation, display truncation, and history operations are cleanly separated.
Technical Specifications
- Browser Support: Modern browsers (Chrome, Firefox, Safari, Edge) with ES6+ support. The architecture is PWA-ready.
- Dependencies: SvelteKit 2.22.5, Svelte 5.35.6, Vite 7.0.4, Lucide-svelte 0.525.0.
6. Development Setup & Testing
Prerequisites
Before starting development, ensure you have the following installed:
- Python 3.8+ with
venv
support
- Node.js 18+ with NPM
- Git for version control
Initial Setup
1. Backend Setup
# Navigate to backend directory
cd backend
# Create virtual environment
python3 -m venv venv
# Activate virtual environment
source venv/bin/activate
# Install Python dependencies
pip install -r requirements.txt
2. Frontend Setup
# Navigate to frontend web directory
cd frontend/web
# Install Node.js dependencies
npm install
Running the Application for Development
1. Start the Backend Server
# From the backend directory
cd backend
./backend.sh start
The backend server will start on http://localhost:8000
. You can manage it with:
./backend.sh start
- Start the server
./backend.sh stop
- Stop the server
./backend.sh restart
- Restart the server
./backend.sh status
- Check server status
2. Start the Frontend Development Server
# From the frontend/web directory
cd frontend/web
npm run dev
The frontend development server will start on http://localhost:5173
with hot module replacement.
Testing the Application
- Backend API Testing: The backend provides a
/calculate
endpoint that accepts POST requests with calculation expressions
- Frontend Testing: Open
http://localhost:5173
in your browser to test the calculator interface
- Hybrid Mode Testing: Stop the backend server to test offline fallback functionality
Development Workflow
- Start both backend and frontend servers
- Make changes to the code
- The frontend automatically reloads with Vite's hot module replacement
- The backend reloads automatically with uvicorn's
--reload
flag
- Test calculations to ensure both online and offline modes work correctly
Build for Production
# Build frontend for production
cd frontend/web
npm run build
# Preview production build
npm run preview
7. Project Governance
Version Control
Git is used for local versioning, with commits made for every major feature update, architecture change, or bug fix. Commit messages are short and descriptive (e.g., feat: add percentage support to calculator
).
Success Metrics
The project successfully meets its primary architectural and technical goals:
- Cross-Platform Ready: The design token system enables future native app development.
- Maintainable & Scalable: Achieved through clear separation of concerns.
- Performance & Privacy: The stateless backend and client-side history ensure efficiency and security.
- Precision & Reliability: Decimal arithmetic and comprehensive error handling are implemented.
- Single Source of Truth: The backend handles all calculation logic.
8. Acknowledgements & Credits
This project was made possible by a number of AI collaborators, open-source frameworks, libraries, and tools. Credit and thanks are extended to the authors and maintainers of the following technologies:
AI Collaboration
- Claude Code Pro: Served as the AI coding assistant, contributing to the implementation and refinement of code components.
- Copilot Free: Employed for rapid, prompt-based assistance with minor code adjustments and simple fixes.
- Gemini Pro: Utilized for prompt engineering, helping to refine architectural documentation and structure the project's narrative.
Backend
- FastAPI: The high-performance web framework used to build the stateless API endpoint.
- Python: The core language used for the backend logic and high-precision calculations.
- Uvicorn: The ASGI server responsible for running the FastAPI application.
Frontend
- Lucide: The icon library providing the clean and professional SVG icons used throughout the UI via the lucide-svelte package.
- SvelteKit: The primary web framework used to build the robust, reactive user interface.
- Tailwind CSS: The utility-first CSS framework used for styling the application, integrated with the design token system.
- Vite: The development server and build tool that provides hot module replacement and a fast developer experience.
- Git: The version control system used for local versioning and managing the project's history.
- GitHub: The platform used for hosting the project's source code repository.
- NPM: The package manager for handling all frontend dependencies.
- Prettier & Black: Code formatters used to enforce consistent style and quality across the JavaScript and Python codebases, respectively.
- Visual Studio Code: The integrated development environment (IDE) used for all coding.
<3 missacele