<!--
 * @file        Package guide for the Fragment-ux core framework.
 * @module      fragment-ux/README.md
 * @author      Jesse Oyofo Dan-Amuda
 * @company     Digitwhale Innovations LTD
 * @copyright   Copyright (c) 2026 Digitwhale Innovations LTD. All rights reserved.
 * @license     MIT
 * @since       0.1.0
-->

# Fragment-ux

Fragment-ux is a TypeScript framework layer for building React applications with class-based pages, observable stores, typed HTTP endpoints, route guards, reusable class components, and application error reporting. It uses React and React Router for rendering and navigation, MobX for observable state, Axios for HTTP requests, and Motion for transitions.

You can use the framework features a piece at a time. A React function component remains an ordinary React function component. You can use React's built-in hooks and your own hooks alongside Fragment pages and stores.

> The npm package page's **Code (Beta)** tab is npm's file browser. It shows the files inside the published package archive. `dist/` contains compiled JavaScript and type declarations, `src/fx/fx.css` is the optional Tailwind animation stylesheet, and `README.md` is the documentation rendered on the package page. “Beta” describes npm's code browser feature; it is not the package's version or release channel.

## Contents

- [Requirements](#requirements)
- [Install](#install)
- [Create an app](#create-an-app)
- [Configure TypeScript and Vite](#configure-typescript-and-vite)
- [Start the app](#start-the-app)
- [Define the app](#define-the-app)
- [Create a typed API](#create-a-typed-api)
- [Create observable stores](#create-observable-stores)
- [Create pages and routes](#create-pages-and-routes)
- [Protect a route](#protect-a-route)
- [Build custom components](#build-custom-components)
- [Use React hooks](#use-react-hooks)
- [Use Fragment hooks](#use-fragment-hooks)
- [Add motion](#add-motion)
- [Style with Tailwind](#style-with-tailwind)
- [Handle errors](#handle-errors)
- [Debug an application](#debug-an-application)
- [Public API](#public-api)
- [Build and deploy](#build-and-deploy)
- [Examples and related packages](#examples-and-related-packages)
- [License](#license)

## Requirements

- Node.js 20 or later.
- TypeScript 5.7 or later, using standard TypeScript decorators.
- React 18 or later and React DOM 18 or later.
- A bundler that supports ESM and JSX. The examples use Vite.
- Tailwind CSS is recommended for styling. It is configured by the application and is not bundled as a runtime dependency of this package.

Fragment uses the current standard decorator model. In `tsconfig.json`, keep `experimentalDecorators` disabled and include `ESNext.Decorators` in the libraries. Do not use the older TypeScript experimental decorator mode for Fragment decorators.

## Install

Install the framework in an existing React application:

```sh
npm install @digitwhale_innovations/fragment-ux react react-dom
npm install -D typescript vite @vitejs/plugin-react tailwindcss @tailwindcss/vite
```

If React and React DOM are already installed, add only `@digitwhale_innovations/fragment-ux` and the development tools your app is missing. The core package also declares React as a peer dependency, so the application owns its React installation.

The package exports three entry points:

| Import                                         | Purpose                                                                                                             |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `@digitwhale_innovations/fragment-ux`          | Framework APIs, hooks, routing, errors, and motion components.                                                      |
| `@digitwhale_innovations/fragment-ux/polyfill` | Defines `Symbol.metadata` for standard decorators where the runtime needs it. Import this before decorated modules. |
| `@digitwhale_innovations/fragment-ux/vite`     | Vite development plugin for project metadata and safe open-in-editor links.                                         |
| `@digitwhale_innovations/fragment-ux/fx.css`   | Optional Tailwind v4 animation utilities for Fragment motion presets.                                               |
| `@digitwhale_innovations/fragment-ux/eslint-plugin` | Flat-config ESLint plugin and recommended Fragment rules.                                                            |
| `frgux`                                         | CLI binary shipped in the same package.                                                                            |

## Create an app

For a complete scaffold, install the same Fragment-ux package globally and create a project:

```sh
npm install -g @digitwhale_innovations/fragment-ux
frgux new my-app
cd my-app
npm install
npm run dev
```

The runtime, CLI, `create-fragment-ux` alias, and ESLint plugin are all shipped by `@digitwhale_innovations/fragment-ux`. The plugin is imported from `@digitwhale_innovations/fragment-ux/eslint-plugin`.

You can also wire Fragment into an existing Vite app manually, as shown below.

## Configure TypeScript and Vite

Use standard decorators and decorator metadata. A minimal `tsconfig.json` looks like this:

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["ES2022", "ESNext.Decorators", "DOM", "DOM.Iterable"],
    "useDefineForClassFields": true,
    "experimentalDecorators": false,
    "strict": true,
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "jsx": "react-jsx",
    "skipLibCheck": true
  }
}
```

Add the Fragment, React, and Tailwind Vite plugins. The React Babel decorator plugin is configured for the standard `2023-11` decorator semantics:

```ts
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import fragment from '@digitwhale_innovations/fragment-ux/vite'

export default defineConfig({
  plugins: [
    fragment({ editor: 'vscode' }),
    react({
      babel: {
        plugins: [
          ['@babel/plugin-proposal-decorators', { version: '2023-11' }],
        ],
      },
    }),
    tailwindcss(),
  ],
})
```

If you configure Babel separately, install `@babel/plugin-proposal-decorators` as a development dependency. Follow the same decorator version in TypeScript, Babel, and your build setup.

## Start the app

Load the polyfill before importing modules that contain decorated classes. Then load the application's Tailwind entry stylesheet and mount Fragment after the page modules have registered their routes:

```tsx
// src/main.tsx
import '@digitwhale_innovations/fragment-ux/polyfill'
import { mount } from '@digitwhale_innovations/fragment-ux'
import config from './fragment.config'
import './styles.css'

mount(
  '#root',
  config,
  import.meta.glob('./pages/**/*.page.tsx', { eager: true }),
)
```

```html
<!-- index.html -->
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
```

The third `mount` argument is available for bundler module loading. Vite's eager glob imports ensure decorated page classes run and register before the router is created.

## Define the app

`defineApp()` sets global defaults and returns the same config object, so it can be the default export from your configuration module:

```ts
// src/fragment.config.ts
import { defineApp } from '@digitwhale_innovations/fragment-ux'

export default defineApp({
  meta: { author: 'Your Name', company: 'Your Company' },
  api: {
    baseURL: import.meta.env.VITE_API_URL ?? 'http://localhost:3000/api',
    retry: 2,
    headers: () => ({ Authorization: `Bearer ${getAccessToken()}` }),
  },
  motion: {
    duration: 180,
    ease: 'out-expo',
    reduced: 'system',
  },
  debug: import.meta.env.DEV,
  errors: {
    mode: import.meta.env.DEV ? 'dev' : 'prod',
    attach: { breadcrumbs: true, stores: false },
    onError(error, report) {
      // Send the redacted report to your telemetry service if desired.
      console.error(error.code, report.generatedAt)
    },
  },
})
```

`api` accepts a base URL, static or computed headers, retry count, and an error callback. Per-class and per-request options can override global request defaults. `motion` controls the default duration, easing, and reduced-motion behavior. `debug` enables grouped API, action, and route logs; breadcrumbs are enabled in development by default. Error settings select the development diagnostic view, production fallback, redaction, and report callback.

## Create a typed API

Decorate a class with `@api()` to set its URL prefix. Decorate fields with an HTTP method and describe their input and response types with `Endpoint<Input, Output>`:

```ts
// src/api/todos.api.ts
import {
  api,
  Get,
  Post,
  Patch,
  Delete,
  type Endpoint,
} from '@digitwhale_innovations/fragment-ux'

export interface Todo {
  id: number
  title: string
  completed: boolean
}

@api('/todos')
export class TodosApi {
  @Get('/')
  list!: Endpoint<{ completed?: boolean }, Todo[]>

  @Get('/:id')
  get!: Endpoint<{ id: number }, Todo>

  @Post('/')
  create!: Endpoint<Pick<Todo, 'title'>, Todo>

  @Patch('/:id')
  update!: Endpoint<
    Pick<Todo, 'id'> & Partial<Pick<Todo, 'title' | 'completed'>>,
    Todo
  >

  @Delete('/:id')
  remove!: Endpoint<{ id: number }, void>
}
```

Inject the API where it is used:

```ts
import { inject } from '@digitwhale_innovations/fragment-ux'
import { TodosApi } from '../api/todos.api'

export class TodosStore {
  @inject(TodosApi) private api!: TodosApi

  async create(title: string) {
    const todo = await this.api.create({ title })
    this.items.push(todo)
  }
}
```

For path segments, matching input fields are URL-encoded and substituted into the endpoint URL. Remaining fields are query parameters for GET and DELETE requests, and request bodies for POST, PUT, and PATCH. An endpoint call can also receive Axios request config as its second argument:

```ts
const todo = await api.get({ id: 42 }, { signal: abortController.signal })
```

An endpoint also exposes `.query(getInput)`. This creates observable `data`, `loading`, and `error` state, refetches when MobX observes a change in the input getter, and provides `refetch()` and `dispose()` methods. Dispose query objects when their owner is finished with them:

```ts
const todosQuery = api.list.query(() => ({ completed: filters.completed }))
// Read todosQuery.data / todosQuery.loading in an observer.
await todosQuery.refetch()
todosQuery.dispose()
```

Requests use Axios. Errors are normalized to `FragmentError`; configured retries apply to failed requests, and request breadcrumbs omit or redact sensitive fields.

## Create observable stores

`@store` makes instance fields observable, getters computed, and methods MobX actions. Construct a store once in the app's dependency container or inject it where needed:

```ts
// src/stores/todos.store.ts
import { inject, store } from '@digitwhale_innovations/fragment-ux'
import { TodosApi, type Todo } from '../api/todos.api'

@store
export class TodosStore {
  @inject(TodosApi) private api!: TodosApi

  items: Todo[] = []
  filter: 'all' | 'open' | 'done' = 'all'
  loading = false

  get visibleItems() {
    if (this.filter === 'open')
      return this.items.filter((item) => !item.completed)
    if (this.filter === 'done')
      return this.items.filter((item) => item.completed)
    return this.items
  }

  async load() {
    this.loading = true
    try {
      this.items = await this.api.list()
    } finally {
      this.loading = false
    }
  }

  async toggle(todo: Todo) {
    const updated = await this.api.update({
      id: todo.id,
      completed: !todo.completed,
    })
    this.items = this.items.map((item) =>
      item.id === updated.id ? updated : item,
    )
  }
}
```

An injected field is intentionally excluded from observable state. When a page renders store state, read observable fields or computed getters from its `render()` method. A MobX action is not a tracked derivation: values read only inside a method call do not establish the render reaction.

`inject(ServiceClass)` returns the same singleton instance for that service from the default container. You can also use it as a property decorator, as in the example. For explicit container management, use the exported `Container` class and `container` singleton.

## Create pages and routes

Extend `Page`, implement `render()`, and register the class with `@page(path)`. Page fields and getters are observable. The router provides `params`, `query`, and `nav`; `load()` runs when the route is entered and when its route parameters change.

```tsx
// src/pages/todos.page.tsx
import { inject, page, Page } from '@digitwhale_innovations/fragment-ux'
import { TodosStore } from '../stores/todos.store'

@page('/todos')
export class TodosPage extends Page {
  @inject(TodosStore) private todos!: TodosStore

  async load() {
    await this.todos.load()
  }

  render() {
    if (this.loading || this.todos.loading) {
      return <p className="text-sm text-slate-500">Loading todos…</p>
    }

    return (
      <main className="mx-auto max-w-2xl p-6">
        <h1 className="text-2xl font-semibold">Todos</h1>
        <ul className="mt-4 divide-y divide-slate-200">
          {this.todos.visibleItems.map((todo) => (
            <li className="py-3" key={todo.id}>
              {todo.title}
            </li>
          ))}
        </ul>
      </main>
    )
  }
}
```

Page options can supply a route guard, a layout component, and an entry transition:

```tsx
@page('/account', {
  guard: SignedInGuard,
  layout: AppLayout,
  transition: 'fade-up',
})
export class AccountPage extends Page {
  render() {
    return <h1>Account</h1>
  }
}
```

Use normal React Router path patterns, including dynamic segments such as `/users/:userId`. Read a matched value from `this.params.userId` and query strings from `this.query`. Navigate with `this.nav('/settings')`.

## Protect a route

Extend `Guard` and implement `canEnter(context)`. Return `true` to continue, `false` to block, or a path string to redirect. The method can be asynchronous:

```ts
import { Guard, type GuardContext } from '@digitwhale_innovations/fragment-ux'

export class SignedInGuard extends Guard {
  async canEnter(_context: GuardContext): Promise<boolean | string> {
    const session = await readSession()
    return session ? true : '/login'
  }
}
```

Attach the guard in the `@page()` options. The guard context includes route `params` and query values.

## Build custom components

Use `@component()` for a reusable React class component that needs observable fields or MobX-aware rendering. Extend `Component<Props, State>` and retain ordinary React props, state, and lifecycle methods:

```tsx
import { Component, component } from '@digitwhale_innovations/fragment-ux'

interface CounterProps {
  initial?: number
}

@component()
export class Counter extends Component<CounterProps> {
  count = this.props.initial ?? 0

  componentDidMount() {
    console.info('Counter mounted')
  }

  componentWillUnmount() {
    console.info('Counter unmounted')
  }

  render() {
    return (
      <button
        className="rounded-md bg-indigo-600 px-3 py-2 text-white hover:bg-indigo-500"
        onClick={() => this.count++}
      >
        Count: {this.count}
      </button>
    )
  }
}
```

The decorator observes the component's own fields and tracks observable values read during `render()`. It disposes its MobX reaction when React unmounts the component. React's `setState`, props, context, and lifecycle methods keep their normal behavior. Hooks cannot run in class methods; use a function component when you need hooks.

## Use React hooks

React hooks remain fully available. Use built-in hooks and custom hooks inside function components, including function components rendered by a Fragment page or class component:

```tsx
import { useEffect, useState } from 'react'

export function SearchBox() {
  const [query, setQuery] = useState('')

  useEffect(() => {
    document.title = query ? `Search: ${query}` : 'Search'
  }, [query])

  return (
    <label className="grid gap-2">
      <span className="text-sm font-medium">Search</span>
      <input
        className="rounded border border-slate-300 px-3 py-2"
        value={query}
        onChange={(event) => setQuery(event.target.value)}
      />
    </label>
  )
}
```

Follow React's Rules of Hooks: call hooks at the top level of function components or other hooks, in the same order on every render. Do not call hooks from a `@page`, `@store`, or `@component` class method.

## Use Fragment hooks

Fragment exports small hooks for common UI and browser state:

| Hook                                        | Returns / purpose                                                                                |
| ------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| `useAsync(operation, immediate?)`           | Async `data`, `error`, `loading`, and a `run()` action.                                          |
| `useClipboard(resetAfterMs?)`               | `copy(text)`, `copied`, and `error`. Requires browser clipboard permission and a secure context. |
| `useCounter(initial?, bounds?)`             | A bounded counter value and increment/decrement/reset actions.                                   |
| `useDebouncedValue(value, delayMs?)`        | A value updated after it stays unchanged for the delay.                                          |
| `useDisclosure(initial?)`                   | `isOpen`, `open`, `close`, and `toggle` actions.                                                 |
| `useEventListener(type, handler, target?)`  | A managed DOM event listener with cleanup.                                                       |
| `useLocalStorage(key, initial)`             | JSON-backed state, setter, and remove action, synchronized across tabs.                          |
| `useMediaQuery(query)`                      | Whether a browser media query matches.                                                           |
| `useOnClickOutside(ref, handler, enabled?)` | Handle pointer presses outside an element.                                                       |
| `usePagination(items, pageSize)`            | Page state, current items, and page navigation helpers.                                          |
| `usePrevious(value)`                        | The previous committed value, or `undefined` on the first render.                                |
| `useToggle(initial?)`                       | Boolean value, toggle action, and setter.                                                        |
| `useInterval(callback, delayMs)`            | Repeated callback; use `null` to pause it.                                                       |

Example:

```tsx
import { useEffect, useState } from 'react'
import {
  useAsync,
  useDebouncedValue,
} from '@digitwhale_innovations/fragment-ux'

function UserSearch() {
  const [query, setQuery] = useState('')
  const stableQuery = useDebouncedValue(query, 300)
  const result = useAsync(() => searchUsers(stableQuery), false)

  useEffect(() => {
    if (stableQuery) void result.run()
  }, [stableQuery, result.run])

  return (
    <input value={query} onChange={(event) => setQuery(event.target.value)} />
  )
}
```

Import `useState` and `useEffect` from React in this example. Fragment hooks are convenience functions; they do not replace React hooks or change their rules.

## Add motion

`<Fx>` wraps a child with an enter and/or exit preset. `as` selects the element type, and `duration` and `delay` customize timing:

```tsx
import { Fx } from '@digitwhale_innovations/fragment-ux'

export function WelcomePanel() {
  return (
    <Fx
      as="section"
      enter="fade-up"
      exit="fade"
      className="rounded-xl bg-white p-6 shadow"
    >
      <h2 className="text-lg font-semibold">Welcome back</h2>
    </Fx>
  )
}
```

`<Fx.List stagger>` animates list children in sequence:

```tsx
<Fx.List stagger className="grid gap-3">
  {items.map((item) => (
    <PostCard key={item.id} post={item} />
  ))}
</Fx.List>
```

Available preset names are the keys of the exported `presets` object; the initial presets include `fade`, `fade-up`, `fade-down`, `slide-left`, `slide-right`, and `scale`. Motion respects the configured reduced-motion setting. The default is `system`, which disables motion when the user's operating system requests reduced motion.

For Tailwind CSS v4, optionally import Fragment's animation utilities from your application's CSS entry point:

```css
@import 'tailwindcss';
@import '@digitwhale_innovations/fragment-ux/fx.css';
```

The stylesheet is optional; `<Fx>` works without it. It only provides Tailwind animation utilities for Fragment's motion presets.

## Style with Tailwind

Fragment's examples use Tailwind utility classes directly in JSX. Keep application tokens and Tailwind setup in the app, and import the generated stylesheet once from the entry point. The recommended flat ESLint config is exported by the same package at `@digitwhale_innovations/fragment-ux/eslint-plugin`; its Tailwind-first rule flags inline JSX `style` props and component-level CSS imports. The rule is a lint policy, not a runtime restriction in the core package.

## Handle errors

Fragment normalizes errors to `FragmentError`, captures React render errors with an error boundary, and listens for unhandled browser errors and promise rejections after `mount()`.

In development, a captured error opens a diagnostic overlay with the error code, source location when available, recent breadcrumbs, and related state. In production, Fragment renders a calm fallback with a support reference. You can replace that production view with `errors.view` or receive reports through `errors.onError`:

```tsx
import {
  defineApp,
  type ErrorViewProps,
} from '@digitwhale_innovations/fragment-ux'

function AppError({ error, reset }: ErrorViewProps) {
  return (
    <main className="mx-auto max-w-lg p-8">
      <h1 className="text-xl font-semibold">We could not load this page</h1>
      <p className="mt-2 text-sm text-slate-600">Reference: {error.id}</p>
      <button
        className="mt-4 rounded bg-slate-900 px-4 py-2 text-white"
        onClick={reset}
      >
        Try again
      </button>
    </main>
  )
}

export default defineApp({
  errors: {
    view: AppError,
    onError(error, report) {
      sendToTelemetry({ code: error.code, id: error.id, report })
    },
    attach: { breadcrumbs: true, stores: false },
    redact: /token|password|secret/i,
  },
})
```

Production views receive a normalized error and reset action, not the diagnostic report. Production reports contain only the breadcrumb and store snapshots you explicitly enable. Fragment applies built-in secret redaction and allows an additional project-specific redaction pattern. Review your telemetry callback and redaction choices before sending reports to an external service.

For a custom not-found page, set `errors.notFound` to a React component accepting `{ path: string }`.

## Debug an application

Enable `debug` in `defineApp()` to see grouped API, action, and route output. Breadcrumbs retain recent activity for error reports. The `@digitwhale_innovations/fragment-ux/vite` plugin enables development-only project metadata and an open-in-editor endpoint, which the diagnostic overlay can use for source links.

In development builds, `mount()` exposes a `window.__FRAGMENT__` helper with store snapshots, route definitions, breadcrumbs, the latest error, a Markdown report, and a manual error trigger. It is only installed when `import.meta.env.DEV` is true.

## Public API

The main package entry point exports:

- **App and routing:** `defineApp`, `mount`, `pageRoutes`, `createFragmentRouter`, `Page`, `page`.
- **Data and dependency injection:** `api`, `Get`, `Post`, `Put`, `Patch`, `Delete`, `Endpoint`, `ApiQuery`, `setGlobalApiConfig`, `store`, `Container`, `container`, `inject`.
- **Components and access control:** `Component`, `component`, `Guard`.
- **Hooks:** all hooks listed in [Use Fragment hooks](#use-fragment-hooks).
- **Motion:** `Fx`, `presets`, `FxProps`, `FxPreset`.
- **Errors and diagnostics:** `FragmentError`, `FRAGMENT_ERROR_CODES`, `FragmentErrorBoundary`, `NotFoundView`, `ProdErrorView`, `reportError`, `breadcrumbs`, `snapshotStores`, and `redact`.

The Vite plugin and optional animation CSS are separate subpath exports described in [Install](#install). Full generated API reference is available in the repository's TypeDoc output.

## Build and deploy

For an application, run the scripts provided by its scaffold. A standard Vite production deployment is:

```sh
npm run build
```

Upload the generated `dist/` directory to your static host. If you use React Router's browser history, configure the host to serve `index.html` for application routes so the client router can resolve them. Configure `VITE_API_URL` for the deployed API endpoint and allow the app's origin in your API's CORS policy.

When publishing a new version of the framework package, increment `version` in the root `package.json`, build and inspect the package archive, then publish from the repository root:

```sh
npm run build:package
npm pack --dry-run
npm publish --access public
```

For release preparation details, see [`RELEASING.md`](https://github.com/Jesse-Dan/fragment-ui/blob/main/RELEASING.md).

## Examples and related packages

- [`examples/todos`](https://github.com/Jesse-Dan/fragment-ui/tree/main/examples/todos) demonstrates APIs, stores, pages, guards, components, and local mock data.
- [`examples/social`](https://github.com/Jesse-Dan/fragment-ui/tree/main/examples/social) demonstrates a hook-based social feed using JSONPlaceholder and remote images.
- `frgux` and `create-fragment-ux` are command binaries included in this package.
- The recommended ESLint plugin is available from `@digitwhale_innovations/fragment-ux/eslint-plugin`.

Use `frgux new my-app` or `create-fragment-ux my-app` to scaffold an application with the package's CLI binaries.

## License

MIT. See the [`LICENSE`](https://github.com/Jesse-Dan/fragment-ui/blob/main/LICENSE) file.

---

Built by Jesse Oyofo Dan-Amuda at Digitwhale Innovations LTD.
