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.*