Skip to content

mineclover/context-action

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Context-Action Framework

npm version TypeScript License Build Status

Revolutionary TypeScript state management with document-centric context separation and MVVM architecture.

๐ŸŽฏ Perfect separation of concerns โ€ข ๐Ÿ”’ Full type safety โ€ข โšก Zero boilerplate โ€ข ๐Ÿ—๏ธ Scalable architecture

๐Ÿ“š Documentation โ€ข ๐Ÿ‡ฐ๐Ÿ‡ท ํ•œ๊ตญ์–ด ๋ฌธ์„œ โ€ข ๐ŸŽฎ Live Demo โ€ข ๐Ÿš€ Quick Start


โšก Quick Start

Installation

npm install @context-action/react
# or
npm install @context-action/core  # Pure TypeScript

30-Second Example

import { createStoreContext, useStoreValue } from '@context-action/react';
import { useCallback } from 'react';

// 1. Create context
const { Provider, useStore } = createStoreContext('User', {
  profile: { name: 'John', email: 'john@example.com' }
});

// 2. Use in component  
function UserProfile() {
  const profileStore = useStore('profile');
  const profile = useStoreValue(profileStore);
  
  return <h1>Welcome, {profile.name}!</h1>;
}

// 3. Wrap with provider
function App() {
  return (
    <Provider>
      <UserProfile />
    </Provider>
  );
}

That's it! ๐ŸŽ‰ Full type safety, reactive updates, and clean architecture.


๐ŸŽฏ Why Context-Action?

โŒ Problems with Existing Libraries

  • High React Coupling โ†’ Difficult component modularization
  • Binary State Approach โ†’ Poor scope-based separation
  • Complex Boilerplate โ†’ Verbose setup and maintenance

โœ… Context-Action's Solution

  • ๐ŸŽฏ Document-Centric Design โ†’ Context separation based on domain boundaries
  • ๐Ÿ—๏ธ MVVM Architecture โ†’ Perfect separation: Model, ViewModel, View layers
  • ๐Ÿ”’ Type-First Approach โ†’ Zero runtime errors with full TypeScript support
  • โšก Zero Boilerplate โ†’ Minimal code, maximum functionality

๐Ÿš€ Key Benefits

// Before: Complex setup with multiple libraries
const store = createStore(reducer);
const dispatch = useDispatch();
const selector = useSelector(state => state.user);
const actions = bindActionCreators(userActions, dispatch);

// After: One line with Context-Action
const { profile, updateProfile } = useUserPage(); // All logic in hook

๐Ÿ—๏ธ Core Patterns

๐Ÿช Store Pattern

Pure state management with reactive subscriptions

const { Provider: UserStoreProvider, useStore: useUserStore } = createStoreContext('User', {
  profile: { name: '', email: '' },
  settings: { theme: 'light' }
});

function UserComponent() {
  const profileStore = useUserStore('profile');
  const profile = useStoreValue(profileStore);

  return <div>{profile.name}</div>;
}

๐ŸŽฏ Action Pattern

Pure action dispatching with business logic separation

interface UserActions extends ActionPayloadMap {
  updateProfile: { name: string; email: string };
  logout: void;
}

const { Provider, useActionDispatch, useActionHandler } =
  createActionContext<UserActions>('UserActions');

function UserLogic() {
  const updateProfileHandler = useCallback(async (payload) => {
    // Business logic here
    await updateUserAPI(payload);
  }, []);

  useActionHandler('updateProfile', updateProfileHandler);
  
  return null; // Logic component
}

๐Ÿ”— Pattern Composition

Combine patterns for complex applications

// MVVM Architecture
function App() {
  return (
    <UserActionProvider>     {/* ViewModel */}
      <UserStoreProvider>    {/* Model */}
        <UserLogic>          {/* Business Logic */}
          <UserProfile />    {/* View */}
        </UserLogic>
      </UserStoreProvider>
    </UserActionProvider>
  );
}

๐Ÿ—๏ธ 5-Layer Hooks Architecture

Context-Action implements a sophisticated 5-layer hooks architecture that provides perfect separation of concerns and optimal performance through delayed evaluation.

