# `ixfx-grouped-item-lister`

A meta-component that renders a typed item list using any sub-component you supply. Items can be displayed in a single sub-component (_ungrouped_ mode) or split into labelled groups, each with its own sub-component (_grouped_ mode), wrapped in `ixfx-panel` sections.

The component uses **Light DOM** so its children are directly accessible to external CSS and can be observed by the page's event listeners without crossing a shadow boundary.

---

## Contents

1. [Quick start](#quick-start)
2. [Properties](#properties)
3. [Providing data](#providing-data)
4. [Built-in adapters](#built-in-adapters)
   - [`createVerticalListAdapter`](#createverticallistadapter)
   - [`createTreeListAdapter`](#createtreelistadapter)
5. [Selection](#selection)
6. [Dispatching commands](#dispatching-commands)
7. [Events](#events)
8. [Writing a custom adapter](#writing-a-custom-adapter)

---

## Quick start

```typescript
import {
  createVerticalListAdapter,
} from '@ixfx/components';
import type { GroupedItemListerElement } from '@ixfx/components';

type FileItem = { id: string; name: string; ext: string };

const lister = document.querySelector<GroupedItemListerElement<FileItem>>('ixfx-grouped-item-lister')!;

// 1. Factory — called once per group (or once for the ungrouped view)
lister.factory = () =>
  createVerticalListAdapter<FileItem>(item => {
    const li = document.createElement('li');
    li.textContent = item.name;
    return li;
  });

// 2. Group key function
lister.groupBy = item => item.ext;

// 3. Data source — sync, Promise, or AsyncIterable
lister.provider = () => myFiles;

// 4. Listen for selection changes
lister.addEventListener('grouped-select', ({ detail }) => {
  const { selected, groupKey } = detail;
  console.log(groupKey, [...selected].map(f => f.name));
});
```

```html
<ixfx-grouped-item-lister grouped></ixfx-grouped-item-lister>
```

---

## Properties

### HTML attributes

| Attribute | Type | Default | Description |
|---|---|---|---|
| `grouped` | `boolean` | `false` | When set, items are split into one sub-component per group key. Without it, all items go into a single sub-component. |
| `cross-group-selection` | `boolean` | `false` | When `grouped` is on, controls whether selecting an item in one group automatically clears all other groups. Has no effect when `grouped` is off. |

### JavaScript-only properties

These carry typed or callable values and cannot be set as HTML attributes.

| Property | Type | Description |
|---|---|---|
| `factory` | `SubComponentFactory<T>` | Called once per group (or once for the ungrouped view) to create a sub-component. **Must be set before items arrive.** |
| `groupBy` | `(item: T) => string` | Derives the group key for each item. Required in grouped mode. |
| `provider` | `IDataProvider<void, T>` | Data source for items. Setting this property triggers an immediate request. |

#### `SubComponentFactory<T>`

```typescript
type SubComponentFactory<T> = (groupKey: string | undefined) => HTMLElement & IGroupedSubComponent<T>;
```

`groupKey` is the group's key string in grouped mode, or `undefined` in ungrouped mode.

---

## Providing data

`provider` accepts any `IDataProvider<void, T>` — a function returning one of:

```typescript
// Sync — items available immediately
lister.provider = () => myItemsArray;

// Async one-shot
lister.provider = async () => {
  const res = await fetch('/api/items');
  return res.json() as T[];
};

// Streaming — items delivered in batches over time
lister.provider = async function* () {
  for await (const page of paginatedFetch('/api/items')) {
    yield { items: page };
  }
};
```

Replacing `provider` cancels any in-flight request and starts a fresh one.

---

## Built-in adapters

Two factory helpers ship with the package, one for each existing list component.

---

### `createVerticalListAdapter`

Wraps `ixfx-vertical-list`. Items are typed as `T`; the adapter converts each item to a DOM element via your `renderItem` function, maintains a `WeakMap<Element, T>` for reverse-lookup, and bridges `list-*` events to the interface names (`select`, `activate`, etc.).

```typescript
import { createVerticalListAdapter } from '@ixfx/components';

lister.factory = () =>
  createVerticalListAdapter<MyItem>(
    // Convert your typed item to a DOM element (typically an <li>)
    item => {
      const li = document.createElement('li');
      li.textContent = item.label;
      li.dataset.key = item.id;
      li.dataset.searchLabel = item.label; // enables Ctrl+F search
      return li;
    },
    {
      selectionMode: 'single',         // 'none' | 'single' | 'multiple'
      interactionMode: 'standard',     // forwarded to ixfx-vertical-list
      onDispatch: (commandId, args, list) => {
        if (commandId === 'sort-alpha' && list) {
          const rows = [...list.querySelectorAll<HTMLElement>('li')];
          rows.sort((a, b) => (a.textContent ?? '').localeCompare(b.textContent ?? ''));
          for (const row of rows) list.appendChild(row);
        }
      },
    },
  );
```

#### Options

| Option | Type | Default | Description |
|---|---|---|---|
| `selectionMode` | `'none' \| 'single' \| 'multiple'` | `'single'` | Forwarded to the inner `ixfx-vertical-list` |
| `interactionMode` | `ListInteractionMode` | `'standard'` | Forwarded to the inner `ixfx-vertical-list` |
| `onDispatch` | `(commandId, args, list?) => void` | — | Called when `lister.dispatch()` is invoked. `list` is the inner `VerticalListElement` |

The inner `ixfx-vertical-list` inherits its full feature set: keyboard navigation, incremental search (Ctrl+F), and all selection modes including checkboxes.

---

### `createTreeListAdapter`

Wraps `ixfx-tree-list`. Builds a `TreeNode` hierarchy from your flat or nested items, stores each original `T` in `TreeItem.data` for selection reverse-mapping, and bridges tree events to the interface.

```typescript
import { createTreeListAdapter } from '@ixfx/components';

lister.factory = () =>
  createTreeListAdapter<CategoryItem>(
    // Convert your item to TreeItem display metadata
    item => ({
      key:   item.id,
      label: item.name,
      isLeaf: item.children.length === 0,
      icon:  item.children.length ? 'folder' : 'file',
    }),
    {
      // Return the item's direct children to build the hierarchy
      getChildren: item => item.children,
      selectionFilter: 'all',
      onDispatch: (commandId, _args, tree) => {
        if (commandId === 'sort-alpha' && tree?.root?.children) {
          tree.root = {
            ...tree.root,
            children: [...tree.root.children].sort((a, b) =>
              a.item.label.localeCompare(b.item.label),
            ),
          };
        }
      },
    },
  );
```

#### Flat item lists

Omit `getChildren` when items have no hierarchy — all items become root-level leaf nodes:

```typescript
lister.factory = () =>
  createTreeListAdapter<FileItem>(
    item => ({ key: item.id, label: item.name, isLeaf: true }),
  );
```

#### Options

| Option | Type | Default | Description |
|---|---|---|---|
| `getChildren` | `(item: T) => readonly T[]` | — | Returns the item's direct children. Omit for flat lists. |
| `interactionMode` | `TreeInteractionMode` | `'standard'` | Forwarded to the inner `ixfx-tree-list` |
| `selectionFilter` | `TreeSelectionFilter` | `'all'` | Which node types are selectable (`'leaf'`, `'branch'`, `'all'`, `'none'`) |
| `exclusivity` | `TreeExclusivity` | `'none'` | Accordion behaviour when expanding nodes |
| `onDispatch` | `(commandId, args, tree?) => void` | — | Called when `lister.dispatch()` is invoked. `tree` is the inner `TreeBaseElement` |

---

## Selection

### Cross-group selection

By default (`cross-group-selection` is off), clicking an item in group B automatically clears selections in all other groups. Set the attribute to allow simultaneous selections across groups:

```html
<ixfx-grouped-item-lister grouped cross-group-selection></ixfx-grouped-item-lister>
```

```typescript
lister.crossGroupSelection = true;
```

This attribute has no effect when `grouped` is off.

### Reading the current selection

```typescript
// Full union of all selected items across every group
const all: ReadonlySet<T> = lister.selectedItems;

// Or via the grouped-select event (see Events)
lister.addEventListener('grouped-select', ({ detail }) => {
  const { selected, groupKey } = detail;
});
```

---

## Dispatching commands

`lister.dispatch(commandId, args?)` forwards a command to every live sub-component by calling their `dispatch` method. Use this to apply global operations — sort order, view mode, filter string — without knowing which groups exist or how many sub-components are active.

```typescript
// Sort all groups alphabetically
lister.dispatch('sort-alpha');

// Pass arguments
lister.dispatch('filter', { query: 'image' });
```

Sub-components receive the command via their `dispatch` method. Both built-in adapters expose an `onDispatch` option for handling commands.

---

## Events

### `grouped-select`

Fired by `ixfx-grouped-item-lister` itself after any sub-component's selection changes (and after cross-group enforcement has been applied). The detail carries the **full cross-group union** — it is the single place to observe the overall selection state regardless of mode.

```typescript
lister.addEventListener('grouped-select', ({ detail }) => {
  const { selected, groupKey } = detail;
  // selected: ReadonlySet<T> — union across all groups
  // groupKey: string | undefined — key of the group that changed;
  //           undefined in ungrouped mode
});
```

### Bubbled sub-component events

Because the component uses Light DOM, events fired by sub-components bubble up through `ixfx-grouped-item-lister` unchanged. Register listeners on the lister element to handle them globally:

```typescript
lister.addEventListener('activate', event => {
  const { item } = (event as CustomEvent<{ item: T }>).detail;
  console.log('activated:', item);
});

lister.addEventListener('item-click', event => { /* ... */ });
lister.addEventListener('tickle',     event => { /* ... */ });
```

`event.target` is the sub-component element that fired the event. In grouped mode, querying `event.target.closest('ixfx-panel')` gives the enclosing panel.

### Full event reference

| Event | Source | Detail | When fired |
|---|---|---|---|
| `grouped-select` | `ixfx-grouped-item-lister` | `{ selected: ReadonlySet<T>, groupKey: string \| undefined }` | After any sub-component fires `select` |
| `select` | sub-component | `{ selected: ReadonlySet<T>, previous: ReadonlySet<T> }` | Selection changes in a single group |
| `activate` | sub-component | `{ item: T }` | User double-clicks or presses Enter on an item |
| `item-click` | sub-component | `{ item: T }` | Raw click on an item |
| `tickle` | sub-component | `{ item: T }` | Pointer hovers over or keyboard cursor moves to an item |

---

## Writing a custom adapter

To use a different rendering component (your own Lit element, a React portal, a canvas renderer, etc.), implement `IGroupedSubComponent<T>` and return an `HTMLElement` that satisfies it from `factory`.

### Interface

```typescript
interface IGroupedSubComponent<T> extends HTMLElement {
  /** Replace the full item list. Called whenever items or grouping changes. */
  setItems(items: readonly T[]): void;

  /**
   * Clear the selection. Called by the lister when enforcing cross-group
   * selection. The implementation MAY fire a 'select' event — the lister
   * guards against re-entrant processing.
   */
  clearSelection(): void;

  readonly selectedItems: ReadonlySet<T>;
  selectionMode: 'none' | 'single' | 'multiple';

  /** Receives commands from lister.dispatch(). */
  dispatch(commandId: string, args?: Record<string, unknown>): void;
}
```

### Required events

Sub-components must fire these events with `bubbles: true, composed: true`:

| Event | Detail | When |
|---|---|---|
| `select` | `{ selected: ReadonlySet<T>, previous: ReadonlySet<T> }` | Selection changes |
| `activate` | `{ item: T }` | Double-click or Enter |
| `item-click` | `{ item: T }` | Raw click on item |
| `tickle` | `{ item: T }` | Hover or keyboard cursor |

### Minimal example

```typescript
class MyItemList extends HTMLElement implements IGroupedSubComponent<MyItem> {
  #items: readonly MyItem[] = [];
  #selected = new Set<MyItem>();

  selectionMode: 'none' | 'single' | 'multiple' = 'single';

  get selectedItems(): ReadonlySet<MyItem> { return this.#selected; }

  setItems(items: readonly MyItem[]): void {
    this.#items = items;
    this.#render();
  }

  clearSelection(): void {
    if (this.#selected.size === 0) return;
    const previous = new Set(this.#selected);
    this.#selected.clear();
    this.#syncStyles();
    this.dispatchEvent(new CustomEvent('select', {
      detail: { selected: new Set(), previous },
      bubbles: true, composed: true,
    }));
  }

  dispatch(commandId: string, _args?: Record<string, unknown>): void {
    // handle commands
  }

  #render(): void {
    this.innerHTML = '';
    for (const item of this.#items) {
      const row = document.createElement('div');
      row.textContent = item.label;
      row.addEventListener('click', () => this.#handleClick(item));
      row.addEventListener('dblclick', () =>
        this.dispatchEvent(new CustomEvent('activate', {
          detail: { item }, bubbles: true, composed: true,
        })),
      );
      row.addEventListener('pointerover', () =>
        this.dispatchEvent(new CustomEvent('tickle', {
          detail: { item }, bubbles: true, composed: true,
        })),
      );
      this.appendChild(row);
    }
  }

  #handleClick(item: MyItem): void {
    this.dispatchEvent(new CustomEvent('item-click', {
      detail: { item }, bubbles: true, composed: true,
    }));
    const previous = new Set(this.#selected);
    if (this.selectionMode === 'single') this.#selected.clear();
    this.#selected.add(item);
    this.#syncStyles();
    this.dispatchEvent(new CustomEvent('select', {
      detail: { selected: new Set(this.#selected), previous },
      bubbles: true, composed: true,
    }));
  }

  #syncStyles(): void { /* update [aria-selected] etc. */ }
}

customElements.define('my-item-list', MyItemList);

// Use it
lister.factory = () => document.createElement('my-item-list') as MyItemList;
```

> **Constructor constraint**: Custom elements cannot call `this.appendChild()` in their constructor. If your sub-component needs child elements, create them lazily on the first `setItems()` call or in `connectedCallback()`.
