From 645ebd07b8d5009fe0eb2c6ddd8a71acacf008a8 Mon Sep 17 00:00:00 2001 From: MarcelOlsen Date: Fri, 1 May 2026 22:26:53 +0200 Subject: [PATCH] docs: update readme --- .zed/settings.json | 41 ++ README.md | 1144 ++++---------------------------------------- 2 files changed, 143 insertions(+), 1042 deletions(-) create mode 100644 .zed/settings.json diff --git a/.zed/settings.json b/.zed/settings.json new file mode 100644 index 0000000..f7c3c70 --- /dev/null +++ b/.zed/settings.json @@ -0,0 +1,41 @@ +{ + "formatter": { + "language_server": { + "name": "biome" + } + }, + "code_actions_on_format": { + "source.organizeImports.biome": true, + "source.fixAll.biome": true + }, + "languages": { + "TypeScript": { + "formatter": { + "language_server": { + "name": "biome" + } + }, + "prettier": { + "allowed": false + } + }, + "TSX": { + "formatter": { + "language_server": { + "name": "biome" + } + }, + "prettier": { + "allowed": false + } + } + }, + "lsp": { + "biome": { + "binary": { + "path": "node_modules/.bin/biome", + "arguments": ["lsp-proxy"] + } + } + } +} diff --git a/README.md b/README.md index c1fb817..8775061 100644 --- a/README.md +++ b/README.md @@ -1,193 +1,43 @@ # MiniReact -A learning project to build a simplified React-like library from scratch, with a focus on understanding virtual DOM, reconciliation, and component-based architecture. This project is developed incrementally in well-defined phases, each with comprehensive test coverage and production-quality code. - ---- - -## Table of Contents - -- [Overview](#overview) -- [Current Status](#current-status) -- [Quick Start](#quick-start) -- [Features](#features) -- [Project Structure](#project-structure) -- [Development Phases](#development-phases) - - [πŸš€ **ALPHA RELEASE TRACK** (Phases 1-11)](#-alpha-release-track-phases-1-11) - - [Phase 1: Element Creation & Basic Rendering βœ…](#phase-1-element-creation--basic-rendering-) - - [Phase 2: Functional Components βœ…](#phase-2-functional-components-) - - [Phase 3: Virtual DOM & Basic Reconciliation βœ…](#phase-3-virtual-dom--basic-reconciliation-) - - [Phase 4: Prop Diffing & Efficient Children Reconciliation βœ…](#phase-4-prop-diffing--efficient-children-reconciliation-) - - [Phase 5: State with useState Hook βœ…](#phase-5-state-with-usestate-hook-) - - [Phase 6: Event Handling βœ…](#phase-6-event-handling-) - - [Phase 7: Effects with useEffect βœ…](#phase-7-effects-with-useeffect-) - - [Phase 8: Context API βœ…](#phase-8-context-api-) - - [Phase 9: Portals and Fragments βœ…](#phase-9-portals-and-fragments-) - - [Phase 10: JSX Support βœ…](#phase-10-jsx-support-) - - [Phase 11: Essential Hooks (useRef & useReducer) βœ…](#phase-11-essential-hooks-useref--usereducer-) - - [πŸŽ‰ **ALPHA RELEASE v0.1.0** - Complete Core React-like Functionality](#-alpha-release-v010---complete-core-react-like-functionality) - - [πŸš€ **STABLE RELEASE TRACK** (Phases 12-20)](#-stable-release-track-phases-12-20) - - [Phase 12: Performance Optimization Suite βœ…](#phase-12-performance-optimization-suite-) - - [Phase 13: Error Boundaries & Resilience](#phase-13-error-boundaries--resilience) - - [Phase 14: Async Features & Suspense](#phase-14-async-features--suspense) - - [Phase 15: Concurrent Features (Advanced)](#phase-15-concurrent-features-advanced) - - [Phase 16: Developer Experience](#phase-16-developer-experience) - - [Phase 17: Server-Side Rendering](#phase-17-server-side-rendering) - - [Phase 18: Advanced Component Patterns](#phase-18-advanced-component-patterns) - - [Phase 19: Testing & Quality Assurance](#phase-19-testing--quality-assurance) - - [Phase 20: Production Optimizations](#phase-20-production-optimizations) - - [🎯 **STABLE RELEASE v1.0.0** - Production-Ready React Alternative](#-stable-release-v100---production-ready-react-alternative) -- [API Reference](#api-reference) -- [Testing](#testing) -- [Code Quality](#code-quality) -- [Contributing](#contributing) -- [License](#license) - ---- +A minimal React-like UI library built from scratch to understand how the virtual DOM, reconciliation, and hooks actually work. ## Overview -**MiniReact** is a step-by-step implementation of a React-like UI library designed for learning and understanding how modern UI frameworks work under the hood. The project emphasizes: - -- **Test-driven development** with full test coverage -- **Quality code** with full TypeScript support and linting -- **Incremental complexity** with well-documented phases -- **Performance optimization** with efficient reconciliation algorithms -- **Real-world patterns** that mirror React's actual implementation - -Each phase includes clear specifications, working implementations, and extensive test coverage to ensure reliability and educational value. - ---- - -## Current Status - -πŸ†• **Current Phase**: Stable Release Track - Phase 12 βœ… **COMPLETE** - -**Latest Achievements**: - -- βœ… **Phase 12 Complete**: Performance Optimization Suite - memo, useMemo, useCallback with comprehensive test coverage -- βœ… **Enhanced Performance**: React.memo equivalent for component memoization and optimization hooks -- βœ… **272 Tests Passing**: Comprehensive test suite covering all functionality including performance optimizations -- βœ… **Zero Linter Issues**: Clean codebase with consistent formatting and biome configuration -- βœ… **Complete Performance Toolkit**: memo, useMemo, useCallback hooks for production-grade optimization -- βœ… **Production-Ready**: Robust error handling, TypeScript support, and comprehensive edge case coverage -- βœ… **Package Preparation**: Ready for npm registry publication with performance features - -**Stable Release Progress**: 1/9 phases complete (11% complete) πŸš€ - -**Immediate Milestones**: - -- πŸš€ **npm Package Publication**: Package will be available on npm registry soon -- πŸ“¦ **Alpha Release v0.1.0**: Complete core React-like functionality now available -- πŸ“š **Documentation & Examples**: Comprehensive guides and demo applications - -**Post-Alpha Roadmap**: 12 additional phases planned for stable v1.0.0 release with advanced features including concurrent rendering, SSR, dev tools, and production optimizations. - ---- +This is a learning project, not a production framework. It implements the core ideas behind Reactβ€”functional components, a virtual DOM, a reconciliation engine, hooks (useState, useEffect, useReducer, useRef, useMemo, useCallback), and the Context APIβ€”without the complexity of the real thing. The goal is to write code that is small enough to read in one sitting, but complete enough to actually build UIs with. ## Quick Start -### Prerequisites - -- [Bun](https://bun.sh/) (for runtime and testing) -- [Biome](https://biomejs.dev/) (for linting/formatting) -- [happy-dom](https://github.com/capricorn86/happy-dom) (for DOM testing environment) - -### Installation - -**πŸ“¦ npm Package (Coming Soon):** - -# Installation - -```bash -npm install @marcelolsen/mini-react -# or -bun add @marcelolsen/mini-react -``` - -**πŸ”§ Development Installation (Current):** +Requires [Bun](https://bun.sh). ```bash -# Clone the repository for development/testing git clone https://github.com/MarcelOlsen/mini-react.git cd mini-react - -# Install dependencies bun install - -# Run tests to verify installation bun test - -# Build the project -bun run build ``` -### Basic Usage +### Usage ```typescript -import { createElement, render } from "@marcelolsen/mini-react"; -import type { FunctionalComponent } from "@marcelolsen/mini-react"; - -// Simple host element -const simpleElement = createElement("h1", { id: "title" }, "Hello MiniReact!"); - -// Functional component with props -const Greeting: FunctionalComponent = (props) => { - const { name } = props as { name: string }; - return createElement("p", { className: "greeting" }, `Hello, ${name}!`); -}; +import { createElement, render, useState } from "@marcelolsen/mini-react"; -// Component with children -const Layout: FunctionalComponent = (props) => { - const { title, children } = props as { title: string; children?: any[] }; - return createElement( - "div", - { className: "app" }, - createElement("h1", null, title), - createElement("div", { className: "content" }, ...(children || [])) - ); -}; +const Counter = () => { + const [count, setCount] = useState(0); -// Complex component composition -const App = () => { return createElement( - Layout, - { title: "MiniReact Demo" }, - createElement(Greeting, { name: "World" }), - createElement("p", null, "Building React from scratch!") + "button", + { onClick: () => setCount(count + 1) }, + `Count: ${count}` ); }; -// Render to DOM -const container = document.getElementById("root")!; -render(createElement(App), container); - -// Dynamic updates (reconciliation in action) -setTimeout(() => { - render(createElement(Greeting, { name: "Universe" }), container); -}, 2000); +render(createElement(Counter), document.getElementById("root")!); ``` -### Running Tests +### JSX -```bash -# Run all tests -bun test - -# Run tests in watch mode -bun test --watch - -# Run specific test file -bun test tests/MiniReact.render.test.ts - -# Check code quality -bunx biome check -``` - -### JSX Usage (New!) - -With Phase 10 complete, you can now use JSX syntax! Configure your build tool (TypeScript/Bun) to use the MiniReact JSX runtime: - -**tsconfig.json:** +Configure your build tool to use the MiniReact JSX runtime: ```json { @@ -198,973 +48,183 @@ With Phase 10 complete, you can now use JSX syntax! Configure your build tool (T } ``` -**JSX Examples:** +Then write components normally: ```tsx -import { render, useState, Fragment } from "@marcelolsen/mini-react"; - -// JSX syntax instead of createElement! -const Greeting = ({ name }: { name: string }) => { - return

