# AAC Board Viewer

Universal AAC (Augmentative and Alternative Communication) board viewer component for React. Display and interact with communication boards from multiple AAC systems.

## Supported Formats

- **Grid 3** (`.gridset` files)
- **TouchChat** (`.ce` files)
- **TD Snap** (`.sps`, `.spb` files)
- **OpenBoard** (`.obf`, `.obz` files)
- **Asterics Grid** (`.grd` files)
- **Apple Panels** (`.plist` files)
- **GoTalk NOW** (`.gtbz` files)
- **OPML** (`.opml` files)
- **Excel** (`.xlsx` boards)
- **DOT files** (`.dot` visualizations)

Note: In-browser loading of SQLite-backed formats (`.sps`, `.spb`, `.ce`) requires SQL.js configuration.

## Features

- 🎯 **Universal Support** - Works with all major AAC file formats
- 📱 **Responsive Design** - Mobile-friendly with touch support
- 🎨 **Preserves Styling** - Maintains original colors, fonts, and layouts
- 🔗 **Interactive Navigation** - Click buttons to navigate between pages
- 🗣️ **Sentence Building** - Tap buttons to build sentences
- 🔧 **Customizable** - Flexible styling and behavior options (toggle message bar, link indicators, effort badges)
- 🌙 **Dark-mode Friendly** - Inherits host app theme when a parent adds the `dark` class

## Demos

- React demo: `demo/`
- Vue demo: `demo-vue/`

## Installation

Requires Node 20+.

```bash
npm install aac-board-viewer
```

Or with yarn:

```bash
yarn add aac-board-viewer
```

## Quick Start

### Browser Usage

SQLite-backed formats (Snap `.sps`/`.spb` and TouchChat `.ce`) require SQL.js to be configured in your bundler before loading files:

```tsx
import { configureBrowserSqlJs, loadAACFile, BoardViewer } from 'aac-board-viewer';
import sqlWasmUrl from 'sql.js/dist/sql-wasm.wasm?url';
import 'aac-board-viewer/styles';

configureBrowserSqlJs({
  locateFile: () => sqlWasmUrl,
});

function MyViewer({ file }: { file: File }) {
  const [tree, setTree] = useState(null);

  useEffect(() => {
    async function load() {
      const loadedTree = await loadAACFile(file);
      setTree(loadedTree);
    }
    load();
  }, [file]);

  if (!tree) return <div>Loading...</div>;
  return <BoardViewer tree={tree} />;
}
```

### Vue 3 Usage

```ts
import { BoardViewer } from 'aac-board-viewer/vue';
import { loadAACFile, configureBrowserSqlJs } from 'aac-board-viewer';
import sqlWasmUrl from 'sql.js/dist/sql-wasm.wasm?url';
import 'aac-board-viewer/styles';

configureBrowserSqlJs({
  locateFile: () => sqlWasmUrl,
});
```

```vue
<template>
  <BoardViewer v-if="tree" :tree="tree" />
  <div v-else>Loading...</div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import type { AACTree } from 'aac-board-viewer';
import { BoardViewer } from 'aac-board-viewer/vue';
import { loadAACFile } from 'aac-board-viewer';

const tree = ref<AACTree | null>(null);

async function loadFile(file: File) {
  tree.value = await loadAACFile(file);
}
</script>
```

### Server-Side / API Usage

```tsx
import { BoardViewer } from 'aac-board-viewer';
import 'aac-board-viewer/styles';

function MyViewer({ treeData }) {
  return (
    <BoardViewer
      tree={treeData}
      buttonMetrics={metricsData}
      showMessageBar={true}
      showEffortBadges={true}
    />
  );
}
```

### Client/Server Split (Lightweight Frontend)

Parse boards on the server and send the `AACTree` JSON to the browser for rendering. This keeps the frontend lightweight while the backend handles heavy formats.

Server (Node/Express):

```ts
import express from 'express';
import { loadAACFile } from 'aac-board-viewer';

const app = express();

app.get('/api/boards/:id', async (req, res) => {
  const tree = await loadAACFile(`/data/boards/${req.params.id}.sps`);
  res.json(tree);
});
```

Client (React):

```tsx
import { BoardViewer } from 'aac-board-viewer';
import 'aac-board-viewer/styles';

function RemoteBoard({ id }: { id: string }) {
  const [tree, setTree] = useState(null);

  useEffect(() => {
    fetch(`/api/boards/${id}`)
      .then((res) => res.json())
      .then(setTree);
  }, [id]);

  if (!tree) return <div>Loading...</div>;
  return <BoardViewer tree={tree} />;
}
```

## Publishing Notes

- The Vue renderer is exported from `aac-board-viewer/vue` and built by `tsup` into `dist/vue.*`.
- `vue` is an optional peer dependency so React-only consumers avoid install warnings, but Vue apps should add `vue` explicitly.
- Publish requires `npm run build` to generate `dist` artifacts (including `dist/vue.*` and `dist/styles.css`).

### With Metrics

