diff --git a/.gitignore b/.gitignore index 2ef857f48..bcac9e498 100755 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,6 @@ node_modules/ test/coverage/ coverage/ -src/**/site/ -theme.config -semantic.json -tasks/**/oauth.js playwright_report/ dev/examples/ dev/ui/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..7d945e720 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,256 @@ +# Semantic UI - Claude Code Integration Guide + +This file provides Claude Code-specific guidance for working with the Semantic UI web component framework. It acts as an intelligent entry point to the comprehensive AI context system located in `/ai/`. + +## Context Loading Strategy + +### **Essential Context Foundation** +Always load these foundational files for any Semantic UI task: +1. **[`ai/00-START-HERE.md`](ai/00-START-HERE.md)** - Navigation hub and task-based routing +2. **[`ai/foundations/mental-model.md`](ai/foundations/mental-model.md)** - Core architectural concepts + +### **Task-Based Context Loading** +``` +Building Components → ai/guides/component-generation-instructions.md +Debugging Issues → ai/foundations/codebase-navigation-guide.md +Implementation Patterns → ai/guides/patterns-cookbook.md +API Reference → ai/foundations/quick-reference.md +HTML/CSS Work → ai/guides/html-css-style-guide.md +``` + +## Claude Code Specific Workflows + +### **Component Development Workflow** +1. **Plan Task**: Use TodoWrite tool for multi-step component work +2. **Load Context**: Read `ai/guides/component-generation-instructions.md` +3. **Explore Codebase**: Use Glob/Grep tools to find similar components +4. **Implement**: Follow established patterns from examples +5. **Validate**: Run lint/typecheck commands if available +6. **Mark Complete**: Update TodoWrite with progress + +### **Debugging Workflow** +1. **Read Navigation Guide**: `ai/foundations/codebase-navigation-guide.md` +2. **Use Search Tools**: Prefer Task tool for keyword searches +3. **Read Specific Files**: Use Read tool for targeted investigation +4. **Apply Mental Model**: Reference `ai/foundations/mental-model.md` for "why" questions + +### **Code Review Workflow** +1. **Load Patterns**: `ai/guides/patterns-cookbook.md` +2. **Check Style Guide**: `ai/guides/html-css-style-guide.md` +3. **Verify API Usage**: `ai/foundations/quick-reference.md` + +## Essential Framework Mental Model + +### **Core Architecture (Complete Reference)** +``` +defineComponent() → Web Component Registration +├── template: HTML with reactive expressions {value} +├── css: Scoped styles with design tokens var(--token) +├── defaultState: Reactive signals (state.value.get/set) +├── defaultSettings: Mutable configuration (settings.property) +├── createComponent: Instance methods (self.method()) +├── events: Event delegation ({ 'click .btn': handler }) +└── lifecycle: onCreated, onRendered, onDestroyed +``` + +### **Reactivity Flow** +``` +Signal Change → Reaction Triggered → Template Updated → DOM Updated +``` + +### **Component Communication** +``` +Parent ↔ Child: findParent('tag-name') / findChild('tag-name') +Events: dispatchEvent() for notifications +State Sharing: Expose signals on component instance +``` + +### **Critical Patterns** +- **Settings vs State**: Settings = configuration, State = dynamic data +- **Template Expressions**: `{value}` auto-reactive, `value.get()` in component logic +- **CSS Tokens**: Use `var(--design-token)`, not custom properties +- **Method References**: Use `self.method()` not `this.method()` + +## Common Task Patterns + +### **Create New Component** +```javascript +// Required files: component.js, component.html, component.css +import { defineComponent, getText } from '@semantic-ui/component'; + +const template = await getText('./component.html'); +const css = await getText('./component.css'); + +defineComponent({ + tagName: 'my-component', + template, + css, + defaultState: { count: 0 }, + defaultSettings: { theme: 'default' }, + createComponent: ({ state, settings, self }) => ({ + increment() { state.count.increment(); } + }), + events: { + 'click .button': ({ self }) => self.increment() + } +}); +``` + +### **Component Communication** +```javascript +// Child accessing parent +const parent = findParent('parent-component'); +const parentData = parent.sharedData.get(); + +// Parent managing child +const child = findChild('child-component'); +child.updateDisplay(); + +// Event notifications +dispatchEvent('dataChanged', { newValue: data }); +``` + +### **Reactive State Management** +```javascript +// In component logic +state.items.push(newItem); // Reactive array mutation +state.user.setProperty('name', 'Alice'); // Reactive object update +state.counter.increment(); // Built-in helpers + +// In templates (automatic reactivity) +{items.length} // Auto-updates +{#if user.isActive}...{/if} // Conditional rendering +{#each items}...{/each} // List rendering +``` + +## Claude Code Tool Optimization + +### **Search Strategy** +``` +Unknown Keywords/Concepts → Task tool (multi-round search) +Specific File Paths → Read tool (direct access) +Class Definitions → Glob tool (pattern matching) +Code Within Files → Grep tool (content search) +``` + +### **Tool Usage Patterns** +```javascript +// ✅ Good: Batch multiple tool calls +TodoWrite → Read → Glob → Edit (single response) + +// ✅ Good: Use Task for exploration +Task: "Find all dropdown components and their configuration patterns" + +// ✅ Good: Specific tool for specific needs +Glob: "**/*dropdown*" → Read specific files + +// ❌ Avoid: Sequential single tool calls +Read → (wait) → Glob → (wait) → Edit +``` + +### **Performance Optimization** +- **Batch tool calls** in single responses when possible +- **Use Task tool** for open-ended exploration +- **Cache common patterns** in todo lists for complex work +- **Prefer specific tools** (Read vs Task) when you know the target + +## Framework-Specific Guidelines + +### **Must-Read Before Component Creation** +1. **CSS Patterns**: [`ai/guides/html-css-style-guide.md`](ai/guides/html-css-style-guide.md) - Design token usage +2. **Method References**: [`ai/foundations/mental-model.md`](ai/foundations/mental-model.md) - `self.method()` patterns +3. **Component Communication**: [`ai/guides/patterns-cookbook.md`](ai/guides/patterns-cookbook.md) - Parent-child patterns + +### **Critical Anti-Patterns to Avoid** +- ❌ Prefixed CSS classes (`.size-large` → use `.large`) +- ❌ `this.method()` → use `self.method()` +- ❌ Hardcoded CSS values → use design tokens `var(--token)` +- ❌ Global state stores → use component tree navigation +- ❌ Direct DOM manipulation → use reactive templates + +### **Design Token Priority** +```css +/* ✅ First: Use existing design tokens */ +color: var(--text-color); +spacing: var(--spacing); +border-radius: var(--border-radius); + +/* ✅ Second: Component-specific values → design tokens */ +--handle-size: 24px; /* Component-specific */ +--track-color: var(--standard-10); /* Maps to design token */ + +/* ❌ Never: Recreate existing tokens */ +--component-text-color: var(--text-color); /* Unnecessary wrapper */ +``` + +## Advanced Context Loading + +### **Specialized Package Work** +``` +Reactivity System → ai/specialized/reactivity-system-guide.md +DOM Querying → ai/specialized/query-system-guide.md +Template System → ai/specialized/templating-system-guide.md +Utility Functions → ai/specialized/utils-package-guide.md +``` + +### **Complex Implementation Contexts** +``` +Template-as-Settings Pattern → ai/guides/patterns-cookbook.md#template-as-settings-pattern +Parent-Child Communication → ai/guides/patterns-cookbook.md#component-communication-patterns +Query Component Configuration → ai/guides/patterns-cookbook.md#query-library-patterns +``` + +## TodoWrite Integration for Complex Tasks + +### **When to Use TodoWrite** +- Multi-step component creation +- Complex debugging across multiple files +- Feature implementation requiring coordination +- Code review with multiple checks + +### **Task Breakdown Examples** +```javascript +// ✅ Component Creation Task List +[ + { content: "Research existing dropdown patterns", status: "pending" }, + { content: "Create dropdown.js with basic structure", status: "in_progress" }, + { content: "Implement template with design tokens", status: "pending" }, + { content: "Add event handling and state management", status: "pending" }, + { content: "Test integration with parent components", status: "pending" }, + { content: "Run lint and typecheck", status: "pending" } +] +``` + +## Context Memory Management + +### **Context Optimization Strategy** +1. **Foundation First**: Begin with navigation hub and mental model +2. **Targeted Loading**: Add specific guides based on task requirements +3. **Cross-Reference Navigation**: Use document links rather than loading all content +4. **Task-Scoped Context**: Load only context relevant to current work + +### **Context Loading Sequence** +``` +1. ai/00-START-HERE.md (navigation foundation) +2. ai/foundations/mental-model.md (architectural foundation) +3. Task-specific guide (component, patterns, etc.) +4. ai/foundations/quick-reference.md (API syntax) +5. Specialized guides (domain-specific requirements) +``` + +--- + +## Context Loading Protocol + +**For any Semantic UI task:** + +1. **Foundation**: [`ai/00-START-HERE.md`](ai/00-START-HERE.md) - Always load first +2. **Architecture**: [`ai/foundations/mental-model.md`](ai/foundations/mental-model.md) - Core concepts +3. **Task-Specific**: Load appropriate specialized guide +4. **Reference**: [`ai/foundations/quick-reference.md`](ai/foundations/quick-reference.md) - API syntax + +**Context Optimization**: The AI context system uses ~8K token documents with cross-references. Load documents sequentially based on task requirements rather than loading multiple large documents simultaneously. + +--- + +*This file serves as an intelligent entry point to the comprehensive AI documentation system. For complete information, always refer to the specialized guides in the `/ai/` directory.* \ No newline at end of file diff --git a/README.md b/README.md index ad9bb643b..54c32c29c 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,79 @@ -## Semantic-UI +# Semantic UI Next [![UnitTests](https://badgen.net/https/wzcozo2uwacu4dfvawkdkmxi640guflx.lambda-url.us-east-1.on.aws?cache=300)](https://github.com/Semantic-Org/Semantic-Next/actions/workflows/ci.yml) [![E2ETests](https://badgen.net/https/ien5pqfy4lsyqy5a2vegyvevpa0petpj.lambda-url.us-east-1.on.aws?cache=300)](https://github.com/Semantic-Org/Semantic-Next/actions/workflows/ci.yml) [![Coverage](https://badgen.net/https/fnipttzwzg6ieemy4winuladuu0jhqef.lambda-url.us-east-1.on.aws?cache=300)](https://github.com/Semantic-Org/Semantic-Next/actions/workflows/ci.yml) -Semantic UI Next is a UI framework built with web components. +A modern, lightweight UI framework built with Web Components. + +> **Note:** This is an early technology preview. APIs and structures may change. + +## Installation + +```bash +npm install @semantic-ui/core +``` + +## Usage + +### Direct Component Imports + +For the most efficient imports, you can import individual components directly: + +```js +// Import specific components +import { UIButton } from '@semantic-ui/core/button'; +import { UICard } from '@semantic-ui/core/card'; + +// Import global theme +import '@semantic-ui/core/theme'; + +// Or import component-specific themes (if needed) +import '@semantic-ui/core/theme/button'; +import '@semantic-ui/core/theme/card'; +``` + +### Full Framework Import + +If you need multiple components, you can import from the main package: + +```js +// Import multiple components +import { UIButton, UICard, UIMenu } from '@semantic-ui/core'; + +// Import global theme +import '@semantic-ui/core/theme'; +``` + +### CDN Usage + +For quick prototyping or projects without a build step, you can use the CDN: + +```html + + + + + +``` + +Or load individual components: + +```html + + + + + + + + +``` + +## Contributing + +Please see [CONTRIBUTING.md](CONTRIBUTING.md) for development setup instructions and contribution guidelines. + +## License + +MIT \ No newline at end of file diff --git a/RELEASE-NOTES.md b/RELEASE-NOTES.md index d30f000d4..293a65f76 100644 --- a/RELEASE-NOTES.md +++ b/RELEASE-NOTES.md @@ -4,17 +4,71 @@ This is a pre-release version and APIs will change quickly. Before `1.0` release Please note after `1.0` Semver will be followed using normal protocols. -# Version 0.10.11 +# Version 0.11.0 + +## Major Changes +* New [**AI**](https://github.com/Semantic-Org/Semantic-Next/tree/main/ai) folder with detailed instructions for AI models working with Semantic UI, including guides for each package and instruction sets for writing components. +* Theming has been reworked inside the UI framework. CSS variables are now attached to `:host` inside the shadow dom instead of globally to `:root`. This means you can no longer access globally component css variables. + +### Positive Trade Offs +- You no longer need to include a separate css theme file in your page for each component you use. You can just import the component and all css will be defined. Note: You still need to include the global theme in the page to define global variables. +- `dark` and `light` can now be added to ANY component to trigger that specific component to be rendered as light or dark mode + +For instance this example: +```html + + + + + +``` + +Will render the page as `dark` mode, the `nav-menu` as light mode and the `ui-input` as dark mode. This can be used for complex layouts that might use light or dark sections. + +### Trade Offs + +- You can no longer reference variables like `button-primary-text-color` in your css. These will only be defined inside the component. This is because the theme is now scoped to the component. +- Component variables need to be scoped to the component and will not inherit + +```css +/* works - value is defined in same scope as component +*/ +ui-button { + --primary-text-color: red; +} + +/* works - value is computed for each component from primary-color +*/ +.parent { + --primary-color: red; +} + +/* + doesnt work - value will be redefined in the component +*/ +.parent { + --primary-text-color: red; +} +``` + +### Additional Changes +Some paths have shifted +* Global theme variables are now included in `semantic-ui.css` instead of a separate `theme/base.css` file. +* Themes/Specs are now included in each component folder +* Component CSS variables are now included in the Shadow DOM scope and NOT global scope. This should vastly improve the global dev tools experience by reducing the number of defined variables in scope. + +## New UI +- **Input** - Added `type` property for inputs +- **Buttton** - Added `type` property for buttons ## New +* Query - Added `$('form').submit()` shorthand for `$('form').trigger('submit');` +* Utils - Added color utils for oklch conversion to hex and rgb. These are essential to use oklch in javascript. * Signals - `increment` and `decrement` now receive a max and min. This can be used to increment a value within a limit. This is particularly useful for keyboard controls that use a `selectedIndex` * Signals - `debugReactivity` has been greatly improved. You can now pass debug context with signals and reactions and read them during flush. * Component - Added reactivity debugging metadata for all reactive template features like each, if, expressions. This will now appear when using `{debugReactivity}` in a template. - -# Version 0.10.10 - -## New * Binding to `checked` or `input` will automatically update the element property if the value changes. Note this is a one way binding, updating the element attribute will not update a signal/setting passed into `value`. +* Template Helpers - Added `isNot` helper ## Bug * Fix `value` / `val` in Query would not set value of custom elements because of too strict html element type checking. diff --git a/ai/00-START-HERE.md b/ai/00-START-HERE.md new file mode 100644 index 000000000..3d53c6560 --- /dev/null +++ b/ai/00-START-HERE.md @@ -0,0 +1,189 @@ +# Semantic UI AI Documentation Hub + +**For:** AI agents working with the Semantic UI web component framework +**Purpose:** Navigate framework documentation and resolve development tasks efficiently + +--- + +## Framework Overview + +Semantic UI is a modern web component framework built on web standards with signals-based reactivity. It provides shadow DOM encapsulated components with automatic dependency tracking, component tree navigation, and template-driven development. + +**Core Philosophy:** Web standards first, progressive enhancement, signals-based reactivity. + +--- + +## Quick Task Resolution + +### 🚀 **Building Components** +**Need to:** Create, modify, or understand components +**Start with:** [`guides/component-generation-instructions.md`](./guides/component-generation-instructions.md) +**Contains:** Complete component creation patterns, lifecycle, templates, events + +### 🧠 **Understanding Architecture** +**Need to:** Grasp framework concepts, mental models, design decisions +**Start with:** [`foundations/mental-model.md`](./foundations/mental-model.md) +**Contains:** Core philosophy, component lifecycle, reactivity system, Shadow DOM + +### 🔍 **Finding Code & Documentation** +**Need to:** Locate files, APIs, examples in the codebase +**Start with:** [`foundations/codebase-navigation-guide.md`](./foundations/codebase-navigation-guide.md) +**Contains:** File structure, search strategies, tool usage, canonical sources + +### ⚡ **API Reference & Syntax** +**Need to:** Quick lookup of method signatures, event syntax, template syntax +**Start with:** [`foundations/quick-reference.md`](./foundations/quick-reference.md) +**Contains:** Complete API reference, decision flowcharts, common recipes + +### 🎯 **Implementation Patterns** +**Need to:** Best practices, common patterns, advanced techniques +**Start with:** [`guides/patterns-cookbook.md`](./guides/patterns-cookbook.md) +**Contains:** Communication patterns, state management, event handling, performance + +### 🎨 **HTML & CSS Guidelines** +**Need to:** Writing templates, styling components, design tokens +**Start with:** [`guides/html-css-style-guide.md`](./guides/html-css-style-guide.md) +**Contains:** Template patterns, CSS architecture, design token usage + +### 🔄 **Reactivity System** (Standalone Library) +**Need to:** Understand signals, reactions, dependency tracking +**Start with:** [`specialized/reactivity-system-guide.md`](./specialized/reactivity-system-guide.md) +**Contains:** Signal API, Reaction API, standalone usage, performance optimization + +### 🔍 **DOM Querying & Manipulation** (Standalone Library) +**Need to:** Query DOM, handle Shadow DOM, configure components +**Start with:** [`specialized/query-system-guide.md`](./specialized/query-system-guide.md) +**Contains:** $ vs $$ usage, component configuration, event handling + +### 🛠️ **Utility Functions** (Standalone Library) +**Need to:** Array processing, object manipulation, type checking, formatting +**Start with:** [`specialized/utils-package-guide.md`](./specialized/utils-package-guide.md) +**Contains:** Complete utility library reference, performance patterns + +--- + +## Context Loading Strategies + +### **Framework Newcomer Context** +Essential context for understanding Semantic UI architecture and patterns: +1. [`foundations/mental-model.md`](./foundations/mental-model.md) - Core concepts and philosophy +2. [`guides/component-generation-instructions.md`](./guides/component-generation-instructions.md) - Component creation patterns +3. [`foundations/quick-reference.md`](./foundations/quick-reference.md) - API reference + +### **Component Development Context** +Context for building and modifying components: +1. [`guides/component-generation-instructions.md`](./guides/component-generation-instructions.md) - Complete creation patterns +2. [`guides/patterns-cookbook.md`](./guides/patterns-cookbook.md) - Communication and state patterns +3. [`guides/html-css-style-guide.md`](./guides/html-css-style-guide.md) - Styling conventions + +### **Advanced Architecture Context** +Context for complex implementation and debugging: +1. [`foundations/mental-model.md`](./foundations/mental-model.md) - Deep architectural understanding +2. [`guides/patterns-cookbook.md`](./guides/patterns-cookbook.md) - Advanced patterns and anti-patterns +3. [`specialized/reactivity-system-guide.md`](./specialized/reactivity-system-guide.md) - Reactive programming +4. [`specialized/query-system-guide.md`](./specialized/query-system-guide.md) - DOM manipulation + +### **Standalone Package Context** +Context for using individual packages outside the framework: +1. [`specialized/reactivity-system-guide.md`](./specialized/reactivity-system-guide.md) - Independent reactive state +2. [`specialized/query-system-guide.md`](./specialized/query-system-guide.md) - Shadow DOM-aware querying +3. [`specialized/utils-package-guide.md`](./specialized/utils-package-guide.md) - Utility functions + +### **Problem Solving Context** +Context for debugging and finding solutions: +1. [`foundations/codebase-navigation-guide.md`](./foundations/codebase-navigation-guide.md) - Locating information +2. [`foundations/quick-reference.md`](./foundations/quick-reference.md) - Quick syntax lookup + +--- + +## Document Descriptions + +| Document | Focus | Audience | Content Type | +|----------|--------|----------|--------------| +| **mental-model.md** | Architecture & Concepts | All levels | Conceptual | +| **component-generation-instructions.md** | Component Creation | Beginners to Intermediate | Tutorial + Reference | +| **patterns-cookbook.md** | Best Practices | Intermediate to Advanced | Patterns + Examples | +| **quick-reference.md** | API Lookup | All levels | Reference | +| **reactivity-system-guide.md** | Signals & Reactions | Intermediate | Tutorial + Reference | +| **query-system-guide.md** | DOM Manipulation | Intermediate | Tutorial + Reference | +| **html-css-style-guide.md** | Styling & Templates | All levels | Guidelines + Examples | +| **utils-package-guide.md** | Utility Functions | All levels | Reference | +| **codebase-navigation-guide.md** | Finding Information | All levels | Navigation Guide | + +--- + +## Decision Trees + +### "I need to..." + +``` +Create a new component? +├── Simple component → component-generation-instructions.md +├── Complex interactions → patterns-cookbook.md (Component Communication) +└── Custom styling → html-css-style-guide.md + +Understand an error or behavior? +├── Find where code is located → codebase-navigation-guide.md +├── Understand the concept → mental-model.md +└── Look up API syntax → quick-reference.md + +Handle component communication? +├── Parent-child coordination → patterns-cookbook.md (Communication Patterns) +├── Event handling → component-generation-instructions.md (Events) +└── State sharing → mental-model.md (Component Tree Navigation) + +Work with reactivity? +├── Basic state management → component-generation-instructions.md (State) +├── Advanced reactive patterns → reactivity-system-guide.md +└── Performance optimization → patterns-cookbook.md (Performance) + +Style components? +├── Basic CSS patterns → html-css-style-guide.md +├── Design token usage → html-css-style-guide.md (CSS Custom Properties) +└── Component-specific styling → component-generation-instructions.md (CSS) + +Query and manipulate DOM? +├── Basic querying → query-system-guide.md (Basic Operations) +├── Shadow DOM traversal → query-system-guide.md (Deep Querying) +└── Component configuration → query-system-guide.md (Component Methods) +``` + +--- + +## Tips for AI Agents + +### **Context Management** +- Each document is designed for ~8K context windows +- Cross-references indicate related content without duplicating it +- Start with the most specific document for your task + +### **Information Hierarchy** +1. **Quick Reference** - API syntax and signatures +2. **Guides** - How-to instructions and tutorials +3. **Patterns** - Best practices and advanced techniques +4. **Architecture** - Concepts and mental models + +### **Common Workflows** +- **Unknown Error:** codebase-navigation-guide.md → Find implementation → mental-model.md for context +- **New Feature:** mental-model.md → component-generation-instructions.md → patterns-cookbook.md +- **Code Review:** patterns-cookbook.md → html-css-style-guide.md → quick-reference.md + +### **Search Strategy** +- Use codebase-navigation-guide.md for file locations +- Use quick-reference.md for API signatures +- Use patterns-cookbook.md for implementation examples +- Use mental-model.md for "why" questions + +--- + +## External References + +- **Live Examples:** `/docs/src/examples/` (canonical component examples) +- **API Documentation:** `/docs/src/pages/api/` (complete API reference) +- **Source Code:** `/packages/` (framework implementation) +- **Component Library:** `/src/components/` (design system components) + +--- + +**Last Updated:** Framework architecture documentation complete and current +**Maintenance:** Update this file when adding new documentation or changing structure \ No newline at end of file diff --git a/ai/component-generation-instructions.md b/ai/component-generation-instructions.md deleted file mode 100755 index 6ee7815fc..000000000 --- a/ai/component-generation-instructions.md +++ /dev/null @@ -1,487 +0,0 @@ -# Framework Component Generation Instructions - -You are a component creation assistant for a modern web component framework. Your task is to create self-contained, reusable components following the framework's patterns and best practices. - -## Component Structure - -- Create files named: `component.js`, `component.html`, `component.css` for the main component -- For subtemplates, use hyphenated names like `todo-item.js`, `todo-item.html`, `todo-item.css` -- Include a usage example in `page.html` (and optionally `page.js` and `page.css` if needed) - -## Component Definition Pattern - -Always follow this pattern for component definition: - -```javascript -import { defineComponent, getText } from '@semantic-ui/component'; -// Import any subcomponents here -import { subComponent } from './sub-component.js'; - -const css = await getText('./component.css'); -const template = await getText('./component.html'); - -const defaultSettings = { - // Props/settings with default values -}; - -const defaultState = { - // Reactive state with initial values -}; - -const createComponent = ({ self, state, settings, $, findParent, reaction, dispatchEvent }) => ({ - // Methods and computed properties - - // Example computed property - getComputedValue() { - // Access state with .get() in JavaScript code - const stateValue = state.someValue.get(); - return stateValue * 2; - }, - - // Example method for setup - setupReactions() { - reaction(() => { - // Set up a reaction that updates when dependencies change - const valueA = state.valueA.get(); - // Update another value based on the change - state.derivedValue.set(valueA * 2); - }); - } -}); - -const events = { - 'click .selector'({ self, event, data }) { - // Handle click event - self.methodName(); - }, - 'input .input-selector'({ state, value }) { - // Update state based on input - state.inputValue.set(value); - } -}; - -const onCreated = ({ self, state }) => { - // Initialize component (before DOM is ready) -}; - -const onRendered = ({ self, state, $ }) => { - // Component is in DOM, can access elements - self.setupReactions(); -}; - -const onDestroyed = ({ self }) => { - // Clean up resources -}; - -export const ComponentName = defineComponent({ - tagName: 'component-name', - template, - css, - defaultSettings, - defaultState, - events, - createComponent, - onCreated, - onRendered, - onDestroyed, - subTemplates: { - // Reference subcomponents here - subComponent - } -}); -``` - -## Template Syntax - -Templates have a flattened data context. Note these important patterns: - -1. In templates, access state values directly without `.get()`: - ```html -
{stateValue}
- ``` - -2. Methods from `createComponent` are available directly: - ```html -
{getComputedValue}
- ``` - -3. Use block helpers for control flow: - ```html - {#if condition} -
Conditional content
- {else if otherCondition} -
Alternative content
- {else} -
Default content
- {/if} - ``` - -4. Use `{#each}` for iteration: - ```html - {#each item in items} -
{item.name} {item.value}
- {/each} - ``` - -5. Include subtemplates with parameters: - ```html - {>subComponent - paramA=valueA - paramB=valueB - } - ``` - -## CSS Guidelines - -Use modern nested CSS with shadow DOM in mind: - -```css -:host { - /* Component-level custom properties */ - --component-spacing: 1rem; -} - -.container { - display: flex; - padding: var(--component-spacing); - - .header { - font-weight: bold; - - .title { - color: var(--standard-80); - } - } - - .content { - margin-top: 1rem; - } -} -``` - -- Use simple class names like `.container` instead of namespaced `.component-container` -- Leverage shadow DOM encapsulation and don't worry about class name collisions -- Use CSS custom properties for customizable aspects -- Use container queries where appropriate: `@container component (min-width: 500px) { ... }` - -## Reactivity Guidelines - -1. In JavaScript code, access state with `.get()`: - ```javascript - const value = state.someValue.get(); - ``` - -2. Update state with `.set()`: - ```javascript - state.someValue.set(newValue); - ``` - -3. For collections, use array methods: - ```javascript - state.items.push(newItem); - state.items.setProperty(itemId, 'completed', true); - state.items.removeItem(itemId); - ``` - -4. For non-reactive reads, use `.peek()`: - ```javascript - const currentValue = state.someValue.peek(); - ``` - -5. Set up reactions for derived state: - ```javascript - reaction(() => { - const source = state.source.get(); - state.derived.set(source * 2); - }); - ``` - -## Parent-Child Communication - -1. Access parent components: - ```javascript - const parent = findParent('parentTagName'); - const parentState = parent.someState.get(); - ``` - -2. Dispatch events to parent: - ```javascript - dispatchEvent('customEvent', { data: value }); - ``` - -## Common Patterns - -1. Initialize component: - ```javascript - onCreated({ state, self }) { - state.value.set(initialValue); - self.setupReactions(); - } - ``` - -2. Query and manipulate DOM: - ```javascript - onRendered({ $ }) { - $('.element').addClass('active'); - } - ``` - -3. Create computed values: - ```javascript - getFilteredItems() { - const items = state.items.get(); - const filter = state.filter.get(); - return items.filter(item => item.type === filter); - } - ``` - -4. Handle form inputs: - ```javascript - 'input .field'({ state, value }) { - state.fieldValue.set(value); - } - ``` - -## Important Notes - -- The framework uses a batched update system - multiple state changes may be coalesced -- In templates, the data context is flattened - properties from settings, state, and methods are all directly accessible -- Always use shadow DOM principles for CSS (simple class names, nested selectors) -- Use reaction() to set up reactive computations, not for side effects - -## Additional Best Practices - -### Class Naming in Shadow DOM -- Keep class names simple and semantic (e.g., `.menu` instead of `.context-menu-container`) -- No need for namespacing or prefixing since Shadow DOM provides encapsulation -- Example: Use `.item`, `.divider`, `.header` instead of `.component-item`, etc. - -### State vs Settings -- `settings`: Use for configurable properties that typically don't change after initialization - ```javascript - const defaultSettings = { - items: [], // ✓ Configuration that the user provides - width: 180, // ✓ Customizable property - }; - ``` -- `state`: Use only for values that change during component lifetime due to user interaction - ```javascript - const defaultState = { - visible: false, // ✓ Changes during component use - activeIndex: -1, // ✓ Changes during component use - items: [] // ✗ Don't duplicate settings in state - }; - ``` - -### Template Syntax Clarifications -- Iteration uses `index` automatically, don't declare an index variable: - ```html - - {#each item in items} -
{item.label}
- {/each} - - - {#each item, index in items} -
{item.label}
- {/each} - ``` - -- Use simple ternary expressions in attribute bindings: - ```html -
- ``` - -### Event Handling -- Always use the provided `dispatchEvent` function rather than creating DOM events manually: - ```javascript - // Correct - dispatchEvent('select', { item, index }); - - // Incorrect - const event = new CustomEvent('select', { - detail: { item, index }, - bubbles: true - }); - element.dispatchEvent(event); - ``` - -- For global events, use `body` rather than `document`: - ```javascript - // Correct - 'global click body'({ self }) { - self.hideMenu(); - } - - // Avoid - 'global click document'({ self }) { - self.hideMenu(); - } - ``` - -### Slotted Content Pattern -- Use slots to create intuitive wrapper components: - ```html -
- {>slot} -
- ``` - -- This enables a natural usage pattern: - ```html - -
Wrapped content
-
- ``` - -### Modern CSS Techniques -- Use `@starting-style` for smooth enter animations: - ```css - .menu.visible { - opacity: 1; - transform: scale(1); - } - @starting-style { - .menu.visible { - opacity: 0; - transform: scale(0.95); - } - } - ``` - -- Use class-based visibility toggling instead of inline styles: - ```css - .menu { - visibility: hidden; - opacity: 0; - } - .menu.visible { - visibility: visible; - opacity: 1; - } - ``` - -### Class Binding with Object Maps -- Return object maps from methods for conditional classes: - ```javascript - getMenuStates() { - return { - visible: state.visible.get(), - active: state.active.get() - }; - } - ``` - -- Use with `classMap` helper in templates: - ```html -
- ``` - -### Performance Optimizations -- Use `requestAnimationFrame` for DOM measurements and position calculations: - ```javascript - showElement() { - state.visible.set(true); - requestAnimationFrame(() => self.measureAndPosition()); - } - ``` - -- For non-reactive reads in calculations, use `.peek()` to avoid triggering reactions: - ```javascript - const position = state.position.peek(); - ``` - -### Lifecycle Events -- Emit events for component lifecycle where appropriate: - ```javascript - showMenu() { - // Setup code... - dispatchEvent('show'); - } - - hideMenu() { - // Cleanup code... - dispatchEvent('hide'); - } - ``` - -### Proper Parameter Access -- Access parameters directly as provided in function arguments: - ```javascript - // Correct - createComponent({ self, state, settings }) { - // Use state and settings directly - } - - // Incorrect - createComponent({ self }) { - // Don't use self.state or self.settings - } - ``` - -### DOM Element Access in Event Handlers -- In event handlers, use `this` to refer to the element that triggered the event: - ```javascript - 'input .field'({ state, $ }) { - const value = $(this).val(); - state.inputValue.set(value); - } - -## Reference Examples - -When creating components, refer to these example implementations in the knowledgebase for guidance on common patterns: - -### Component Composition -- **TodoMVC** - A complete task management implementation demonstrating: - - Parent-child component composition - - State management across multiple components - - Local storage persistence - - Filtering and computed values - - Reference files: `todo-list.js`, `todo-item.js`, `todo-header.js`, `todo-footer.js` - -### User Interface Patterns -- **Context Menu** - Right-click menu system demonstrating: - - Slotted content pattern - - Position calculations - - Keyboard navigation - - Animation transitions - - Reference files: `component.js`, `component.html`, `component.css` - -- **UI-Panel** - Resizable panels demonstrating: - - Drag interaction handling - - Size calculations - - Layout persistence - - Reference files: `Panel.js`, `Panel.html`, `Panel.css`, `Panels.js` - -### Search & Input Patterns -- **Search Component** - Search with dynamic results demonstrating: - - Asynchronous data handling - - Dynamic filtering - - Keyboard navigation of results - - Reference files: `component.js`, `component.html`, `component.css` - -### Data Visualization -- **Spectrum Analyzer** - Audio visualization demonstrating: - - Canvas drawing - - Animation loops - - Media API integration - - Reference files: `component.js` - -### Context Menu -- **Context Menu** - Customizable right-click menu demonstrating: - - Slotted content wrapper pattern for intuitive usage - - Dynamic positioning with viewport boundary detection - - Keyboard navigation with arrow keys, Enter, and Escape - - Modern CSS transitions with `@starting-style` - - Class-based state management with object maps - - Accessibility support with ARIA roles and keyboard focus - - Event delegation with `deep contextmenu` handling - - Reference files: `component.js`, `component.html`, `component.css` - -When implementing a new component, consider: -1. Does an existing example demonstrate a similar interaction pattern? -2. How does the reference example handle state management? -3. What event handling patterns might be applicable? -4. How is component composition structured? - -Refer to these examples for practical implementations of the patterns described in these instructions. diff --git a/ai/foundations/codebase-navigation-guide.md b/ai/foundations/codebase-navigation-guide.md new file mode 100644 index 000000000..8dc0b4eda --- /dev/null +++ b/ai/foundations/codebase-navigation-guide.md @@ -0,0 +1,774 @@ +# Semantic UI Codebase Navigation Guide + +## Table of Contents + +- [Quick Location Reference](#quick-location-reference) +- [Documentation Reading Order](#documentation-reading-order) +- [Tool Usage Strategies](#tool-usage-strategies) +- [Documentation Locations](#documentation-locations) +- [Source Code Locations](#source-code-locations) +- [Example Code Locations](#example-code-locations) +- [Configuration & Build Files](#configuration--build-files) +- [Search Strategies by Topic](#search-strategies-by-topic) +- [Common Investigation Patterns](#common-investigation-patterns) + +--- + +## Quick Location Reference + +### 🏠 **Root Structure** +``` +/home/jack/semantic/next/ +├── ai/ ← AI context documentation (YOU ARE HERE) +├── docs/ ← Documentation website and examples +├── packages/ ← Core framework source code +├── examples/ ← Standalone examples and demos +├── src/ ← Component library (design system) +├── tests/ ← Test suites and configurations +└── scripts/ ← Build and utility scripts +``` + +### 📚 **Documentation Hub**: `/docs/` +``` +docs/ +├── src/pages/ ← All documentation content +│ ├── api/ ← **CANONICAL** API reference docs (organized by package) +│ ├── components/ ← Component system guides +│ ├── templates/ ← Template syntax guides +│ ├── reactivity/ ← Reactivity system guides +│ ├── query/ ← Query library guides +│ └── *.mdx ← Top-level guides +├── src/examples/ ← **CANONICAL** examples (hand-written best practices) +└── src/helpers/menus.js ← **ESSENTIAL** Documentation menu structure +``` + +### 🔧 **Core Framework**: `/packages/` +``` +packages/ +├── component/ ← Web component framework +├── reactivity/ ← Signals-based reactivity +├── templating/ ← AST template compiler +├── query/ ← DOM querying library +├── renderer/ ← Lit integration +├── utils/ ← Shared utilities +└── specs/ ← Component specifications +``` + +--- + +## Documentation Reading Order + +> **IMPORTANT**: Documentation should be read in menu order as defined in `/docs/src/helpers/menus.js`. This mirrors how human users navigate and learn the framework. + +### 📖 **Framework Documentation** (`sidebarMenuFramework`) + +#### **1. Introduction** +- `/introduction` - Start here for overview and getting started + +#### **2. Components** (Core system) +- `/components` - Component overview and features +- `/components/create` - Creating components with defineComponent +- `/components/instances` - Component functionality +- `/components/lifecycle` - Component lifecycle hooks +- `/components/rendering` - Templates & Data Context +- `/components/settings` - Component configuration +- `/components/state` - Component state management +- `/components/events` - **⭐ ESSENTIAL** Event handling patterns +- `/components/reactivity` - Reactivity in components +- `/components/dom` - DOM manipulation and querying +- `/components/styling` - Component styling approaches +- `/components/keys` - Keyboard bindings + +#### **3. Templates** (Template system) +- `/templates` - Template overview and syntax +- `/templates/expressions` - **⭐ ESSENTIAL** Expression syntax and evaluation +- `/templates/conditionals` - If/else logic in templates +- `/templates/loops` - **⭐ ESSENTIAL** Each loops and iteration +- `/templates/slots` - Content projection +- `/templates/subtemplates` - Component composition +- `/templates/snippets` - **⭐ ESSENTIAL** Inline template fragments +- `/templates/helpers` - Global template helpers + +#### **4. Reactivity** (Signals system) +- `/reactivity` - Reactivity overview +- `/reactivity/signals` - Signal primitives +- `/reactivity/reactions` - Reactive computations +- `/reactivity/mutation-helpers` - Array/object helpers +- `/reactivity/flush` - Update batching and timing +- `/reactivity/controls` - Controlling reactivity +- `/reactivity/performance` - Optimization strategies +- `/reactivity/debugging` - Debugging reactive code +- `/reactivity/signal-options` - Advanced signal configuration + +#### **5. Query** (DOM helpers) +- `/query` - Query library overview +- `/query/basics` - Basic DOM querying +- `/query/shadow-dom` - **⭐ ESSENTIAL** Shadow DOM traversal +- `/query/components` - **⭐ ESSENTIAL** Component configuration (.settings, .initialize, .component) +- `/query/chaining` - Method chaining patterns +- `/query/browser` - Browser usage patterns + +### 📋 **API Reference** (`sidebarMenuAPI`) + +> **CANONICAL LOCATION**: All API documentation is at `/docs/src/pages/api/` organized by package and grouped by function. + +#### **1. Components** (`/api/component/`) +- `/api/component/define-component` - Main component creation API +- `/api/component/utilities` - Component utility functions +- `/api/component/web-component-base` - Base web component class + +#### **2. Template Helpers** (`/api/helpers/`) +- `/api/helpers/arrays` - Array manipulation helpers +- `/api/helpers/comparison` - Comparison and logic helpers +- `/api/helpers/css` - CSS and styling helpers +- `/api/helpers/dates` - Date formatting helpers +- `/api/helpers/debug` - Debugging helpers +- `/api/helpers/logical` - Logical operators +- `/api/helpers/numeric` - Number manipulation +- `/api/helpers/objects` - Object manipulation +- `/api/helpers/reactivity` - Reactivity helpers +- `/api/helpers/strings` - String manipulation + +#### **3. Reactivity** (`/api/reactivity/`) +- `/api/reactivity/signal` - Signal implementation +- `/api/reactivity/reaction` - Reaction implementation +- `/api/reactivity/scheduler` - Update scheduling +- `/api/reactivity/dependency` - Dependency tracking +- `/api/reactivity/number-helpers` - Number signal helpers +- `/api/reactivity/boolean-helpers` - Boolean signal helpers +- `/api/reactivity/array-helpers` - Array signal helpers +- `/api/reactivity/collection-helpers` - Collection signal helpers +- `/api/reactivity/date-helpers` - Date signal helpers + +#### **4. Query** (`/api/query/`) +- `/api/query/basic` - Basic querying methods +- `/api/query/attributes` - Attribute manipulation +- `/api/query/components` - **⭐ ESSENTIAL** Component methods (.settings, .initialize, etc.) +- `/api/query/content` - Content manipulation +- `/api/query/css` - CSS manipulation +- `/api/query/dimensions` - Size and positioning +- `/api/query/dom-manipulation` - DOM modification +- `/api/query/dom-traversal` - DOM navigation +- `/api/query/events` - Event handling +- `/api/query/iterators` - Collection iteration +- `/api/query/logical-operators` - Logic operations +- `/api/query/utilities` - Utility methods +- `/api/query/internal` - Internal methods + +#### **5. Utils** (`/api/utils/`) +- `/api/utils/arrays` - Array utilities +- `/api/utils/browser` - Browser detection +- `/api/utils/cloning` - Object cloning +- `/api/utils/colors` - Color manipulation +- `/api/utils/crypto` - Cryptographic functions +- `/api/utils/dates` - Date utilities +- `/api/utils/equality` - Equality checking +- `/api/utils/errors` - Error handling +- `/api/utils/functions` - Function utilities +- `/api/utils/looping` - Iteration utilities +- `/api/utils/numbers` - Number utilities +- `/api/utils/objects` - Object utilities +- `/api/utils/types` - Type checking +- `/api/utils/regex` - Regular expressions +- `/api/utils/ssr` - Server-side rendering +- `/api/utils/strings` - String utilities + +#### **6. Template Compiler** (`/api/templating/`) +- `/api/templating/template-compiler` - Template compilation +- `/api/templating/ast` - Abstract Syntax Tree +- `/api/templating/template` - Template class +- `/api/templating/string-scanner` - Template parsing + +#### **7. Renderer** (`/api/renderer/`) +- `/api/renderer/lit-renderer` - Lit integration +- `/api/renderer/lit-directives` - Custom Lit directives + +> **Note**: If a specific documentation path is not available, always refer to `/docs/src/helpers/menus.js` for the current menu structure. + +--- + +## Semantic UI Search Patterns + +### **Common Grep Patterns** + +```bash +# Find all defineComponent usages +pattern="defineComponent" include="*.js" path="/docs/src/examples/" + +# Find parent-child communication patterns +pattern="findParent|findChild" include="*.js" path="/docs/src/examples/" + +# Find reactivity patterns +pattern="signal|reaction" include="*.js" path="/packages/reactivity/" + +# Find design token usage +pattern="var\\(--" include="*.css" path="/src/" + +# Find event handling patterns +pattern="events.*:" include="*.js" path="/docs/src/examples/" + +# Find CSS class patterns +pattern="\\.[a-z-]+\\s*{" include="*.css" path="/src/components/" +``` + +### **Common Glob Patterns** + +```bash +# Component examples +pattern="*component.js" path="/docs/src/examples/" + +# All CSS files in components +pattern="*.css" path="/src/components/" + +# Test files +pattern="*.test.js" path="/tests/" + +# Token definition files +pattern="*.css" path="/src/css/tokens/" +``` + +--- + +## Tool Usage Strategies + +### 🎯 **When to Use Each Tool** + +#### **Use `Read` tool when:** +- You know the exact file path +- Reading specific documentation files +- Examining individual source files +- Looking at specific examples + +#### **Use `Grep` tool when:** +- Searching for specific code patterns +- Finding implementations of a feature +- Locating all files using a specific API +- Searching within a specific directory tree + +#### **Use `Glob` tool when:** +- Finding files by name pattern +- Locating all files of a certain type +- Discovering related files + +#### **Use `Task` tool when:** +- Complex multi-step investigations +- Need to search across multiple locations +- Uncertain about exact location +- Researching broad topics + +### 🔍 **Efficient Search Patterns** + +#### **For API Information:** +```bash +# 1. Check API documentation first (CANONICAL) +Read: /docs/src/pages/api/{package}/{function} +# 2. Find implementation +Grep: pattern="export.*{functionName}" include="*.js" path="/packages/" +# 3. Look for examples +Grep: pattern="{functionName}" include="*.js" path="/docs/src/examples/" +``` + +#### **For Component Examples:** +```bash +# 1. Check canonical examples +Glob: pattern="*{topic}*" path="/docs/src/examples/" +# 2. Search for usage patterns +Grep: pattern="{componentName}" include="*.html,*.js" path="/docs/src/examples/" +``` + +#### **For Implementation Details:** +```bash +# 1. Find main implementation +Read: /packages/{packageName}/src/ +# 2. Check tests for usage +Grep: pattern="{feature}" include="*.test.js" path="/packages/{packageName}/test/" +``` + +--- + +## Documentation Locations + +### 📖 **User-Facing Documentation**: `/docs/src/pages/` + +#### **Top-Level Guides** +- `introduction.mdx` - Getting started, overview +- `guide.mdx` - Main user guide +- `expert-guide.mdx` - Advanced usage patterns +- `theming.mdx` - Styling and design system + +#### **Component System** (`/docs/src/pages/components/`) +- `index.mdx` - Component overview and features +- `create.mdx` - Creating components with defineComponent +- `state.mdx` - Component state management +- `settings.mdx` - Component configuration +- `reactivity.mdx` - Reactivity in components +- `events.mdx` - **⭐ ESSENTIAL** Event handling patterns +- `keys.mdx` - Keyboard bindings +- `lifecycle.mdx` - Component lifecycle hooks +- `styling.mdx` - Component styling approaches +- `dom.mdx` - DOM manipulation and querying + +#### **Template System** (`/docs/src/pages/templates/`) +- `index.mdx` - Template overview and syntax +- `expressions.mdx` - **⭐ ESSENTIAL** Expression syntax and evaluation +- `conditionals.mdx` - If/else logic in templates +- `loops.mdx` - **⭐ ESSENTIAL** Each loops and iteration +- `snippets.mdx` - **⭐ ESSENTIAL** Inline template fragments +- `subtemplates.mdx` - Component composition +- `slots.mdx` - Content projection +- `helpers.mdx` - Global template helpers + +#### **Reactivity System** (`/docs/src/pages/reactivity/`) +- `index.mdx` - Reactivity overview +- `signals.mdx` - Signal primitives +- `reactions.mdx` - Reactive computations +- `mutation-helpers.mdx` - Array/object helpers +- `performance.mdx` - Optimization strategies +- `controls.mdx` - Controlling reactivity +- `debugging.mdx` - Debugging reactive code + +#### **Query Library** (`/docs/src/pages/query/`) +- `index.mdx` - Query library overview +- `basics.mdx` - Basic DOM querying +- `shadow-dom.mdx` - **⭐ ESSENTIAL** Shadow DOM traversal +- `components.mdx` - **⭐ ESSENTIAL** Component configuration (.settings, .initialize, .component) +- `chaining.mdx` - Method chaining patterns + +#### **API Reference** (`/docs/src/pages/api/`) +> **CANONICAL LOCATION**: All API documentation organized by package and function +``` +api/ +├── component/ ← defineComponent, utilities, web-component-base +├── reactivity/ ← Signal, Reaction, Dependency, helpers +├── templating/ ← Template, compiler, helpers +├── query/ ← $, $$, DOM methods +├── renderer/ ← Lit integration +├── helpers/ ← Global template helpers +└── utils/ ← Utility functions +``` + +### 🎯 **Finding Documentation** + +#### **By Topic:** +```bash +# Component creation +Read: /docs/src/pages/components/create.mdx + +# Event handling +Read: /docs/src/pages/components/events.mdx + +# Template syntax +Read: /docs/src/pages/templates/expressions.mdx + +# API reference +Read: /docs/src/pages/api/{package}/index.mdx +``` + +#### **By Feature:** +```bash +# Settings configuration +Grep: pattern="settings" include="*.mdx" path="/docs/src/pages/" + +# findParent/findChild usage +Grep: pattern="findParent|findChild" include="*.mdx" path="/docs/src/pages/" + +# Template-as-settings +Grep: pattern="Template.*settings|settings.*Template" include="*.mdx" path="/docs/src/pages/" +``` + +--- + +## Source Code Locations + +### 🔧 **Core Implementation**: `/packages/` + +#### **Component System** (`/packages/component/`) +``` +component/ +├── src/ +│ ├── define-component.js ← Main component creation API +│ ├── web-component.js ← Base web component class + settings proxy +│ ├── index.js ← Package exports +│ └── helpers/ ← Component utilities +├── test/ ← Component tests +└── types/ ← TypeScript definitions +``` + +#### **Reactivity System** (`/packages/reactivity/`) +``` +reactivity/ +├── src/ +│ ├── signal.js ← Signal implementation +│ ├── reaction.js ← Reaction implementation +│ ├── dependency.js ← Dependency tracking +│ ├── scheduler.js ← Update batching +│ └── index.js ← Package exports +└── test/ ← Reactivity tests +``` + +#### **Template System** (`/packages/templating/`) +``` +templating/ +├── src/ +│ ├── template.js ← Template class and lifecycle +│ ├── template-helpers.js ← Global helpers +│ ├── compiler/ +│ │ ├── template-compiler.js ← **⭐ ESSENTIAL** AST compilation +│ │ └── string-scanner.js ← Template parsing +│ └── index.js ← Package exports +└── test/ ← Template tests +``` + +#### **Query Library** (`/packages/query/`) +``` +query/ +├── src/ +│ ├── query.js ← **⭐ ESSENTIAL** Main query implementation +│ ├── node-wrapper.js ← DOM node utilities +│ └── index.js ← Package exports +└── test/ ← Query tests +``` + +### 🔍 **Finding Implementation** + +#### **By Feature:** +```bash +# Settings reactivity implementation +Read: /packages/component/src/web-component.js +# Look for: createSettingsProxy, settingsVars + +# Template compilation +Read: /packages/templating/src/compiler/template-compiler.js +# Look for: compile, parseEach, parseIf + +# Signal implementation +Read: /packages/reactivity/src/signal.js +# Look for: get, set, mutation helpers + +# Query shadow DOM crossing +Read: /packages/query/src/query.js +# Look for: querySelectorAllDeep, $$ +``` + +#### **By Pattern:** +```bash +# Event handling implementation +Grep: pattern="attachEvent|addEventListener" include="*.js" path="/packages/" + +# Template evaluation +Grep: pattern="evaluateExpression|evaluateConditional" include="*.js" path="/packages/" + +# Component tree navigation +Grep: pattern="findParent|findChild" include="*.js" path="/packages/" +``` + +--- + +## Example Code Locations + +### 🌟 **Canonical Examples**: `/docs/src/examples/` + +#### **⭐ ESSENTIAL Examples** (Hand-written best practices) +``` +examples/ +├── todo-list/ ← **BEST** Parent-child communication +├── component/ +│ ├── templates/ +│ │ ├── advanced-subtemplates/ ← **ESSENTIAL** Template-as-settings +│ │ ├── color-picker/ ← Template composition +│ │ ├── snippets/ ← Snippet usage patterns +│ │ └── subtemplates/ ← Component composition +│ ├── events/ +│ │ ├── event-binding/ ← Event handler patterns +│ │ ├── event-data/ ← Data attribute handling +│ │ └── global-events/ ← Global event patterns +│ ├── complex/ +│ │ ├── accordion/ ← Deep events, parent-child +│ │ ├── test-element/ ← Comprehensive component +│ │ └── clock/ ← Lifecycle and timers +│ ├── tabs/ ← Component coordination +│ ├── context-menu/ ← Dynamic positioning +│ └── maximal/ ← Full-featured component +├── form-builder/ ← Dynamic forms +├── star-rating/ ← Interactive components +├── reactivity/ +│ ├── birthday/ ← Reactivity concepts +│ ├── ball-simulation/ ← Performance patterns +│ └── template-reactivity/ ← Template reactivity +└── loops/ ← Template iteration +``` + +#### **⚠️ AI-Generated Example** (Use with caution) +``` +examples/component/dropdown/ ← Contains potential anti-patterns +``` + +### 🔍 **Finding Examples** + +#### **By Pattern:** +```bash +# Parent-child communication +Read: /docs/src/examples/todo-list/ +Read: /docs/src/examples/component/complex/accordion/ + +# Template-as-settings +Read: /docs/src/examples/component/templates/advanced-subtemplates/ + +# Event handling +Read: /docs/src/examples/component/events/ + +# Reactivity patterns +Glob: pattern="*reactivity*" path="/docs/src/examples/" +``` + +#### **By Feature:** +```bash +# findParent/findChild usage +Grep: pattern="findParent|findChild" include="*.js" path="/docs/src/examples/" + +# dispatchEvent patterns +Grep: pattern="dispatchEvent" include="*.js" path="/docs/src/examples/" + +# Settings configuration +Grep: pattern="\.settings\(" include="*.js" path="/docs/src/examples/" + +# Template syntax usage +Grep: pattern="#each|#if|>template" include="*.html" path="/docs/src/examples/" +``` + +--- + +## Configuration & Build Files + +### ⚙️ **Project Configuration** +``` +Root Level: +├── package.json ← Main package configuration +├── dprint.json ← Code formatting +├── meta.json ← Project metadata +└── scripts/ ← Build utilities + +Tests: +├── tests/configs/ ← Test configurations +├── tests/scripts/ ← Test utilities +└── tests/setup/ ← Test setup + +Documentation: +├── docs/package.json ← Docs site dependencies +├── docs/astro.config.mjs ← Documentation site config +├── docs/src/helpers/menus.js ← **ESSENTIAL** Documentation menu structure +└── docs/tsconfig.json ← TypeScript config +``` + +### 🔍 **Finding Configuration** + +#### **Build Process:** +```bash +# Main build config +Read: /package.json +Read: /scripts/ + +# Documentation build +Read: /docs/package.json +Read: /docs/astro.config.mjs + +# Menu structure (ESSENTIAL for documentation order) +Read: /docs/src/helpers/menus.js + +# Test configuration +Read: /tests/configs/ +``` + +#### **Dependencies:** +```bash +# Framework dependencies +Grep: pattern="@semantic-ui" include="package.json" path="/" + +# Development tools +Grep: pattern="vite|astro|playwright" include="package.json" path="/" +``` + +--- + +## Search Strategies by Topic + +### 🎯 **Component Creation** +```bash +1. Read: /docs/src/pages/components/create.mdx +2. Read: /docs/src/pages/api/component/define-component.mdx +3. Read: /packages/component/src/define-component.js +4. Grep: pattern="defineComponent" include="*.js" path="/docs/src/examples/" +5. Read: /docs/src/examples/component/minimal/ +``` + +### 🎯 **Event Handling** +```bash +1. Read: /docs/src/pages/components/events.mdx # ESSENTIAL +2. Read: /docs/src/pages/api/query/events.mdx +3. Read: /packages/templating/src/template.js # Implementation +4. Grep: pattern="events.*:" include="*.js" path="/docs/src/examples/" +5. Read: /docs/src/examples/component/events/ +``` + +### 🎯 **Template Syntax** +```bash +1. Read: /docs/src/pages/templates/expressions.mdx +2. Read: /docs/src/pages/templates/loops.mdx +3. Read: /docs/src/pages/api/templating/template-compiler.mdx +4. Read: /packages/templating/src/compiler/template-compiler.js +5. Grep: pattern="#each|#if|{>" include="*.html" path="/docs/src/examples/" +``` + +### 🎯 **Reactivity System** +```bash +1. Read: /docs/src/pages/reactivity/index.mdx +2. Read: /docs/src/pages/api/reactivity/signal.mdx +3. Read: /packages/reactivity/src/signal.js +4. Read: /packages/reactivity/src/reaction.js +5. Read: /docs/src/examples/reactivity/ +``` + +### 🎯 **Component Configuration** +```bash +1. Read: /docs/src/pages/query/components.mdx # ESSENTIAL +2. Read: /docs/src/pages/api/query/components.mdx +3. Grep: pattern="\.settings\(|\.initialize\(" include="*.js" path="/docs/src/examples/" +4. Read: /packages/query/src/query.js +5. Read: /docs/src/examples/component/templates/advanced-subtemplates/ +``` + +### 🎯 **Parent-Child Communication** +```bash +1. Read: /docs/src/examples/todo-list/ # BEST example +2. Grep: pattern="findParent|findChild" include="*.js" path="/docs/src/examples/" +3. Grep: pattern="dispatchEvent" include="*.js" path="/docs/src/examples/" +4. Read: /docs/src/examples/component/complex/accordion/ +5. Read: /docs/src/pages/components/events.mdx # For event patterns +``` + +### 🎯 **Performance & Debugging** +```bash +1. Read: /docs/src/pages/reactivity/performance.mdx +2. Read: /docs/src/pages/reactivity/debugging.mdx +3. Read: /docs/src/pages/api/reactivity/scheduler.mdx +4. Read: /docs/src/examples/reactivity/ball-simulation/ +5. Grep: pattern="afterFlush|Reaction\.nonreactive" include="*.js" path="/packages/" +``` + +--- + +## Common Investigation Patterns + +### 🕵️ **"How do I..." Questions** + +#### **"How do I create a component?"** +```bash +1. Read: /docs/src/pages/components/create.mdx +2. Read: /docs/src/pages/api/component/define-component.mdx +3. Read: /docs/src/examples/component/minimal/component.js +4. Grep: pattern="defineComponent" include="*.js" path="/docs/src/examples/" | head -5 +``` + +#### **"How do I handle events?"** +```bash +1. Read: /docs/src/pages/components/events.mdx +2. Read: /docs/src/pages/api/query/events.mdx +3. Read: /docs/src/examples/component/events/event-binding/ +4. Grep: pattern="'click|'deep|'global" include="*.js" path="/docs/src/examples/" +``` + +#### **"How do I use templates?"** +```bash +1. Read: /docs/src/pages/templates/index.mdx +2. Read: /docs/src/pages/api/templating/template-compiler.mdx +3. Read: /docs/src/examples/component/templates/ +4. Grep: pattern="template.*:" include="*.js" path="/docs/src/examples/" +``` + +### 🕵️ **"Where is..." Questions** + +#### **"Where is [specific feature] implemented?"** +```bash +1. Grep: pattern="{feature}" include="*.js" path="/packages/" +2. Read: /packages/{likely-package}/src/ +3. Grep: pattern="{feature}" include="*.test.js" path="/packages/" +4. Read: /docs/src/pages/api/{package}/ +``` + +#### **"Where are examples of [pattern]?"** +```bash +1. Grep: pattern="{pattern}" include="*.js,*.html" path="/docs/src/examples/" +2. Task: "Find examples of {pattern} in the docs/src/examples directory" +``` + +### 🕵️ **"Why does..." Questions** + +#### **"Why does [behavior] happen?"** +```bash +1. Read: /ai/semantic-ui-mental-model.md # Design rationale +2. Grep: pattern="{behavior}" include="*.js" path="/packages/" +3. Read: Implementation file to understand logic +4. Read: /docs/src/pages/{relevant-section}/ # Conceptual explanation +``` + +#### **"Why is [pattern] recommended?"** +```bash +1. Read: /ai/semantic-ui-patterns-cookbook.md +2. Grep: pattern="{pattern}" include="*.mdx" path="/docs/src/pages/" +3. Read: /docs/src/examples/ # See canonical usage +``` + +### 🕵️ **"What's the difference..." Questions** + +#### **"What's the difference between State and Settings?"** +```bash +1. Read: /docs/src/pages/components/state.mdx +2. Read: /docs/src/pages/components/settings.mdx +3. Read: /ai/semantic-ui-mental-model.md # Conceptual differences +4. Read: /docs/src/pages/api/component/ # API differences +``` + +#### **"What's the difference between $ and $$?"** +```bash +1. Read: /docs/src/pages/query/shadow-dom.mdx +2. Read: /docs/src/pages/api/query/basic.mdx +3. Read: /packages/query/src/query.js +4. Read: /docs/src/examples/query/dom/shadow-dom/ +``` + +--- + +## 🎯 **Quick Reference for Common Needs** + +### **Need to understand concepts?** +→ `/ai/semantic-ui-mental-model.md` + +### **Need API reference?** +→ `/docs/src/pages/api/` (CANONICAL) or `/ai/semantic-ui-quick-reference.md` + +### **Need code patterns?** +→ `/ai/semantic-ui-patterns-cookbook.md` + +### **Need implementation details?** +→ `/packages/{package}/src/` + +### **Need usage examples?** +→ `/docs/src/examples/` + +### **Need documentation?** +→ `/docs/src/pages/` (read in menu order from `/docs/src/helpers/menus.js`) + +### **Need to debug?** +→ Search for `.test.js` files + implementation + +### **Need menu structure?** +→ `/docs/src/helpers/menus.js` (ESSENTIAL for documentation navigation order) + +--- + +**Remember**: +1. **Always start with documentation** (`/docs/src/pages/`) in menu order from `menus.js` +2. **API documentation is CANONICAL** at `/docs/src/pages/api/` organized by package +3. **Use canonical examples** (`/docs/src/examples/`) before diving into implementation +4. **Use the `Task` tool** for complex investigations that span multiple locations +5. **Refer to `menus.js`** if specific documentation paths are not available \ No newline at end of file diff --git a/ai/foundations/mental-model.md b/ai/foundations/mental-model.md new file mode 100644 index 000000000..f0f715946 --- /dev/null +++ b/ai/foundations/mental-model.md @@ -0,0 +1,775 @@ +# Semantic UI Mental Model + +> **For:** AI agents seeking deep architectural understanding +> **Prerequisites:** None - foundational document +> **Related:** [Component Guide](../guides/component-generation-instructions.md) • [Patterns Cookbook](../guides/patterns-cookbook.md) • [Quick Reference](../foundations/quick-reference.md) +> **Back to:** [Documentation Hub](../00-START-HERE.md) + +--- + +## Table of Contents + +- [Core Philosophy](#core-philosophy) +- [Architectural Foundation](#architectural-foundation) +- [Reactivity Mental Model](#reactivity-mental-model) +- [Component Lifecycle Model](#component-lifecycle-model) +- [Data Flow Architecture](#data-flow-architecture) +- [Component Tree Navigation](#component-tree-navigation) +- [Shadow DOM & Encapsulation](#shadow-dom--encapsulation) +- [Template Compilation Model](#template-compilation-model) +- [Performance Architecture](#performance-architecture) +- [Design System Integration](#design-system-integration) +- [Framework Interoperability](#framework-interoperability) + +--- + +## Core Philosophy + +### Web Standards First + +Semantic UI is built on the fundamental belief that **web standards are the foundation of sustainable web development**. Unlike frameworks that abstract away the platform, Semantic UI enhances and amplifies web standards: + +``` +Traditional Framework Approach: +Framework APIs → Virtual Abstraction → Platform Translation → DOM + +Semantic UI Approach: +Enhanced Web Standards → Direct Platform Integration → DOM +``` + +**Why this matters**: This approach ensures longevity, reduces vendor lock-in, and aligns with the platform's evolution rather than fighting against it. + +### Progressive Enhancement Philosophy + +The framework embodies progressive enhancement at its core: + +1. **Static HTML** works without JavaScript +2. **Enhanced HTML** gains interactivity when JavaScript loads +3. **Reactive HTML** becomes fully dynamic with the framework + +This isn't just about graceful degradation—it's about building components that naturally integrate into any environment. + +### Signals-First Reactivity + +Semantic UI adopts Signals as the fundamental reactive primitive because: + +- **Fine-grained updates**: Only the exact DOM nodes that need updating are touched +- **Automatic dependency tracking**: No manual subscription management +- **Synchronous by default**: Predictable state updates with optional async batching +- **Composable**: Signals can be combined and transformed declaratively + +--- + +## Architectural Foundation + +### The Hybrid Prototype/Instance Pattern + +Understanding this pattern is crucial to grasping how Semantic UI components work: + +``` +Component Definition (Prototype) +├── Template AST (compiled once, shared) +├── CSS Styles (processed once, shared) +├── Default Configuration +└── Behavior Definitions + + ↓ defineComponent() registers + +Component Instance (Per DOM Element) +├── Shadow DOM Root +├── Reactive State (unique per instance) +├── Mutable Settings (unique per instance) +├── Local Event Handlers +└── Lifecycle Callbacks +``` + +**Why this architecture**: +- **Memory efficiency**: Shared template compilation across instances +- **Isolation**: Each instance has independent reactive state and settings +- **Performance**: One-time compilation with multiple instantiations + +### Modular Package System + +``` +@semantic-ui/component ← Web Component framework + ↓ depends on +@semantic-ui/reactivity ← Signals system +@semantic-ui/templating ← AST-based templates +@semantic-ui/query ← Shadow DOM aware queries +@semantic-ui/utils ← Shared utilities +``` + +Each package can be used independently, enabling: +- **Gradual adoption**: Use only what you need +- **Framework agnostic**: Reactivity system works outside components +- **Testing isolation**: Mock or replace individual systems + +--- + +## Reactivity Mental Model + +### The Signal→Reaction→DOM Flow + +Understanding reactivity requires thinking in terms of directed graphs: + +``` +Signal (Data) + ↓ change triggers +Reaction (Computation) + ↓ updates +DOM (View) +``` + +**Template reactivity is automatic**: +```html + +

Count: {counter}

+ + +{#if isActive} +
Active content
+{/if} +``` + +**Component logic reactivity is explicit**: +```javascript +// Manual reaction creation +reaction(() => { + if (state.counter.get() > 10) { + state.warning.set(true); + } +}); +``` + +### The Dual Access Pattern + +Signals have different access patterns based on context: + +```javascript +// In component logic (explicit) +state.counter.get() // Read value +state.counter.set(5) // Write value +state.counter.increment() // Helper method + +// In templates (implicit) +{counter} // Automatic .get() call +``` + +**Why this distinction**: Templates are reactive contexts where dependency tracking is automatic. Component logic requires explicit control over when reactivity occurs. + +### Reactivity vs Non-Reactivity + +Understanding when reactivity happens is crucial: + +**Reactive Contexts** (automatic dependency tracking): +- Template expressions `{value}` +- Template conditionals `{#if condition}` +- Template loops `{#each items}` +- Manual reactions `reaction(() => {})` + +**Non-Reactive Contexts** (manual control): +- Event handlers +- Lifecycle callbacks +- Component methods +- External function calls + +**Mental Model**: Reactivity is "contagious" within reactive contexts and must be explicitly invoked elsewhere. + +--- + +## Component Lifecycle Model + +### The Three-Phase Lifecycle + +``` +CREATION PHASE +├── Component constructor called +├── defaultState → reactive Signals +├── defaultSettings → mutable configuration +├── createComponent() returns instance methods +└── onCreated() for initialization + +RENDERING PHASE +├── Template compilation (once per component type) +├── Shadow DOM creation +├── Data context binding +├── Event handler attachment +└── onRendered() for post-render setup + +DESTRUCTION PHASE +├── Event handler cleanup (automatic) +├── Reaction cleanup (automatic) +├── onDestroyed() for manual cleanup +└── Shadow DOM removal +``` + +**Key Insight**: Most cleanup is automatic thanks to AbortController usage and reaction tracking. Manual cleanup in `onDestroyed` should be rare. + +### Settings vs State vs Component Props Mental Model + +This distinction is fundamental to component design: + +``` +SETTINGS (Public API - Reactive Configuration) +├── Public interface for component consumers +├── Passed at component creation or modified during lifecycle +├── Controls component behavior and appearance +├── Fully reactive everywhere (proxy-based) +├── Think: "component's public API" +└── Examples: theme, size, disabled, variant, maxItems + +STATE (Internal Reactive Data) +├── Internal component memory and conditions +├── Created and managed within component lifecycle +├── Reactive signals for internal state tracking +├── Not directly accessible from outside +├── Think: "component's private memory" +└── Examples: isOpen, currentValue, validationErrors, loading + +COMPONENT PROPS (Non-Reactive Data) +├── Properties on the object returned from createComponent +├── Accessible as self.propName and directly in templates +├── Non-reactive data for performance optimization +├── Static values, snapshots, utilities, timers +├── Think: "component's static utilities" +└── Examples: apiEndpoint, cachedCalculations, debounceTimer +``` + +**Key Patterns**: +```javascript +const createComponent = ({ settings, state, self }) => ({ + // Component props - direct instance properties + apiEndpoint: '/api/users', // Non-reactive static data + validationRules: getRules(), // Cached calculation + debounceTimer: null, // Mutable non-reactive + + updateTheme(newTheme) { + settings.theme = newTheme; // Settings are mutable and reactive + }, + + toggleOpen() { + state.isOpen.toggle(); // State uses signal API + }, + + makeApiCall() { + fetch(self.apiEndpoint) // Access component props via self + .then(data => state.data.set(data)); + } +}); +``` + +**Decision Rules**: +- **Settings** → External consumers should configure this (public API) +- **State** → Internal reactive data that drives UI updates +- **Component Props** → Static, cached, or non-reactive data + +--- + +## Data Flow Architecture + +### The Data Context Model + +Templates operate within a "data context" - think of it as "all variables available in this scope": + +``` +Component Data Context: +├── State signals (reactive, automatic .get() in templates) +├── Settings (fully reactive, direct access) +├── Component props (non-reactive, direct access via self.propName) +├── Local template variables +├── Helper functions (only for complex logic or external API) +└── Parent context (in sub-templates) +``` + +**Template Access Patterns**: +```html + +{value} +{items.length} + + +{theme} +{size} + + +{apiEndpoint} +{maxRetries} +``` + +**Mental Model**: The data context provides direct access to all component data without needing getter methods. Templates automatically handle reactivity for state and settings. + +### Settings Reactivity Implementation + +The `settings` object is a proxy that makes its **top-level properties** reactive. When you assign a new value to a setting (e.g., `settings.theme = 'dark';` or `settings.complexObject = newObject;`), the underlying signal for that property is updated, triggering reactions and template updates. + +**Deep Reactivity of Object/Array Settings:** +If a setting holds an object or an array (e.g., `settings.config = { enabled: true, items: [1,2] };`), the reactivity of *changes made directly within* that object or array (e.g., `settings.config.enabled = false;` or `settings.config.items.push(3);`) needs careful consideration: + +* **Reassigning the Top-Level Property (Always Reactive):** Changing the entire object/array instance on the setting will always trigger reactivity correctly: + ```javascript + // This IS reactive because settings.config itself is being reassigned + settings.config = { ...settings.config, enabled: false }; + settings.config = { ...settings.config, items: [...settings.config.items, 3] }; + ``` + +* **Direct Deep Mutation (Behavior Details):** + The settings proxy primarily tracks assignments to its top-level properties. If you retrieve an object or array from settings (e.g., `const myConf = settings.config;`) and then mutate `myConf` directly (e.g., `myConf.enabled = false;`), this direct mutation does not pass through the settings proxy's `set` trap for the `config` property itself. + Therefore, for reliable reactivity with complex object/array settings, it's generally recommended to treat them as if they were immutable: reassign the top-level setting property with a new, modified object or array. + This behavior is distinct from `Signal` instances, where the `Signal` API provides explicit helper methods (like `setProperty()`, `push()`) for achieving reactive deep mutations on the data held by the signal. Always consult specific component documentation if it details different behavior for its particular settings. + +Settings are fully reactive everywhere through a sophisticated proxy system: + +```javascript +// Settings proxy creates hidden signals for reactivity +createSettingsProxy() { + component.settingsVars = new Map(); + return new Proxy({}, { + get: (target, property) => { + let signal = component.settingsVars.get(property); + if (signal) { + signal.get(); // Creates dependency in reactive contexts + } + return currentValue; + }, + set: (target, property, value) => { + component.setSetting(property, value); + signal.set(value); // Triggers reactive updates + } + }); +} +``` + +**Settings Access Patterns**: +```javascript +// In templates (reactive) +{theme} // Automatically reactive +{#if large} // Boolean setting as conditional + +// In component logic (reactive when inside reactions) +reaction(() => { + console.log(settings.theme); // Creates dependency, will re-run +}); + +// Direct modification (triggers reactivity) +settings.theme = 'dark'; // Updates hidden signal +settings.size = 'large'; // Template updates automatically +``` + +--- + +## Component Tree Navigation + +### The findParent/findChild Pattern + +`findParent(tagName)` searches for an ancestor component. The search mechanism prioritizes the DOM tree: it traverses upwards from the current component's host element (`template.element?.parentNode`), looking for an ancestor element that hosts a component matching the specified `tagName`. It will return the *closest* such DOM ancestor. + +As a fallback for non-DOM-based nesting (e.g., logical template partials embedded directly within another template's render logic), it may also consult internal `parentTemplate` links established during template rendering. If no `tagName` is provided, `findParent` typically finds the closest component parent regardless of its tag name. + +For finding multiple parents or searching more globally across all rendered templates by their developer-assigned `templateName`, utilities like `findParents(tagName)` (if available) or `Template.findTemplate(templateName)` (which accesses a map of all rendered templates by `templateName`) can be considered. + +Semantic UI provides a powerful component tree navigation system for **intentional parent-child component relationships**. This is the preferred method for sharing state between components designed to work together: + +```javascript +// Child component accessing its designed parent +const createComponent = ({ findParent }) => ({ + getTodos() { + // todo-item accessing its todo-list parent + return findParent('todoList').todos; // Access parent's todos signal + }, + addTodo(todo) { + const parent = findParent('todoList'); + parent.todos.push(todo); // Mutate parent state + } +}); + +// Parent component managing its children +const createComponent = ({ findChild, getChildren }) => ({ + selectAllButtons() { + // button-group managing its button children + const buttons = getChildren('ui-button'); + buttons.forEach(button => button.setSelected(true)); + } +}); +``` + +**Use Cases for findParent/findChild**: +- **Component Systems**: button-group ↔ button, accordion ↔ accordion-panel +- **Container Components**: form ↔ form-field, table ↔ table-row +- **Layout Components**: pane-group ↔ pane, tab-container ↔ tab +- **List Components**: todo-list ↔ todo-item, menu ↔ menu-item + +### Parent-Child Communication Patterns + +``` +PARENT → CHILD (Configuration) +Parent sets child's settings via attributes/properties + +CHILD → PARENT (State Access) +Child uses findParent() to access parent's exposed properties + +PARENT → CHILD (Direct Access) +Parent uses findChild() to access child components + +SIBLING ↔ SIBLING (Via Parent) +Siblings communicate through shared parent state +``` + +### State Sharing Architecture + +**Local State** (single component): +```javascript +defaultState: { + isOpen: false, + selectedItem: null +} +``` + +**Shared State** (parent-child coordination): +```javascript +// Parent component exposes state +createComponent: ({ signal }) => ({ + todos: signal([]), // Exposed for children to access + + addTodo(todo) { + this.todos.push(todo); + } +}); + +// Child component accesses parent state +createComponent: ({ findParent }) => ({ + getTodos() { + return findParent('todoList').todos; + } +}); +``` + +**Complex Tree Communication**: +```javascript +// Deep nesting with multiple parents +const createComponent = ({ findParent }) => ({ + getAppContext() { + return findParent('app-shell'); // Skip intermediate parents + }, + getFormData() { + return findParent('form-container').formData; + } +}); +``` + +### Anti-Patterns to Avoid + +❌ **Global State Stores** (use component tree instead): +```javascript +// Avoid: Global singletons +import { globalStore } from './store.js'; +``` + +✅ **Component Tree Navigation**: +```javascript +// Preferred: Component tree traversal +const parent = findParent('data-provider'); +``` + +❌ **Direct Child State Access**: +```javascript +// Avoid: Reaching into child state +const child = findChild('todo-item'); +child.state.completed.set(true); +``` + +✅ **Child Method Invocation**: +```javascript +// Preferred: Call child methods +const child = findChild('todo-item'); +child.markCompleted(); +``` + +--- + +## Shadow DOM & Encapsulation + +### The Encapsulation Strategy + +Semantic UI uses Shadow DOM for true style and DOM encapsulation: + +``` +Light DOM (Application) +└── + └── Shadow DOM (Component) + ├──