Skip to content

Implement context API (createContext and useContext) for dsl-lite #199

@rafbcampos

Description

@rafbcampos

Description

Implement a React-like context API for dsl-lite to allow component authors to share values without explicit prop passing. This should include both createContext and useContext functions.

Tasks

  • Implement a context stack mechanism to manage context values
  • Create createContext function to create context objects
  • Implement useContext hook to consume context values
  • Ensure proper typing for context values
  • Add provider functionality to inject context values
  • Create tests for context creation and consumption

Technical Details

// Context implementation
const contextStack: Array<{ context: any, value: any }> = [];

// createContext function
export function createContext<T>(defaultValue: T) {
  const context = {
    $$typeof: Symbol.for('jsx.context'),
    _defaultValue: defaultValue,
    Provider: null as any
  };

  context.Provider = {
    $$typeof: Symbol.for('jsx.provider'),
    _context: context
  };

  return context;
}

// useContext hook
export function useContext<T>(context: any): T {
  hookIndex++; // Increment hook index to maintain order

  // Search for context in stack
  for (let i = contextStack.length - 1; i >= 0; i--) {
    if (contextStack[i].context === context) {
      return contextStack[i].value;
    }
  }

  // Return default if not found
  return context._defaultValue;
}

// Push context to stack
export function pushContext(context: any, value: any) {
  contextStack.push({ context, value });
}

// Pop context from stack
export function popContext() {
  contextStack.pop();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request
    No fields configured for Feature.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions