-
Notifications
You must be signed in to change notification settings - Fork 4
feat: context api #15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
|
Caution Review failedThe pull request is closed. Note Other AI code review bot(s) detectedCodeRabbit 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. WalkthroughAdds 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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
Comment |
There was a problem hiding this 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, anduseContext - Fixed compiler to wrap component calls in
htmltemplate 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.
There was a problem hiding this 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 templatesWrapping 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 checkWrapping 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 consistencyElsewhere 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-guardThrowing 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 cleanupdispose_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 internalsget_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
⛔ Files ignored due to path filters (6)
packages/compiler/src/__tests__/__snapshots__/children-reactive.spec.ts.snapis excluded by!**/*.snappackages/compiler/src/__tests__/__snapshots__/ref-directive.spec.ts.snapis excluded by!**/*.snappackages/compiler/src/__tests__/__snapshots__/spread-props.spec.ts.snapis excluded by!**/*.snappackages/compiler/src/__tests__/__snapshots__/test.spec.ts.snapis excluded by!**/*.snappackages/compiler/src/__tests__/__snapshots__/unwrapped-components.spec.ts.snapis excluded by!**/*.snappnpm-lock.yamlis 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 removinguntrackedwrappers is documented and tested.The git diff confirms this change is intentional (commit 318f321):
untrackedwrappers were removed from bothprops.childrenandprops.fallbackin 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.snapand contains 23 snapshot entries with the expected transformation patterns:htmltemplate literals,component()calls,get children()reactive getters, and correct imports fromkaori.js. The Vitest snapshot format is valid.packages/playground/src/main.tsx (2)
148-148: Context shape is clearUsing Signal<'light' | 'dark'> | null with a null default is fine, and the consumer null-guards. LGTM.
190-227: Provider placement looks rightWrapping 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 solidCaching template and batching setValue via schedule_update is sound; guarding on isConnected prevents stray writes. LGTM.
352-359: Export surface changesRenaming kaori_effect as effect and adding useContext/createContext/provideContext exports is fine. Ensure docs and any downstream packages are updated accordingly.
Added context api
Fix compiler issues with lifecycle and rerendering
Summary by CodeRabbit
New Features
Documentation
Bug Fixes
Tests