# @favish/staffbase-drawer

A reusable drawer component for React applications with **automatic CSS isolation** for multi-widget environments.

## 📦 Installation

```bash
pnpm add @favish/staffbase-drawer
# or
npm install @favish/staffbase-drawer
```

## 🚀 Quick Start

### 1. Add the Vite Plugin

The plugin **automatically generates unique CSS class prefixes** to prevent collisions between multiple widgets:

```ts
// vite.config.ts
import react from '@vitejs/plugin-react'
import { staffbaseDrawer } from '@favish/staffbase-drawer/vite-plugin'
import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [
    react(),
    staffbaseDrawer() // 🎉 Auto-generates unique prefix!
  ]
})
```

### 2. Use the Component (Shadow DOM - Required)

```tsx
// main.tsx
import { useState } from 'react'
import { StaffbaseDrawerShadowRoot } from '@favish/staffbase-drawer'

function App() {
  const [isOpen, setIsOpen] = useState(false)

  return (
    <>
      <button onClick={() => setIsOpen(true)}>Open Drawer</button>

      <StaffbaseDrawerShadowRoot
        open={isOpen}
        onClose={() => setIsOpen(false)}
        variant="drawer"
      >
        <h1>Drawer Content</h1>
        <p>Your content goes here...</p>
      </StaffbaseDrawerShadowRoot>
    </>
  )
}
```

**Why this matters:** the drawer (and its portal content) is rendered inside a
per-instance `ShadowRoot`, and the compiled CSS is injected into that ShadowRoot
only. This prevents global CSS (e.g. Tailwind preflight) from affecting the drawer
and prevents the drawer’s CSS from leaking into the host page.

By default, the component also **clones the host page stylesheets into the
ShadowRoot** so embedded content (e.g., Staffbase article styling) renders
correctly. You can disable that with `includeHostStyles={false}` if needed.

If you only want specific host styles copied (e.g., widget content styles), use
`hostStyleSelectors`:

```tsx
<StaffbaseDrawer
  open={isOpen}
  onClose={onClose}
  hostStyleSelectors={[
    'link[href*="staffbase"]',
    'style[data-widget-styles]',
  ]}
>
  <ArticleContent />
</StaffbaseDrawer>
```

### 3. Modal Variant + Fully Isolated Shadow DOM

Use `variant="modal"` to render a centered dialog instead of a right-side drawer.
Use `modalWidth` to set the panel width (e.g. `"90vw"` or `"min(720px, 90vw)"`); when omitted, it defaults to `min(720px, 90vw)`.

Use `isolated` to run in a fully isolated Shadow DOM mode:

- host styles are not copied
- `hostStyleSelectors` is ignored
- a `:host` reset is applied to prevent host-page style inheritance

```tsx
<StaffbaseDrawerShadowRoot
  open={isOpen}
  onClose={() => setIsOpen(false)}
  variant="modal"
  modalWidth="90vw"
  isolated
>
  <h2>Modal Title</h2>
  <p>Modal content in a fully isolated shadow environment.</p>
</StaffbaseDrawerShadowRoot>
```

> Note: `StaffbaseDrawer` is now an alias of `StaffbaseDrawerShadowRoot` to make
> Shadow DOM the only supported rendering path.

**That's it!** The Vite plugin automatically:

- Generates a unique prefix based on your `package.json` name
- If you build multiple widgets from the same repo, also incorporates build config (e.g. `outDir`/entry) to avoid collisions
- Configures JS to use the same prefix at runtime
- Logs the prefix during build: `[staffbase-drawer] Using prefix: "d8f3a2"`

## 📋 Props

All props supported by `StaffbaseDrawerShadowRoot` (and the `StaffbaseDrawer` alias):

