# 🚀 FX Framework - Complete Beginner's Guide ## What is FX Framework? **FX Framework** is a revolutionary JavaScript/TypeScript framework that makes everything **reactive** and **synchronous**, even complex operations like database queries and cross-server communication. ### Why is FX Different? Most frameworks force you to use `async/await` everywhere, leading to complex code: ```javascript // Traditional approach - async everywhere async function loadUserDashboard(userId) { try { const user = await database.users.findById(userId); const posts = await database.posts.findByUserId(userId); const notifications = await api.notifications.getForUser(userId); // Update UI manually document.getElementById('username').textContent = user.name; document.getElementById('posts').innerHTML = posts.map(renderPost).join(''); updateNotificationBadge(notifications.length); } catch (error) { showErrorMessage(error); } } ``` **FX Framework approach - everything feels synchronous**: ```javascript // FX approach - clean and simple function loadUserDashboard(userId) { // These look synchronous but are highly optimized under the hood! const user = $db.users.find(`#${userId}`); const posts = $db.posts.where(`[userId=${userId}]`); const notifications = $api.notifications.get({ userId }); // DOM updates automatically via reactive binding! $('#username').text($$('user.name')); $('#posts').html($$('user.posts')); $('#notification-badge').text($$('user.notifications.count')); // Set the data - everything else happens automatically $$('user').set({ name: user.name, posts, notifications }); } ``` ## Core Concepts (5 Minutes to Understand) ### 1. Everything is a Node In FX, everything is stored in a **node graph**. Think of it as a giant JavaScript object that's reactive: ```javascript // Create/access nodes with paths $$('app.user.name').set('John'); $$('app.user.email').set('john@example.com'); $$('app.user.age').set(30); // Get values const name = $$('app.user.name').get(); // "John" // The structure looks like: { app: { user: { name: "John", email: "john@example.com", age: 30 } } } ``` ### 2. Everything is Reactive When you change a node, **everything connected to it updates automatically**: ```javascript // Set up automatic DOM updates $('#welcome').text($$('app.user.name')); // Change the data $$('app.user.name').set('Alice'); // DOM automatically shows "Alice" - no manual updates needed! ``` ### 3. Synchronous APIs for Everything Even complex operations feel synchronous: ```javascript // Database query (looks sync, uses SAB + Worker under the hood) const users = $db.users.where('[age>=21]'); // API call (looks sync, uses Worker bridge) const data = $api.external.get('/users/42'); // Cross-server flow (looks sync, uses SAB bridge) $flow('processOrder').start('validate', orderData); // All of these return immediately but work asynchronously in the background! ``` ## Your First FX Application Let's build a simple todo app to learn the basics: ### Step 1: Set Up the HTML ```html FX Todo App

My Todo App