graph TD
    %% Context Share Layer
    subgraph ContextShare["Context Share Layer Provider"]
        Store[Store]
        subgraph ActionsContainer["Actions"]
            Actions[Actions]
            Pipeline[Pipeline<br/>- Business logic registration<br/>- Execution order management<br/>- Middleware processing]
        end
        Ref[Ref<br/>- Singleton instance management]
    end

    %% 6-Layer Hooks Structure
    subgraph Hooks["6-Layer Hooks Consumer"]
        ContextDef[contexts<br/>Resource type definitions]
        Business[business<br/>Pure business logic<br/>functions]
        Handlers[handlers<br/>Handler injection pattern<br/>implementation]
        Actions[actions<br/>Action dispatch<br/>callback functions]
        Subscriptions[hooks<br/>Store subscriptions<br/>computed values]
        Views[views<br/>Pure UI components]
    end

    %% UI Layer
    subgraph UI["UI Layer - views"]
        Page[Page - route]
        Layout[Layout - device Layer]
        Widget[Widget - design system]
    end

    %% Data Flow
    Store -->|State management| ContextDef
    ContextDef -->|Type definitions| Business
    Business -->|Pure functions| Handlers
    Handlers -->|Handler injection| Actions
    Actions -->|Action execution| Pipeline
    Pipeline -->|Pipeline execution| Store
    Store -->|Subscription| Subscriptions
    Subscriptions -->|Data transfer| Views
    Views -->|UI rendering| UI
    Actions -->|Action dispatch| Pipeline

    %% UI Mount Order
    Page -->|Mount| Layout
    Layout -->|Mount| Widget
Loading

๐Ÿ”„ Data Flow Principles

  1. Context Share Layer (Provider)

    • Store: Centralized state management with reactive subscriptions
    • Actions/Pipeline: Business logic registration and execution order management
    • Ref: Singleton instance management for performance optimization
  2. 6-Layer Hooks Structure (Consumer)

    • contexts: Resource type definitions and context access
    • business: Pure business logic functions separated from side effects
    • handlers: Handler injection pattern implementation with latest value access
    • actions: Action dispatch functions and callback management
    • hooks: Store subscriptions and computed values for reactive data
    • views: Pure UI components with minimal coupling
  3. UI Layer (Views)

    • Page: Route-level components
    • Layout: Device-specific layout components
    • Widget: Design system components

โšก Performance Benefits

  • Delayed Evaluation: Handlers access latest state via store.getValue()
  • Selective Subscriptions: Components subscribe only to needed state slices
  • Minimal Re-renders: Optimized dependency tracking prevents unnecessary updates
  • Singleton Management: Ref layer ensures efficient resource sharing
// 6-Layer Implementation Example
function UserPage() {
  // Layer 1: contexts - Resource type definitions
  const userStore = useUserStore('profile');

  // Layer 2: handlers - Internal function definitions
  const updateUserHandler = useCallback(async (payload) => {
    const currentUser = userStore.getValue(); // Delayed evaluation
    const updatedUser = { ...currentUser, ...payload };
    userStore.setValue(updatedUser);
  }, [userStore]);

  // Layer 3: subscriptions - Selective state subscriptions
  const user = useStoreValue(userStore);

  // Layer 4: registries - Handler registration
  useActionHandler('updateUser', updateUserHandler);

  // Layer 5: dispatchers - View-oriented action dispatchers
  const onUpdateUser = useActionDispatch('updateUser');

  return (
    <div>
      <h1>{user.name}</h1>
      <button onClick={() => onUpdateUser({ name: 'New Name' })}>
        Update User
      </button>
    </div>
  );
}

๐Ÿ”— Type System Guidelines

Context-Action implements a sophisticated type system that provides full TypeScript safety across Action, Store, and Ref connections with zero runtime overhead.

๐ŸŽฏ Type Declaration Architecture

graph TB
    %% Type Declaration Layer
    subgraph TypeDeclarations["๐Ÿ”ค Type Declaration Layer"]
        PayloadMap[ActionPayloadMap<br/>Action payload type map]
        StoreTypes[StoreDefinitions<br/>Store type definitions]
        RefTypes[Ref Types<br/>Singleton reference types]
    end

    %% Context Creation Layer
    subgraph ContextCreation["โš™๏ธ Context Creation Layer"]
        ActionContext[createActionContext&lt;T&gt;<br/>Action context creation]
        StoreContext[createStoreContext&lt;T&gt;<br/>Store context creation]
        RefManager[RefManager&lt;T&gt;<br/>Reference manager]
    end

    %% Hook Layer
    subgraph HookLayer["๐Ÿช Hook Layer"]
        ActionHooks[useActionDispatch<br/>useActionHandler]
        StoreHooks[useStore<br/>useStoreValue]
        RefHooks[useRef<br/>useCallback]
    end

    %% Type Flow Connections
    PayloadMap -->|extends| ActionContext
    StoreTypes -->|initialStores| StoreContext
    RefTypes -->|singleton| RefManager

    ActionContext -->|typed hooks| ActionHooks
    StoreContext -->|typed hooks| StoreHooks
    RefManager -->|stable refs| RefHooks

    %% Type Safety Flow
    ActionHooks -->|type-safe dispatch| PayloadMap
    StoreHooks -->|reactive types| StoreTypes
    RefHooks -->|stable references| RefTypes
Loading

โšก Type Connection Patterns

1. Action Type Declaration & Connection