Hello, {name}!

; -}; - -const Counter = () => { - const [count, setCount] = useState(0); - - return ( -
-

Count: {count}

- -
- ); -}; - -// Fragments work too! const App = () => { return ( - <> -

MiniReact with JSX!

- +
+

Hello

- - ); -}; - -// Render with JSX -render(, document.getElementById("root")!); -``` - -### Advanced Usage Examples - -#### Portal Usage - -```typescript -import { - createElement, - render, - createPortal, - useState, -} from "@marcelolsen/mini-react"; - -// Create a portal target in your HTML -// - -const Modal = ({ - children, - onClose, -}: { - children: any; - onClose: () => void; -}) => { - const modalRoot = document.getElementById("modal-root"); - if (!modalRoot) return null; - - return createPortal( - createElement( - "div", - { - className: "modal-overlay", - onClick: onClose, - style: { - position: "fixed", - top: "0", - left: "0", - right: "0", - bottom: "0", - backgroundColor: "rgba(0,0,0,0.5)", - display: "flex", - alignItems: "center", - justifyContent: "center", - }, - }, - createElement( - "div", - { - className: "modal-content", - onClick: (e: Event) => e.stopPropagation(), - style: { - backgroundColor: "white", - padding: "20px", - borderRadius: "5px", - }, - }, - children, - createElement("button", { onClick: onClose }, "Close") - ) - ), - modalRoot - ); -}; - -const App = () => { - const [showModal, setShowModal] = useState(false); - - return createElement( - "div", - null, - createElement("h1", null, "Portal Demo"), - createElement( - "button", - { onClick: () => setShowModal(true) }, - "Open Modal" - ), - showModal && - createElement( - Modal, - { onClose: () => setShowModal(false) }, - createElement("h2", null, "Modal Content"), - createElement("p", null, "This modal is rendered using createPortal!") - ) - ); -}; -``` - -#### Fragment Usage - -```typescript -import { createElement, Fragment } from "@marcelolsen/mini-react"; - -// Multiple children without wrapper element -const ItemList = ({ items }: { items: string[] }) => { - return createElement( - Fragment, - null, - ...items.map((item, index) => createElement("li", { key: index }, item)) - ); -}; - -const App = () => { - return createElement( - "ul", - null, - createElement(ItemList, { items: ["Apple", "Banana", "Cherry"] }) +
); }; ``` ---- +## What's Implemented -## Features - -### 🌟 Core React-Like Functionality - -- **πŸ—οΈ Virtual DOM**: Efficient virtual DOM implementation with reconciliation algorithm -- **⚑ Component System**: Functional components with props and children support -- **🎣 Complete Hook Ecosystem**: All essential React hooks implemented - - **useState**: State management with automatic re-rendering - - **useEffect**: Side effects with dependency arrays and cleanup - - **useContext**: Context API for prop drilling elimination - - **useRef**: DOM references and mutable values without re-renders - - **useReducer**: Complex state management with reducer patterns -- **⚑ Event Handling**: Synthetic event system with proper event delegation and cleanup -- **🌐 Context API**: createContext and useContext hooks with provider/consumer pattern -- **πŸŒ‰ Portals**: createPortal for rendering content to different DOM containers with React tree event bubbling -- **πŸ“¦ Fragments**: React.Fragment equivalent for rendering multiple children without wrapper DOM nodes -- **🎨 JSX Support**: Full JSX syntax with jsx/jsxs/jsxDEV runtime functions and TypeScript integration - -### 🎨 Advanced Capabilities - -- **JSX Syntax**: Full JSX syntax support with modern runtime (jsx, jsxs, jsxDEV) -- **TypeScript JSX**: Complete type safety for JSX elements and components -- **Nested Components**: Deep component hierarchies with proper reconciliation -- **Mixed Content**: Text nodes, numbers, and elements as children -- **Conditional Rendering**: Support for null/undefined elements with enhanced error handling -- **Performance Optimized**: Key-based reconciliation for efficient list operations -- **Memory Efficient**: Proper cleanup and DOM node reuse -- **Edge Case Handling**: Robust error handling and boundary conditions with recent bug fixes -- **Portal Event System**: Events bubble through React component tree, not DOM tree -- **Portal Context Propagation**: Context values work seamlessly across portal boundaries -- **Fragment Reconciliation**: Efficient updates for fragment children without wrapper elements - -### πŸ“‹ Testing & Quality - -- **261 Comprehensive Tests**: Full test coverage for all features and edge cases including all hooks -- **TypeScript Support**: Full type safety with detailed type definitions -- **Linting & Formatting**: Biome-based code quality and consistent formatting -- **Error Handling**: Graceful degradation and helpful error messages -- **Performance Testing**: Reconciliation benchmarks and memory leak detection -- **Integration Testing**: Full component lifecycle and interaction testing - ---- +- **Virtual DOM & Reconciliation**: Diff and patch the DOM efficiently. +- **Functional Components**: Props, children, and composition. +- **Hooks**: useState, useEffect, useReducer, useRef, useMemo, useCallback. +- **Context API**: createContext / useContext for passing data through the tree. +- **Portals**: Render children into a different DOM container while keeping the React tree structure. +- **Fragments**: Group children without wrapper nodes. +- **JSX Runtime**: Production and development JSX transforms (jsx, jsxs, jsxDEV). +- **Events**: Standard DOM events attached directly to nodes. +- **Performance**: Basic memoization via `memo`, `useMemo`, and `useCallback`. ## Project Structure ``` -mini-react/ -β”œβ”€β”€ src/ -β”‚ β”œβ”€β”€ MiniReact.ts # Main library exports and JSX runtime -β”‚ β”œβ”€β”€ types.ts # TypeScript type definitions -β”‚ β”œβ”€β”€ vdom.ts # Virtual DOM creation and utilities -β”‚ β”œβ”€β”€ reconciler.ts # Virtual DOM reconciliation engine -β”‚ β”œβ”€β”€ hooks.ts # Hook implementations (useState, useEffect, useContext) -β”‚ β”œβ”€β”€ context.ts # Context API implementation -β”‚ β”œβ”€β”€ portals.ts # Portal system implementation -β”‚ β”œβ”€β”€ events.ts # Event system and synthetic events -β”‚ └── jsx/ # JSX runtime functions -β”‚ β”œβ”€β”€ jsx-runtime.ts # Production JSX runtime -β”‚ └── jsx-dev-runtime.ts # Development JSX runtime with debugging -β”œβ”€β”€ tests/ # Comprehensive test suite -β”‚ β”œβ”€β”€ MiniReact.render.test.ts -β”‚ β”œβ”€β”€ MiniReact.functional-components.test.ts -β”‚ β”œβ”€β”€ MiniReact.reconciliation.test.ts -β”‚ β”œβ”€β”€ MiniReact.hooks.test.ts -β”‚ β”œβ”€β”€ MiniReact.events.test.ts -β”‚ β”œβ”€β”€ MiniReact.context.test.ts -β”‚ β”œβ”€β”€ MiniReact.portals.test.ts -β”‚ β”œβ”€β”€ MiniReact.fragments.test.ts -β”‚ └── MiniReact.jsx.test.ts -β”œβ”€β”€ examples/ # Usage examples and demos -β”‚ β”œβ”€β”€ jsx-examples/ # JSX syntax examples -β”‚ β”œβ”€β”€ basic-usage/ # Basic API examples -β”‚ β”œβ”€β”€ advanced-patterns/ # Advanced usage patterns -β”‚ └── performance-tests/ # Performance benchmarks -└── package.json # Dependencies and scripts +src/ +β”œβ”€β”€ MiniReact.ts # Main exports and JSX runtime +β”œβ”€β”€ types.ts # TypeScript definitions +β”œβ”€β”€ vdom.ts # Virtual DOM creation +β”œβ”€β”€ reconciler.ts # Reconciliation / diffing engine +β”œβ”€β”€ hooks.ts # Hook implementations +β”œβ”€β”€ context.ts # Context API +β”œβ”€β”€ portals.ts # Portals +β”œβ”€β”€ events.ts # Event system +└── jsx/ + β”œβ”€β”€ jsx-runtime.ts + └── jsx-dev-runtime.ts ``` ---- - ## Development Phases -### πŸš€ **ALPHA RELEASE TRACK** (Phases 1-11) - -#### Phase 1: Element Creation & Basic Rendering βœ… - -**Features:** - -- βœ… createElement function for host elements (div, span, etc.) -- βœ… Basic render function that creates real DOM from virtual DOM -- βœ… Support for props (attributes, event handlers, etc.) -- βœ… Support for children (text nodes, nested elements) -- βœ… Comprehensive test coverage for element creation and rendering - ---- - -#### Phase 2: Functional Components βœ… - -**Features:** - -- βœ… Support for functional components that return virtual DOM -- βœ… Props passing to functional components -- βœ… Component composition and nesting -- βœ… Proper TypeScript types for functional components -- βœ… Test coverage for functional component rendering and composition - ---- - -#### Phase 3: Virtual DOM & Basic Reconciliation βœ… - -**Features:** - -- βœ… Virtual DOM tree structure with proper typing -- βœ… Basic reconciliation algorithm to diff virtual DOM trees -- βœ… Efficient DOM updates (add, remove, update nodes) -- βœ… Text content updates and mixed content handling -- βœ… Element type changes and property updates -- βœ… Test coverage for virtual DOM creation and reconciliation - ---- - -#### Phase 4: Prop Diffing & Efficient Children Reconciliation βœ… - -**Features:** - -- βœ… Intelligent prop diffing with add/remove/update detection -- βœ… Key-based reconciliation for efficient list rendering and reordering -- βœ… Advanced children reconciliation with position tracking -- βœ… Style object diffing and updates -- βœ… Event handler updates and cleanup -- βœ… Edge case handling for complex reconciliation scenarios - ---- - -#### Phase 5: State with useState Hook βœ… - -**Features:** - -- βœ… useState hook implementation with proper state management -- βœ… Component re-rendering on state changes -- βœ… State preservation between renders -- βœ… Functional state updates and batching -- βœ… Hook rules enforcement and error handling -- βœ… Integration with reconciliation system for efficient updates - ---- - -#### Phase 6: Event Handling βœ… - -**Features:** - -- βœ… Synthetic event system with cross-browser compatibility -- βœ… Event delegation and efficient event management -- βœ… Event handler prop updates during reconciliation -- βœ… Event cleanup and memory leak prevention -- βœ… Support for all common DOM events (click, change, submit, etc.) -- βœ… Event object normalization and additional properties - ---- - -#### Phase 7: Effects with useEffect βœ… - -**Features:** - -- βœ… useEffect hook with dependency array support -- βœ… Effect cleanup functions and proper lifecycle management -- βœ… Effect scheduling and execution timing -- βœ… Dependency comparison and change detection -- βœ… Mount, update, and unmount effect handling -- βœ… Integration with component lifecycle and state changes - ---- - -#### Phase 8: Context API βœ… - -**Features:** - -- βœ… createContext function for context creation -- βœ… Context Provider component with value passing -- βœ… useContext hook for consuming context values -- βœ… Context value change detection and re-rendering -- βœ… Nested context support and context composition -- βœ… Performance optimization for context updates - ---- - -#### Phase 9: Portals and Fragments βœ… - -**Features:** - -- βœ… createPortal function for rendering to different DOM containers -- βœ… Portal event bubbling through React tree (not DOM tree) -- βœ… Context propagation across portal boundaries -- βœ… Portal cleanup and lifecycle management -- βœ… React.Fragment equivalent for grouping elements without wrapper -- βœ… Fragment reconciliation and efficient updates - ---- - -#### Phase 10: JSX Support βœ… - -**Features:** - -- βœ… JSX syntax support for component definitions and element creation -- βœ… JSX runtime functions (`jsx`, `jsxs`, `jsxDEV`) for build tool integration -- βœ… Fragment support with `<>` and `` syntax -- βœ… TypeScript JSX declarations for full type safety -- βœ… Build tool configuration (TypeScript/Babel integration) -- βœ… Development mode enhancements with source maps and debugging -- βœ… Backward compatibility with existing `createElement` API - ---- - -#### Phase 11: Essential Hooks (useRef & useReducer) βœ… - -**Features:** - -- βœ… useRef hook for DOM references and mutable values without re-renders -- βœ… useReducer hook for complex state management with reducer patterns -- βœ… Ref object with mutable .current property that persists across renders -- βœ… Reducer pattern with actions, state transitions, and dispatch function -- βœ… Integration with existing hook system and component lifecycle -- βœ… Comprehensive test coverage for all hook scenarios and edge cases -- βœ… TypeScript support with proper type inference and safety - ---- - -### πŸŽ‰ **ALPHA RELEASE v0.1.0** - Complete Core React-like Functionality - -**Status**: βœ… **NPM PACKAGE PUBLISHED** - -**Alpha Release Features:** - -- βœ… Full React-like component system with JSX support -- βœ… Complete hook ecosystem (useState, useEffect, useContext, useRef, useReducer) -- βœ… Advanced rendering (Portals, Fragments) -- βœ… Production-ready reconciliation engine -- βœ… Comprehensive TypeScript support -- βœ… 261 tests with full coverage -- βœ… Developer-friendly API matching React patterns -- βœ… npm package ready for publication - ---- - -### πŸš€ **STABLE RELEASE TRACK** (Phases 12-20) - -#### Phase 12: Performance Optimization Suite βœ… - -**Features:** - -- βœ… Memoization (React.memo equivalent) for component optimization -- βœ… useMemo hook for expensive computation memoization -- βœ… useCallback hook for function reference stability -- βœ… Shallow prop comparison with custom comparison support -- βœ… Performance tracking and measurement utilities -- βœ… Comprehensive test coverage for all optimization features -- βœ… TypeScript support with proper type inference and safety - -#### Phase 13: Error Boundaries & Resilience - -- Error boundary implementation -- Graceful error handling and recovery -- Development mode error overlays -- Production error reporting -- Component error isolation - -#### Phase 14: Async Features & Suspense - -- Suspense component for async rendering -- Lazy loading and code splitting support -- Async component patterns -- Loading state management -- Error handling for async operations - -#### Phase 15: Concurrent Features (Advanced) - -- Time slicing for smooth rendering -- Priority-based rendering -- Interruptible rendering -- Scheduler implementation -- Advanced reconciliation strategies - -#### Phase 16: Developer Experience +This project is built in incremental phases. Each phase has a clear goal, an implementation, and tests. -- Development tools and debugging -- Component inspector -- Hook debugging utilities -- Performance profiler -- Development warnings and tips +### Alpha Track (Done) -#### Phase 17: Server-Side Rendering +1. **Element Creation & Basic Rendering** +2. **Functional Components** +3. **Virtual DOM & Reconciliation** +4. **Prop Diffing & Children Reconciliation** +5. **State with useState** +6. **Event Handling** +7. **Effects with useEffect** +8. **Context API** +9. **Portals and Fragments** +10. **JSX Support** +11. **useRef & useReducer** -- SSR capabilities -- Hydration support -- Server/client rendering parity -- SEO optimization features -- Static site generation support +### Stable Track (In Progress) -#### Phase 18: Advanced Component Patterns +12. **Performance Optimization Suite** β€” memo, useMemo, useCallback +13. **Error Boundaries & Resilience** +14. **Async Features & Suspense** +15. **Concurrent Features** +16. **Developer Experience** +17. **Server-Side Rendering** +18. **Advanced Component Patterns** +19. **Testing & Quality Assurance** +20. **Production Optimizations** -- Higher-order components (HOCs) -- Render props pattern -- Compound components -- Advanced composition patterns -- Performance optimization patterns +## API -#### Phase 19: Testing & Quality Assurance +### `createElement(type, props, ...children)` -- Testing utilities and helpers -- Component testing patterns -- Integration testing tools -- Performance testing suite -- Accessibility testing support - -#### Phase 20: Production Optimizations - -- Tree shaking and dead code elimination -- Advanced bundling strategies -- Runtime optimization -- Memory usage optimization -- Production monitoring tools - ---- - -### 🎯 **STABLE RELEASE v1.0.0** - Production-Ready React Alternative - -**Target**: 6-8 months after Alpha Release - -**Stable Release Features:** - -- Complete React API compatibility -- Advanced performance optimizations -- Full SSR and concurrent rendering support -- Comprehensive developer tools -- Production-ready with monitoring -- Enterprise-level documentation and support - ---- - -## API Reference - -### createElement +Creates a virtual DOM element. ```typescript -function createElement( - type: string | FunctionalComponent, - props: Props | null, - ...children: (MiniReactElement | string | number | null | undefined)[] -): MiniReactElement; +const el = createElement("div", { id: "app" }, "Hello"); ``` -Creates a virtual DOM element. Supports both host elements (strings) and functional components. - -**Parameters:** - -- `type`: Element type (e.g., 'div', 'span') or functional component -- `props`: Element properties/attributes object or null -- `children`: Child elements, text nodes, or primitive values +### `render(element, container)` -**Example:** +Renders a virtual element into a real DOM container. ```typescript -const greeting = createElement(Greeting, { name: "World" }); +render(createElement(App), document.getElementById("root")!); ``` -### render - -```typescript -function render( - element: AnyMiniReactElement | null | undefined, - container: HTMLElement -): void; -``` +### `useState(initialValue)` -Renders a virtual DOM element into a real DOM container with efficient reconciliation. - -**Parameters:** - -- `element`: Virtual DOM element to render -- `container`: Target DOM container element - -**Example:** +Returns a state tuple `[value, setValue]`. ```typescript -const app = createElement("div", null, "Hello World"); -render(app, document.getElementById("root")!); +const [count, setCount] = useState(0); ``` -### Functional Components +### `useEffect(effect, deps?)` -```typescript -type FunctionalComponent