```tsx
import { BoardViewer, loadAACFile, calculateMetrics } from 'aac-board-viewer';

function MetricsViewer({ filePath }) {
  const [tree, setTree] = useState(null);
  const [metrics, setMetrics] = useState(null);

  useEffect(() => {
    async function load() {
      const loadedTree = await loadAACFile(filePath);
      const calculatedMetrics = await calculateMetrics(loadedTree);

      setTree(loadedTree);
      setMetrics(calculatedMetrics);
    }
    load();
  }, [filePath]);

  if (!tree) return <div>Loading...</div>;

  return (
    <BoardViewer
      tree={tree}
      buttonMetrics={metrics}
      showEffortBadges={true}
    />
  );
}
```

## Props

### BoardViewer

```typescript
interface BoardViewerProps {
  tree: AACTree;
  buttonMetrics?: ButtonMetric[] | null;
  showMessageBar?: boolean;
  showEffortBadges?: boolean;
  showLinkIndicators?: boolean;
  onButtonClick?: (button: AACButton) => void;
  onPageChange?: (pageId: string) => void;
  className?: string;
}
```

### AACTree

```typescript
interface AACTree {
  pages: { [key: string]: AACPage };
  rootId?: string;
  toolbarId?: string;
  metadata?: {
    format?: string;
    name?: string;
    description?: string;
    [key: string]: any;
  };
}
```

## Advanced Usage

### Custom Styling

```tsx
<BoardViewer
  tree={tree}
  className="my-custom-board"
/>
```

### Event Handling

```tsx
<BoardViewer
  tree={tree}
  onButtonClick={(button) => {
    console.log('Button clicked:', button.label);
    // Track analytics, play sound, etc.
  }}
  onPageChange={(pageId) => {
    console.log('Page changed to:', pageId);
    // Track navigation
  }}
/>
```

### Hide Message Bar

```tsx
<BoardViewer
  tree={tree}
  showMessageBar={false}
/>
```

## File Loading

The library provides utilities for loading AAC files:

### Programmatic Loading

```tsx
import { loadAACFile } from 'aac-board-viewer';

const tree = await loadAACFile('/path/to/file.gridset');
```

### From File Input

```tsx
import { loadAACFileFromFile } from 'aac-board-viewer';

function FileInput() {
  const handleChange = async (e) => {
    const file = e.target.files[0];
    const tree = await loadAACFileFromFile(file);
    // Use tree...
  };

  return <input type="file" onChange={handleChange} />;
}
```

## Metrics Calculation

Calculate cognitive effort metrics for buttons:

```tsx
import { calculateMetrics } from 'aac-board-viewer';

const metrics = await calculateMetrics(tree, {
  accessMethod: 'direct', // or 'scanning'
  scanningConfig: {
    pattern: 'row-column', // 'linear', 'row-column', 'block'
    selectionMethod: 'auto-1-switch',
    errorCorrection: false,
  },
});

// metrics is an array of ButtonMetric objects:
// [{ id, label, effort, count, is_word, level }, ...]
```

## Format-Specific Notes

### Apple Panels

Apple Panels use free-form positioning. The viewer automatically:
- Converts absolute positioning to grid layout
- Calculates appropriate grid dimensions
- Preserves original button placement

### Asterics Grid

Asterics files (`.grd`) are automatically detected and processed using the Asterics Grid processor.

### GridSet / SNAP / TouchChat

These formats use native grid layouts and are displayed as-is, preserving:
- Grid dimensions (rows × columns)
- Button colors and borders
- Font sizes and styles
- Navigation links between pages

## Development

```bash
# Install dependencies
npm install

# Run demo app
npm run dev

# Build library
npm run build

# Type check
npm run type-check

# Lint
npm run lint
```

## Examples

See the `/demo` directory for complete examples:
- Basic viewer
- With metrics
- Multiple formats
- Server-side rendering

## Contributing

Contributions are welcome! Please read our contributing guidelines before submitting PRs.

## Changelog

### v0.3.0

- Bumped [`@willwade/aac-processors`](https://github.com/willwade/AACProcessors-nodejs) to `^0.3.1`.
- **GoTalk NOW support** — `.gtbz` archives (Attainment Company) are now detected and rendered via the underlying processors library.
- **GridSet improvements** — web browser and computer control commands are now preserved for Grid 3 `.gridset` files; gridset cell coordinates and the gridset validator (now checks the real Grid 3 archive structure) were fixed.
- **OBF/OBZ fixes** — the OBZ manifest `root` is now written as the board file path (e.g. `"1.obf"`) instead of the board ID, and `load_board` paths were corrected, so exported archives validate and open in external OBF viewers.
- **Mutation API** — `AACPage` mutation support added (OBF/Gridset), with assets preserved when saving modified trees.
- **Morphology** — morphology support added for TD Snap and fixed for Grid 3 metrics.

## License

MIT License - see LICENSE file for details.

## Related Packages

- [@willwade/aac-processors](https://github.com/willwade/AACProcessors-nodejs) - Core AAC file processing library

## Support

- Issues: [GitHub Issues](https://github.com/willwade/aac-board-viewer/issues)
- Documentation: [Full Docs](https://github.com/willwade/aac-board-viewer/wiki)