// 1๏ธโƒฃ Define Action Payload Types
interface UserActions extends ActionPayloadMap {
  updateProfile: { name: string; email: string; avatar?: File };
  deleteAccount: { confirmPassword: string };
  logout: void; // No payload
}

// 2๏ธโƒฃ Create Typed Action Context
const {
  Provider: UserActionProvider,
  useActionDispatch: useUserAction,
  useActionHandler: useUserActionHandler
} = createActionContext<UserActions>('UserActions');

// 3๏ธโƒฃ Type-Safe Handler Registration
function UserLogic() {
  // โœ… Payload automatically typed as { name: string; email: string; avatar?: File }
  useUserActionHandler('updateProfile', useCallback(async (payload) => {
    // payload.name โœ… string
    // payload.email โœ… string
    // payload.avatar โœ… File | undefined
    await updateUserAPI(payload);
  }, []));

  // โœ… Payload automatically typed as void
  useUserActionHandler('logout', useCallback(async () => {
    await clearSession();
  }, []));
}

// 4๏ธโƒฃ Type-Safe Action Dispatching
function UserComponent() {
  const dispatch = useUserAction();

  return (
    <button onClick={() =>
      dispatch('updateProfile', {
        name: 'John',
        email: 'john@example.com'
        // โœ… TypeScript enforces correct payload shape
      })
    }>
      Update Profile
    </button>
  );
}

2. Store Type Declaration & Connection

// 1๏ธโƒฃ Define Store Types (Two Approaches)

// Approach A: Simple Object Types
const { Provider, useStore } = createStoreContext('User', {
  profile: { name: '', email: '', isOnline: false }, // โœ… Type inferred
  settings: { theme: 'light' as const, notifications: true }, // โœ… const assertions
  preferences: { language: 'en', timezone: 'UTC' }
});

// Approach B: Explicit Store Configuration
interface UserStoreConfig {
  profile: StoreConfig<UserProfile>;
  settings: StoreConfig<UserSettings>;
  cache: StoreConfig<CacheData>; // โœ… With strategy configuration
}

const { Provider, useStore } = createStoreContext('User', {
  profile: { initialValue: { name: '', email: '' } },
  settings: { initialValue: { theme: 'light' }, strategy: 'shallow' },
  cache: { initialValue: new Map(), strategy: 'reference' }
} satisfies UserStoreConfig);

// 2๏ธโƒฃ Type-Safe Store Access & Subscription
function UserProfile() {
  const profileStore = useStore('profile'); // โœ… Store<UserProfile>
  const profile = useStoreValue(profileStore); // โœ… UserProfile type

  // โœ… Type-safe store operations
  profileStore.setValue({ name: 'John', email: 'john@example.com', isOnline: true });
  profileStore.update(prev => ({ ...prev, isOnline: !prev.isOnline }));

  return <div>{profile.name}</div>; // โœ… profile.name is string
}

3. Ref Type Declaration & Singleton Management

// 1๏ธโƒฃ Ref Type Declarations for Singleton Resources
interface AppRefs {
  apiClient: ApiClient;
  eventBus: EventBus;
  cache: LRUCache<string, any>;
}

// 2๏ธโƒฃ Context with Ref Management
const {
  Provider: AppProvider,
  useStore,
  useRef: useAppRef
} = createStoreContext('App', {
  user: { name: '', email: '' },
  // โœ… Ref types managed alongside stores
}, {
  refs: {
    apiClient: () => new ApiClient(),
    eventBus: () => new EventBus(),
    cache: () => new LRUCache(1000)
  } as AppRefs
});

// 3๏ธโƒฃ Type-Safe Ref Access
function ApiComponent() {
  const apiClient = useAppRef('apiClient'); // โœ… ApiClient type
  const userStore = useStore('user');

  const fetchUser = useCallback(async (id: string) => {
    // โœ… apiClient.get is typed method
    const userData = await apiClient.get(`/users/${id}`);
    userStore.setValue(userData);
  }, [apiClient, userStore]);

  return <button onClick={() => fetchUser('123')}>Fetch User</button>;
}

๐Ÿ›ก๏ธ Type Safety Benefits

Compile-Time Validation

  • โœ… Action Payload Validation: Incorrect payload shapes caught at compile time
  • โœ… Store Type Consistency: Store value types enforced across components
  • โœ… Ref Type Stability: Singleton reference types maintained across re-renders
  • โœ… Hook Return Types: All hooks return properly typed values and functions

IntelliSense & Developer Experience

  • ๐Ÿ” Auto-completion: Full IntelliSense for action names, payload properties, store keys
  • ๐Ÿท๏ธ Type Hints: Hover information shows exact payload and store types
  • โš ๏ธ Error Prevention: TypeScript prevents runtime errors before they happen
  • ๐Ÿ”„ Refactoring Safety: Type-safe refactoring across the entire codebase