> = ( - props: P & { children?: AnyMiniReactElement[] } -) => AnyMiniReactElement | null; -``` - -Components are functions that take props and return virtual DOM elements. The type is generic, allowing for strongly typed props with destructuring. **Now supports inferred component types just like React!** - -**Examples:** +Runs side effects after render. Return a cleanup function if needed. ```typescript -// βœ… Inferred component (React-style) - RECOMMENDED -const Component = ({ id }: { id: string }) => { - return createElement("div", { id }, "Hello World"); -}; - -// βœ… Inferred with optional props -const Greeting = ({ - name = "Anonymous", - age, -}: { - name?: string; - age?: number; -}) => { - return createElement( - "p", - null, - age ? `${name} is ${age} years old` +useEffect(() => { + const id = setInterval(() => setTime(t => t + 1), 1000); + return () => clearInterval(id); +}, []); ``` -### useState - -```typescript -function useState( - initialValue: T -): [T, (newValue: T | ((prev: T) => T)) => void]; -``` - -Hook for managing component state with automatic re-rendering. - -**Example:** - -```typescript -const Counter = () => { - const [count, setCount] = useState(0); - return createElement( - "button", - { onClick: () => setCount(count + 1) }, - `Count: ${count}` - ); -}; -``` +### `useReducer(reducer, initialState)` -### useEffect +State management with a reducer function. ```typescript -function useEffect( - effect: () => void | (() => void), - dependencies?: any[] -): void; +const [state, dispatch] = useReducer(counterReducer, { count: 0 }); ``` -Hook for side effects with optional cleanup and dependency tracking. +### `useRef(initialValue)` -**Example:** +Mutable reference that persists across renders without causing re-renders. ```typescript -const Timer = () => { - const [time, setTime] = useState(0); - - useEffect(() => { - const interval = setInterval(() => setTime((t) => t + 1), 1000); - return () => clearInterval(interval); // Cleanup - }, []); // Empty dependency array = run once on mount - - return createElement("div", null, `Time: ${time}`); -}; +const inputRef = useRef(null); ``` -### createContext & useContext +### `useMemo(factory, deps)` / `useCallback(fn, deps)` -```typescript -function createContext(defaultValue: T): Context; -function useContext(context: Context): T; -``` +Memoize expensive computations and stable function references. -Context API for passing data through component tree without prop drilling. +### `createContext(defaultValue)` / `useContext(context)` -**Example:** +Create and consume context to avoid prop drilling. ```typescript const ThemeContext = createContext("light"); - -const ThemedButton = () => { - const theme = useContext(ThemeContext); - return createElement( - "button", - { style: { background: theme === "dark" ? "#333" : "#fff" } }, - "Themed Button" - ); -}; - -const App = () => { - return createElement( - ThemeContext.Provider, - { value: "dark" }, - createElement(ThemedButton) - ); -}; -``` - -### createPortal - -```typescript -function createPortal( - children: MiniReactElement, - container: HTMLElement -): PortalElement; -``` - -Renders children into a different DOM container while maintaining React tree relationships. - -**Example:** - -```typescript -const Modal = ({ children }: { children: MiniReactElement }) => { - const modalRoot = document.getElementById("modal-root")!; - return createPortal(children, modalRoot); -}; +const theme = useContext(ThemeContext); ``` -### Fragment +### `createPortal(children, container)` -```typescript -const Fragment: symbol; -``` - -Component for grouping multiple children without adding extra DOM nodes. - -**Example:** +Render children into a different DOM node. ```typescript -const ItemList = () => { - return createElement( - Fragment, - null, - createElement("li", null, "Item 1"), - createElement("li", null, "Item 2") - ); -}; +createPortal(createElement(Modal), document.getElementById("modal-root")!); ``` -### JSX Runtime Functions +### `Fragment` -```typescript -function jsx(type: any, props: any, key?: string): MiniReactElement; -function jsxs(type: any, props: any, key?: string): MiniReactElement; -function jsxDEV( - type: any, - props: any, - key?: string, - isStaticChildren?: boolean, - source?: any, - self?: any -): MiniReactElement; -``` - -JSX runtime functions for transpiled JSX syntax. These are automatically used by build tools and shouldn't be called directly. - -### useRef +Group multiple elements without adding a wrapper to the DOM. ```typescript -function useRef(initialValue: T): MutableRefObject; - -interface MutableRefObject { - current: T; -} +createElement(Fragment, null, child1, child2); ``` -Hook for creating mutable references that persist across re-renders without triggering re-renders when changed. Useful for DOM references and storing mutable values. - -**Example:** - -```typescript -const InputComponent = () => { - const inputRef = useRef(null); - const renderCountRef = useRef(0); - - // Track renders without causing re-renders - renderCountRef.current += 1; - - const focusInput = () => { - if (inputRef.current) { - inputRef.current.focus(); - } - }; - - return createElement( - "div", - null, - createElement("input", { ref: inputRef, type: "text" }), - createElement("button", { onClick: focusInput }, "Focus Input"), - createElement("p", null, `Render count: ${renderCountRef.current}`) - ); -}; -``` - -### useReducer - -```typescript -function useReducer( - reducer: (state: State, action: Action) => State, - initialState: State -): [State, (action: Action) => void]; - -function useReducer( - reducer: (state: State, action: Action) => State, - initialArg: Init, - init: (arg: Init) => State -): [State, (action: Action) => void]; -``` - -Hook for managing complex state with a reducer function. Ideal for state that involves multiple sub-values or complex update logic. - -**Example:** - -```typescript -interface CounterState { - count: number; - step: number; -} - -type CounterAction = - | { type: "INCREMENT" } - | { type: "DECREMENT" } - | { type: "SET_STEP"; payload: number } - | { type: "RESET" }; - -const counterReducer = ( - state: CounterState, - action: CounterAction -): CounterState => { - switch (action.type) { - case "INCREMENT": - return { ...state, count: state.count + state.step }; - case "DECREMENT": - return { ...state, count: state.count - state.step }; - case "SET_STEP": - return { ...state, step: action.payload }; - case "RESET": - return { count: 0, step: 1 }; - default: - return state; - } -}; - -const Counter = () => { - const [state, dispatch] = useReducer(counterReducer, { count: 0, step: 1 }); - - return createElement( - "div", - null, - createElement("h3", null, `Count: ${state.count}`), - createElement( - "button", - { onClick: () => dispatch({ type: "INCREMENT" }) }, - "+" - ), - createElement( - "button", - { onClick: () => dispatch({ type: "DECREMENT" }) }, - "-" - ), - createElement( - "button", - { onClick: () => dispatch({ type: "RESET" }) }, - "Reset" - ) - ); -}; -``` - ---- - ## Testing -The project uses [Bun](https://bun.sh) as the test runner with [happy-dom](https://github.com/capricorn86/happy-dom) for DOM simulation. - -### Running Tests +Tests run with Bun and use happy-dom for DOM simulation. ```bash -# Run all tests -bun test - -# Run tests in watch mode -bun test --watch - -# Run specific test file -bun test tests/MiniReact.render.test.ts - -# Run tests with coverage -bun test --coverage -``` - -### Test Structure - -``` -tests/ -β”œβ”€β”€ MiniReact.render.test.ts # Basic rendering tests -β”œβ”€β”€ MiniReact.functional-components.test.ts # Component tests -β”œβ”€β”€ MiniReact.reconciliation.test.ts # Virtual DOM reconciliation -β”œβ”€β”€ MiniReact.hooks.test.ts # Hook implementations -β”œβ”€β”€ MiniReact.events.test.ts # Event system tests -β”œβ”€β”€ MiniReact.context.test.ts # Context API tests -β”œβ”€β”€ MiniReact.portals.test.ts # Portal functionality -β”œβ”€β”€ MiniReact.fragments.test.ts # Fragment rendering -└── MiniReact.jsx.test.ts # JSX runtime tests +bun test # run all tests +bun test --watch # watch mode +bun test --coverage # with coverage ``` -### Test Coverage - -Current test coverage: **261 tests** covering: - -- βœ… Element creation and rendering -- βœ… Functional component composition -- βœ… Virtual DOM reconciliation algorithms -- βœ… Hook lifecycle and state management (useState, useEffect, useContext, useRef, useReducer) -- βœ… Event handling and cleanup -- βœ… Context propagation and updates -- βœ… Portal rendering and event bubbling -- βœ… Fragment reconciliation -- βœ… JSX syntax and runtime functions -- βœ… Edge cases and error conditions -- βœ… Performance and memory leak prevention - ---- - ## Code Quality -### Linting and Formatting - -The project uses [Biome](https://biomejs.dev/) for linting and code formatting: +Linting and formatting with Biome: ```bash -# Check code quality bunx biome check - -# Fix auto-fixable issues bunx biome check --apply - -# Format code -bunx biome format --write . -``` - -### TypeScript Configuration - -Full TypeScript support with strict type checking: - -```json -{ - "compilerOptions": { - "strict": true, - "target": "ES2022", - "module": "ESNext", - "moduleResolution": "bundler", - "jsx": "react-jsx", - "jsxImportSource": "./src/MiniReact" - } -} -``` - -### Development Workflow - -1. **Write Tests First**: Follow TDD approach with comprehensive test coverage -2. **Type Safety**: Use TypeScript for all code with strict type checking -3. **Code Quality**: Run Biome checks before committing -4. **Documentation**: Keep README and code comments updated -5. **Performance**: Profile and optimize critical paths - ---- - -## Contributing - -### Development Setup - -1. Clone the repository: - -```bash -git clone https://github.com/MarcelOlsen/mini-react.git -cd mini-react ``` -2. Install dependencies: - -```bash -bun install -``` - -3. Run tests: - -```bash -bun test --watch -``` - -4. Start developing and follow the phase-based approach! - -### Contribution Guidelines - -- Follow the established phase structure -- Write comprehensive tests for new features -- Maintain TypeScript type safety -- Use consistent code formatting (Biome) -- Document new APIs and patterns -- Focus on educational value and code clarity - -### Phase Development Process - -1. **Plan**: Review phase specifications and requirements -2. **Test**: Write comprehensive tests for the new functionality -3. **Implement**: Build the feature with focus on clarity and correctness -4. **Validate**: Ensure all tests pass and code quality standards are met -5. **Document**: Update README, API documentation, and examples -6. **Review**: Code review focusing on educational value and best practices - ---- - ## License -MIT License - feel free to use this project for learning and educational purposes. +MIT --- -**Happy Coding! πŸš€** - -_Building React from scratch, one phase at a time._ +*Built to learn. Read the code, break it, fix it, understand it.*