| Prop                 | Type                     | Required | Default              | Description                                                                 |
| -------------------- | ------------------------ | -------- | -------------------- | --------------------------------------------------------------------------- |
| `open`               | `boolean`                | Yes      | —                    | Controls whether the drawer is visible.                                    |
| `onClose`            | `() => void`             | Yes      | —                    | Callback when the user requests close (button, overlay, ESC, swipe).        |
| `children`           | `ReactNode`              | No       | —                    | Content rendered inside the drawer panel.                                   |
| `onClosed`           | `() => void`             | No       | —                    | Callback after the close animation has finished.                           |
| `title`              | `string`                 | No       | `'Drawer'`           | Accessible name for the dialog (used as `aria-label` / `aria-labelledby`). Set per locale for i18n. |
| `closeLabel`         | `string`                 | No       | `'Close drawer'`     | Accessible label for the close button (`aria-label`). Set per locale for i18n. |
| `variant`            | `'drawer' \| 'modal'`    | No       | `'drawer'`           | `'drawer'`: slide-in from right; `'modal'`: centered overlay panel.        |
| `modalWidth`         | `string`                 | No       | `min(720px, 90vw)`   | When `variant="modal"`, the panel width (e.g. `'90vw'`, `'min(720px, 90vw)'`). |
| `hideCloseButton`    | `boolean`                | No       | `false`              | Hide the close button in the drawer header.                                |
| `hideTitle`          | `boolean`                | No       | `false`              | Hide the drawer title / accessibility label.                               |
| `additionalCss`      | `string`                 | No       | —                    | Extra CSS text injected into the ShadowRoot (widget-specific styles).       |
| `hostStyleSelectors` | `string[]`               | No       | —                    | CSS selectors limiting which host styles are cloned (e.g. `['link[href*="staffbase"]']`). |
| `includeHostStyles`  | `boolean`                | No       | `true`               | Clone host page stylesheets into the ShadowRoot so embedded content can use host styling. |
| `isolated`           | `boolean`                | No       | `false`              | Fully isolate Shadow DOM: no host styles copied, `:host` reset applied.     |
| `mode`               | `'open' \| 'closed'`     | No       | `'open'`             | Shadow root mode; `'open'` is recommended for debugging and portal targeting. |

> **Note:** `portalContainer` is not part of the public API for `StaffbaseDrawerShadowRoot`; the component portals into its own ShadowRoot automatically.

> **Rendering:** Drawer content (`children`) is only mounted while the drawer is open and is unmounted once it is fully closed. There is no separate `lazyRender` toggle — lazy mounting is the default behavior.

## 🔒 Host Environment & Trust Contract

This component is an intentionally high-privilege, full-viewport overlay. When embedding it in a Staffbase app, be aware of the following contract:

- **DOM footprint:** Each instance appends a `position: fixed` host element to `document.documentElement` (the `<html>` element, to escape transformed/filtered ancestors in iOS WKWebView) with `z-index: 2147483647` (the maximum). It sits above all host chrome; `pointer-events` are disabled on the host and re-enabled only on the drawer's own surfaces. The host is removed on unmount.
- **Host stylesheet cloning (`includeHostStyles`, default `true`):** Each instance clones the host page's `<link rel="stylesheet">` and `<style>` nodes into its ShadowRoot so embedded article content inherits host styling. This means the drawer inherits the host's CSS trust boundary — compromised or broken host CSS affects the drawer. Notes:
  - Cloning runs once at mount; stylesheets the host injects later (lazy/SPA navigation) are not re-synced.
  - CSSOM-only styles (e.g. `adoptedStyleSheets`, styled-components, Emotion) and `@import`-based CSS are **not** captured.
  - On pages with several widget instances, scope cloning with `hostStyleSelectors`, or use `isolated` / `includeHostStyles={false}`, to avoid cloning every host stylesheet into every instance.
- **`additionalCss` is injected verbatim** into a `<style>` element (via `textContent`, so it is not parsed as HTML). **Never build this string from unsanitized user input.**

> This package is `@favish/staffbase-drawer`, a Vite library-mode component consumed **by** Staffbase widgets/pages. It is not a `@staffbase/create-widget` widget and does not depend on `@staffbase/widget-sdk`; SDK/config wiring belongs in the consuming widget.

## 🎨 Custom Prefix

If you want to specify your own prefix instead of auto-generating:

```ts
staffbaseDrawer({ prefix: 'mybulletins' })
```

If you build multiple widgets from the same repository/package name, you can also provide a seed:

```ts
staffbaseDrawer({ seed: 'alerts-widget' })
```

## ⚙️ Manual Configuration (Without Plugin)

If you're not using the Vite plugin, you must configure the JS prefix directly:

```ts
// vite.config.ts
import { defineConfig } from 'vite'

const DRAWER_PREFIX = 'mywidget'

export default defineConfig({
  define: {
    __SBAW_PREFIX__: JSON.stringify(DRAWER_PREFIX)
  }
})
```

> ⚠️ **Critical**: Ensure the prefix is unique per widget build to avoid collisions.

## ✅ Verifying Your Setup

In browser dev tools, CSS selectors should show your unique prefix:

```css
/* ✅ Correct - unique prefix */
[class*='-d8f3a2-overlay'] { ... }

/* ❌ Wrong - default prefix (collision risk) */
[class*='-sbaw-overlay'] { ... }
```

## 📦 Package Exports

| Export                                 | Description                                           |
| -------------------------------------- | ----------------------------------------------------- |
| `@favish/staffbase-drawer`             | Main component (Shadow DOM only)                      |
| `@favish/staffbase-drawer/vite-plugin` | Vite plugin for auto-prefix                           |

> Note: Deep imports (e.g. `@favish/staffbase-drawer/scss` or `@favish/staffbase-drawer/styles`)
> are intentionally unsupported. Only the top-level package export is supported.

## 🔧 Exported Utilities

```tsx
import {
  StaffbaseDrawer,
  StaffbaseDrawerShadowRoot,
  DRAWER_CLASS_PREFIX,    // Current prefix (for debugging)
  DrawerClasses,          // Class name constants
  DrawerCSSVars,          // CSS variable names
  createDrawerSelector    // Generate DOM selectors
} from '@favish/staffbase-drawer'
```

## 💻 Local Development

```bash
# Clone
git clone https://github.com/favish/staffbase-drawer.git

# Install
pnpm install

# Build
pnpm build

# Dev server
pnpm dev
```

## 🛠 Available Scripts

| Script             | Description                                        |
| ------------------ | -------------------------------------------------- |
| `pnpm build`       | Compiles the project                               |
| `pnpm dev`         | Starts development server                          |
| `pnpm format`      | Formats code using Prettier                        |
| `pnpm lint`        | Runs ESLint                                        |
| `pnpm type-check`  | Checks TypeScript types                            |
| `pnpm test`        | Runs the Jest unit/component test suite            |
| `pnpm publish:patch` | Bump patch and publish (use publish:minor/major for other bumps) |

## 📝 Publishing

### Recommended: release from GitHub Actions (no local npm login)

Releases are published by the **Release** workflow (`.github/workflows/release.yml`):

1. Go to **Actions -> Release -> Run workflow** (branch `main`).
2. Pick the bump in **Semver bump**:
   - `patch` / `minor` / `major` -> bumps `package.json`, commits, tags, publishes, and pushes the tag back to `main`.
   - `none` -> publishes the **current** `package.json` version as-is (no bump, no new commit/tag). Use this to publish a version you already bumped locally.
3. Run it. The workflow type-checks, lints, tests, builds, and publishes.

> **Provenance note:** npm provenance attestations require a **public source
> repository**. While this repo is private, provenance is skipped (expected).
> If the repo is ever made public, trusted publishing attaches provenance
> automatically — no workflow change needed.

**Auth is tokenless via npm Trusted Publishing (OIDC) — there is no `NPM_TOKEN`
to manage or rotate.** It is configured on npmjs.com under the package's
**Settings -> Trusted publishing -> GitHub Actions** with:

- **Organization or user:** `favish`
- **Repository:** `staffbase-drawer`
- **Workflow filename:** `release.yml`
- **Allowed actions:** `npm publish`

The workflow requests an OIDC id-token (`permissions: id-token: write`), pnpm
exchanges it for a short-lived publish credential, and provenance is attached
automatically. Requirements: recent npm/pnpm and Node >= 22 (the workflow uses
pnpm 11 and Node 24).

> If you ever change the workflow **filename**, update the trusted publisher
> entry on npmjs.com to match, or publishing will start failing on auth.

### Fallback: publish locally

Requires `npm login` first. Ensure your git working directory is **clean**.

```bash
pnpm publish:patch  # Bug fixes (1.0.0 -> 1.0.1)
pnpm publish:minor  # New features (1.0.0 -> 1.1.0)
pnpm publish:major  # Breaking changes (1.0.0 -> 2.0.0)
```

## 📝 License

UNLICENSED - © Favish