Zero Runtime Overhead

  • โšก Compile-Time Only: All type information removed in production builds
  • ๐Ÿ“ฆ No Type Libraries: No runtime type checking dependencies
  • ๐ŸŽฏ Direct Performance: Types guide optimization without runtime cost

๐Ÿ“š Detailed Type System Documentation

For comprehensive type system coverage, see our dedicated guides:

English Documentation

Korean Documentation

Core Type System Features

  • Action Type Safety: Complete ActionPayloadMap interface with pipeline controller types
  • Store Type Inference: Automatic type inference from initial values with strategy support
  • Handler Configuration: Type-safe handler registration with comprehensive options
  • Integration Patterns: Store integration, async handling, and error management
  • Advanced Features: Conditional types, branded types, and generic utilities

๐Ÿ“‹ API Reference

Core Functions

createStoreContext(name, stores)

Create typed store context with reactive subscriptions.

const { Provider, useStore } = createStoreContext('App', {
  user: { name: '', email: '' },
  settings: { theme: 'light' }
});

createActionContext<T>(name)

Create typed action context with pipeline processing.

interface Actions extends ActionPayloadMap {
  update: { id: string };
}
const { Provider, useActionDispatch } = createActionContext<Actions>('App');

Essential Hooks

useStoreValue(store)

Subscribe to store changes with automatic re-renders.

const userStore = useStore('user');
const user = useStoreValue(userStore); // Reactive subscription

useActionHandler(action, handler)

Register business logic handlers for actions.

const updateProfileHandler = useCallback(async (payload) => {
  // Business logic here
}, []);

useActionHandler('updateProfile', updateProfileHandler);

useActionDispatch()

Dispatch actions to the pipeline.

const dispatch = useActionDispatch();
dispatch('updateProfile', { name: 'John', email: 'john@example.com' });

๐ŸŽฎ Examples & Demos

๐Ÿš€ Live Interactive Examples

Explore 20+ working examples โ†’

๐Ÿช Store System

๐ŸŽฏ Action System

๐Ÿ”— MVVM Architecture

๐Ÿ“– Real-World Examples

// E-commerce Cart System
const CartStores = createStoreContext('Cart', {
  items: [] as CartItem[],
  total: 0,
  shipping: { method: 'standard', cost: 0 }
});

// User Management System  
interface UserActions extends ActionPayloadMap {
  login: { email: string; password: string };
  updateProfile: Partial<UserProfile>;
  logout: void;
}

๐Ÿ” New in v0.7.0: Enhanced LogMonitor Documentation

  • ๐Ÿ“Š Logger System Demo - Interactive LogMonitor showcase
  • Real-time log collection - Live demo with practical examples
  • Integration patterns - Parent/Child handler implementations
  • Dependency warnings - Avoid infinite loops with best practices

๐Ÿ—๏ธ Architecture

Context-Action Framework implements multiple architectural approaches for different application needs:

๐Ÿ“ Context-Driven Architecture

Context-Driven Architecture - Core frontend architecture for clear document-based separation

Philosophy: "The document is the architecture" - Each context exists as a unit for managing documents and deliverables of its domain.

Key Features:

  • Document-Centric Context Separation: Clear boundaries between domain contexts
  • 6-Layer Hooks Architecture: Provider/Consumer pattern with delayed evaluation
  • Domain Context Isolation: Business, UI, Validation, Design, Architecture contexts
  • Effective Artifact Management: State management supporting document-deliverable relationships

๐Ÿ”ง Implementation Guides


๐Ÿ“š Documentation

๐Ÿ“– Complete Guides

๐ŸŒ Multi-Language Support


๐Ÿ“ฆ Packages

Pure TypeScript action pipeline - Framework agnostic core

npm install @context-action/core
  • ๐Ÿ”’ Full TypeScript support
  • โšก Action pipeline system
  • ๐Ÿ›ก๏ธ Advanced action guards
  • ๐Ÿšซ Zero dependencies

React integration - Complete MVVM architecture

npm install @context-action/react
  • ๐Ÿช Declarative store patterns
  • ๐ŸŽฏ Action context integration
  • ๐Ÿช Advanced React hooks
  • ๐Ÿ—๏ธ HOC support

๐Ÿ› ๏ธ Development

Quick Development Setup

git clone https://github.com/mineclover/context-action.git
cd context-action
pnpm install
pnpm dev  # Start example app

Project Resources


๐Ÿ“„ License

Apache-2.0 ยฉ mineclover


Built with โค๏ธ for modern TypeScript applications

โญ Star on GitHub โ€ข ๐Ÿ› Report Bug โ€ข ๐Ÿ’ก Request Feature

About

No description, website, or topics provided.

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •