# Project Hints and Findings

## TypeScript 6.0 & Build Tooling (2026-04-12)

### TypeScript 6.0 Strict Defaults
TypeScript 6.0.2 (shipped with tsbuild 4.4.0) changes `strict` to `true` by default. The project explicitly sets `"strict": false` in tsconfig.json to preserve pre-TS6 behavior. Also added `"types": ["node"]` since TS6 changed `@types/*` auto-discovery.

### Config Migration: npmextra.json → .smartconfig.json
Build tools (tsbundle 2.10.0, tswatch 3.3.2) now use `@push.rocks/smartconfig` which reads `.smartconfig.json` (with leading dot). The old `npmextra.json` was renamed.

### tsbundle Configuration
The `tsbundle element` subcommand no longer exists. Instead, bundle configuration lives in `.smartconfig.json` under `"@git.zone/tsbundle"` with a `bundles` array. Entry point is `./html/index.ts` → `./dist_bundle/bundle.js`.

---

## Section-based Configuration API (2025-12-27)

### Overview
Refactored `setupWccTools` to accept a section-based configuration object instead of separate elements/pages arguments. This allows multiple custom sections with filtering, sorting, and collapsible headers.

### New API
```typescript
import * as deesWccTools from '@design.estate/dees-wcctools';

deesWccTools.setupWccTools({
  sections: [
    {
      name: 'Pages',
      type: 'pages',
      items: pages,
    },
    {
      name: 'Elements',
      type: 'elements',
      items: elements,
      filter: (name, item) => !name.startsWith('internal-'),
      sort: ([a], [b]) => a.localeCompare(b),
    },
    {
      name: 'Views',
      type: 'elements',
      items: elements,
      filter: (name, item) => name.startsWith('view-'),
      icon: 'web',
      collapsed: true,  // Start collapsed
    },
  ],
});
```

### Section Properties
- `name`: Display name for the section header
- `type`: `'elements'` (shows demos) or `'pages'` (renders directly)
- `items`: Record of items (element classes or page factories)
- `filter`: Optional `(name, item) => boolean` to filter items
- `sort`: Optional `([name, item], [name, item]) => number` for ordering
- `icon`: Optional Material icon name for section header
- `collapsed`: Optional boolean to start section collapsed

### Backwards Compatibility
Legacy format is still supported:
```typescript
deesWccTools.setupWccTools(elements, pages);  // Still works
```

### URL Routing
Changed from `/wcctools-route/:itemType/:itemName/...` to `/wcctools-route/:sectionName/:itemName/...`
Section names are URL-encoded. Legacy routes (`element`/`page` as section name) still work for backwards compatibility.

### Files Changed
- `ts_web/wcctools.interfaces.ts` - New types: `IWccSection`, `IWccConfig`
- `ts_web/index.ts` - Updated `setupWccTools` with backwards compat detection
- `ts_web/elements/wcc-dashboard.ts` - Uses sections, updated routing
- `ts_web/elements/wcc-sidebar.ts` - Dynamic section rendering

---

## Element Demo Groups (2026-01-27)

### Overview
Elements can declare `demoGroups` (renamed from `demoGroup`) as a static property to appear grouped in the sidebar. Supports `string | string[]` — elements with an array appear in multiple groups simultaneously.

### Usage
```typescript
// Single group
public static demoGroups = 'Buttons';

// Multiple groups — element appears in both
public static demoGroups = ['Buttons', 'Form Controls'];
```

### Features
- Search matches group names (searching "Buttons" shows all elements in that group)
- Groups sorted alphabetically by group name
- Multi-group elements show `library_books` icon instead of `featured_video`
- Context menu shows "Show in Group:" with clickable group entries that scroll to and highlight the group
- `data-group` attribute on `.item-group` containers for DOM querying

### Files Changed
- `ts_web/elements/wcc-sidebar.ts` — grouping logic, search filter, sort key, icon, context menu, scrollToGroup
- `test/elements/test-button-*.ts`, `test/elements/test-input-*.ts` — renamed `demoGroup` → `demoGroups`

---

## UI Redesign with Shadcn-like Styles (2025-06-27)

### Changes Made
Updated the WCC Dashboard UI components (properties and sidebar) to use shadcn-like design patterns:

1. **Color System**: Implemented CSS variables for theming:
   - `--background`, `--foreground`, `--card`, `--primary`, `--secondary`
   - `--muted`, `--accent`, `--border`, `--input`, `--ring`
   - Consistent dark theme with subtle borders and proper contrast
   - Dynamic theme switching between light and dark modes

2. **Properties Panel Improvements (Updated)**: 
   - Changed from fixed 3-column grid to flexible flexbox layout
   - Properties now wrap and use space more efficiently
   - Added rounded corners (using --radius-md) and better spacing
   - Property items use flexbox with min-width for responsive layout
   - Property labels now show as styled headers with type info
   - Form controls updated with shadcn-style focus states and transitions
   - Complex properties (Objects/Arrays) show "Edit" button
   - Advanced JSON editor appears above properties panel when editing complex types
   - Dynamic height adjustment (50px when editor is open, 120px normally)

3. **Sidebar Styling**:
   - Updated with consistent color scheme
   - Added rounded corners to menu items
   - Improved hover states with smooth transitions
   - Better typography with proper font weights

4. **Advanced Property Editor**:
   - JSON editor for complex types (Objects and Arrays)
   - Monaco-style monospace font for code editing
   - Live updates to element properties
   - Positioned above the properties panel with smooth transitions