Total: 0 | Completed: 0
``` ### Step 2: Initialize FX and Plugins ```javascript // app.js import { fx, $$ } from './fx.js'; // Load plugins $$('plugins.dom@./plugins/fx-dom-dollar.ts'); $$('plugins.storage@./plugins/fx-cache.ts'); // Initialize app data $$('app.todos').set([]); $$('app.nextId').set(1); console.log('FX Todo App initialized!'); ``` ### Step 3: Set Up Reactive UI ```javascript // Reactive counters (update automatically) $('#total-count').text($$('app.todos.length')); $('#completed-count').text($$('app.todos.completed.length')); // Watch for todo changes and update counts $$('app.todos').watch((todos) => { const completed = todos.filter(todo => todo.completed); $$('app.todos.completed.length').set(completed.length); // Update the todo list display updateTodoDisplay(); }); function updateTodoDisplay() { const todos = $$('app.todos').get(); const todoHTML = todos.map(todo => `
${todo.text}
`).join(''); $('#todo-list').html(todoHTML); } ``` ### Step 4: Add Todo Functionality ```javascript // Add new todo $('#add-todo-form').on('submit', function(e) { e.preventDefault(); const text = $('#new-todo').val(); if (!text) return; // Get current data const todos = $$('app.todos').get(); const nextId = $$('app.nextId').get(); // Add new todo const newTodo = { id: nextId, text: text, completed: false, created: new Date() }; // Update FX state (everything else happens automatically!) $$('app.todos').set([...todos, newTodo]); $$('app.nextId').set(nextId + 1); // Clear input $('#new-todo').val(''); }); // Toggle todo completion function toggleTodo(id) { const todos = $$('app.todos').get(); const updated = todos.map(todo => todo.id === id ? { ...todo, completed: !todo.completed } : todo ); $$('app.todos').set(updated); // UI updates automatically via reactive binding! } // Delete todo function deleteTodo(id) { const todos = $$('app.todos').get(); const filtered = todos.filter(todo => todo.id !== id); $$('app.todos').set(filtered); // UI updates automatically! } ``` ### Step 5: Add Persistence ```javascript // Auto-save todos to cache $$('app.todos').watch((todos) => { $cache.set('saved-todos', todos); }); // Load saved todos on startup const savedTodos = $cache.get('saved-todos'); if (savedTodos) { $$('app.todos').set(savedTodos); } ``` **That's it!** You now have a fully functional todo app with: - ✅ Reactive UI that updates automatically - ✅ Clean, synchronous-feeling code - ✅ Automatic persistence - ✅ No manual DOM updates - ✅ No async/await complexity ## Key Mental Models ### 1. Node Paths are Like File Paths ```javascript $$('app.user.profile.name') // Like app/user/profile/name $$('session.data.token') // Like session/data/token $$('cache.api.users') // Like cache/api/users ``` ### 2. Reactive Binding vs. Snapshots ```javascript // Reactive (updates automatically) $('#output').text($$('data.message')); // Passes the FX node // Snapshot (one-time value) $('#output').text($$('data.message').get()); // Passes the current value // Change data $$('data.message').set('Updated!'); // First example updates automatically, second doesn't ``` ### 3. The $ vs $$ Difference ```javascript // $ = DOM manipulation (fx-dom-dollar plugin) $('#element').text('Hello'); // $$ = FX node access (core FX) $$('app.data').set('Hello'); // They work together $('#element').text($$('app.data')); // DOM element shows FX data ``` ## What Makes FX Special ### 1. No Async Contamination **Traditional frameworks force async everywhere**: ```javascript // This spreads through your entire codebase async function getUser() { return await database.findUser(); } async function updateUI() { const user = await getUser(); /* ... */ } async function handleClick() { await updateUI(); } // Every function becomes async! ``` **FX keeps everything synchronous**: ```javascript // Clean, readable code function getUser() { return $db.users.find('#42'); } function updateUI() { const user = getUser(); /* ... */ } function handleClick() { updateUI(); } // No async contamination! ``` ### 2. Automatic Everything - **DOM Updates**: Change FX data → DOM updates automatically - **Error Handling**: Circuit breakers and retries built-in - **State Persistence**: Auto-save with debouncing - **Performance**: Lazy loading and caching automatic - **Debugging**: Real-time monitoring included ### 3. Plugin Ecosystem FX is designed around plugins that enhance each other: ```javascript // DOM manipulation $('.items').addClass('loading'); // Database operations const items = $db.items.where('[category="urgent"]'); // Procedure flows $flow('processItems').start('validate', items); // Safety nets $safe.circuit('external-api').execute(() => callAPI()); // Time travel debugging $time.snapshot('Before dangerous operation'); // All work together seamlessly! ``` ## Next Steps ### For Beginners: 1. **Try the Interactive Demos**: Visit each plugin page in the showcase 2. **Read Plugin Docs**: Start with [fx-dom-dollar](./01-fx-dom-dollar.md) 3. **Build Something Small**: Create a simple app using the patterns above 4. **Explore Reactivity**: The automatic updates are the key to understanding FX ### For Experienced Developers: 1. **Study the Architecture**: Learn about SharedArrayBuffer + Atomics bridge 2. **Explore Cross-Realm**: See how client/server execution works 3. **Try the Safety System**: Circuit breakers, retries, time travel 4. **Use the DevTools**: Real-time monitoring of everything ### For Framework Developers: 1. **Study the Source**: See how synchronous APIs are implemented 2. **Create Plugins**: Extend FX with your own reactive plugins 3. **Contribute**: Help improve the ecosystem ## Development Environment ### Quick Start: ```bash # Full development mode with DevTools deno run --allow-all fx-dev.ts # Opens: # - Showcase: http://localhost:8787 # - DevTools: http://localhost:8787/__fx-devtools ``` ### Or Client-Only: ```bash # Use VS Code Live Server # Right-click index.html → "Open with Live Server" ``` ## Learning Path 1. **🎯 DOM Manipulation** - Start here if you know jQuery 2. **🗄️ Database Operations** - Learn the revolutionary ORM 3. **🔄 Flow Control** - Dynamic procedure graphs 4. **🛡️ Safety Systems** - Circuit breakers and time travel 5. **💾 Data Persistence** - Serialization and caching 6. **📊 Visualization** - Real-time graph monitoring 7. **🔧 DevTools** - Professional debugging experience --- **Welcome to the future of reactive programming! 🎉** FX Framework eliminates the complexity of async code while providing more power than any other framework. You're about to discover a completely new way to build applications!