Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@golok727
Copy link
Owner

@golok727 golok727 commented Oct 24, 2025

Added context api
Fix compiler issues with lifecycle and rerendering

Summary by CodeRabbit

  • New Features

    • Public Context API added: createContext, useContext and provideContext to share state across components.
    • Example Theme provider added to the playground demonstrating context usage.
  • Documentation

    • Comprehensive Context API guide with patterns, examples, TypeScript guidance, and best practices.
  • Bug Fixes

    • Improved reactivity in control-flow components.
    • Effect utility renamed for consistent public export.
  • Tests

    • New comprehensive test suite covering component transformation scenarios.

@coderabbitai
Copy link

coderabbitai bot commented Oct 24, 2025

Caution

Review failed

The pull request is closed.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds a Context API and lifecycle teardown utilities to kaori.js, updates compiler JSX handling to wrap component calls in html template literals, introduces tests and docs for unwrapped components and Context, bumps several package versions, adds jsdom dev dependency, and adds a Theme context demo in the playground.

Changes

Cohort / File(s) Summary
Context core & lifecycle
packages/kaori/src/index.ts, packages/kaori/src/flow.ts
Introduced Context types and utilities (create_context, provide_context, get_context) exported as createContext, provideContext, useContext; added KaoriContextSymbol; added provide to ComponentHandle; centralized teardown via handle_add_teardown; simplified Show branch returns by removing untracked. Renamed/exported effect API (kaori_effecteffect) and adjusted internal handle fields and disposal flow.
Compiler transform & tests
packages/compiler/src/babel-plugin.ts, packages/compiler/src/__tests__/unwrapped-components.spec.ts
Compiler now wraps JSX component invocations in html\`` template literals and ensures html` import when needed. Added extensive tests validating wrapping behavior across nested structures, control flow, fragments, arrays, and edge cases.
Playground demo
packages/playground/src/main.tsx, packages/playground/src/eye.tsx
Added ThemeContext, ThemeProvider, and ContextExample demonstrating create/provide/useContext with signals; updated imports. eye.tsx had comment cleanup only.
Documentation
docs/guide/context.md
New comprehensive Context guide covering rationale, creation, provision, consumption, multiple contexts, reactivity, custom hooks, TypeScript examples, and best practices with code samples.
Package version bumps
packages/kaori/package.json, packages/compiler/package.json, packages/create-kaori/package.json
Bumped package versions: kaori 0.0.9 → 0.0.10, compiler 0.0.9 → 0.0.10, create-kaori 0.0.13 → 0.0.14.
Template dependency updates
packages/create-kaori/templates/basic/package.json, packages/create-kaori/templates/tailwind/package.json
Updated template dependencies: kaori.js and kaori-compiler from ^0.0.9^0.0.10.
Root dev dependencies
package.json
Added jsdom ^27.0.1 to devDependencies.

Sequence Diagram(s)

sequenceDiagram
    participant ProviderComp as Provider Component
    participant Runtime as kaori runtime
    participant Handle as ComponentHandle/__h
    participant ConsumerComp as Consumer Component

    ProviderComp->>Runtime: createContext(default)
    Runtime-->>ProviderComp: Context<T>

    ProviderComp->>Handle: provide(context, value)
    Handle->>Runtime: store context value (directive map)

    ConsumerComp->>Runtime: useContext(context)
    Runtime->>Handle: traverse directive/handle tree
    alt found
        Handle-->>Runtime: return provided value
        Runtime-->>ConsumerComp: value
    else not found
        Runtime-->>ConsumerComp: default value
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Poem

🐇 I tunneled through code to plant a seed,
A context for themes and every deed,
Providers snug, consumers hop in line,
Signals ripple — oh how they shine! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.76% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "feat: context api" directly and accurately reflects the primary objective of the changeset. The changes introduce a new Context system to kaori.js, including new public APIs (createContext, useContext, provideContext), a Context type, context-providing capability via ComponentHandle.provide, comprehensive documentation, tests, and example implementations. The title is concise, specific, and uses proper conventional commit format, making it clear to reviewers and future history browsers that this PR adds context API functionality.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 44fb311 and 881defe.

📒 Files selected for processing (1)
  • packages/kaori/src/index.ts (7 hunks)

Comment @coderabbitai help to get the list of available commands and usage tips.

@golok727 golok727 requested a review from Copilot October 24, 2025 10:55
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR introduces a Context API to the Kaori.js framework, enabling component tree-based data sharing without explicit prop drilling. The implementation includes core context functionality (creation, provision, consumption), compiler updates to properly wrap component calls in HTML templates, and comprehensive documentation.

Key changes:

  • Added context API functions: createContext, provideContext, and useContext
  • Fixed compiler to wrap component calls in html template literals for proper rendering
  • Updated lifecycle management to support context traversal through parent chains

Reviewed Changes

Copilot reviewed 18 out of 19 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
packages/kaori/src/index.ts Implements context API with tree traversal, updates component lifecycle management, and adds teardown handling
packages/kaori/src/flow.ts Removes untracked wrapper from Show component children
packages/compiler/src/babel-plugin.ts Wraps component calls in html template literals for proper lit-html integration
packages/compiler/src/tests/unwrapped-components.spec.ts Comprehensive test suite for component wrapping behavior
packages/playground/src/main.tsx Demo implementation of context API with ThemeProvider example
packages/playground/src/eye.tsx Removes excessive comments for cleaner code
docs/guide/context.md Complete documentation for context API usage patterns
packages/*/package.json Version bumps to 0.0.10 across packages
Files not reviewed (1)
  • pnpm-lock.yaml: Language not supported

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

@golok727 golok727 merged commit 1aadea2 into main Oct 24, 2025
1 check passed
@golok727 golok727 deleted the context branch October 24, 2025 10:59
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (7)
packages/compiler/src/__tests__/unwrapped-components.spec.ts (1)

420-437: Consider reducing snapshot dependency for better maintainability.

While snapshots are useful, this test suite relies heavily on them (19 instances). Consider adding more specific assertions for critical transformation patterns to make test failures more debuggable and reduce the maintenance burden when intentional output format changes occur.

For example, augment snapshot tests with targeted assertions like:

// In addition to snapshots, verify specific patterns
expect(output).toMatch(/html`\$\{component\(Child.*\)\(\)\}`/);
expect(output).toContain('get children()');
packages/compiler/src/babel-plugin.ts (2)

478-491: Good call wrapping components in html templates

Wrapping component JSX in html`` prevents passing a bare directive to render and guarantees a TemplateResult. Consider a light guard to skip wrapping if the expression is already a TaggedTemplateExpression to avoid accidental double-wrapping in future transforms.


1026-1039: Children component wrapping: consistency check

Wrapping component children in html`` aligns their type with other child TemplateResults. Verify no callers expect raw directive results for children; if any do, gate wrapping behind a check or an option to avoid changing their semantics.

packages/playground/src/main.tsx (2)

230-237: TS: children type consistency

Elsewhere in this file you use JSX.JSXElement for children. To avoid TS friction, align the provider’s prop type.

Apply one of:

-function ThemeProvider(props: { children: JSX.Element }) {
+function ThemeProvider(props: { children: JSX.JSXElement }) {

Or, broaden:

-function ThemeProvider(props: { children: JSX.Element }) {
+function ThemeProvider(props: { children: JSX.Element | JSX.JSXElement }) {

239-244: Consumer null-guard

Throwing if context is missing makes failures obvious in dev. Consider extracting a useTheme() helper that encapsulates this pattern for reuse.

packages/kaori/src/index.ts (2)

167-186: Remove debug logs from core cleanup

dispose_handle still logs “Here” and dumps directive objects. Route through KaoriLogger or remove to keep library output clean.

Apply:

-  console.log('Here', directive);
+  // (optional) logger.log('Disposed', handle.dbg_n);

216-252: Fragile traversal of lit-html internals

get_context relies on non-public fields (__part, _$parent, __directive). This may break with lit-html updates. Add guards and avoid console.log noise.

Proposed hardening:

-  while (directive) {
-    console.log(directive);
-    const c_map = (directive as any).__c as Map<symbol, any> | undefined;
+  while (directive) {
+    const c_map = (directive as any).__c as Map<symbol, any> | undefined;
     if (c_map && c_map.has(cx.__key)) {
       return c_map.get(cx.__key)!;
     }
-    let part = (directive as any).__part as Part | undefined;
+    let part = (directive as any).__part as Part | undefined;
     let nextDirective = null;
     while (part) {
-      const parent = (part as any)._$parent as Part | undefined;
+      const parent = (part as any)._$parent as Part | undefined;
       if (
         parent &&
         '__directive' in parent &&
         parent.__directive instanceof ComponentDirective
       ) {
         nextDirective = parent.__directive;
         break;
       }
       part = parent;
     }
     directive = nextDirective;
   }

And consider feature-detecting these properties and falling back to cx.__default when absent, to avoid runtime crashes.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6a2fb87 and 44fb311.

⛔ Files ignored due to path filters (6)
  • packages/compiler/src/__tests__/__snapshots__/children-reactive.spec.ts.snap is excluded by !**/*.snap
  • packages/compiler/src/__tests__/__snapshots__/ref-directive.spec.ts.snap is excluded by !**/*.snap
  • packages/compiler/src/__tests__/__snapshots__/spread-props.spec.ts.snap is excluded by !**/*.snap
  • packages/compiler/src/__tests__/__snapshots__/test.spec.ts.snap is excluded by !**/*.snap
  • packages/compiler/src/__tests__/__snapshots__/unwrapped-components.spec.ts.snap is excluded by !**/*.snap
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (13)
  • docs/guide/context.md (1 hunks)
  • package.json (1 hunks)
  • packages/compiler/package.json (1 hunks)
  • packages/compiler/src/__tests__/unwrapped-components.spec.ts (1 hunks)
  • packages/compiler/src/babel-plugin.ts (2 hunks)
  • packages/create-kaori/package.json (1 hunks)
  • packages/create-kaori/templates/basic/package.json (1 hunks)
  • packages/create-kaori/templates/tailwind/package.json (1 hunks)
  • packages/kaori/package.json (1 hunks)
  • packages/kaori/src/flow.ts (1 hunks)
  • packages/kaori/src/index.ts (7 hunks)
  • packages/playground/src/eye.tsx (1 hunks)
  • packages/playground/src/main.tsx (4 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
packages/compiler/src/__tests__/unwrapped-components.spec.ts (1)
packages/compiler/src/__tests__/utils.ts (1)
  • compile (4-12)
packages/playground/src/main.tsx (2)
packages/kaori/src/index.ts (4)
  • Signal (366-366)
  • nothing (378-378)
  • Show (342-342)
  • signal (365-365)
packages/kaori/src/flow.ts (1)
  • Show (34-44)
packages/kaori/src/index.ts (2)
packages/kaori/src/utils.ts (1)
  • invariant (1-8)
packages/kaori/src/types.ts (1)
  • Component (1-3)
🔇 Additional comments (13)
packages/playground/src/eye.tsx (1)

6-6: LGTM - Cosmetic cleanup with no runtime impact.

The whitespace and comment removal keeps the code clean without affecting functionality. The eye-tracking implementation remains correct with proper event cleanup and signal management.

package.json (1)

22-22: LGTM!

Adding jsdom as a dev dependency is appropriate for testing DOM-related features like the new Context API.

packages/create-kaori/package.json (1)

3-3: LGTM!

Version bump aligns with the broader package updates in this release.

packages/kaori/package.json (1)

3-3: LGTM!

Version bump reflects the new Context API features introduced in this release.

packages/create-kaori/templates/tailwind/package.json (1)

12-12: LGTM!

Dependency versions correctly updated to align with the new kaori.js and kaori-compiler releases.

Also applies to: 16-16

packages/compiler/package.json (1)

3-3: LGTM!

Version bump coordinated with the broader release.

packages/create-kaori/templates/basic/package.json (1)

12-12: LGTM!

Dependency versions correctly updated to match the new releases.

Also applies to: 15-15

packages/kaori/src/flow.ts (1)

39-42: Verify the impact of removing untracked wrappers is documented and tested.

The git diff confirms this change is intentional (commit 318f321): untracked wrappers were removed from both props.children and props.fallback in the Show component. This enables reactive tracking where it was previously disabled.

The removal impacts Show usages in:

  • packages/playground/src/main.tsx
  • packages/create-kaori/templates (basic and tailwind)
  • packages/compiler/tests (test.spec.ts, unwrapped-components.spec.ts)

Ensure the following are addressed before merging:

  • Verify existing Show usages continue to work with the new reactive tracking behavior
  • Add migration guidance documenting this behavioral change
  • Confirm tests cover the reactive behavior (compiler tests exist but focus on code generation, not runtime reactivity)
packages/compiler/src/__tests__/unwrapped-components.spec.ts (1)

1-492: All snapshot verification checks pass.

Snapshot file is properly committed to the repository at packages/compiler/src/__tests__/__snapshots__/unwrapped-components.spec.ts.snap and contains 23 snapshot entries with the expected transformation patterns: html template literals, component() calls, get children() reactive getters, and correct imports from kaori.js. The Vitest snapshot format is valid.

packages/playground/src/main.tsx (2)

148-148: Context shape is clear

Using Signal<'light' | 'dark'> | null with a null default is fine, and the consumer null-guards. LGTM.


190-227: Provider placement looks right

Wrapping the existing UI with ThemeProvider and consuming via ContextExample is correct and follows setup‑phase context usage.

packages/kaori/src/index.ts (2)

278-318: Update scheduling and caching look solid

Caching template and batching setValue via schedule_update is sound; guarding on isConnected prevents stray writes. LGTM.


352-359: Export surface changes

Renaming kaori_effect as effect and adding useContext/createContext/provideContext exports is fine. Ensure docs and any downstream packages are updated accordingly.

@golok727 golok727 linked an issue Oct 24, 2025 that may be closed by this pull request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[core] context api

2 participants