5. **Theme and Viewport Selectors (New)**:
   - Redesigned buttons with flexbox layout for better icon/text alignment
   - Added hover effects with transform and shadow
   - Smooth transitions on all interactive elements
   - Selected state uses primary color variables
   - Icons reduced in size for better balance

6. **Form Controls (New)**:
   - Input fields and selects now have:
     - Rounded corners (--radius-sm)
     - Consistent padding (0.5rem 0.75rem)
     - Focus states with ring effect using box-shadow
     - Smooth transition animations
   - Checkboxes use accent-color for theming

### Technical Details
- Uses system font stack ('Inter' preferred) for better native appearance
- Subtle borders with CSS variables for consistency
- Consistent spacing using rem units
- Smooth transitions (0.2s ease) for interactive elements
- Custom scrollbar styling for better visual integration
- Grid layout with 1px gaps creating subtle dividers
- Warning display with backdrop blur and rounded corners

## Advanced Complex Properties Editor (2025-06-27)

### Overview
Implemented an advanced editor for complex properties (Arrays and Objects) that appears between the wcc-properties panel and frame when activated.

### Features
1. **Dynamic Layout**: Frame shrinks by 300px from bottom when editor opens
2. **Multiple Editors**: Can edit multiple properties simultaneously side by side
3. **JSON Editor**: 
   - Monospace font for code editing
   - Tab key support for indentation
   - Syntax validation with error messages
   - Live preview of changes
4. **Smooth Transitions**: Animated opening/closing with 0.3s ease
5. **Error Handling**: Invalid JSON shows clear error messages that disappear on typing
6. **Close All Button**: Single button to close all open editors at once

### Technical Implementation (Updated)
- **State Management**: Changed from single editor to array of editors with unique IDs
- **Editor Structure**: Each editor instance contains:
  - `id`: Unique identifier (`propertyName-timestamp`)
  - `name`: Property name
  - `value`: Original value
  - `element`: Reference to the element
  - `editorValue`: Current JSON string
  - `editorError`: Validation error message
- **Event System**: Uses custom 'editorStateChanged' event to communicate with parent dashboard
- **Dynamic Styling**: wcc-frame's bottom position changes from 100px to 400px when any editor is open
- **Property Types**: Object and Array properties show "Edit Object/Array" button instead of inline controls

### User Flow
1. Click "Edit Object/Array" button on complex property
2. Editor slides up between properties panel and frame
3. Click additional "Edit" buttons to open more properties side by side
4. Each editor can be saved/cancelled independently
5. "Close All" button dismisses all editors at once
6. Frame automatically resizes back when all editors are closed

### Layout Details
- **Container**: Flexbox with horizontal scrolling when multiple editors overflow
- **Editor Width**: Min 300px, max 500px, flexible between
- **Scrollbar**: Custom styled thin scrollbar for horizontal overflow
- **Header Bar**: Fixed top bar with "Property Editors" title and "Close All" button

## Properties Panel Element Detection Issue (Fixed)

### Problem
The properties panel had timing issues detecting rendered elements because:
1. Elements are rendered asynchronously via lit's `render()` function in the dashboard component
2. The properties panel tried to find elements immediately without waiting for render completion
3. Element search only looked at direct children of the viewport, missing nested elements or those inside shadow DOM

### Solution Implemented
1. Added a 100ms initial delay to allow render completion
2. Implemented recursive element search that:
   - Searches through nested children up to 5 levels deep
   - Checks both light DOM and shadow DOM for all elements
   - Handles complex DOM structures generically
   - Works with any wrapper elements, not specific to dees-demowrapper
3. Added retry mechanism with up to 5 attempts (200ms between retries)
4. Improved error messages to show retry count
5. Comprehensive error handling:
   - Errors in element search don't break the update cycle
   - Individual property errors don't prevent other properties from rendering
   - scheduleUpdate always completes even if createProperties fails
   - Clears warnings and property content appropriately on errors

### Code Flow
1. Dashboard renders element demo into viewport using `render(anonItem.demo(), viewport)`
2. Properties panel waits 200ms for demo wrappers to run and set initial values
3. Searches recursively for the element instance
4. If not found, retries with delays to handle async rendering
5. Once found, extracts and displays element properties
6. Uses property binding (`.value=`) instead of attribute binding to prevent input events during initialization

## Demo Tools

### DeesDemoWrapper Component
A utility component for wrapping demo elements with post-render functionality.

**Usage:**
```typescript
import * as demoTools from '@design.estate/dees-wcctools/demotools';

// In your demo function:
demo: () => html`
  <dees-demowrapper .runAfterRender=${(wrapper) => {
    // Use querySelector for specific elements
    const myElement = wrapper.querySelector('my-custom-element');
    myElement?.setAttribute('data-demo', 'true');
    
    // Access all children
    console.log('All children:', wrapper.children);
    
    // Use querySelectorAll for multiple elements
    wrapper.querySelectorAll('div').forEach(div => {
      console.log('Found div:', div);
    });
    
    // Full DOM API available
    const firstChild = wrapper.firstElementChild;
    const hasClass = wrapper.querySelector('.my-class');
  }}>
    <my-custom-element></my-custom-element>
    <div>Additional content</div>
  </dees-demowrapper>
`
```

**Features:**
- Wraps demo elements without affecting layout (uses `display: contents`)
- Provides the wrapper element itself with full DOM API access
- Use querySelector/querySelectorAll for powerful element selection
- Access children via wrapper.children property
- Supports async operations in runAfterRender callback
- Automatically handles timing to ensure elements are fully rendered