# API Reference URL: /docs/guide/api-reference Reference documentation for the @kivacore/api-client — type-safe REST client with streaming, token management, and error handling. The `@kivacore/api-client` is a modern, type-safe API client for JavaScript and TypeScript. It works across Web, React Native, and Node.js. ## Installation ```bash tab="pnpm" pnpm add @kivacore/api-client ``` ```bash tab="npm" npm install @kivacore/api-client ``` ## Quick Start ```tsx import { RestApiClient } from '@kivacore/api-client'; const client = new RestApiClient({ baseUrl: 'https://api.example.com', getAccessToken: () => getToken(), }); // GET request const users = await client.get('/v1/users'); // POST with body const user = await client.post('/v1/users', { body: { name: 'Ali', email: 'ali@example.com' }, }); ``` ## Client Configuration ```tsx const client = new RestApiClient({ baseUrl: string; // API base URL (required) getAccessToken: () => Promise; // Token provider refreshToken?: () => Promise; // Auto-refresh on 401 onUnauthorized?: () => void; // Callback when auth fails headers?: Record; // Default headers timeout?: number; // Request timeout (ms) }); ``` | Option | Type | Required | Description | |--------|------|----------|-------------| | `baseUrl` | `string` | Yes | API base URL | | `getAccessToken` | `() => Promise` | Yes | Returns current access token | | `refreshToken` | `() => Promise` | No | Called on 401 — refreshes token and retries | | `onUnauthorized` | `() => void` | No | Called when both token and refresh fail | | `headers` | `Record` | No | Default headers for every request | | `timeout` | `number` | No | Request timeout in milliseconds | ## HTTP Methods ### GET ```tsx // Simple GET const data = await client.get('/v1/users'); // With query parameters const data = await client.get('/v1/users', { params: { page: 1, limit: 20, search: 'Ali' }, }); // With type safety interface User { id: string; name: string; email: string } const users = await client.get('/v1/users'); ``` ### POST ```tsx const user = await client.post('/v1/users', { body: { name: 'Ali', email: 'ali@example.com' }, }); ``` ### PUT / PATCH ```tsx await client.put('/v1/users/123', { body: { name: 'Updated Name' }, }); await client.patch('/v1/users/123', { body: { email: 'new@example.com' }, }); ``` ### DELETE ```tsx await client.delete('/v1/users/123'); ``` ## Streaming For real-time data and server-sent events: ```tsx const stream = client.stream('/v1/chat/completions', { method: 'POST', body: { message: 'Hello', model: 'gpt-4' }, }); for await (const chunk of stream) { console.log(chunk); // Process each chunk as it arrives } ``` ## Error Handling ```tsx import { ApiError } from '@kivacore/api-client'; try { await client.post('/v1/users', { body: userData }); } catch (error) { if (error instanceof ApiError) { console.log(error.status); // HTTP status code console.log(error.message); // Error message console.log(error.data); // Response body } } ``` | Property | Type | Description | |----------|------|-------------| | `status` | `number` | HTTP status code (400, 401, 404, 500, etc.) | | `message` | `string` | Error message from the server | | `data` | `unknown` | Full response body | ## Token Management The client handles token refresh automatically: 1. Request fails with `401 Unauthorized` 2. Client calls `refreshToken()` to get a new token 3. Original request is retried with the new token 4. If refresh also fails, `onUnauthorized()` is called ```tsx const client = new RestApiClient({ baseUrl: 'https://api.example.com', getAccessToken: () => tokenStore.getAccessToken(), refreshToken: async () => { const newToken = await authService.refresh(); tokenStore.setAccessToken(newToken); return newToken; }, onUnauthorized: () => { // Redirect to login router.push('/login'); }, }); ``` ## Usage with React ### With TanStack Query ```tsx import { useQuery, useMutation } from '@tanstack/react-query'; function useUsers() { const client = useApiClient(); // Your custom hook return useQuery({ queryKey: ['users'], queryFn: () => client.get('/v1/users'), }); } function useCreateUser() { const client = useApiClient(); return useMutation({ mutationFn: (data: CreateUserInput) => client.post('/v1/users', { body: data }), }); } ``` ### With React Native The API client works identically in React Native — no additional configuration needed: ```tsx import { RestApiClient } from '@kivacore/api-client'; import * as SecureStore from 'expo-secure-store'; const client = new RestApiClient({ baseUrl: 'https://api.example.com', getAccessToken: () => SecureStore.getItemAsync('access_token'), }); ``` ## Related - [Packages](/docs/guide/packages) — All `@kivacore/*` NPM packages - [CLI](/docs/guide/cli) — Authentication and project setup commands --- # Changelog URL: /docs/guide/changelog Latest releases and updates for the Kiva UI CLI. Track the latest changes, features, and bug fixes for the `@kivacore/ui-cli` command-line tool. For component library releases, see [Web Releases](/docs/web/guide/releases) and [Native Releases](/docs/native/guide/releases). --- # CLI URL: /docs/guide/cli The Kiva UI CLI for authentication, project scaffolding, and component management. The `@kivacore/ui-cli` is a command-line tool that handles authentication, project creation, component installation, theme management, and code generation from the Kiva registry. [npm](https://www.npmjs.com/package/@kivacore/ui-cli) ## Installation You can use the CLI directly with `npx` without installing it globally: ```bash npx @kivacore/ui-cli ``` Or install it globally: ```bash tab="pnpm" pnpm add -g @kivacore/ui-cli ``` ```bash tab="npm" npm install -g @kivacore/ui-cli ``` ```bash tab="yarn" yarn global add @kivacore/ui-cli ``` ```bash tab="bun" bun add -g @kivacore/ui-cli ``` Or install it globally for quicker access: Once installed globally, you can use the `kiva-ui` command directly: ```bash kiva-ui add button ``` ## Commands ### Authentication | Command | Description | |---------|-------------| | `kiva-ui login` | Log in with browser-based SSO | | `kiva-ui login --email` | Log in with email and password | | `kiva-ui login -e user@example.com` | Log in with pre-filled email | | `kiva-ui logout` | Clear stored auth tokens | | `kiva-ui whoami` | Display current logged-in user info | ### Components | Command | Description | |---------|-------------| | `kiva-ui add [items...]` | Add components, hooks, or utilities from the registry | | `kiva-ui add button dialog` | Add multiple components at once | | `kiva-ui add --all web` | Install all web components | | `kiva-ui add --all react-native` | Install all React Native components | | `kiva-ui add --all-web` | Shortcut for `--all web` | | `kiva-ui add --all-rn` | Shortcut for `--all react-native` | | `kiva-ui add --overwrite` | Skip file conflict prompts | | `kiva-ui add --dry-run` | Preview installation without writing files | | `kiva-ui add --path ./src/ui` | Custom target path for installation | | `kiva-ui update` | Update all installed Kiva components to latest | | `kiva-ui update button toast` | Update specific components only | | `kiva-ui update rn-card rn-button` | Update specific native components | | `kiva-ui update --prune` | Update and remove components deleted from registry | | `kiva-ui update --dry-run` | Preview what would be updated | | `kiva-ui list` | List available components, hooks, and utilities | | `kiva-ui list --packages` | List published @kivacore npm packages | ### Themes | Command | Description | |---------|-------------| | `kiva-ui themes list` | List available theme presets | | `kiva-ui themes add [name]` | Apply a theme preset to your project | | `kiva-ui themes add --url ` | Apply theme from a share URL | | `kiva-ui themes add --file ` | Apply theme from a local JSON file | | `kiva-ui themes current` | Show current `:root` and `.dark` CSS variables | ### Code Generation | Command | Description | |---------|-------------| | `kiva-ui generate api-spec` | Download OpenAPI spec from the Kiva API | | `kiva-ui generate api-spec -o ./spec.json` | Custom output path for the spec file | | `kiva-ui generate db [spec]` | Generate TanStack Query collections from an OpenAPI spec | | `kiva-ui generate db ./spec.json -o ./src/api` | Custom output directory | ### Project Setup | Command | Description | |---------|-------------| | `kiva-ui commitlint` | Set up commitlint, husky, and lint-staged | | `kiva-ui commitlint --scopes cli,ui,web` | Pre-configure allowed commit scopes | | `kiva-ui commitlint --monorepo` | Auto-detect workspace scopes for monorepo | | `kiva-ui commitlint --scope-strategy required` | Set scope strategy (required, optional, none) | | `kiva-ui commitlint -y` | Accept defaults and overwrite existing files | ### System | Command | Description | |---------|-------------| | `kiva-ui info` | Display CLI version, Node.js, OS, and auth status | | `kiva-ui config --show` | Show current configuration | | `kiva-ui config --token` | Update the stored Kiva token | | `kiva-ui config --theme` | Change help output color theme | | `kiva-ui upgrade` | Upgrade CLI to the latest version | | `kiva-ui completion ` | Generate shell completion script (bash, zsh, fish) | ### Global Options | Option | Description | |--------|-------------| | `--json` | Output results in JSON format | | `-v, --version` | Display CLI version | | `-h, --help` | Display help information | ## Examples ```bash # Log in and add components kiva-ui login kiva-ui add button dialog date-time-picker kiva-ui add --all web kiva-ui add --all-rn # Update all installed components kiva-ui update # Update specific components kiva-ui update button toast rn-card # Update and remove components deleted from registry kiva-ui update --prune # Browse and apply a theme kiva-ui themes list kiva-ui themes add midnight # Generate TanStack Query code from an API spec kiva-ui generate api-spec kiva-ui generate db openapi.json --output src/ # Set up commitlint in a monorepo kiva-ui commitlint --monorepo ``` --- # Distributions URL: /docs/guide/distributions Component distributions and core libraries that power Kiva UI. Kiva UI is built on top of the shadcn ecosystem and depends on several major open-source libraries. This page lists the component distributions we work alongside and the core libraries our components are built on. ## Component Distributions ## Web Libraries The major open-source libraries that Kiva UI web components are built on. | Library | Description | Used In | |---------|-------------|---------| | [Radix UI](https://www.radix-ui.com) | Unstyled, accessible UI primitives. Provides the foundation for dialogs, popovers, tooltips, dropdowns, and more. | Primitives, Components | | [Plate.js](https://platejs.org) | Plugin-based rich text editor framework. Powers the WYSIWYG editor with AI, comments, mentions, tables, and 30+ plugins. | Editor | | [Motion](https://motion.dev) | Production-ready animation library for React. Used for enter/exit transitions, layout animations, and gesture interactions. | Components | | [TanStack Table](https://tanstack.com/table) | Headless table library with sorting, filtering, grouping, and virtualization. Powers the Data Grid component. | Data Grid | | [TanStack Virtual](https://tanstack.com/virtual) | Headless virtualization for large lists and grids. Provides smooth scrolling for thousands of rows. | Data Grid | | [TanStack Form](https://tanstack.com/form) | Type-safe form library with framework-agnostic validation. Powers the form-fields system with schema-driven field rendering. | Form Fields | | [React Day Picker](https://daypicker.dev) | Flexible date picker component. Powers the Day Picker and Date Time Picker components. | Day Picker, Date Time Picker | | [Recharts](https://recharts.org) | Composable charting library built on D3. Used for data visualization components. | Charts | | [CodeMirror](https://codemirror.net) | Extensible code editor with syntax highlighting, autocompletion, and language support. | Code Editor | | [Embla Carousel](https://www.embla-carousel.com) | Lightweight carousel library with touch support and extensible plugins. | Carousel | | [cmdk](https://cmdk.paco.me) | Fast, composable command palette component. | Command | | [Vaul](https://vaul.emilkowal.ski) | Drawer component for React with smooth touch interactions. | Drawer | | [Sonner](https://sonner.emilkowal.ski) | Opinionated toast notification library. | Toast | ## React Native Libraries The core libraries that Kiva UI native components are built on. | Library | Description | Used In | |---------|-------------|---------| | [Expo](https://expo.dev) | Framework and platform for universal React applications. Provides managed workflow, OTA updates, and native module access. | All Native Components | | [Uniwind](https://github.com/nicepkg/uniwind) | Build-time Tailwind CSS v4 integration for React Native. Compiles `className` to `StyleSheet` objects via a Metro plugin. | All Native Components | | [React Native SVG](https://github.com/software-mansion/react-native-svg) | SVG support for React Native. Used for icons, charts, and vector graphics. | Icons, Charts | | [Expo Document Picker](https://docs.expo.dev/versions/latest/sdk/document-picker) | Native file picker with multi-file support. | Document Picker | | [Expo Localization](https://docs.expo.dev/versions/latest/sdk/localization) | Locale and internationalization utilities. | Localize | | [React Native Reanimated](https://docs.swmansion.com/react-native-reanimated) | High-performance animation library running on the UI thread. Used for gesture-driven animations. | Animations | | [React Native Gesture Handler](https://docs.swmansion.com/react-native-gesture-handler) | Native gesture system for touch interactions. Powers swipe, pinch, and drag gestures. | Gestures | | [DateTimePicker](https://github.com/react-native-datetimepicker/datetimepicker) | Native date and time picker for iOS and Android. | DateTimePicker | --- # FAQ URL: /docs/guide/faq Frequently asked questions about Kiva UI — installation, usage, customization, and troubleshooting. ## General ### What is Kiva UI? Kiva UI is a component library built on top of [shadcn/ui](https://ui.shadcn.com) primitives. It provides **business-grade compound components** — calendars, data grids, pricing engines, resource schedulers, and more — that go beyond basic UI primitives. Unlike traditional component libraries published to NPM, Kiva UI uses the **shadcn registry pattern**: components are copied into your project as source code, giving you full ownership and customization control. ### How is Kiva UI different from shadcn/ui? | | shadcn/ui | Kiva UI | |---|----------|------------| | **Focus** | UI primitives (Button, Card, Dialog) | Business components (Calendar, DataGrid, PricingEngine) | | **Built on** | Radix UI | shadcn/ui + Radix UI + AI Elements | | **Distribution** | Registry (copy to project) | Registry (copy to project) | | **Styling** | Tailwind CSS | Tailwind CSS v4 | | **Variants** | CVA | CVA (web), tailwind-variants (native) | | **Platform** | Web only | Web + React Native | Kiva UI **includes** shadcn/ui as vendor primitives. When you install a Kiva component, its shadcn dependencies are installed automatically. ### Is Kiva UI free? Yes. Kiva UI is open-source. You can use it in personal and commercial projects. ### Which frameworks are supported? **Web:** - Next.js 16+ (App Router) - React 19 + Vite - Vue 3.5 + Vite (via templates) **Native:** - React Native 0.83+ with Expo SDK 55+ ### Do I need to use the CLI? The CLI (`@kivacore/ui-cli`) is the recommended way to install components. It handles dependency resolution, import rewriting, and file placement automatically. --- ## Installation ### Why do components get copied into my project? This is the **shadcn pattern** — instead of importing from `node_modules`, components live in your codebase. Benefits: - **Full control**: Modify any component to match your needs - **No version lock-in**: Components don't break when the library updates - **Tree-shaking**: Only the components you use are in your bundle - **No runtime dependency**: Your project has zero dependency on Kiva UI at runtime ### Where do components get installed? | Type | Default Location | |------|-----------------| | Kiva components | `components/kiva/` | | shadcn primitives | `components/ui/` | | Hooks | `hooks/` | | Utilities | `lib/` | | Native components | `components/kiva-native/` | These paths are configurable via your project's `components.json`. ### How do I install all components at once? ```bash # All web components kiva-ui add --all web # All native components kiva-ui add --all react-native # Specific component kiva-ui add calendar kiva-ui add rn-button ``` ### I'm getting peer dependency warnings Kiva components may require peer dependencies like `motion`, `date-fns`, or `@tanstack/react-table`. The CLI warns you about missing peer dependencies during installation. Install them with: ```bash pnpm add ``` --- ## Customization ### How do I change the color theme? Kiva UI uses CSS variables with the OKLCH color space. You can: 1. **Use the Theme Generator** at [kivacore.com/themes](/themes) to create a custom theme visually 2. **Edit CSS variables** directly in your `globals.css` — see the [Web Theming Guide](/docs/web/guide/theming) or [Native Theming Guide](/docs/native/guide/theming) ### Can I use a different color palette? Yes. The theme system supports any OKLCH color values. You can change the primary, secondary, accent, and all other colors by updating CSS variables. The [Theme Generator](/themes) provides preset palettes and a visual editor. ### How do I override component styles? Every component accepts a `className` prop for Tailwind CSS overrides: ```tsx ``` For deeper customization, edit the component source directly — it's in your project. ### Can I use CSS Modules or styled-components instead of Tailwind? Kiva UI is built with Tailwind CSS v4 and CVA (class-variance-authority). While you can technically replace the styling system, it would require significant refactoring. We recommend using Tailwind CSS for the best experience. --- ## React Native ### Do I need Expo? Expo is **recommended** but not strictly required. Kiva UI Native components use React Native APIs and some Expo packages. Components that require Expo-specific packages are clearly marked in the [Expo section](/docs/native/expo) of the documentation. ### Can I preview native components in a browser? No. Native components are previewed exclusively via the **Expo Preview app** on a physical device or simulator. The documentation shows a QR code to open the preview in Expo Go. ### How do I style native components? Native components use **Tailwind CSS via Uniwind** for static styling (`className` prop) and the `useKivaTheme()` hook only for dynamic values (Ionicons colors, platform shadows, runtime lookups). See the [Native Theming Guide](/docs/native/guide/theming) for setup and customization. ```tsx {/* Static styling — use className */} {/* Dynamic values only — use useKivaTheme() */} const { colors, isDark } = useKivaTheme(); ``` --- ## Troubleshooting ### Components don't render / blank screen 1. Make sure you have `'use client'` directive if using Next.js App Router 2. Check that all peer dependencies are installed 3. For Tailwind v4, ensure you have `@import` directives in your CSS entry file ### TypeScript errors after installation Components are installed as `.tsx` source files. Ensure your `tsconfig.json` has: ```json { "compilerOptions": { "jsx": "react-jsx", "paths": { "@/*": ["./src/*"] } } } ``` The `@/` alias must resolve to your `src/` directory (or wherever components are installed). ### Motion animations not working Components using motion (framer-motion) require the `motion` package: ```bash pnpm add motion ``` If using Next.js, ensure the component has `'use client'` since motion requires client-side rendering. ### Icons not displaying Kiva uses icons from Lucide React and the Kiva CDN (Font Awesome Brands + Huge Icons). Install Lucide: ```bash pnpm add lucide-react ``` For Kiva CDN icons, ensure your CSP (Content Security Policy) allows loading from the Kiva CDN domain. ### How do I report a bug? Open an issue on GitHub with: - Component name and version - Framework and version (Next.js, Vite, Expo) - Minimal reproduction steps - Expected vs actual behavior --- # Internationalization (i18n) URL: /docs/guide/i18n How to add multi-language support to Kiva UI components. ## Overview Kiva UI components have built-in i18n support through a **provider-agnostic** translation system. Components display English by default and automatically switch to the active language when a translation provider is present. No dependency on any specific i18n library — works with `@kivacore/i18n`, `react-i18next`, `next-intl`, or any custom solution. ## Quick Start ### 1. Wrap your app with `UiTranslationProvider` ```tsx import { UiTranslationProvider } from '@kivacore/ui/hooks/use-ui-translation'; function App() { return ( ); } ``` The `t` prop accepts any function with the signature: ```ts (key: string, fallback?: string | Record) => string ``` ### 2. Without a provider Components render in **English** with no setup required: ```tsx // No provider needed — English fallback works automatically ``` ## Ready-made catalogs Kiva UI ships complete catalogs for the `ui.*` keys in **English, Turkish, German and French**, so you do not have to translate the library's own copy. ```bash kiva-ui add ui-locales ``` The files land in `locales/kiva/` (`en.json`, `tr.json`, `de.json`, `fr.json`) as flat `key → text` maps. Mount one with the `messages` prop — no i18n library required: ```tsx import tr from '@/locales/kiva/tr.json'; import { UiTranslationProvider } from '@/hooks/use-ui-translation'; function AppShell({ children }: { children: React.ReactNode }) { return ( ); } ``` For React Native the item is `rn-locales` and the files land in `locales/kiva-native/`. ### Combining a catalog with your own i18n Pass both. Your `t` is consulted first, so anything your app already translates wins; the catalog covers every key you have not translated yourself, and the English source text covers anything neither provides. ```tsx ``` ## Integration Examples ### @kivacore/i18n ```tsx import { useKivaI18n } from '@kivacore/i18n'; import { UiTranslationProvider } from '@kivacore/ui/hooks/use-ui-translation'; function AppShell({ children }: { children: React.ReactNode }) { const { t } = useKivaI18n(); return ( ); } ``` ### react-i18next ```tsx import { useTranslation } from 'react-i18next'; import { UiTranslationProvider } from '@kivacore/ui/hooks/use-ui-translation'; function AppShell({ children }: { children: React.ReactNode }) { const { t } = useTranslation(); return ( ); } ``` ### next-intl ```tsx import { useTranslations } from 'next-intl'; import { UiTranslationProvider } from '@kivacore/ui/hooks/use-ui-translation'; function AppShell({ children }: { children: React.ReactNode }) { const t = useTranslations(); return ( ); } ``` ## Translation Keys All component translation keys follow the `ui..` convention: | Group | Prefix | Example Key | English Default | |-------|--------|-------------|-----------------| | Common | `ui.common` | `ui.common.search` | Search | | Calendar | `ui.calendar` | `ui.calendar.addEvent` | Add Event | | Data Grid | `ui.dataGrid` | `ui.dataGrid.filter` | Filter | | Form Fields | `ui.formField` | `ui.formField.selectPlaceholder` | Select... | | Pricing Engine | `ui.pricing` | `ui.pricing.subtotal` | Subtotal | | Mega Select | `ui.megaSelect` | `ui.megaSelect.search` | Search | | Team Chat | `ui.teamChat` | `ui.teamChat.writePost` | Write a post... | | Contact Activity | `ui.contactActivity` | `ui.contactActivity.all` | All | | Log Activity | `ui.logActivity` | `ui.logActivity.taskSubject` | Task subject | | Email Composer | `ui.emailComposer` | `ui.emailComposer.send` | Send | | Record Sharing | `ui.recordSharing` | `ui.recordSharing.share` | Share | | Query Builder | `ui.queryBuilder` | `ui.queryBuilder.columns` | Columns | | Data Grid View | `ui.dataGridView` | `ui.dataGridView.selectView` | Select view | | Time Slot | `ui.timeSlot` | `ui.timeSlot.available` | Available | | Scheduler | `ui.scheduler` | `ui.scheduler.today` | Today | | Agent | `ui.agent` | `ui.agent.sendMessage` | Send message | | Tree View | `ui.treeView` | `ui.treeView.expandAll` | Expand All | | Place Autocomplete | `ui.placeAutocomplete` | `ui.placeAutocomplete.searchPlaces` | Search places... | ## How It Works Components use the `useUiTranslation` hook internally: ```tsx import { useUiTranslation } from '@/hooks/use-ui-translation'; function MyComponent() { const { t } = useUiTranslation(); return ( ); } ``` - **First argument:** Translation key - **Second argument:** English source text — rendered when neither your `t` nor the catalog resolves the key - **Third argument (optional):** runtime values for the `{{name}}` placeholders in the text ```tsx t('ui.dataGrid.rowsSelected', '{{count}} rows selected', { count }) ``` Resolution order, highest first: your `t` → the `messages` catalog → the English source text. A translated string must keep exactly the placeholders its source has. `pnpm i18n:sync` fails the build on any catalog entry that drops, adds or re-spells one. ## Customizing Translations To override a specific component's text, add the corresponding key to your i18n translation dictionary. For example, to change the Calendar's "Add Event" button to "New Appointment" in Turkish: ```json { "ui.calendar.addEvent": "Yeni Randevu" } ``` Any key not present in your dictionary will fall back to the English default embedded in the component. ## API Reference ### UiTranslationProvider | Prop | Type | Description | |------|------|-------------| | `t` | `(key: string, fallback?: string \| Record) => string` | Translation function from your i18n library | | `children` | `ReactNode` | Child components | ### useUiTranslation ```ts function useUiTranslation(): { t: TranslateFn } ``` Returns `{ t }` where `t(key, fallback)` resolves to: - Translated string from provider (if available) - English fallback string (if no provider or key not found) --- # Introduction URL: /docs/guide Kiva UI is an open-source component distribution built with React, TypeScript, Tailwind CSS, and the shadcn registry. ## What is Kiva UI? Kiva UI is an open-source component distribution — not an installable NPM library. Built with React, TypeScript, Tailwind CSS v4, and the shadcn registry, it provides production-ready UI components, hooks, and utilities that you copy directly into your codebase. Inspired by the shadcn/ui philosophy, Kiva UI gives you full ownership and control over every component. No wrapper overhead, no version lock-in — just open code that lives in your project. ## Not a library — an open component distribution Traditional UI libraries ship as NPM packages you import. When something doesn't fit, you're stuck waiting for a PR or working around the API. Kiva UI takes a different approach. Every component is installed as source code into your project. You own it, you modify it, you style it however you want. The registry simply delivers the starting point. ## What's included - **Components** — Production-ready UI pieces built on top of Radix UI, covering forms, data display, navigation, feedback, and more. Each component uses CVA for variant management and supports full theme customization. - **Hooks** — Reusable React hooks for common patterns like debouncing, media queries, local storage, disclosure state, and more. - **Utilities** — Helper functions for class name merging, type-safe operations, and other everyday needs. - **Icons** — Kiva Icon system with support for Font Awesome, Huge Icons, and custom icon sets via CDN. ## Why Kiva UI? - **Open source and copy-first** — Every component lives in your codebase. Full ownership, zero lock-in. - **Built on shadcn registry** — Install components with the `shadcn` CLI or the Kiva UI CLI. Same workflow you already know. - **Tailwind CSS v4** — Designed from the ground up for Tailwind CSS v4 with CSS-based configuration and modern utility classes. - **Type-safe** — Full TypeScript support with strict types, generics, and inference across all components, hooks, and utilities. - **Accessible by default** — Built on Radix UI primitives with WAI-ARIA compliance, keyboard navigation, and screen reader support out of the box. - **Performance-conscious** — Sensible defaults, tree-shakeable exports, and minimal runtime overhead. Ship only what you use. --- # Installation URL: /docs/guide/installation How to install and set up Kiva UI components in your project. ## Prerequisites Kiva UI components are distributed via the shadcn registry. Before you start, make sure your project has shadcn/ui initialized. If you haven't set up shadcn/ui yet, run the init command to create a `components.json` configuration file in your project root: ```bash npx shadcn@latest init ``` ## Add the Kiva registry Add the Kiva registry to your `components.json` file so the CLI knows where to fetch components from: ```json title="components.json" { "registries": { "kiva": { "url": "https://ui.kivacore.com/r" } } } ``` ## Add components Install components using the **Kiva UI CLI**: ```bash # Install a component npx @kivacore/ui-cli add button # Install a hook npx @kivacore/ui-cli add hooks-debounce # Install a utility npx @kivacore/ui-cli add utils-cn # Install multiple items at once npx @kivacore/ui-cli add button dialog hooks-debounce ``` The CLI reads your `components.json` configuration and installs the correct variant automatically. ## Import and use Once installed, import the component from your local components directory and use it in your project: ```tsx title="app/page.tsx" import { Button } from '@/components/kiva/button'; export default function Home() { return (
); } ``` Components are installed as source code — you can freely modify, extend, or restyle them to fit your needs. --- # Native Migration URL: /docs/guide/native-migration How to migrate from other React Native UI libraries to Kiva UI Native. ## Overview This guide helps you migrate from popular React Native UI libraries to Kiva UI Native. Each section covers the key differences and provides mapping tables for common components. ## From React Native Paper [React Native Paper](https://callstack.github.io/react-native-paper/) uses Material Design. Kiva UI Native follows a custom design system with semantic color tokens. ### Theme Migration ```tsx // Before (Paper) import { Provider as PaperProvider, DefaultTheme } from 'react-native-paper'; const theme = { ...DefaultTheme, colors: { ...DefaultTheme.colors, primary: '#6200ee', accent: '#03dac4', }, }; // After (Kiva) import { KivaThemeProvider } from '@/lib/theme'; ``` ### Component Mapping | Paper | Kiva UI Native | Notes | |-------|-------------------|-------| | ` // After (Kiva) import { KivaThemeProvider } from '@/lib/theme'; ``` ### Styling Differences ```tsx // NativeBase — utility props // Kiva — style objects with theme const { colors, spacing, borderRadius } = useKivaTheme(); ``` ### Component Mapping | NativeBase | Kiva UI Native | Notes | |------------|-------------------|-------| | ` // Kiva — style objects const { colors, spacing, borderRadius } = useKivaTheme(); ``` ## From Gluestack UI [Gluestack UI](https://gluestack.io/) is the spiritual successor to NativeBase with a new styling engine. ### Key Differences | Feature | Gluestack | Kiva UI Native | |---------|-----------|-------------------| | Styling | `styled()` + utility props | `useKivaTheme()` + style objects | | Tokens | Design tokens via config | Semantic colors + spacing scale | | Components | Headless + styled | Styled with theme | ### Migration Pattern ```tsx // Gluestack import { Button, ButtonText } from '@gluestack-ui/themed'; // Kiva import { Button } from '@/components/kiva-native/button'; ``` ## General Migration Tips ### 1. Install KivaThemeProvider First Before migrating any components, set up the theme provider at your app root. This ensures all migrated components have access to theme values. ### 2. Migrate Bottom-Up Start with leaf components (Button, Input, Badge) and work up to compound components (DataTable, Form). This minimizes cascading changes. ### 3. Keep Both Libraries Temporarily During migration, you can use both libraries simultaneously. Remove the old library only after all components are migrated. ```json { "dependencies": { "react-native-paper": "^5.0.0", "@kivacore/ui-native": "workspace:*" } } ``` ### 4. Map Your Color Tokens Create a mapping between your current library's color tokens and Kiva semantic tokens: | Your Token | Kiva Token | |-----------|---------------| | `primary` | `colors.primary` | | `onPrimary` | `colors.primaryForeground` | | `surface` | `colors.card` | | `onSurface` | `colors.cardForeground` | | `error` | `colors.destructive` | | `background` | `colors.background` | ### 5. Replace Theme Hooks Find-and-replace your current theme hook with Kiva: ```tsx // Common patterns to replace useTheme() → useKivaTheme() theme.colors.X → colors.X theme.spacing.X → spacing[X] theme.roundness → borderRadius.DEFAULT ``` ### 6. Update Imports After installing Kiva components via CLI: ```bash kiva-ui add rn-button rn-input rn-card rn-badge ``` Update imports: ```tsx // Before import { Button } from 'react-native-paper'; // After import { Button } from '@/components/kiva-native/button'; ``` --- # Packages URL: /docs/guide/packages Official Kiva NPM packages for authentication, API integration, code generation, and developer tooling. All `@kivacore/*` packages are published on [NPM](https://www.npmjs.com/org/kiva) and designed to work together. They cover authentication, API integration, code generation, and developer tooling for Kiva-powered applications. ## Core ### @kivacore/api-client A modern, type-safe API client for JavaScript and TypeScript with support for multiple backend types, streaming, error handling, and token management. [npm](https://www.npmjs.com/package/@kivacore/api-client) ```bash tab="pnpm" pnpm add @kivacore/api-client ``` ```bash tab="npm" npm install @kivacore/api-client ``` ```bash tab="yarn" yarn add @kivacore/api-client ``` ```bash tab="bun" bun add @kivacore/api-client ``` --- ### @kivacore/signin Authentication provider for Kiva apps. Supports React, Vue, Electron, and Next.js SSR with OAuth2 and session management. [npm](https://www.npmjs.com/package/@kivacore/signin) ```bash tab="pnpm" pnpm add @kivacore/signin ``` ```bash tab="npm" npm install @kivacore/signin ``` ```bash tab="yarn" yarn add @kivacore/signin ``` ```bash tab="bun" bun add @kivacore/signin ``` --- ### @kivacore/i18n Internationalization provider with API-based and static translation support, cookie-based locale persistence, and variable interpolation. Works across **Web**, **React Native**, and **Vue**. [npm](https://www.npmjs.com/package/@kivacore/i18n) ```bash tab="pnpm" pnpm add @kivacore/i18n ``` ```bash tab="npm" npm install @kivacore/i18n ``` ```bash tab="yarn" yarn add @kivacore/i18n ``` ```bash tab="bun" bun add @kivacore/i18n ``` #### Web Usage Wrap your app with `KivaI18nProvider`: ```tsx import { KivaI18nProvider } from '@kivacore/i18n'; ; } ``` **Key differences from web:** | Feature | Web | React Native | |---------|-----|-------------| | Import | `@kivacore/i18n` | `@kivacore/i18n/rn` | | Provider | `KivaI18nProvider` | `KivaI18nProvider` | | Hook | `useTranslation()`, `useKivaI18n()` | `useI18n()`, `useTranslation()` | | Storage | Cookie (`CookieStorageAdapter`) | MMKV / AsyncStorage (`getString`/`setString`) | | Languages | Any locale string | `'en'` \| `'tr'` | | Translation format | Flat dictionary | Nested (`{ en: { common: { key: 'val' } } }`) | | Fallback without provider | Throws | Graceful (returns key) | --- ## Dev Tools ### @kivacore/tanstack-db-generator Code generator for TanStack Query and database integration. Generates typed collections from OpenAPI specs for the Kiva API. [npm](https://www.npmjs.com/package/@kivacore/tanstack-db-generator) ```bash tab="pnpm" pnpm add -D @kivacore/tanstack-db-generator ``` ```bash tab="npm" npm install -D @kivacore/tanstack-db-generator ``` ```bash tab="yarn" yarn add -D @kivacore/tanstack-db-generator ``` ```bash tab="bun" bun add -D @kivacore/tanstack-db-generator ``` --- ### @kivacore/rules Shared ESLint and Biome configurations for Kiva projects. Provides consistent linting and formatting rules across your codebase. [npm](https://www.npmjs.com/package/@kivacore/rules) ```bash tab="pnpm" pnpm add -D @kivacore/rules ``` ```bash tab="npm" npm install -D @kivacore/rules ``` ```bash tab="yarn" yarn add -D @kivacore/rules ``` ```bash tab="bun" bun add -D @kivacore/rules ``` #### ESLint Configs Each config is composable — combine them based on your stack: | Config | Import | Use for | |--------|--------|---------| | `baseConfig` | `@kivacore/rules/eslint` | All projects (TypeScript, import ordering, stylistic) | | `reactConfig` | `@kivacore/rules/eslint` | React projects (hooks, react-refresh) | | `nextjsConfig` | `@kivacore/rules/eslint` | Next.js projects (core-web-vitals) | | `reactNativeConfig` | `@kivacore/rules/eslint` | React Native / Expo projects | | `vueConfig` | `@kivacore/rules/eslint` | Vue 3 projects | | `astroConfig` | `@kivacore/rules/eslint` | Astro projects | | `electronConfig` | `@kivacore/rules/eslint` | Electron projects | | `aiConfig` | `@kivacore/rules/eslint` | AI/LLM integrations | **Next.js setup** (`eslint.config.mjs`): ```js import { baseConfig, reactConfig, nextjsConfig } from '@kivacore/rules/eslint'; export default [ ...baseConfig, ...reactConfig, ...nextjsConfig, ]; ``` **React + Vite setup:** ```js import { baseConfig, reactConfig } from '@kivacore/rules/eslint'; export default [ ...baseConfig, ...reactConfig, ]; ``` **Expo / React Native setup:** ```js import { baseConfig, reactConfig, reactNativeConfig } from '@kivacore/rules/eslint'; export default [ ...baseConfig, ...reactConfig, ...reactNativeConfig, ]; ``` **Key rules enforced by `baseConfig`:** | Rule | Behavior | |------|----------| | TypeScript | Consistent type imports (`import type`), no unused vars | | Import ordering | `type → builtin → external → internal → sibling` with blank lines | | Unused imports | Error on unused imports | | Stylistic | 2-space indent, single quotes, semicolons, trailing commas | | React named imports | `React.*` namespace access forbidden — use named imports | | No `console.log` | Warning (allows `warn`, `error`, `info`) | | `prefer-const` | Error | #### Biome Configs Available as JSON preset files: | Config | Path | |--------|------| | Base | `@kivacore/rules/biome/base` | | React | `@kivacore/rules/biome/react` | | Next.js | `@kivacore/rules/biome/nextjs` | | Vue | `@kivacore/rules/biome/vue` | | Astro | `@kivacore/rules/biome/astro` | | Cloudflare | `@kivacore/rules/biome/cloudflare` | | Electron | `@kivacore/rules/biome/electron` | **Biome setup** (`biome.json`): ```json { "extends": ["@kivacore/rules/biome/nextjs"] } ``` ## Utilities ### @kivacore/addin-client Client for embedded add-ins to communicate with the host app from an iframe using postMessage. Handles handshake, RPC calls, and event dispatching. [npm](https://www.npmjs.com/package/@kivacore/addin-client) ```bash tab="pnpm" pnpm add @kivacore/addin-client ``` ```bash tab="npm" npm install @kivacore/addin-client ``` ```bash tab="yarn" yarn add @kivacore/addin-client ``` ```bash tab="bun" bun add @kivacore/addin-client ``` --- ### @kivacore/logo-asset-generator CLI tool to generate favicon and app icons from a source logo. Produces all required sizes for web, iOS, and Android. [npm](https://www.npmjs.com/package/@kivacore/logo-asset-generator) ```bash tab="pnpm" pnpm add -D @kivacore/logo-asset-generator ``` ```bash tab="npm" npm install -D @kivacore/logo-asset-generator ``` ```bash tab="yarn" yarn add -D @kivacore/logo-asset-generator ``` ```bash tab="bun" bun add -D @kivacore/logo-asset-generator ``` --- ### @kivacore/dom-selector-client DOM selector CLI client for programmatic element selection and inspection in web pages. [npm](https://www.npmjs.com/package/@kivacore/dom-selector-client) ```bash tab="pnpm" pnpm add @kivacore/dom-selector-client ``` ```bash tab="npm" npm install @kivacore/dom-selector-client ``` ```bash tab="yarn" yarn add @kivacore/dom-selector-client ``` ```bash tab="bun" bun add @kivacore/dom-selector-client ``` --- # Troubleshooting URL: /docs/guide/troubleshooting Common issues and solutions when using Kiva UI. ## Verify your versions Make sure your environment meets or exceeds these minimum versions to ensure Kiva UI components work correctly. ### Web | Dependency | Minimum Version | |---|---| | React | 19 | | Next.js | 16 | | Tailwind CSS | 4.0 | | Node.js | 18 | | Radix UI | 1.4.0 | ### React Native | Dependency | Minimum Version | |---|---| | React | 19 | | React Native | 0.83 | | Expo SDK | 55 | | Uniwind | 0.1+ | | Node.js | 18 | ## Web ### Registry not found If you see a "registry not found" error when installing components, make sure you've added the Kiva registry to your `components.json` file. The registry URL should point to `https://ui.kivacore.com/r`. Without this entry, neither the shadcn CLI nor the Kiva UI CLI will know where to fetch components from. ### Components not resolving after installation After installing a component, your imports should point to the local file path where the component was placed — not to an NPM package. If your IDE shows unresolved imports, check that the component files were actually written to disk and that your TypeScript path aliases match the install location. ### Tailwind CSS v4 classes not applying Tailwind CSS v4 uses a CSS-based configuration system. If component styles aren't applying, make sure your CSS entry file includes a `@source` directive that covers the directory where Kiva UI components are installed. Without this, Tailwind's compiler won't scan those files for utility classes. ### Dark mode not working Kiva UI components use CSS custom properties (CSS variables) for theming. Dark mode relies on these variables being defined in your global stylesheet. If dark mode isn't working, verify that your theme variables are set up correctly for both light and dark color schemes. ### Motion library version conflicts Some Kiva UI components use the Motion library for animations. If you see runtime errors related to motion or framer-motion, make sure you're using a compatible version. Kiva UI targets Motion v12 and above. ## React Native ### Theme not applying Make sure your app is wrapped with `KivaThemeProvider` at the root level. Without this provider, components will fall back to default styles. If using Expo Router, wrap it in your root `_layout.tsx`. ### Expo Go compatibility Some native components require a development build and won't work in Expo Go. Check the component's `expoGoCompatible` flag in the documentation. Components that use native modules (e.g., `expo-document-picker`, `expo-localization`) require `npx expo prebuild` and a custom dev client. ### Missing peer dependencies Native components declare peer dependencies for packages like `react-native-svg`, `expo-document-picker`, and `expo-localization`. If you see module resolution errors, install the required peer dependency: ```bash npx expo install react-native-svg ``` ### Font Awesome icons not loading If `KivaIcon` is not rendering icons, make sure you've configured the icon CDN path correctly. Native icons are loaded from the Kiva CDN — verify your network connectivity and that the icon name matches the registry. ## Still having issues? If none of the above solutions resolve your problem, please [open an issue on GitHub](https://github.com/Kivacore/kiva-ui/issues) with a description of what you're experiencing and your environment details. --- # rn-accordion URL: /docs/native/components/accordion Collapsible content sections with animated expand/collapse transitions. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-accordion ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) ## Usage ```tsx import { AccordionRoot, AccordionItem, AccordionTrigger, AccordionContent } from '@/components/kiva-native/accordion'; ``` ## API Reference ### AccordionRoot | Prop | Type | Default | Description | |------|------|---------|-------------| | `type` | `'single' \| 'multiple'` | `'single'` | Whether one or multiple items can be open at once | | `collapsible` | `boolean` | `true` | Whether open items can be collapsed (single mode only) | | `value` | `string \| string[]` | — | Controlled open value(s) | | `defaultValue` | `string \| string[]` | — | Initial open value(s) | | `onValueChange` | `(val: string \| string[]) => void` | — | Callback when open state changes | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Size of trigger and content text | | `variant` | `'default' \| 'outline' \| 'filled'` | `'default'` | Visual style variant | | `chevronPosition` | `'left' \| 'right'` | `'right'` | Position of the expand/collapse chevron | | `spacing` | `'none' \| 'sm' \| 'md' \| 'lg'` | `'none'` | Gap between accordion items | | `className` | `string` | — | Additional CSS classes | | `children` | `ReactNode` | — | AccordionItem children | ### AccordionItem | Prop | Type | Default | Description | |------|------|---------|-------------| | `value` | `string` | — | Unique identifier for the item | | `disabled` | `boolean` | — | Whether the item is disabled | | `className` | `string` | — | Item container CSS classes | | `children` | `ReactNode` | — | Trigger and content children | ### AccordionTrigger | Prop | Type | Default | Description | |------|------|---------|-------------| | `children` | `ReactNode` | — | Trigger label (string or custom node) | | `className` | `string` | — | Trigger CSS classes | | `textClassName` | `string` | — | Text CSS classes | ### AccordionContent | Prop | Type | Default | Description | |------|------|---------|-------------| | `children` | `ReactNode` | — | Content to show when expanded (string or custom node) | | `className` | `string` | — | Content area CSS classes | ## Components | Component | Description | |-----------|-------------| | `AccordionRoot` | Root container managing open state and context | | `AccordionItem` | Individual collapsible item wrapper | | `AccordionTrigger` | Pressable header that toggles open/close | | `AccordionContent` | Animated content area that expands/collapses | ## Type Exports | Type | Description | |------|-------------| | `AccordionRootProps` | Props for AccordionRoot component | | `AccordionItemProps` | Props for AccordionItem component | | `AccordionTriggerProps` | Props for AccordionTrigger component | | `AccordionContentProps` | Props for AccordionContent component | | `AccordionType` | `'single' \| 'multiple'` | | `AccordionSize` | `'sm' \| 'md' \| 'lg'` | | `AccordionVariant` | `'default' \| 'outline' \| 'filled'` | --- # rn-alert-dialog URL: /docs/native/components/alert-dialog Confirmation dialog with customizable title, description, variant colors, and action buttons. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-alert-dialog ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) ## Usage ```tsx import { AlertDialog } from '@/components/kiva-native/alert-dialog'; handleDelete()} onCancel={() => console.log('cancelled')} /> ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `visible` | `boolean` | — | Controlled visibility state | | `onConfirm` | `() => void` | — | Confirm button handler | | `onCancel` | `() => void` | — | Cancel button handler | | `title` | `string` | `'Are you sure?'` | Dialog title text | | `description` | `string` | — | Dialog description text | | `confirmText` | `string` | `'Confirm'` | Confirm button label | | `cancelText` | `string` | `'Cancel'` | Cancel button label | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Dialog size | | `variant` | `'default' \| 'destructive' \| 'success' \| 'warning'` | `'default'` | Confirm button color variant | | `backdropOpacity` | `'light' \| 'medium' \| 'dark'` | `'medium'` | Backdrop darkness level | | `animationType` | `'none' \| 'slide' \| 'fade'` | `'fade'` | Modal animation type | | `trigger` | `ReactNode \| ((opts: { onPress: () => void }) => ReactNode)` | — | Custom trigger element or render function | | `triggerLabel` | `string` | — | Default trigger button label | | `className` | `string` | — | Additional CSS classes | | `backdropClassName` | `string` | — | Backdrop CSS classes | | `contentClassName` | `string` | — | Content area CSS classes | | `titleClassName` | `string` | — | Title text CSS classes | | `descriptionClassName` | `string` | — | Description text CSS classes | | `confirmButtonClassName` | `string` | — | Confirm button CSS classes | | `cancelButtonClassName` | `string` | — | Cancel button CSS classes | | `triggerClassName` | `string` | — | Trigger CSS classes | ## Translation Keys Built-in copy is read through `useUiTranslation()` — provide these keys via ``. Without a provider the English fallback is shown. | Key | English fallback | Used for | |-----|------------------|----------| | `ui.alertDialog.title` | Are you sure? | Default title (`title` prop wins) | | `ui.alertDialog.confirm` | Confirm | Confirm button (`confirmText` prop wins) | | `ui.common.cancel` | Cancel | Cancel button (`cancelText` prop wins) | ## Type Exports | Type | Description | |------|-------------| | `AlertDialogProps` | Props for AlertDialog component | | `AlertDialogVariant` | `'default' \| 'destructive' \| 'success' \| 'warning'` | | `AlertDialogSize` | `'sm' \| 'md' \| 'lg'` | --- # rn-alert URL: /docs/native/components/alert Inline alert banner with variant colors, sizes, and rounded corners. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-alert ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) ## Usage ```tsx import { Alert } from '@/components/kiva-native/alert'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `title` | `string` | — | Alert title text | | `description` | `string` | — | Alert description text | | `variant` | `'info' \| 'success' \| 'warning' \| 'destructive'` | `'info'` | Visual style variant | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Component size | | `rounded` | `'none' \| 'sm' \| 'md' \| 'lg' \| 'xl'` | `'md'` | Border radius preset | | `className` | `string` | — | Additional CSS classes | | `titleClassName` | `string` | — | Title text CSS classes | | `descriptionClassName` | `string` | — | Description text CSS classes | ## Type Exports | Type | Description | |------|-------------| | `AlertProps` | Props for Alert component | | `AlertVariant` | `'info' \| 'success' \| 'warning' \| 'destructive'` | | `AlertSize` | `'sm' \| 'md' \| 'lg'` | --- # rn-avatar URL: /docs/native/components/avatar User avatar component with image, initials fallback, status indicator, and pressable support. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-avatar ``` ## Usage ```tsx import { Avatar } from '@/components/kiva-native/avatar'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `uri` | `string` | — | Image URI for the avatar | | `name` | `string` | — | Name used to generate initials fallback | | `shape` | `'circle' \| 'rounded'` | `'circle'` | Avatar shape | | `size` | `'xs' \| 'sm' \| 'md' \| 'lg'` | `'md'` | Avatar size | | `variant` | `'solid' \| 'soft' \| 'outline'` | `'solid'` | Background style variant | | `status` | `'none' \| 'online' \| 'offline' \| 'busy' \| 'away'` | `'none'` | Status indicator dot | | `onPress` | `() => void` | — | Press handler (wraps in Pressable) | | `className` | `string` | — | Additional CSS classes | | `textClassName` | `string` | — | Initials text CSS classes | ## Type Exports | Type | Description | |------|-------------| | `AvatarProps` | Props for Avatar component | | `AvatarShape` | `'circle' \| 'rounded'` | | `AvatarSize` | `'xs' \| 'sm' \| 'md' \| 'lg'` | | `AvatarVariant` | `'solid' \| 'soft' \| 'outline'` | | `AvatarStatus` | `'none' \| 'online' \| 'offline' \| 'busy' \| 'away'` | --- # rn-badge URL: /docs/native/components/badge Small label component for status, categories, or counts with variant and size options. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-badge ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) ## Usage ```tsx import { Badge } from '@/components/kiva-native/badge'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `children` | `ReactNode` | — | Badge content | | `variant` | `'default' \| 'secondary' \| 'destructive' \| 'outline'` | `'default'` | Visual style variant | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Badge size | | `className` | `string` | — | Additional CSS classes | | `textClassName` | `string` | — | Text CSS classes | ## Type Exports | Type | Description | |------|-------------| | `BadgeProps` | Props for Badge component | | `BadgeVariant` | `'default' \| 'secondary' \| 'destructive' \| 'outline'` | | `BadgeSize` | `'sm' \| 'md' \| 'lg'` | --- # rn-button URL: /docs/native/components/button Pressable button component with multiple variants and sizes for user actions. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-button ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) ## Usage ```tsx import { Button } from '@/components/kiva-native/button'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `children` | `ReactNode` | — | Button content | | `variant` | `'default' \| 'secondary' \| 'destructive' \| 'outline' \| 'ghost' \| 'link'` | `'default'` | Visual style variant | | `size` | `'sm' \| 'md' \| 'lg' \| 'icon'` | `'md'` | Button size | | `disabled` | `boolean` | `false` | Disable interaction | | `loading` | `boolean` | `false` | Show loading spinner with smooth layout transition | | `feedbackVariant` | `'scale' \| 'scale-highlight' \| 'none'` | `'scale-highlight'` | Press feedback animation type | | `onPress` | `() => void` | — | Press handler | | `onLongPress` | `() => void` | — | Long press handler | | `className` | `string` | — | Additional CSS classes | | `textClassName` | `string` | — | Text CSS classes | | `accessibilityLabel` | `string` | — | Accessibility label | ## Type Exports | Type | Description | |------|-------------| | `ButtonProps` | Props for Button component | | `ButtonVariant` | `'default' \| 'secondary' \| 'destructive' \| 'outline' \| 'ghost' \| 'link'` | | `ButtonSize` | `'sm' \| 'md' \| 'lg' \| 'icon'` | --- # rn-card URL: /docs/native/components/card Versatile card container with header, footer, animations, and pressable support. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-card ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) ## Usage ```tsx import { Card } from '@/components/kiva-native/card'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `children` | `ReactNode` | — | Card body content | | `variant` | `'default' \| 'outlined' \| 'elevated' \| 'ghost'` | `'default'` | Visual style variant | | `size` | `'sm' \| 'md' \| 'lg' \| 'xl'` | `'md'` | Card padding and text sizing | | `header` | `ReactNode` | — | Header content rendered above body | | `title` | `string` | — | Card title text | | `description` | `string` | — | Card description text | | `footer` | `ReactNode` | — | Footer content rendered below body | | `onPress` | `() => void` | — | Press handler (makes card pressable) | | `animation` | `'none' \| 'fade' \| 'scale' \| 'slideUp' \| 'slideDown' \| 'slideLeft' \| 'slideRight'` | `'none'` | Entry animation type | | `className` | `string` | — | Additional CSS classes | | `titleClassName` | `string` | — | Title text CSS classes | | `descriptionClassName` | `string` | — | Description text CSS classes | ## Type Exports | Type | Description | |------|-------------| | `CardProps` | Props for Card component | | `CardVariant` | `'default' \| 'outlined' \| 'elevated' \| 'ghost'` | | `CardSize` | `'sm' \| 'md' \| 'lg' \| 'xl'` | | `CardAnimationType` | `'none' \| 'fade' \| 'scale' \| 'slideUp' \| 'slideDown' \| 'slideLeft' \| 'slideRight'` | --- # rn-carousel URL: /docs/native/components/carousel Horizontal content carousel with pagination dots and arrow navigation. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-carousel ``` ## Usage ```tsx import { Carousel } from '@/components/kiva-native/carousel'; , , ]} showDots showArrows /> ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `data` | `ReactNode[]` | — | Array of slide content (required) | | `autoPlay` | `boolean` | `false` | Enable auto-play | | `autoPlayInterval` | `number` | `3000` | Auto-play interval (ms) | | `showDots` | `boolean` | `true` | Show pagination dots | | `showArrows` | `boolean` | `false` | Show navigation arrows | | `loop` | `boolean` | `false` | Enable infinite loop | | `onIndexChange` | `(index: number) => void` | — | Slide change callback | | `className` | `string` | — | Additional CSS classes | | `itemClassName` | `string` | — | Slide item CSS classes | | `dotClassName` | `string` | — | Inactive dot CSS classes | | `activeDotClassName` | `string` | — | Active dot CSS classes | ## Type Exports | Type | Description | |------|-------------| | `CarouselProps` | Props for Carousel component | --- # rn-checkbox URL: /docs/native/components/checkbox Standalone checkbox component with optional label and size variants. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-checkbox ``` ## Usage ```tsx import { Checkbox } from '@/components/kiva-native/checkbox'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `checked` | `boolean` | `false` | Checkbox state | | `onCheckedChange` | `(checked: boolean) => void` | — | State change handler | | `disabled` | `boolean` | `false` | Disable interaction | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Checkbox size | | `label` | `string` | — | Optional label text | | `className` | `string` | — | Additional CSS classes | | `labelClassName` | `string` | — | Label CSS classes | | `accessibilityLabel` | `string` | — | Accessibility label | ## Type Exports | Type | Description | |------|-------------| | `CheckboxProps` | Props for Checkbox component | | `CheckboxSize` | `'sm' \| 'md' \| 'lg'` | --- # rn-collapsible URL: /docs/native/components/collapsible Expandable/collapsible container with animated height transitions. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-collapsible ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) ## Usage ```tsx import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@/components/kiva-native/collapsible'; ``` ## API Reference ### Collapsible | Prop | Type | Default | Description | |------|------|---------|-------------| | `open` | `boolean` | — | Controlled open state | | `defaultOpen` | `boolean` | `false` | Initial open state (uncontrolled) | | `onOpenChange` | `(open: boolean) => void` | — | Open state change handler | | `children` | `ReactNode` | — | Trigger and Content children | | `className` | `string` | — | Additional CSS classes | ### CollapsibleTrigger | Prop | Type | Default | Description | |------|------|---------|-------------| | `children` | `ReactNode` | — | Trigger content | | `className` | `string` | — | Additional CSS classes | ### CollapsibleContent | Prop | Type | Default | Description | |------|------|---------|-------------| | `children` | `ReactNode` | — | Collapsible content | | `className` | `string` | — | Additional CSS classes | ## Components | Component | Description | |-----------|-------------| | `Collapsible` | Root container with context provider | | `CollapsibleTrigger` | Pressable trigger that toggles content | | `CollapsibleContent` | Animated content container | ## Type Exports | Type | Description | |------|-------------| | `CollapsibleProps` | Props for Collapsible | | `CollapsibleTriggerProps` | Props for CollapsibleTrigger | | `CollapsibleContentProps` | Props for CollapsibleContent | --- # rn-drawer URL: /docs/native/components/drawer Slide-in side panel with animated entrance, backdrop, and swipe-to-dismiss support. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-drawer ``` **Dependencies:** - [react-native-gesture-handler](https://www.npmjs.com/package/react-native-gesture-handler) - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) - [react-native-worklets](https://www.npmjs.com/package/react-native-worklets) ## Usage ```tsx import { Drawer } from '@/components/kiva-native/drawer'; } > ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `visible` | `boolean` | — | Controlled visibility state | | `onClose` | `() => void` | — | Close handler | | `side` | `'left' \| 'right'` | `'left'` | Side the drawer slides in from | | `width` | `number` | `300` | Drawer width in pixels | | `variant` | `'default' \| 'elevated' \| 'minimal' \| 'glass'` | `'default'` | Visual variant | | `backdropOpacity` | `'light' \| 'medium' \| 'dark'` | `'medium'` | Backdrop darkness level | | `header` | `ReactNode` | — | Header content element | | `footer` | `ReactNode` | — | Footer content element | | `swipeToDismiss` | `boolean` | `true` | Enable swipe gesture to close | | `animationDuration` | `number` | `200` | Open/close animation duration in ms | | `children` | `ReactNode` | — | Drawer body content | | `trigger` | `ReactNode \| ((opts: { onPress: () => void }) => ReactNode)` | — | Custom trigger element or render function | | `triggerLabel` | `string` | `'Open Drawer'` | Default trigger button label | | `hideTrigger` | `boolean` | `true` | Hide default trigger when no custom trigger | | `className` | `string` | — | Additional CSS classes | | `backdropClassName` | `string` | — | Backdrop CSS classes | | `contentClassName` | `string` | — | Content area CSS classes | | `headerClassName` | `string` | — | Header CSS classes | | `footerClassName` | `string` | — | Footer CSS classes | | `triggerClassName` | `string` | — | Trigger CSS classes | ## Type Exports | Type | Description | |------|-------------| | `DrawerProps` | Props for Drawer component | | `DrawerSide` | `'left' \| 'right'` | | `DrawerVariant` | `'default' \| 'elevated' \| 'minimal' \| 'glass'` | --- # rn-dropdown-menu URL: /docs/native/components/dropdown-menu Menu popup component with items, separators, and destructive actions. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-dropdown-menu ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) ## Usage ```tsx import { DropdownMenu } from '@/components/kiva-native/dropdown-menu'; } items={[ { label: 'Edit', onPress: handleEdit }, { label: 'Duplicate', onPress: handleDuplicate }, { type: 'separator' }, { label: 'Delete', onPress: handleDelete, destructive: true }, ]} /> ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `trigger` | `ReactNode` | — | Trigger element (required) | | `items` | `DropdownMenuEntry[]` | — | Menu items and separators (required) | | `align` | `'start' \| 'end'` | — | Menu alignment | | `className` | `string` | — | Additional CSS classes | | `menuClassName` | `string` | — | Menu panel CSS classes | ### DropdownMenuItem | Property | Type | Description | |----------|------|-------------| | `label` | `string` | Item label | | `icon` | `ReactNode` | Optional icon | | `onPress` | `() => void` | Press handler | | `destructive` | `boolean` | Destructive action styling | | `disabled` | `boolean` | Disable this item | ### DropdownMenuSeparator | Property | Type | Description | |----------|------|-------------| | `type` | `'separator'` | Separator marker | ## Type Exports | Type | Description | |------|-------------| | `DropdownMenuProps` | Props for DropdownMenu | | `DropdownMenuItem` | Menu item type | | `DropdownMenuSeparator` | Separator type | | `DropdownMenuEntry` | Union of item and separator | --- # rn-emoji-picker URL: /docs/native/components/emoji-picker Emoji picker in a bottom sheet with search, categories, recently used emoji and skin tones, built on the same emoji-mart dataset as web. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-emoji-picker ``` **Dependencies:** - [@emoji-mart/data](https://www.npmjs.com/package/@emoji-mart/data) - [@shopify/flash-list](https://www.npmjs.com/package/@shopify/flash-list) `EmojiPicker` opens `EmojiPickerPanel` in a bottom `ActionSheet`. The panel has a search box, a skin-tone chooser, category tabs (plus a **Frequently used** tab once something was picked) and a `FlashList` grid. Emoji render as system-font text. Long-press an emoji to preview its name and shortcode in the footer. Ids and shortcodes come from `@emoji-mart/data`, so they match web exactly. Recent emoji and the skin tone persist through `lib/storage` (the `'local'` store the app registered, under the web keys `docyrus:emoji-recents` / `docyrus:emoji-skin-tone`), or you can control both with props. ## Usage ```tsx import { EmojiPicker } from '@/components/kiva-native/emoji-picker'; import { KivaIcon } from '@/components/kiva-native/kiva-icon'; ``` Pass a non-pressable node as `children`: it is wrapped in a `Pressable` that opens the sheet. To drive the sheet from your own button, omit `children` and control `open`: ```tsx const [open, setOpen] = useState(false); insert(emoji.native)} /> ``` The panel can also be rendered inline: ```tsx import { EmojiPickerPanel } from '@/components/kiva-native/emoji-picker'; setReaction(emoji.id)} /> ``` ## API Reference ### EmojiPicker | Prop | Type | Default | Description | |------|------|---------|-------------| | `children` | `ReactNode` | - | Trigger content, wrapped in a Pressable that opens the sheet. Omit to drive the sheet via open / onOpenChange | | `onSelect` | `(emoji: SelectedEmoji) => void` | - | Fired with { id, native, shortcode } resolved for the active skin tone (required) | | `defaultSkinTone` | `number` | `0` | Initial skin tone when none is persisted (0 = default, 1–5 = Fitzpatrick) | | `perLine` | `number` | `8` | Emoji cells per row | | `closeOnSelect` | `boolean` | `true` | Close the sheet after a selection | | `align` | `'start' \| 'center' \| 'end'` | - | Accepted for web parity — ignored (bottom sheet) | | `side` | `'top' \| 'right' \| 'bottom' \| 'left'` | - | Accepted for web parity — ignored (bottom sheet) | | `open` | `boolean` | - | Controlled open state | | `onOpenChange` | `(open: boolean) => void` | - | Open state change callback | | `contentClassName` | `string` | - | Classes for the panel inside the sheet | | `recentEmojis` | `string[]` | - | Controlled recently-used emoji ids (persisted through lib/storage when omitted) | | `onRecentEmojisChange` | `(recents: string[]) => void` | - | Fired with the next recents list after a pick | | `skinTone` | `number` | - | Controlled skin tone (0–5) | | `onSkinToneChange` | `(tone: number) => void` | - | Fired when the user picks a skin tone | | `disabled` | `boolean` | `false` | Disables the trigger | | `title` | `string` | `'Emoji'` | Sheet title | | `className` | `string` | - | Trigger container classes | ### EmojiPickerPanel | Prop | Type | Default | Description | |------|------|---------|-------------| | `onSelect` | `(emoji: SelectedEmoji) => void` | - | Fired when an emoji is chosen (required) | | `defaultSkinTone` | `number` | `0` | Initial skin tone when none is persisted | | `perLine` | `number` | `8` | Emoji cells per row | | `recentEmojis` | `string[]` | - | Controlled recents | | `onRecentEmojisChange` | `(recents: string[]) => void` | - | Recents change callback | | `skinTone` | `number` | - | Controlled skin tone | | `onSkinToneChange` | `(tone: number) => void` | - | Skin tone change callback | | `gridHeight` | `number` | `280` | Grid height in px | | `className` | `string` | - | Container classes | ### SelectedEmoji | Field | Type | Description | |-------|------|-------------| | `id` | `string` | emoji-mart id, e.g. `smile` | | `native` | `string` | Unicode character for the active skin tone | | `shortcode` | `string` | Shortcode, e.g. `:smile:` | ## Helpers | Export | Description | |--------|-------------| | `searchEmojis(query, limit?)` | AND-substring search over id, name, keywords, emoticons and aliases (default limit 90) | | `resolveNative(id, skinTone)` | Unicode character for an id at a skin tone (0–5) | | `getShortcode(id)` | `:id:` | ## Components | Component | Description | |-----------|-------------| | `EmojiPicker` | Trigger + bottom-sheet picker | | `EmojiPickerPanel` | The picker panel on its own | ## Type Exports | Type | Description | |------|-------------| | `EmojiPickerProps` | Props for `EmojiPicker` | | `EmojiPickerPanelProps` | Props for `EmojiPickerPanel` | | `SelectedEmoji` | Payload of `onSelect` | ## Differences from web - The popover is a bottom sheet. `align` and `side` are accepted and ignored. - Hover preview is replaced by long-press preview. - New props: `recentEmojis` / `onRecentEmojisChange`, `skinTone` / `onSkinToneChange`, `disabled`, `title`, `className`, and `gridHeight` on the panel. --- # Overview URL: /docs/native/components React Native UI primitives for mobile applications with iOS and Android support. Browse all available Kiva UI native primitives. These are the core building blocks — buttons, inputs, cards, modals, and more. ## Available Components | Component | Description | |-----------|-------------| | [rn-accordion](/docs/native/components/accordion) | Collapsible content sections with animated expand/collapse transitions. | | [rn-alert](/docs/native/components/alert) | Inline alert banner with variant colors, sizes, and rounded corners. | | [rn-alert-dialog](/docs/native/components/alert-dialog) | Confirmation dialog with customizable title, description, variant colors, and action buttons. | | [rn-avatar](/docs/native/components/avatar) | User avatar component with image, initials fallback, status indicator, and pressable support. | | [rn-badge](/docs/native/components/badge) | Small label component for status, categories, or counts with variant and size options. | | [rn-button](/docs/native/components/button) | Pressable button component with multiple variants and sizes for user actions. | | [rn-card](/docs/native/components/card) | Versatile card container with header, footer, animations, and pressable support. | | [rn-carousel](/docs/native/components/carousel) | Horizontal content carousel with pagination dots and arrow navigation. | | [rn-checkbox](/docs/native/components/checkbox) | Standalone checkbox component with optional label and size variants. | | [rn-collapsible](/docs/native/components/collapsible) | Expandable/collapsible container with animated height transitions. | | [rn-confirmation-button](/docs/native/components/confirmation-button) | Button that opens a countdown confirmation modal before executing the action. | | [rn-date-time-picker](/docs/native/components/date-time-picker) | A modal date and time picker with calendar grid and scrollable time controls. | | [rn-date-time-range-picker](/docs/native/components/date-time-range-picker) | A modal date-time range picker with start/end tabs, calendar grid, and time controls. | | [rn-day-picker](/docs/native/components/day-picker) | An inline calendar day picker supporting single, multiple, and range selection modes. | | [rn-kiva-icon](/docs/native/components/kiva-icon) | CDN-powered icon component supporting Font Awesome, Huge Icons, emojis, and custom libraries. | | [rn-drawer](/docs/native/components/drawer) | Slide-in side panel with animated entrance, backdrop, and swipe-to-dismiss support. | | [rn-dropdown-menu](/docs/native/components/dropdown-menu) | Menu popup component with items, separators, and destructive actions. | | [rn-duration-select](/docs/native/components/duration-select) | Duration picker with hours and minutes grid, supporting multiple display formats. | | [rn-empty-state](/docs/native/components/empty-state) | Placeholder display for empty content areas with variant-specific icons and actions. | | [rn-error-state](/docs/native/components/error-state) | Error display with variant-specific messaging, retry actions, and expandable error details. | | [rn-fab](/docs/native/components/fab) | Floating action button with expandable menu, position control, and variant colors. | | [rn-grid](/docs/native/components/grid) | Responsive grid layout with configurable columns, gap control, and spanning grid items. | | [rn-input](/docs/native/components/input) | Text input primitive with size variants, icons, and validation states. | | [rn-input-otp](/docs/native/components/input-otp) | OTP code input with segmented cells for verification codes. | | [rn-label](/docs/native/components/label) | Form label component with size variants and required indicator. | | [rn-mini-calendar](/docs/native/components/mini-calendar) | Compact date picker calendar with month navigation and locale-aware day names. | | [rn-modal](/docs/native/components/modal) | Flexible modal dialog with preset types, header/footer configurations, and position options. | | [rn-network-banner](/docs/native/components/network-banner) | Animated banner for displaying network connectivity status with retry and dismiss actions. | | [rn-notification-stack](/docs/native/components/notification-stack) | Stacked notification cards with dismiss, load more, and action buttons. | | [rn-pagination](/docs/native/components/pagination) | Page navigation control with page numbers, ellipsis, and info text. | | [rn-phone-input](/docs/native/components/phone-input) | Phone number input with country code picker and search. | | [rn-popover](/docs/native/components/popover) | Floating content panel with arrow, placement options, and multiple visual variants. | | [rn-progress](/docs/native/components/progress) | Linear progress bar with label, size, and color variant options. | | [rn-qr-code](/docs/native/components/qr-code) | QR code display component with size variants and optional logo overlay. | | [rn-radio-group](/docs/native/components/radio-group) | Radio button group component with compound pattern for single-option selection. | | [rn-rating](/docs/native/components/rating) | Star rating input with half-star support and custom icon rendering. | | [rn-search-input](/docs/native/components/search-input) | Search input with debounce and clear button, supporting manual and automatic search modes. | | [rn-select](/docs/native/components/select) | Dropdown select component with modal picker for option selection. | | [rn-separator](/docs/native/components/separator) | Visual divider component for horizontal or vertical separation. | | [rn-skeleton](/docs/native/components/skeleton) | Animated loading placeholders with card, list, table, and calendar presets. | | [rn-slider](/docs/native/components/slider) | Draggable slider with custom range, step, tooltip, and track marks. | | [rn-spinner](/docs/native/components/spinner) | Loading indicator component with size and variant options. | | [rn-status](/docs/native/components/status) | Status indicator badge with dot and colored variants. | | [rn-stepper](/docs/native/components/stepper) | Step indicator component for multi-step wizards and onboarding flows. | | [rn-switch](/docs/native/components/switch) | Toggle switch component with optional label and size variants. | | [rn-table](/docs/native/components/table) | Lightweight data table with sorting, striped rows, grouping, and built-in pagination. | | [rn-tabs](/docs/native/components/tabs) | Tabbed navigation with horizontal/vertical orientation and multiple visual variants. | | [rn-textarea](/docs/native/components/textarea) | Multi-line text input component with size variants and validation. | | [rn-timeline](/docs/native/components/timeline) | Vertical timeline component for displaying chronological events. | | [rn-toast](/docs/native/components/toast) | Stackable toast notification system with rich colors, swipe-to-dismiss, and a Sonner-like imperative API. | | [rn-toggle](/docs/native/components/toggle) | Toggle button component with pressed state and variant options. | | [rn-toggle-group](/docs/native/components/toggle-group) | Segmented control component for single or multiple option selection. | | [rn-tooltip](/docs/native/components/tooltip) | Contextual popup with configurable placement, arrow, and visual variants. | | [rn-tree-view](/docs/native/components/tree-view) | Hierarchical tree component with expand/collapse, search, and optional checkboxes. | | [rn-wheel-picker](/docs/native/components/wheel-picker) | Scrollable wheel picker for selecting from a list of options with snap-to-item behavior. | --- # rn-input-otp URL: /docs/native/components/input-otp OTP code input with segmented cells for verification codes. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-input-otp ``` ## Usage ```tsx import { InputOtp } from '@/components/kiva-native/input-otp'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `value` | `string` | `''` | Current OTP value | | `onValueChange` | `(value: string) => void` | — | Value change handler | | `onComplete` | `(value: string) => void` | — | Called when all digits are entered | | `length` | `number` | `6` | Number of digits | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Cell size | | `disabled` | `boolean` | `false` | Disable interaction | | `invalid` | `boolean` | `false` | Show invalid state | | `mask` | `boolean` | `false` | Mask entered digits | | `className` | `string` | — | Additional CSS classes | | `cellClassName` | `string` | — | Individual cell CSS classes | | `textClassName` | `string` | — | Digit text CSS classes | | `accessibilityLabel` | `string` | — | Accessibility label | ## Type Exports | Type | Description | |------|-------------| | `InputOtpProps` | Props for InputOtp component | | `InputOtpSize` | `'sm' \| 'md' \| 'lg'` | --- # rn-input URL: /docs/native/components/input Text input primitive with size variants, icons, and validation states. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-input ``` ## Usage ```tsx import { Input } from '@/components/kiva-native/input'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Input size | | `disabled` | `boolean` | `false` | Disable interaction | | `invalid` | `boolean` | `false` | Show invalid state | | `startIcon` | `ReactNode` | — | Icon at the start | | `endIcon` | `ReactNode` | — | Icon at the end | | `className` | `string` | — | Additional CSS classes | | `inputClassName` | `string` | — | TextInput CSS classes | All standard `TextInputProps` are also supported (except `style`). ## Type Exports | Type | Description | |------|-------------| | `InputProps` | Props for Input component | | `InputSize` | `'sm' \| 'md' \| 'lg'` | --- # rn-label URL: /docs/native/components/label Form label component with size variants and required indicator. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-label ``` ## Usage ```tsx import { Label } from '@/components/kiva-native/label'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `children` | `string` | — | Label text | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Label size | | `required` | `boolean` | `false` | Show required asterisk | | `disabled` | `boolean` | `false` | Muted color for disabled state | | `nativeID` | `string` | — | Native ID for accessibility linking | | `className` | `string` | — | Additional CSS classes | ## Type Exports | Type | Description | |------|-------------| | `LabelProps` | Props for Label component | | `LabelSize` | `'sm' \| 'md' \| 'lg'` | --- # rn-modal URL: /docs/native/components/modal Flexible modal dialog with preset types, header/footer configurations, and position options. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-modal ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) ## Usage ```tsx import { Modal } from '@/components/kiva-native/modal'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `visible` | `boolean` | — | Whether the modal is visible | | `onClose` | `() => void` | — | Close handler | | `onConfirm` | `() => void` | — | Confirm handler (for confirm/picker types) | | `title` | `string` | — | Modal title | | `closeOnOverlayPress` | `boolean` | — | Close on backdrop tap (auto-configured by modalType) | | `size` | `'sm' \| 'md' \| 'lg' \| 'full'` | `'md'` | Modal width/height size | | `position` | `'center' \| 'bottom'` | `'center'` | Modal position on screen | | `variant` | `'default' \| 'elevated' \| 'bordered'` | `'default'` | Visual variant | | `backdropOpacity` | `number` | `0.4` | Backdrop opacity (0 to 1) | | `modalType` | `'default' \| 'info' \| 'confirm' \| 'picker' \| 'custom'` | `'default'` | Preset type (auto-configures header/footer) | | `headerType` | `'none' \| 'title-close' \| 'title-actions'` | — | Header layout (auto-set by modalType unless custom) | | `footerType` | `'none' \| 'actions'` | — | Footer layout (auto-set by modalType unless custom) | | `confirmText` | `string` | `'Confirm'` | Confirm button label | | `cancelText` | `string` | `'Cancel'` | Cancel button label | | `header` | `ReactNode` | — | Custom header element | | `footer` | `ReactNode` | — | Custom footer element | | `children` | `ReactNode` | — | Modal body content | | `className` | `string` | — | Additional CSS classes | | `backdropClassName` | `string` | — | Backdrop CSS classes | | `contentClassName` | `string` | — | Content area CSS classes | | `headerClassName` | `string` | — | Header CSS classes | | `titleClassName` | `string` | — | Title text CSS classes | | `footerClassName` | `string` | — | Footer CSS classes | | `accessibilityLabel` | `string` | — | Accessibility label for the modal | ### Modal Type Presets | Type | Header | Footer | Close on overlay | |------|--------|--------|------------------| | `default` / `info` | title-close (if title set) | none | yes | | `confirm` | none | actions | no | | `picker` | title-actions | none | yes | | `custom` | configurable | configurable | yes | ## Translation Keys Built-in copy is read through `useUiTranslation()` — provide these keys via ``. Without a provider the English fallback is shown. | Key | English fallback | Used for | |-----|------------------|----------| | `ui.modal.confirm` | Confirm | Confirm button (`confirmText` prop wins) | | `ui.common.cancel` | Cancel | Cancel button (`cancelText` prop wins) | | `ui.modal.done` | Done | Done button of the `picker` modal | ## Type Exports | Type | Description | |------|-------------| | `ModalProps` | Props for Modal component | | `ModalType` | `'default' \| 'info' \| 'confirm' \| 'picker' \| 'custom'` | | `ModalHeaderType` | `'none' \| 'title-close' \| 'title-actions'` | | `ModalFooterType` | `'none' \| 'actions'` | | `ModalSize` | `'sm' \| 'md' \| 'lg' \| 'full'` | | `ModalPosition` | `'center' \| 'bottom'` | | `ModalVariant` | `'default' \| 'elevated' \| 'bordered'` | --- # rn-morph-popover URL: /docs/native/components/morph-popover A trigger button that morphs into a floating panel, animated with Reanimated. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-morph-popover ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) The trigger is measured with `measureInWindow`. A transparent `Modal` then shows a panel that starts at the trigger's size and corner radius and grows to the content size, while the content fades and slides in. Closing plays the animation in reverse. Tapping outside the panel closes it. The panel opens on `side` and flips to the other side when there is not enough room. It is centred on the trigger and kept 16pt from the screen edges. If the content changes height while open, the panel resizes in place. When the system's reduce-motion setting is on, the panel appears without animation. ## Usage ```tsx import { MorphPopover } from '@/components/kiva-native/morph-popover'; ``` ```tsx }> ``` Content text does not inherit colour on React Native, so style the children to contrast with `bgClassName`. The default background is `bg-neutral-900` in light mode and `bg-neutral-100` in dark mode. ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `children` | `ReactNode` | - | Panel content (required) | | `trigger` | `ReactNode` | - | Trigger content (default: a plus icon) | | `triggerSize` | `number` | `44` | Square trigger size (px) | | `triggerWidth` | `number` | - | Trigger width (overrides triggerSize) | | `triggerHeight` | `number` | - | Trigger height (overrides triggerSize) | | `triggerRadius` | `number` | `triggerSize / 2 (6 with custom dimensions)` | Trigger corner radius | | `triggerClassName` | `string` | - | Trigger classes | | `disabled` | `boolean` | `false` | Disables the trigger | | `isOpen` | `boolean` | - | Controlled open state | | `onOpenChange` | `(open: boolean) => void` | - | Open state change callback | | `side` | `'top' \| 'bottom'` | `'top'` | Preferred side; flips when there is not enough room | | `sideOffset` | `number` | `24` | Gap between trigger and panel (px) | | `contentWidth` | `number` | `240` | Panel width, clamped to screen width minus a 16pt gutter | | `speed` | `number` | `0.25` | Animation duration in seconds | | `bgClassName` | `string` | `'bg-neutral-900 dark:bg-neutral-100'` | Background classes shared by trigger and panel | | `contentClassName` | `string` | - | Panel content classes | | `className` | `string` | - | Wrapper classes | ## Type Exports | Type | Description | |------|-------------| | `MorphPopoverProps` | Props for `MorphPopover` | ## Differences from web - GSAP is replaced by Reanimated. The SVG "goo" filter has no React Native equivalent and is not reproduced. - `speed` is still in seconds. - Outside clicks and Escape become a backdrop tap and the Android back button. --- # rn-pagination URL: /docs/native/components/pagination Page navigation control with page numbers, ellipsis, and info text. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-pagination ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) ## Usage ```tsx import { Pagination } from '@/components/kiva-native/pagination'; const [page, setPage] = useState(1); ``` ### With Info Text ```tsx ``` ### First/Last Buttons ```tsx ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `currentPage` | `number` | — | Current active page (1-based) | | `totalPages` | `number` | — | Total number of pages | | `onPageChange` | `(page: number) => void` | — | Callback when page changes | | `totalItems` | `number` | — | Total item count (used for info text) | | `pageSize` | `number` | — | Items per page (used for info text) | | `maxVisiblePages` | `number` | `7` | Maximum number of page buttons to show | | `showFirstLast` | `boolean` | `false` | Show first/last page buttons | | `showPageNumbers` | `boolean` | `true` | Show individual page number buttons | | `showInfo` | `boolean` | `false` | Show "Showing X-Y of Z" info text | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Button and text size | | `disabled` | `boolean` | `false` | Disable all pagination controls | | `className` | `string` | — | Additional CSS classes | ## Translation Keys Built-in copy is read through `useUiTranslation()` — provide these keys via ``. Without a provider the English fallback is shown. | Key | English fallback | Used for | |-----|------------------|----------| | `ui.pagination.info` | Showing {start}–{end} of {total} | Info text when `showInfo` is on — `{start}`, `{end}`, `{total}` are replaced | ## Type Exports | Type | Description | |------|-------------| | `PaginationProps` | Props for Pagination component | | `PaginationSize` | `'sm' \| 'md' \| 'lg'` | --- # rn-popover URL: /docs/native/components/popover Floating content panel with arrow, placement options, and multiple visual variants. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-popover ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) ## Usage ```tsx import { Popover } from '@/components/kiva-native/popover'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `visible` | `boolean` | — | Controlled open state | | `defaultOpen` | `boolean` | `false` | Initial open state (uncontrolled) | | `onOpenChange` | `(open: boolean) => void` | — | Open state change callback | | `onClose` | `() => void` | — | Called when popover closes | | `title` | `string` | — | Popover title text | | `placement` | `PopoverPlacement` | `'bottom'` | Popover placement relative to trigger | | `offset` | `number` | `10` | Distance from trigger in pixels | | `arrow` | `boolean` | `true` | Show directional arrow | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Popover size | | `variant` | `'default' \| 'elevated' \| 'minimal' \| 'glass'` | `'default'` | Visual variant | | `delayHide` | `number` | `0` | Auto-hide delay in ms (0 = manual close) | | `maxWidth` | `number` | — | Maximum popover width | | `children` | `ReactNode` | — | Trigger element | | `content` | `ReactNode` | — | Popover content (string or element) | | `className` | `string` | — | Popover container CSS classes | | `contentClassName` | `string` | — | Content area CSS classes | ### PopoverPlacement `'top' | 'bottom' | 'left' | 'right' | 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight'` ## Type Exports | Type | Description | |------|-------------| | `PopoverProps` | Props for Popover component | | `PopoverPlacement` | Placement position union type | | `PopoverSize` | `'sm' \| 'md' \| 'lg'` | | `PopoverVariant` | `'default' \| 'elevated' \| 'minimal' \| 'glass'` | --- # rn-pressable-feedback URL: /docs/native/components/pressable-feedback Animated press feedback wrapper with scale and highlight effects. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-pressable-feedback ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) ## Usage ```tsx import { PressableFeedback } from '@/components/kiva-native/pressable-feedback'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `children` | `ReactNode` | — | Content to wrap | | `feedbackVariant` | `'scale' \| 'scale-highlight' \| 'none'` | `'scale-highlight'` | Type of press feedback | | `scaleValue` | `number` | `0.97` | Scale factor on press | | `highlightOpacity` | `number` | `0.7` | Opacity on press (scale-highlight only) | | `disabled` | `boolean` | `false` | Disable interactions | | `className` | `string` | — | Additional classes | All `PressableProps` are also accepted. ## Type Exports | Type | Description | |------|-------------| | `PressableFeedbackProps` | Props for PressableFeedback | | `FeedbackVariant` | `'scale' \| 'scale-highlight' \| 'none'` | --- # rn-progress URL: /docs/native/components/progress Linear progress bar with label, size, and color variant options. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-progress ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) ## Usage ```tsx import { Progress } from '@/components/kiva-native/progress'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `value` | `number` | — | Progress value (0-100) | | `showLabel` | `boolean` | `false` | Show percentage label | | `size` | `'xs' \| 'sm' \| 'md' \| 'lg'` | `'md'` | Track height size | | `variant` | `'default' \| 'secondary' \| 'success' \| 'warning' \| 'destructive'` | `'default'` | Fill color variant | | `className` | `string` | — | Additional CSS classes | | `labelClassName` | `string` | — | Label text CSS classes | | `trackClassName` | `string` | — | Track background CSS classes | | `fillClassName` | `string` | — | Fill bar CSS classes | ## Type Exports | Type | Description | |------|-------------| | `ProgressProps` | Props for Progress component | | `ProgressSize` | `'xs' \| 'sm' \| 'md' \| 'lg'` | | `ProgressVariant` | `'default' \| 'secondary' \| 'success' \| 'warning' \| 'destructive'` | --- # rn-radio-group URL: /docs/native/components/radio-group Single-option radio group with an options-driven or compound API, a card variant, icons, colours, descriptions and responsive columns. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-radio-group ``` ## Usage ### Options mode (same API as web) ```tsx import { RadioGroup, type RadioGroupOption } from '@/components/kiva-native/radio-group'; const plans: RadioGroupOption[] = [ { value: 'starter', label: 'Starter', description: 'Up to 3 projects', icon: 'fal seedling', color: 'emerald' }, { value: 'pro', label: 'Pro', description: 'Unlimited projects', icon: 'fal rocket', color: 'indigo-500' }, { value: 'legacy', label: 'Legacy', disabled: true } ]; ``` ### Compound mode ```tsx import { RadioGroup, RadioGroupItem } from '@/components/kiva-native/radio-group'; ``` ## API Reference ### RadioGroup | Prop | Type | Default | Description | |------|------|---------|-------------| | `options` | `RadioGroupOption[]` | — | Options-driven mode (web parity). When set, `children` are ignored | | `children` | `ReactNode` | — | Compound mode — `RadioGroupItem` elements | | `value` | `string` | — | Controlled selected value | | `defaultValue` | `string` | — | Initial value for uncontrolled mode. Ignored when `value` is provided | | `onValueChange` | `(value: string) => void` | — | Selection change handler | | `disabled` | `boolean` | `false` | Disable all items | | `variant` | `'default' \| 'card'` | `'default'` | `card` renders each option as a bordered pressable card with a check indicator | | `columnCount` | `1 \| 2 \| 3 \| 4 \| 5` | `1` | Grid columns. Collapses to 1 column below 400pt window width and to at most 2 below 768pt (mirrors web `sm:` / `lg:`). Values > 1 override `orientation` | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Radio indicator + label size (native-only) | | `orientation` | `'vertical' \| 'horizontal'` | `'vertical'` | Layout direction (single-column layout only) | | `className` | `string` | — | Additional classes for the group container | ### RadioGroupOption | Field | Type | Default | Description | |-------|------|---------|-------------| | `value` | `string` | — | Option value (required) | | `label` | `string` | — | Label text (required) | | `description` | `string` | — | Secondary text below the label | | `icon` | `string` | — | KivaIcon identifier (e.g. `"fal star"`) | | `color` | `string` | — | Icon tint, or a colour dot when there is no icon. Tailwind colour name (`"blue"`, `"blue-500"`) or hex | | `disabled` | `boolean` | `false` | Disable this option | ### RadioGroupItem | Prop | Type | Default | Description | |------|------|---------|-------------| | `value` | `string` | — | Item value (required) | | `label` | `string` | — | Label text | | `description` | `string` | — | Secondary text below the label | | `icon` | `string` | — | KivaIcon identifier | | `color` | `string` | — | Icon tint / colour dot (Tailwind colour name or hex) | | `disabled` | `boolean` | `false` | Disable this item | | `className` | `string` | — | Additional classes for the pressable row / card | | `labelClassName` | `string` | — | Label classes | ## Components | Component | Description | |-----------|-------------| | `RadioGroup` | Root container — renders `options`, or provides context to `RadioGroupItem` children | | `RadioGroupItem` | Individual radio (row or card, depending on the group `variant`) | ## Type Exports | Type | Description | |------|-------------| | `RadioGroupProps` | Props for RadioGroup | | `RadioGroupItemProps` | Props for RadioGroupItem | | `RadioGroupOption` | Option shape for the `options` mode | | `RadioGroupSize` | `'sm' \| 'md' \| 'lg'` | | `RadioGroupOrientation` | `'vertical' \| 'horizontal'` | | `RadioGroupVariant` | `'default' \| 'card'` | | `RadioGroupColumnCount` | `1 \| 2 \| 3 \| 4 \| 5` | --- # rn-scroll-shadow URL: /docs/native/components/scroll-shadow ScrollView wrapper with animated gradient shadows indicating scrollable content. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-scroll-shadow ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) ## Usage ```tsx import { ScrollShadow } from '@/components/kiva-native/scroll-shadow'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `children` | `ReactNode` | — | Scrollable content | | `orientation` | `'horizontal' \| 'vertical'` | `'vertical'` | Scroll direction | | `shadowSize` | `number` | `40` | Shadow gradient size in px | | `className` | `string` | — | Additional classes | All `ScrollViewProps` are also accepted. ## Type Exports | Type | Description | |------|-------------| | `ScrollShadowProps` | Props for ScrollShadow | | `ScrollShadowOrientation` | `'horizontal' \| 'vertical'` | --- # rn-select URL: /docs/native/components/select Dropdown select component with modal picker for option selection. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-select ``` ## Usage ```tsx import { Select } from '@/components/kiva-native/select'; const options = [ { label: 'Apple', value: 'apple' }, { label: 'Banana', value: 'banana' }, { label: 'Cherry', value: 'cherry' }, ]; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `options` | `SelectOption[]` | — | Array of options (required) | | `value` | `string` | — | Selected option value | | `onValueChange` | `(value: string) => void` | — | Selection change handler | | `placeholder` | `string` | `'Select...'` (translated) | Placeholder text | | `disabled` | `boolean` | `false` | Disable interaction | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Trigger size | | `title` | `string` | — | Modal header title | | `className` | `string` | — | Trigger CSS classes | | `textClassName` | `string` | — | Trigger text CSS classes | | `accessibilityLabel` | `string` | — | Accessibility label | ### SelectOption | Property | Type | Description | |----------|------|-------------| | `label` | `string` | Display text | | `value` | `string` | Option value | | `disabled` | `boolean` | Disable this option | ## Translation Keys Built-in copy is read through `useUiTranslation()` — provide these keys via ``. Without a provider the English fallback is shown. | Key | English fallback | Used for | |-----|------------------|----------| | `ui.select.placeholder` | Select... | Trigger text when nothing is selected (`placeholder` prop wins) | | `ui.select.currentSelection` | Current selection | Hint under the selected option | | `ui.select.tapToChoose` | Tap to choose | Hint under the other options | ## Type Exports | Type | Description | |------|-------------| | `SelectProps` | Props for Select component | | `SelectOption` | Option item type | | `SelectSize` | `'sm' \| 'md' \| 'lg'` | --- # rn-separator URL: /docs/native/components/separator Visual divider component for horizontal or vertical separation. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-separator ``` ## Usage ```tsx import { Separator } from '@/components/kiva-native/separator'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `orientation` | `'horizontal' \| 'vertical'` | `'horizontal'` | Separator direction | | `color` | `string` | theme `border` | Custom color | | `thickness` | `number` | `1` | Line thickness | | `className` | `string` | — | Additional CSS classes | ## Type Exports | Type | Description | |------|-------------| | `SeparatorProps` | Props for Separator component | | `SeparatorOrientation` | `'horizontal' \| 'vertical'` | --- # rn-simple-markdown-editor URL: /docs/native/components/simple-markdown-editor Plain-text markdown editor with a formatting toolbar, optional rendered preview and word count. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-simple-markdown-editor ``` The web editor wraps the DOM-only `overtype` library. The native editor is a multiline `TextInput` with the same props. The toolbar applies markdown to the current selection: | Button | Result | |--------|--------| | Bold / Italic / Strikethrough / Code | Wraps the selection in `**` / `_` / `~~` / `` ` `` (inserts a placeholder when nothing is selected) | | Link | `[text](https://)` | | Heading / Bulleted list / Numbered list / Quote | Adds or removes `## ` / `- ` / `1. ` / `> ` on every selected line | `preview` renders the markdown with the shared native markdown renderer: `true` shows it under the input, `'toggle'` adds Write / Preview tabs. Live syntax highlighting (overtype's overlay) is not available on native. ## Usage ```tsx import { SimpleMarkdownEditor } from '@/components/kiva-native/simple-markdown-editor'; const [value, setValue] = useState(''); ``` ```tsx ``` ### Ref ```tsx const editorRef = useRef(null); editorRef.current?.insertText('@Alice '); editorRef.current?.getInput(); // the underlying TextInput ``` | Method | Description | |--------|-------------| | `focus()` / `blur()` | Focus control | | `getValue()` / `setValue(value)` | Read / replace the markdown | | `insertText(text)` | Insert at the caret, replacing the selection | | `getInput()` | Underlying `TextInput` (web: `getTextarea()`) | ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `ref` | `Ref` | - | focus / blur / getValue / setValue / insertText / getInput | | `value` | `string` | - | Controlled markdown value | | `defaultValue` | `string` | - | Uncontrolled initial value | | `onValueChange` | `(value: string) => void` | - | Change callback | | `variant` | `'default' \| 'muted'` | `'default'` | Visual style | | `size` | `'sm' \| 'default' \| 'lg'` | `'default'` | Size (min heights 180 / 240 / 320) | | `toolbar` | `boolean` | `true` | Show the formatting toolbar | | `showStats` | `boolean` | `false` | Show a words / characters footer | | `autoResize` | `boolean` | `false` | Grow with content between minHeight and maxHeight | | `minHeight` | `number \| string` | `by size` | Minimum editor height | | `maxHeight` | `number \| string \| null` | `null` | Maximum editor height | | `lineHeight` | `number` | `1.6` | Line-height multiplier | | `fontSize` | `number \| string` | `14 (16 for lg)` | Font size | | `placeholder` | `string` | `'Write markdown…'` | Placeholder | | `spellcheck` | `boolean` | `false` | Maps to spellCheck + autoCorrect | | `resizable` | `boolean` | - | Accepted for web parity — ignored | | `inputProps` | `Omit` | - | Extra TextInput props (web: textareaProps) | | `preview` | `boolean \| 'toggle'` | `false` | Rendered preview below the input (true) or Write / Preview tabs (toggle) | | `className` | `string` | - | Container classes | ## Helpers | Export | Description | |--------|-------------| | `wrapMarkdownSelection(value, selection, before, after?, placeholder?)` | Pure wrap transform used by the toolbar | | `prefixMarkdownLines(value, selection, prefix \| 'ordered')` | Pure line-prefix toggle used by the toolbar | ## Type Exports | Type | Description | |------|-------------| | `SimpleMarkdownEditorProps` | Props | | `SimpleMarkdownEditorRef` | Ref handle | | `SimpleMarkdownEditorVariant` / `SimpleMarkdownEditorSize` | Variant / size unions | | `MarkdownEdit` | `{ value, selection }` result of the helpers | ## Differences from web - `textareaProps` is `inputProps` (React Native `TextInputProps`). - `resizable` is accepted and ignored. Use `autoResize`. - The ref's `getTextarea()` is `getInput()`. - New `preview` prop. --- # rn-skeleton URL: /docs/native/components/skeleton Animated loading placeholders with card, list, table, and calendar presets. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-skeleton ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) ## Usage ```tsx import { SkeletonBase, SkeletonCard, SkeletonList, SkeletonTable, SkeletonCalendar } from '@/components/kiva-native/skeleton'; ``` ## API Reference ### SkeletonBase | Prop | Type | Default | Description | |------|------|---------|-------------| | `width` | `number \| string \| 'auto'` | `'100%'` | Element width (number for px, string for %) | | `height` | `number \| string \| 'auto'` | — | Element height (falls back to size preset) | | `variant` | `'default' \| 'light' \| 'dark'` | `'default'` | Background color variant | | `rounded` | `'none' \| 'sm' \| 'md' \| 'lg' \| 'full'` | `'md'` | Border radius preset | | `size` | `'xs' \| 'sm' \| 'md' \| 'lg' \| 'xl'` | `'md'` | Height preset when height is not set | | `animated` | `boolean` | `true` | Enable pulse animation | | `className` | `string` | — | Additional CSS classes | ### SkeletonCard | Prop | Type | Default | Description | |------|------|---------|-------------| | `showImage` | `boolean` | `true` | Show image placeholder | | `imageHeight` | `number` | `160` | Image placeholder height | | `lines` | `number` | `3` | Number of text line placeholders | | `variant` | `'default' \| 'light' \| 'dark'` | `'default'` | Color variant | | `className` | `string` | — | Additional CSS classes | ### SkeletonList | Prop | Type | Default | Description | |------|------|---------|-------------| | `items` | `number` | `5` | Number of list items | | `showAvatar` | `boolean` | `true` | Show avatar circle placeholder | | `showSubtitle` | `boolean` | `false` | Show subtitle line | | `showAction` | `boolean` | `false` | Show action button placeholder | | `variant` | `'default' \| 'light' \| 'dark'` | `'default'` | Color variant | | `className` | `string` | — | Additional CSS classes | ### SkeletonTable | Prop | Type | Default | Description | |------|------|---------|-------------| | `rows` | `number` | `5` | Number of table rows | | `columns` | `number` | `4` | Number of table columns | | `showHeader` | `boolean` | `true` | Show header row | | `variant` | `'default' \| 'light' \| 'dark'` | `'default'` | Color variant | | `className` | `string` | — | Additional CSS classes | ### SkeletonCalendar | Prop | Type | Default | Description | |------|------|---------|-------------| | `events` | `number` | `3` | Number of event placeholders | | `variant` | `'default' \| 'light' \| 'dark'` | `'default'` | Color variant | | `className` | `string` | — | Additional CSS classes | ## Components | Component | Description | |-----------|-------------| | `SkeletonBase` | Base animated skeleton element | | `SkeletonCard` | Card loading placeholder with image and text lines | | `SkeletonList` | List loading placeholder with avatar and text | | `SkeletonTable` | Table loading placeholder with header and rows | | `SkeletonCalendar` | Calendar loading placeholder with grid and events | ## Type Exports | Type | Description | |------|-------------| | `SkeletonBaseProps` | Props for SkeletonBase | | `SkeletonCardProps` | Props for SkeletonCard | | `SkeletonListProps` | Props for SkeletonList | | `SkeletonTableProps` | Props for SkeletonTable | | `SkeletonCalendarProps` | Props for SkeletonCalendar | | `SkeletonVariant` | `'default' \| 'light' \| 'dark'` | | `SkeletonRounded` | `'none' \| 'sm' \| 'md' \| 'lg' \| 'full'` | | `SkeletonSize` | `'xs' \| 'sm' \| 'md' \| 'lg' \| 'xl'` | --- # rn-slider URL: /docs/native/components/slider Draggable slider with custom range, step, tooltip, and track marks. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-slider ``` **Dependencies:** - [react-native-gesture-handler](https://www.npmjs.com/package/react-native-gesture-handler) - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) - [react-native-worklets](https://www.npmjs.com/package/react-native-worklets) ## Usage ```tsx import { Slider } from '@/components/kiva-native/slider'; setValue(v)} /> ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `value` | `number` | `0` | Current slider value | | `min` | `number` | `0` | Minimum value | | `max` | `number` | `100` | Maximum value | | `step` | `number` | `1` | Step increment | | `disabled` | `boolean` | `false` | Disabled state | | `showTooltip` | `boolean` | `false` | Show value tooltip while dragging | | `marks` | `boolean` | `false` | Show track marks | | `markInterval` | `number` | `25` | Interval between marks | | `formatTooltip` | `(value: number) => string` | — | Custom tooltip formatter | | `onValueChange` | `(value: number) => void` | — | Value change handler (while dragging) | | `onSlidingComplete` | `(value: number) => void` | — | Handler called when sliding ends | | `trackHeight` | `number` | `4` | Track height in pixels | | `thumbSize` | `number` | `20` | Thumb diameter in pixels | | `tintColor` | `string` | — | Custom fill color (overrides theme primary) | | `className` | `string` | — | Additional CSS classes | ## Type Exports | Type | Description | |------|-------------| | `SliderProps` | Props for Slider component | --- # rn-spinner URL: /docs/native/components/spinner Loading indicator component with size and variant options. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-spinner ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) - [react-native-svg](https://www.npmjs.com/package/react-native-svg) ## Usage ```tsx import { Spinner } from '@/components/kiva-native/spinner'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Spinner size | | `variant` | `'default' \| 'primary' \| 'secondary' \| 'destructive'` | `'default'` | Color variant | | `color` | `string` | — | Custom color (overrides variant) | | `speed` | `number` | `800` | Rotation speed in ms | | `children` | `ReactNode` | — | Custom spinner icon (replaces default SVG arc) | | `className` | `string` | — | Additional CSS classes | ## Type Exports | Type | Description | |------|-------------| | `SpinnerProps` | Props for Spinner component | | `SpinnerSize` | `'sm' \| 'md' \| 'lg'` | | `SpinnerVariant` | `'default' \| 'primary' \| 'secondary' \| 'destructive'` | --- # rn-switch URL: /docs/native/components/switch Toggle switch component with optional label and size variants. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-switch ``` ## Usage ```tsx import { Switch } from '@/components/kiva-native/switch'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `checked` | `boolean` | `false` | Switch state | | `onCheckedChange` | `(value: boolean) => void` | — | State change handler | | `disabled` | `boolean` | `false` | Disable interaction | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Switch size | | `label` | `string` | — | Optional label text | | `className` | `string` | — | Additional CSS classes | | `labelClassName` | `string` | — | Label CSS classes | | `accessibilityLabel` | `string` | — | Accessibility label | ## Type Exports | Type | Description | |------|-------------| | `SwitchProps` | Props for Switch component | | `SwitchSize` | `'sm' \| 'md' \| 'lg'` | --- # rn-table URL: /docs/native/components/table Lightweight data table with sorting, striped rows, grouping, and built-in pagination. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-table ``` ## Usage ```tsx import { Table } from '@/components/kiva-native/table'; type Product = { id: string; name: string; price: number }; const data: Product[] = [ { id: '1', name: 'Widget', price: 9.99 }, { id: '2', name: 'Gadget', price: 19.99 }, ]; item.id} /> ``` ### Striped & Bordered ```tsx
item.id} striped bordered /> ``` ### With Sorting ```tsx const [sortKey, setSortKey] = useState(); const [sortDir, setSortDir] = useState<'asc' | 'desc' | null>(null);
item.id} sortKey={sortKey} sortDirection={sortDir ?? undefined} onSort={(key, dir) => { setSortKey(key); setSortDir(dir); }} /> ``` ### With Pagination ```tsx
item.id} currentPage={page} totalPages={5} totalItems={50} pageSize={10} onPageChange={setPage} /> ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `data` | `T[]` | — | Array of data items to display | | `columns` | `TableColumn[]` | — | Column definitions | | `keyExtractor` | `(item: T) => string` | — | Function to extract unique key per row | | `sortKey` | `string` | — | Currently sorted column key | | `sortDirection` | `'asc' \| 'desc'` | — | Current sort direction | | `onSort` | `(key: string, direction: 'asc' \| 'desc' \| null) => void` | — | Sort change callback | | `striped` | `boolean` | `false` | Alternate row background colors | | `bordered` | `boolean` | `false` | Show column border lines | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Table cell padding and font size | | `groupBy` | `string` | — | Data key to group rows by | | `groupHeaderRender` | `(groupKey: string, items: T[]) => ReactNode` | — | Custom group header renderer | | `emptyMessage` | `string` | `'No data available'` | Message when data is empty | | `loading` | `boolean` | `false` | Show loading state | | `currentPage` | `number` | — | Current page for pagination | | `totalPages` | `number` | — | Total pages for pagination | | `totalItems` | `number` | — | Total item count for pagination info | | `pageSize` | `number` | — | Items per page for pagination info | | `onPageChange` | `(page: number) => void` | — | Page change callback | | `className` | `string` | — | Additional CSS classes | ### TableColumn\ | Prop | Type | Default | Description | |------|------|---------|-------------| | `key` | `string` | — | Data field key | | `title` | `string` | — | Column header text | | `width` | `number` | `120` | Column width in pixels | | `sortable` | `boolean` | `false` | Whether column is sortable | | `align` | `'left' \| 'center' \| 'right'` | `'left'` | Text alignment | | `render` | `(value: unknown, item: T, index: number) => ReactNode` | — | Custom cell renderer | ## Translation Keys Built-in copy is read through `useUiTranslation()` — provide these keys via ``. Without a provider the English fallback is shown. | Key | English fallback | Used for | |-----|------------------|----------| | `ui.table.loading` | Loading... | Loading row | | `ui.table.empty` | No data available | Empty text (`emptyMessage` prop wins) | ## Type Exports | Type | Description | |------|-------------| | `TableProps` | Props for Table component | | `TableColumn` | Column definition type | | `TableSize` | `'sm' \| 'md' \| 'lg'` | --- # rn-tabs URL: /docs/native/components/tabs Tabbed navigation with animated sliding indicator, horizontal/vertical orientation, and multiple visual variants. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-tabs ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) ## Usage ```tsx import { TabsRoot, TabsList, TabsTrigger, TabsContent } from '@/components/kiva-native/tabs'; ``` ## API Reference ### TabsRoot | Prop | Type | Default | Description | |------|------|---------|-------------| | `value` | `string` | — | Controlled active tab value | | `defaultValue` | `string` | — | Initial active tab value | | `onValueChange` | `(value: string) => void` | — | Callback when active tab changes | | `orientation` | `'horizontal' \| 'vertical'` | `'horizontal'` | Tab layout orientation | | `variant` | `'default' \| 'pills' \| 'underline'` | `'default'` | Visual style variant | | `children` | `ReactNode` | — | TabsList and TabsContent children | | `className` | `string` | — | Additional CSS classes | | `accessibilityLabel` | `string` | `'Tabs'` | Accessibility label for the tab list | ### TabsList | Prop | Type | Default | Description | |------|------|---------|-------------| | `scrollable` | `boolean` | `false` | Wrap triggers in a horizontal/vertical ScrollView | | `children` | `ReactNode` | — | TabsTrigger children | | `className` | `string` | — | List container CSS classes | ### TabsTrigger | Prop | Type | Default | Description | |------|------|---------|-------------| | `value` | `string` | — | Unique tab identifier (must match TabsContent value) | | `disabled` | `boolean` | `false` | Whether the trigger is disabled | | `textClassName` | `string` | — | Text CSS classes | | `children` | `ReactNode` | — | Trigger label | | `className` | `string` | — | Trigger CSS classes | ### TabsContent | Prop | Type | Default | Description | |------|------|---------|-------------| | `value` | `string` | — | Tab identifier (must match TabsTrigger value) | | `children` | `ReactNode` | — | Content to render when tab is active | | `className` | `string` | — | Content area CSS classes | ## Components | Component | Description | |-----------|-------------| | `TabsRoot` | Root container managing active tab state and context | | `TabsList` | Container for tab triggers with animated sliding indicator (Reanimated spring) | | `TabsTrigger` | Pressable tab button with layout measurement for indicator positioning | | `TabsContent` | Content panel with Reanimated fade-in/fade-out transitions | ## Type Exports | Type | Description | |------|-------------| | `TabsRootProps` | Props for TabsRoot component | | `TabsListProps` | Props for TabsList component | | `TabsTriggerProps` | Props for TabsTrigger component | | `TabsContentProps` | Props for TabsContent component | | `TabsOrientation` | `'horizontal' \| 'vertical'` | | `TabsVariant` | `'default' \| 'pills' \| 'underline'` | --- # rn-textarea URL: /docs/native/components/textarea Multi-line text input component with size variants and validation. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-textarea ``` ## Usage ```tsx import { Textarea } from '@/components/kiva-native/textarea'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Input size | | `disabled` | `boolean` | `false` | Disable interaction | | `invalid` | `boolean` | `false` | Show invalid state | | `rows` | `number` | `3` | Minimum visible rows | | `className` | `string` | — | Additional CSS classes | | `inputClassName` | `string` | — | TextInput CSS classes | All standard `TextInputProps` are also supported (except `style` and `multiline`). ## Type Exports | Type | Description | |------|-------------| | `TextareaProps` | Props for Textarea component | | `TextareaSize` | `'sm' \| 'md' \| 'lg'` | --- # rn-toast URL: /docs/native/components/toast Stackable toast notification system with rich colors, swipe-to-dismiss, and a Sonner-like imperative API. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-toast ``` **Dependencies:** - [react-native-gesture-handler](https://www.npmjs.com/package/react-native-gesture-handler) - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) - [react-native-worklets](https://www.npmjs.com/package/react-native-worklets) ## Usage Wrap your app with ` ); } // Fire toasts from anywhere toast.success('Changes saved'); toast.error('Upload failed'); toast.warning('Disk almost full'); toast.info('New update available'); toast.loading('Processing...'); ``` ## Toaster Props | Prop | Type | Default | Description | |------|------|---------|-------------| | `children` | `ReactNode` | — | App content to wrap | | `position` | `ToastPosition` | `'bottom-center'` | Default position for toasts | | `duration` | `number` | `4000` | Auto-dismiss duration in ms | | `gap` | `number` | `1` | Gap between stacked toasts | | `visibleToasts` | `number` | `3` | Maximum visible toast count | | `swipeDirection` | `'up' \| 'down' \| 'left' \| 'right'` | `'up'` | Swipe direction to dismiss | | `richColors` | `boolean` | `true` | Use colored backgrounds per variant | | `closeButton` | `boolean` | `false` | Show close button on all toasts | | `swipeThreshold` | `number` | `100` | Swipe distance to trigger dismiss | | `titleMaxLines` | `number` | `2` | Maximum title text lines | | `descMaxLines` | `number` | `3` | Maximum description text lines | | `variantColors` | `Partial>>` | — | Override default variant colors | ## ToastData Props | Prop | Type | Default | Description | |------|------|---------|-------------| | `id` | `string \| number` | — | Unique toast identifier (auto-generated) | | `type` | `'success' \| 'error' \| 'info' \| 'warning' \| 'default' \| 'loading'` | `'default'` | Toast variant type | | `title` | `ReactNode` | — | Toast title content | | `description` | `ReactNode` | — | Toast description content | | `duration` | `number` | `4000` | Auto-dismiss duration in ms | | `action` | `ToastAction` | — | Action button with label and onClick | | `icon` | `ReactNode` | — | Custom icon element | | `closeButton` | `boolean` | `false` | Show close button | | `important` | `boolean` | — | Prevent auto-dismiss | | `onDismiss` | `(toast: ToastData) => void` | — | Called when toast is dismissed | | `onAutoClose` | `(toast: ToastData) => void` | — | Called when toast auto-closes | | `dismissible` | `boolean` | `true` | Allow swipe-to-dismiss | | `position` | `ToastPosition` | — | Override default position for this toast | | `className` | `string` | — | Toast container CSS classes | | `titleLines` | `number` | — | Override title max lines | | `descLines` | `number` | — | Override description max lines | | `colors` | `Partial` | — | Override variant colors for this toast | ## Type Exports | Type | Description | |------|-------------| | `ToasterProps` | Props for Toaster provider component | | `ToastData` | Individual toast data object | | `ToastType` | `'success' \| 'error' \| 'info' \| 'warning' \| 'default' \| 'loading'` | | `ToastPosition` | `'top-center' \| 'bottom-center' \| 'top-left' \| 'top-right' \| 'bottom-left' \| 'bottom-right'` | | `ToastAction` | `{ label: string; onClick: () => void }` | | `ToastVariantColors` | `{ bg: string; fg: string; icon?: string; border?: string }` | --- # rn-toggle-group URL: /docs/native/components/toggle-group Segmented control component for single or multiple option selection. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-toggle-group ``` ## Usage ```tsx import { ToggleGroup, ToggleGroupItem } from '@/components/kiva-native/toggle-group'; ``` ## API Reference ### ToggleGroup | Prop | Type | Default | Description | |------|------|---------|-------------| | `type` | `'single' \| 'multiple'` | `'single'` | Selection mode | | `value` | `string \| string[]` | — | Selected value(s) | | `onValueChange` | `(value: string \| string[]) => void` | — | Value change handler | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Item size | | `variant` | `'default' \| 'outline'` | `'default'` | Visual variant | | `disabled` | `boolean` | `false` | Disable all items | | `children` | `ReactNode` | — | ToggleGroupItem elements | | `className` | `string` | — | Additional CSS classes | ### ToggleGroupItem | Prop | Type | Default | Description | |------|------|---------|-------------| | `value` | `string` | — | Item value (required) | | `children` | `ReactNode` | — | Item content | | `disabled` | `boolean` | `false` | Disable this item | | `className` | `string` | — | Item CSS classes | | `textClassName` | `string` | — | Text CSS classes | ## Components | Component | Description | |-----------|-------------| | `ToggleGroup` | Root container with context provider | | `ToggleGroupItem` | Individual toggle item | ## Type Exports | Type | Description | |------|-------------| | `ToggleGroupProps` | Props for ToggleGroup | | `ToggleGroupItemProps` | Props for ToggleGroupItem | | `ToggleGroupType` | `'single' \| 'multiple'` | | `ToggleGroupSize` | `'sm' \| 'md' \| 'lg'` | | `ToggleGroupVariant` | `'default' \| 'outline'` | --- # rn-toggle URL: /docs/native/components/toggle Toggle button component with pressed state and variant options. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-toggle ``` ## Usage ```tsx import { Toggle } from '@/components/kiva-native/toggle'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `pressed` | `boolean` | `false` | Toggle pressed state | | `onPressedChange` | `(pressed: boolean) => void` | — | State change handler | | `children` | `ReactNode` | — | Toggle content | | `variant` | `'default' \| 'outline'` | `'default'` | Visual style variant | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Toggle size | | `disabled` | `boolean` | `false` | Disable interaction | | `className` | `string` | — | Additional CSS classes | | `textClassName` | `string` | — | Text CSS classes | | `accessibilityLabel` | `string` | — | Accessibility label | ## Type Exports | Type | Description | |------|-------------| | `ToggleProps` | Props for Toggle component | | `ToggleVariant` | `'default' \| 'outline'` | | `ToggleSize` | `'sm' \| 'md' \| 'lg'` | --- # rn-tooltip URL: /docs/native/components/tooltip Contextual popup with configurable placement, arrow, and visual variants. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-tooltip ``` **Dependencies:** - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) ## Usage ```tsx import { Tooltip } from '@/components/kiva-native/tooltip'; ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `visible` | `boolean` | — | Controlled visibility state | | `defaultOpen` | `boolean` | `false` | Whether the tooltip is initially open | | `onOpenChange` | `(open: boolean) => void` | — | Callback when visibility changes | | `onClose` | `() => void` | — | Callback when tooltip closes | | `text` | `string` | — | Tooltip text content (required) | | `placement` | `'top' \| 'bottom' \| 'left' \| 'right' \| 'topLeft' \| 'topRight' \| 'bottomLeft' \| 'bottomRight'` | `'bottom'` | Tooltip position relative to the trigger | | `offset` | `number` | `8` | Distance from the trigger element in pixels | | `arrow` | `boolean` | `true` | Show directional arrow | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Tooltip padding and font size | | `variant` | `'default' \| 'dark' \| 'light'` | `'default'` | Visual style variant | | `delayHide` | `number` | `0` | Auto-hide delay in milliseconds (0 = manual close only) | | `maxWidth` | `number` | — | Maximum tooltip width | | `children` | `ReactNode` | — | Trigger element | | `className` | `string` | — | Tooltip bubble CSS classes | | `contentClassName` | `string` | — | Inner content container CSS classes | | `textClassName` | `string` | — | Tooltip text CSS classes | ## Type Exports | Type | Description | |------|-------------| | `TooltipProps` | Props for Tooltip component | | `TooltipPlacement` | `'top' \| 'bottom' \| 'left' \| 'right' \| 'topLeft' \| 'topRight' \| 'bottomLeft' \| 'bottomRight'` | | `TooltipSize` | `'sm' \| 'md' \| 'lg'` | | `TooltipVariant` | `'default' \| 'dark' \| 'light'` | --- # ActionSheet URL: /docs/native/expo/action-sheet iOS-style bottom sheet with gesture-driven interactions, multiple detents, and optional Liquid Glass effect. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-action-sheet ``` ```bash # Optional: expo-glass-effect (for Liquid Glass variant on iOS 26+) npx expo install expo-glass-effect ``` **Dependencies:** - [react-native-gesture-handler](https://www.npmjs.com/package/react-native-gesture-handler) - [react-native-reanimated](https://www.npmjs.com/package/react-native-reanimated) - [react-native-worklets](https://www.npmjs.com/package/react-native-worklets) - [expo-glass-effect](https://www.npmjs.com/package/expo-glass-effect) > **Note:** `expo-glass-effect` is optional. ActionSheet works fully without it — the `glass` variant gracefully falls back to the `default` variant when the module is not installed or when running on non-iOS 26+ devices. ## Usage ```tsx import { ActionSheet } from '@/components/kiva-native/action-sheet'; const [visible, setVisible] = useState(false); ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `visible` | `boolean` | — | Whether the sheet is visible | | `onClose` | `() => void` | — | Callback when the sheet is closed | | `sheetId` | `string` | — | Unique ID for programmatic control via `SheetManager` | | `variant` | `'default' \| 'elevated' \| 'minimal' \| 'glass'` | `'default'` | Sheet visual style variant | | `detent` | `'small' \| 'medium' \| 'large' \| 'fit'` | `'medium'` | Sheet height detent | | `detents` | `ActionSheetDetent[]` | — | Array of detents for multi-stop snapping | | `title` | `string` | — | Sheet header title | | `message` | `string` | — | Sheet header message below the title | | `actions` | `ActionSheetAction[]` | — | Array of action items to display | | `showCancel` | `boolean` | `true` | Show the cancel button at the bottom | | `cancelLabel` | `string` | `'Cancel'` | Custom label for the cancel button | | `showHandle` | `boolean` | `true` | Show the drag handle at the top | | `closeOnBackdrop` | `boolean` | `true` | Close when tapping the backdrop | | `glassEffectStyle` | `'regular' \| 'prominent' \| 'clear'` | — | Glass blur style (only with `variant="glass"`) | | `glassTintColor` | `string` | — | Glass tint color override (only with `variant="glass"`) | | `children` | `ReactNode` | — | Custom content instead of actions | | `className` | `string` | — | Additional CSS classes | ### ActionSheetAction | Prop | Type | Default | Description | |------|------|---------|-------------| | `key` | `string` | — | Unique identifier for the action | | `label` | `string` | — | Action button text | | `icon` | `string` | — | Emoji or text icon displayed before label | | `destructive` | `boolean` | `false` | Style as destructive (red text) | | `disabled` | `boolean` | `false` | Disable the action | | `onPress` | `() => void` | — | Callback when the action is pressed | ## Translation Keys Built-in copy is read through `useUiTranslation()` — provide these keys via ``. Without a provider the English fallback is shown. | Key | English fallback | Used for | |-----|------------------|----------| | `ui.common.cancel` | Cancel | Cancel button (`cancelLabel` prop wins) | ## Type Exports | Type | Description | |------|-------------| | `ActionSheetProps` | Props for ActionSheet component | | `ActionSheetAction` | Action item configuration | | `ActionSheetDetent` | `'small' \| 'medium' \| 'large' \| 'fit'` | ## Compatibility | Platform | Support | |----------|---------| | Expo Go | Yes (glass variant falls back to default) | | Dev Client | Yes | | Bare RN | Yes (glass variant requires expo-glass-effect config plugin) | --- # KivaFieldDateRange URL: /docs/native/expo/date-range Date range picker form field with start/end selector using native date picker. ## Overview `KivaFieldDateRange` provides a start and end date picker. On iOS it uses an ActionSheet with tab-based Start/End switching; on Android it opens sequential native date picker dialogs. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-form-fields ``` ```bash # Required: @react-native-community/datetimepicker npx expo install @react-native-community/datetimepicker ``` **Dependencies:** - [@react-native-community/datetimepicker](https://www.npmjs.com/package/@react-native-community/datetimepicker) ## Usage ```tsx import { KivaFieldDateRange } from '@/components/kiva-native/form-fields/kiva-field-date-range'; const [range, setRange] = useState<{ startDate: Date | null; endDate: Date | null; }>({ startDate: null, endDate: null }); ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `value` | `KivaFieldDateRangeValue` | `{ startDate: null, endDate: null }` | Start and end dates | | `onChange` | `(value: KivaFieldDateRangeValue) => void` | — | Called when value changes | | `onBlur` | `() => void` | — | Blur handler | | `onFocus` | `() => void` | — | Focus handler | | `minimumDate` | `Date` | — | Minimum selectable date | | `maximumDate` | `Date` | — | Maximum selectable date | | `dateFormat` | `'short' \| 'medium' \| 'long' \| 'full'` | `'medium'` | Date format preset | | `format` | `string` | — | Custom date pattern | | `separator` | `string` | `' – '` | Separator between start and end display | | `clearable` | `boolean` | `true` | Show clear button | | `allowSameDate` | `boolean` | `true` | Allow start and end to be the same date | | `calendarIcon` | `ReactNode` | — | Custom calendar icon | | `clearIcon` | `ReactNode` | — | Custom clear icon | | `iconSize` | `number` | `20` | Icon size in pixels | | `iconColor` | `string` | — | Icon color override | Inherits all [rn-form-fields](/docs/native/kiva/form-fields) (name, label, placeholder, helpText, required, disabled, readOnly, error, size, variant, etc.) ## Platform Behavior | Platform | Behavior | |----------|----------| | iOS | ActionSheet with Start/End tabs + spinner picker | | Android | Sequential native date picker dialogs | | Web | Fallback message (native picker not available) | ## Type Exports | Type | Description | |------|-------------| | `KivaFieldDateRangeValue` | `{ startDate: Date \| null; endDate: Date \| null }` | | `KivaFieldDateRangeProps` | Props for KivaFieldDateRange component | ## Compatibility | Platform | Support | |----------|---------| | Expo Go | Yes | | Dev Client | Yes | | Bare RN | Yes (auto-linked) | --- # KivaFieldDate URL: /docs/native/expo/date Native date/time picker form field using @react-native-community/datetimepicker. ## Overview `KivaFieldDate` provides a native date, time, or datetime picker. On iOS it uses an ActionSheet with a spinner picker; on Android it opens the native dialog. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-form-fields ``` ```bash # Required: @react-native-community/datetimepicker npx expo install @react-native-community/datetimepicker ``` **Dependencies:** - [@react-native-community/datetimepicker](https://www.npmjs.com/package/@react-native-community/datetimepicker) ## Usage ```tsx import { KivaFieldDate } from '@/components/kiva-native/form-fields/kiva-field-date'; const [date, setDate] = useState(null); ``` ### Time Picker ```tsx ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `value` | `Date \| null` | `null` | Selected date | | `onChange` | `(date: Date \| null) => void` | — | Called when date changes | | `onBlur` | `() => void` | — | Blur handler | | `onFocus` | `() => void` | — | Focus handler | | `mode` | `'date' \| 'datetime' \| 'time'` | `'date'` | Picker mode | | `minimumDate` | `Date` | — | Minimum selectable date | | `maximumDate` | `Date` | — | Maximum selectable date | | `dateFormat` | `'short' \| 'medium' \| 'long' \| 'full'` | `'medium'` | Date format preset | | `timeFormat` | `'12h' \| '24h'` | `'12h'` | Time format | | `format` | `string` | — | Custom pattern (e.g., `"dd/MM/yyyy HH:mm"`) | | `clearable` | `boolean` | `true` | Show clear button | | `calendarIcon` | `ReactNode` | — | Custom calendar icon | | `clearIcon` | `ReactNode` | — | Custom clear icon | | `iconSize` | `number` | `20` | Icon size in pixels | | `iconColor` | `string` | — | Icon color override | Inherits all [rn-form-fields](/docs/native/kiva/form-fields) (name, label, placeholder, helpText, required, disabled, readOnly, error, size, variant, etc.) ## Platform Behavior | Platform | Behavior | |----------|----------| | iOS | ActionSheet with spinner picker + Cancel/Done buttons | | Android | Native date picker dialog | | Web | Fallback message (native picker not available) | ## Type Exports | Type | Description | |------|-------------| | `KivaFieldDateProps` | Props for KivaFieldDate component | ## Compatibility | Platform | Support | |----------|---------| | Expo Go | Yes | | Dev Client | Yes | | Bare RN | Yes (auto-linked) | --- # KivaFieldDatetime URL: /docs/native/expo/datetime Combined date and time picker form field — thin wrapper around KivaFieldDate. ## Overview `KivaFieldDatetime` is a convenience wrapper around [`KivaFieldDate`](/docs/native/expo/date) with `mode="datetime"` always set. It presents both a date and time picker in a single interaction. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-form-fields ``` ```bash # Required: @react-native-community/datetimepicker npx expo install @react-native-community/datetimepicker ``` **Dependencies:** - [@react-native-community/datetimepicker](https://www.npmjs.com/package/@react-native-community/datetimepicker) ## Usage ```tsx import { KivaFieldDatetime } from '@/components/kiva-native/form-fields/kiva-field-datetime'; const [dateTime, setDateTime] = useState(null); ``` ## API Reference All props from [`KivaFieldDate`](/docs/native/expo/date) except `mode` (always `'datetime'`). | Prop | Type | Default | Description | |------|------|---------|-------------| | `value` | `Date \| null` | `null` | Selected date and time | | `onChange` | `(date: Date \| null) => void` | — | Called when value changes | | `minimumDate` | `Date` | — | Minimum selectable date | | `maximumDate` | `Date` | — | Maximum selectable date | | `dateFormat` | `'short' \| 'medium' \| 'long' \| 'full'` | `'medium'` | Date format preset | | `timeFormat` | `'12h' \| '24h'` | `'12h'` | Time format | | `clearable` | `boolean` | `true` | Show clear button | Inherits all [rn-form-fields](/docs/native/kiva/form-fields) (name, label, placeholder, helpText, required, disabled, readOnly, error, size, variant, etc.) ## Type Exports | Type | Description | |------|-------------| | `KivaFieldDatetimeProps` | `Omit` | --- # Expo & Native Modules URL: /docs/native/expo Components that require Expo SDK modules or community native modules as additional dependencies. ## Overview Some `@kivacore/ui-native` components depend on **Expo SDK modules** or **community native modules** for platform-specific features like file picking, date/time pickers, geolocation, or glass effects. These components work in Expo managed workflow projects and require the listed packages as additional dependencies. If you're using a **bare React Native** project (without Expo), community native modules will auto-link, but Expo SDK modules require manual installation. ## Expo SDK Modules | Component | Module | Purpose | |-----------|--------|---------| | [`ActionSheet`](/docs/native/expo/action-sheet) | `expo-glass-effect` | iOS Liquid Glass bottom sheet variant (iOS 26+) | | [`KivaFieldUpload`](/docs/native/expo/upload) | `expo-document-picker` | File picking from device storage | ```bash # expo-glass-effect (for ActionSheet glass variant, optional) npx expo install expo-glass-effect # expo-document-picker (for KivaFieldUpload) npx expo install expo-document-picker ``` ## Community Native Modules | Component | Module | Purpose | |-----------|--------|---------| | [`KivaFieldDate`](/docs/native/expo/date) | `@react-native-community/datetimepicker` | Native date/time picker (iOS spinner, Android dialog) | | [`KivaFieldDatetime`](/docs/native/expo/datetime) | `@react-native-community/datetimepicker` | Combined date & time picker | | [`KivaFieldDateRange`](/docs/native/expo/date-range) | `@react-native-community/datetimepicker` | Date range picker with start/end selector | | [`KivaFieldLocationSelect`](/docs/native/expo/location-select) | `@react-native-community/geolocation` + `react-native-geocoding` | Device GPS location + reverse geocoding | | `localize` utilities | `react-native-localize` | Device locale, timezone, 24h clock detection | ```bash # @react-native-community/datetimepicker (for KivaFieldDate, KivaFieldDatetime, KivaFieldDateRange) npx expo install @react-native-community/datetimepicker # @react-native-community/geolocation (for KivaFieldLocationSelect) npx expo install @react-native-community/geolocation # react-native-geocoding (for KivaFieldLocationSelect reverse geocoding) npm install react-native-geocoding # react-native-localize (for enhanced locale detection in localize utilities) npx expo install react-native-localize ``` ## Compatibility | Module | Expo Go | Dev Client | Bare RN | |--------|---------|------------|---------| | `expo-glass-effect` | Yes | Yes | Requires config plugin | | `expo-document-picker` | Yes | Yes | Requires config plugin | | `@react-native-community/datetimepicker` | Yes | Yes | Yes (auto-linked) | | `@react-native-community/geolocation` | No | Yes | Yes (auto-linked) | | `react-native-geocoding` | Yes (JS only) | Yes | Yes | | `react-native-localize` | Yes | Yes | Yes (auto-linked) | All modules listed here are declared as **optional peer dependencies** in `@kivacore/ui-native`. Components gracefully handle missing modules at runtime — they won't crash your app if the module isn't installed, but the related functionality will be unavailable. --- # Localize Utilities URL: /docs/native/expo/localize Device locale, timezone, and formatting utilities with react-native-localize fallback. ## Overview The `localize` module provides device locale detection, timezone, date/number/currency formatting, and measurement system detection. It requires `react-native-localize` for accurate native locale data and falls back to `Intl` APIs when unavailable. ## Installation ```bash npx expo install react-native-localize ``` **Dependencies:** - [react-native-localize](https://www.npmjs.com/package/react-native-localize) ### Expo Configuration Add `react-native-localize` as a plugin in your `app.config.ts` with the locales your app supports: ```ts { plugins: [ [ 'react-native-localize', { locales: ['en', 'tr', 'de', 'fr'] } ] ] } ``` > **Note:** Without this plugin config, locale detection may not work correctly on iOS. The `locales` array determines which languages your app declares support for. ## Usage ```tsx import { getDeviceLocale, getDeviceLanguage, getDeviceCountry, getDeviceTimeZone, uses24HourClock, usesMetricSystem, formatDate, formatNumber, formatCurrency, } from '@/lib/kiva/localize'; // Device info const locale = getDeviceLocale(); // 'tr-TR' const lang = getDeviceLanguage(); // 'tr' const country = getDeviceCountry(); // 'TR' const tz = getDeviceTimeZone(); // 'Europe/Istanbul' const is24h = uses24HourClock(); // true const metric = usesMetricSystem(); // true // Formatting formatDate(new Date(), { dateStyle: 'long' }); // '5 Mart 2026' formatNumber(1234.56); // '1.234,56' formatCurrency(99.99, 'TRY'); // '₺99,99' ``` ## API Reference ### Device Info | Function | Return Type | Description | |----------|-------------|-------------| | `getDeviceLocale()` | `string` | Full locale tag (e.g., `'tr-TR'`). Falls back to `'en-US'` | | `getDeviceLanguage()` | `string` | Language code (e.g., `'tr'`). Falls back to `'en'` | | `getDeviceCountry()` | `string \| undefined` | Country code (e.g., `'TR'`) | | `getDeviceTimeZone()` | `string` | IANA timezone (e.g., `'Europe/Istanbul'`). Falls back to `'UTC'` | | `uses24HourClock()` | `boolean` | Whether device uses 24-hour clock | | `usesMetricSystem()` | `boolean` | Whether device uses metric system | | `getPreferredLocales()` | `string[]` | All preferred locale tags | ### Formatting | Function | Parameters | Description | |----------|-----------|-------------| | `formatNumber(value, options?, locale?)` | `number, Intl.NumberFormatOptions?, string?` | Locale-aware number formatting | | `formatDate(date, options?, locale?)` | `Date, Intl.DateTimeFormatOptions?, string?` | Locale-aware date formatting | | `formatCurrency(value, currencyCode?, locale?)` | `number, string?, string?` | Currency formatting (default: `'USD'`) | | `getCurrencySymbol(currencyCode)` | `string` | Get currency symbol (e.g., `'₺'` for `'TRY'`) | ## Fallback Behavior | Feature | With `react-native-localize` | Without (Intl fallback) | |---------|------------------------------|------------------------| | Locale detection | Device's preferred locale list | `Intl.DateTimeFormat` resolved locale | | Timezone | `RNLocalize.getTimeZone()` | `Intl.DateTimeFormat` resolved timezone | | 24h clock | `RNLocalize.uses24HourClock()` | AM/PM presence check | | Metric system | `RNLocalize.usesMetricSystem()` | Country code heuristic (US, LR, MM → imperial) | ## Compatibility | Platform | Support | |----------|---------| | Expo Go | Yes | | Dev Client | Yes | | Bare RN | Yes (auto-linked) | --- # Location Select URL: /docs/native/expo/location-select Location picker field with device geolocation and reverse geocoding support. ## Overview `KivaFieldLocationSelect` uses **community native modules** for device-specific location features: - **`@react-native-community/geolocation`** — Access device GPS to get current coordinates - **`react-native-geocoding`** — Reverse geocode coordinates to human-readable addresses (requires Google Maps API key) Without these modules installed, the location picker still works with manual text search and predefined locations — but the "Use Current Location" button will be unavailable. ## Installation ```bash # Geolocation (for "Use Current Location" feature) npx expo install @react-native-community/geolocation # Reverse geocoding (for converting coordinates to addresses) npm install react-native-geocoding ``` ### Google Maps API Key Reverse geocoding requires a Google Maps Geocoding API key. Pass it as a prop or set the `EXPO_PUBLIC_GOOGLE_MAPS_API_KEY` environment variable: ```tsx ``` ## Compatibility | Module | Expo Go | Dev Client | Bare RN | |--------|---------|------------|---------| | `@react-native-community/geolocation` | No | Yes | Yes (auto-linked) | | `react-native-geocoding` | Yes (JS only) | Yes | Yes | > **Note:** `@react-native-community/geolocation` requires a **development build** — it does not work in Expo Go. The component handles this gracefully at runtime. ## Usage ```tsx import { KivaFieldLocationSelect } from '@/components/kiva-native/form-fields/kiva-field-location-select'; { // Your permission handling logic return 'granted'; }} onChange={(location) => console.log(location)} /> ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `value` | `LocationInfo` | — | Current location value | | `onChange` | `(value: LocationInfo) => void` | — | Called when location changes | | `placeholder` | `string` | `'Select location'` | Placeholder text | | `allowCurrentLocation` | `boolean` | `true` | Show "Use Current Location" button | | `showCoordinates` | `boolean` | `true` | Show coordinates under location items | | `predefinedLocations` | `LocationInfo[]` | Popular cities | Custom location list | | `requestLocationPermission` | `() => Promise<'granted' \| 'denied'>` | — | Permission request callback | | `googleMapsApiKey` | `string` | `EXPO_PUBLIC_GOOGLE_MAPS_API_KEY` | Google Maps API key for geocoding | ### LocationInfo Type | Field | Type | Description | |-------|------|-------------| | `name` | `string` | Display name | | `address` | `string?` | Full address | | `coordinates` | `{ latitude: number; longitude: number }?` | GPS coordinates | | `country` | `string?` | Country name | | `city` | `string?` | City name | | `region` | `string?` | Region/state | | `postalCode` | `string?` | Postal code | | `type` | `'current' \| 'saved' \| 'search'?` | Location source | --- # Speech Recognition URL: /docs/native/expo/speech-recognition Setting up expo-speech-recognition for useSpeechRecognition and the KivaAgent microphone button. ## Overview [`useSpeechRecognition`](/docs/native/hooks/use-speech-recognition) and the KivaAgent mic button (`KivaAgentChatInputMicButton` / `KivaAgentChatInputMic`) use `expo-speech-recognition`. It is an **optional peer**: without it (and always in **Expo Go**, which cannot load its native code) the hook reports `isSupported: false` and the mic button is hidden, so the rest of the chat keeps working. ## Installation ```bash npx expo install expo-speech-recognition ``` **Dependencies:** - [expo-speech-recognition](https://www.npmjs.com/package/expo-speech-recognition) ### Expo Configuration Add the config plugin, then create a development build (`npx expo run:ios` / `eas build --profile development`): ```ts { plugins: [ [ 'expo-speech-recognition', { microphonePermission: 'Allow $(PRODUCT_NAME) to use the microphone for voice prompts.', speechRecognitionPermission: 'Allow $(PRODUCT_NAME) to transcribe your voice prompts.' } ] ] } ``` The plugin writes `NSMicrophoneUsageDescription` / `NSSpeechRecognitionUsageDescription` on iOS and `RECORD_AUDIO` on Android. Permissions are requested on the first `start()`. ## Behaviour | Situation | `isSupported` | Mic button | |-----------|---------------|------------| | Dev / production build with the module | `true` | Visible | | Expo Go | `false` | Hidden | | Module not installed | `false` | Hidden | | Device reports recognition unavailable | `false` | Hidden | | Permission denied | `true` (`error = 'not-allowed'`) | Visible, recording doesn't start | --- # KivaFieldUpload URL: /docs/native/expo/upload File upload form field using expo-document-picker for native file selection. ## Overview `KivaFieldUpload` provides a native file picker using `expo-document-picker`. Users can select single or multiple files from device storage with configurable file type filters and size limits. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-form-fields ``` ```bash # Required: expo-document-picker npx expo install expo-document-picker ``` **Dependencies:** - [expo-document-picker](https://www.npmjs.com/package/expo-document-picker) ## Usage ```tsx import { KivaFieldUpload } from '@/components/kiva-native/form-fields/kiva-field-upload'; console.log(files)} /> ``` ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `value` | `UploadedFile[]` | `[]` | Array of uploaded files | | `onChange` | `(files: UploadedFile[]) => void` | — | Called when files change | | `maxFiles` | `number` | `10` | Maximum number of files allowed | | `maxSizeBytes` | `number` | — | Max size per file in bytes | | `allowedTypes` | `string[]` | `['*/*']` | MIME type filters | | `onUpload` | `(files: UploadedFile[]) => Promise` | — | Optional upload handler | | `uploadLabel` | `string` | `'Select files'` | Custom button label | Inherits all [rn-form-fields](/docs/native/kiva/form-fields) (name, label, placeholder, helpText, required, disabled, readOnly, error, size, variant, etc.) ## Type Exports | Type | Description | |------|-------------| | `UploadedFile` | `{ uri: string; name: string; size: number; mimeType: string }` | | `KivaFieldUploadProps` | Props for KivaFieldUpload component | ## Compatibility | Platform | Support | |----------|---------| | Expo Go | Yes | | Dev Client | Yes | | Bare RN | Requires config plugin | --- # Distributions URL: /docs/native/guide/distributions Core libraries that power Kiva UI native components. Kiva UI native components are built on top of the React Native and Expo ecosystems. Most dependencies are **optional peer dependencies** — you only need to install them if you use the components that require them. ## Core Libraries | Library | Description | Used In | |---------|-------------|---------| | [TanStack Table](https://tanstack.com/table) | Headless table library with sorting, filtering, grouping, and virtualization. | Data Table | | [JSONata](https://jsonata.org) | Lightweight query and transformation language for JSON data. | Pivot Grid | ## UI & Graphics | Library | Description | Required | |---------|-------------|----------| | [React Native SVG](https://github.com/software-mansion/react-native-svg) | SVG support for icons, charts, and vector graphics. | Optional | | [React Native Safe Area Context](https://github.com/th3rdwave/react-native-safe-area-context) | Safe area insets for notches and system bars. | Optional | | [React Native QRCode SVG](https://github.com/nicholaslee119/react-native-qrcode-svg) | QR code generation as SVG. | Optional | | [Expo Glass Effect](https://docs.expo.dev/versions/latest/sdk/glass-effect) | Glassmorphism blur effects for overlays and panels. | Optional | ## Animation & Gestures | Library | Description | Required | |---------|-------------|----------| | [React Native Reanimated](https://docs.swmansion.com/react-native-reanimated) | High-performance animation library running on the UI thread. | Optional | | [React Native Gesture Handler](https://docs.swmansion.com/react-native-gesture-handler) | Native gesture system for swipe, pinch, and drag interactions. | Optional | | [React Native Worklets](https://github.com/nicholasgasior/react-native-worklets) | Worklet runtime for running JS on the UI thread. | Optional | ## Expo Modules | Module | Description | Required | |--------|-------------|----------| | [Expo Document Picker](https://docs.expo.dev/versions/latest/sdk/document-picker) | Native file picker with multi-file support. | Optional | | [Expo File System](https://docs.expo.dev/versions/latest/sdk/filesystem) | File system access for reading, writing, and managing files. | Optional | | [Expo Sharing](https://docs.expo.dev/versions/latest/sdk/sharing) | Native share dialog for sharing files and content. | Optional | ## Maps & Location | Library | Description | Required | |---------|-------------|----------| | [React Native Maps](https://github.com/react-native-maps/react-native-maps) | Google Maps and Apple Maps integration for React Native. | Optional | | [@react-native-community/geolocation](https://github.com/michalchudziak/react-native-geolocation) | Geolocation API for accessing device location. | Optional | | [React Native Geocoding](https://github.com/marlove/react-native-geocoding) | Geocoding and reverse geocoding services. | Optional | ## Date & Localization | Module | Description | Required | |--------|-------------|----------| | [DateTimePicker](https://github.com/react-native-datetimepicker/datetimepicker) | Native date and time picker for iOS and Android. | Optional | | [React Native Localize](https://github.com/zoontek/react-native-localize) | Locale detection and internationalization utilities. | Optional | --- # Examples & Recipes URL: /docs/native/guide/examples Practical patterns and recipes for building React Native apps with Kiva UI Native. Real-world patterns that combine multiple Kiva UI Native components. These examples assume you have the Expo + Kiva UI Native setup from the [installation guide](/docs/native/guide/installation). ## List with Search and Filters A searchable list view with pull-to-refresh and empty state handling: ```tsx import { useState, useCallback } from 'react'; import { View, FlatList, RefreshControl } from 'react-native'; import { SearchInput } from '@/components/kiva-native/search-input'; import { ListBox } from '@/components/kiva-native/list-box'; import { EmptyState } from '@/components/kiva-native/empty-state'; import { Badge } from '@/components/kiva-native/badge'; import { Spinner } from '@/components/kiva-native/spinner'; export function ContactList() { const [search, setSearch] = useState(''); const [refreshing, setRefreshing] = useState(false); const filtered = contacts.filter((c) => c.name.toLowerCase().includes(search.toLowerCase()) ); const onRefresh = useCallback(async () => { setRefreshing(true); await fetchContacts(); setRefreshing(false); }, []); return ( {filtered.length === 0 ? ( ) : ( } onPress={() => router.push(`/contact/${item.id}`)} /> )} /> )} ); } ``` ## Form Screen A multi-field form with validation using Kiva form fields: ```tsx import { View, ScrollView, KeyboardAvoidingView, Platform } from 'react-native'; import { Input } from '@/components/kiva-native/input'; import { Textarea } from '@/components/kiva-native/textarea'; import { Select } from '@/components/kiva-native/select'; import { Switch } from '@/components/kiva-native/switch'; import { Button } from '@/components/kiva-native/button'; import { Label } from '@/components/kiva-native/label'; const priorities = [ { label: 'Low', value: 'low' }, { label: 'Medium', value: 'medium' }, { label: 'High', value: 'high' }, ]; export function CreateTaskScreen() { const [title, setTitle] = useState(''); const [description, setDescription] = useState(''); const [priority, setPriority] = useState('medium'); const [notify, setNotify] = useState(true); return ( ); } ``` ## Dashboard with Stats and Charts A mobile dashboard combining stats cards, charts, and quick actions: ```tsx import { ScrollView, View } from 'react-native'; import { AwesomeStats } from '@/components/kiva-native/awesome-stats'; import { AwesomeCard } from '@/components/kiva-native/awesome-card'; import { Button } from '@/components/kiva-native/button'; import { Badge } from '@/components/kiva-native/badge'; import { Separator } from '@/components/kiva-native/separator'; export function DashboardScreen() { return ( {/* Quick actions */} {/* Recent activity */} ))} ); } ``` ## Data Table with Actions A native data table with sorting, row actions, and delete confirmation: ```tsx import { View } from 'react-native'; import { DataTable } from '@/components/kiva-native/data-table'; import { DeleteConfirmDialog } from '@/components/kiva-native/delete-confirm-dialog'; import { ActionSheet } from '@/components/kiva-native/action-sheet'; import { Toast } from '@/components/kiva-native/toast'; export function ProductsScreen() { const [deleteId, setDeleteId] = useState(null); const [actionItem, setActionItem] = useState ); } ``` ## Tab Navigation with Stepper Multi-step wizard flow using tabs and a stepper component: ```tsx import { useState } from 'react'; import { View, ScrollView } from 'react-native'; import { Tabs } from '@/components/kiva-native/tabs'; import { Stepper } from '@/components/kiva-native/stepper'; import { Button } from '@/components/kiva-native/button'; import { Input } from '@/components/kiva-native/input'; import { Label } from '@/components/kiva-native/label'; const steps = [ { title: 'Account', description: 'Basic info' }, { title: 'Profile', description: 'Your details' }, { title: 'Review', description: 'Confirm' }, ]; export function OnboardingScreen() { const [step, setStep] = useState(0); return ( )} {step === 1 && ( )} {step === 2 && ( )} )} ); } ``` ## Related - [Installation](/docs/native/guide/installation) — Set up Kiva UI Native in your Expo project - [Components](/docs/native/components) — Browse all native components - [Theming](/docs/native/guide/theming) — Customize the native theme --- # Installation URL: /docs/native/guide/installation How to install and set up Kiva UI native components in your Expo project. ## Preview App Install Scan the QR code to open the Expo install page. This installs the latest internal development build on a provisioned device. ## Prerequisites Kiva UI native components require an Expo project with React Native. Make sure your environment meets these requirements: | Dependency | Minimum Version | |---|---| | React | 19 | | React Native | 0.86 | | Expo SDK | 57 | | Node.js | 18 | ## Install the CLI Install the Kiva UI CLI globally or use it via npx: ```bash npm install -g @kivacore/ui-cli ``` ## Add native components Install native components using the `rn-` prefix: ```bash # Install a native component npx @kivacore/ui-cli add rn-button # Install multiple native components npx @kivacore/ui-cli add rn-button rn-input rn-card # Install all native components npx @kivacore/ui-cli add --all-rn ``` Components are installed to your `components/kiva-native/` directory. ## Install peer dependencies Native components require Tailwind CSS v4 for React Native via **Uniwind**, plus common React Native libraries: ```bash # Tailwind CSS v4 for React Native (required) npx expo install uniwind tailwindcss # Common peer dependencies npx expo install react-native-svg npx expo install react-native-reanimated react-native-worklets npx expo install react-native-gesture-handler react-native-safe-area-context ``` Kiva-connected components and every `rn-hooks-*` hook also need `@tanstack/react-query` (a required peer). Other native modules — `expo-file-system`, `expo-sharing`, `expo-print`, `expo-clipboard`, `expo-image-picker`, `react-native-maps`, `react-native-webview`, `expo-speech-recognition`, … — are **optional peers**: components load them lazily and degrade gracefully when they are missing. The CLI writes the peers a component needs into your `peerDependencies`; install them with `npx expo install `. Component styling also uses these packages (installed automatically by the CLI): ```bash npm install tailwind-variants clsx tailwind-merge ``` ## Set up Uniwind Kiva Native components use `className` prop for styling via Uniwind — a build-time Tailwind CSS v4 integration for React Native. ### 1. Configure Metro Add the Uniwind Metro plugin to your `metro.config.js`: ```js title="metro.config.js" const { getDefaultConfig } = require('expo/metro-config'); const { withUniwindConfig } = require('uniwind/metro'); const config = getDefaultConfig(__dirname); module.exports = withUniwindConfig(config, { cssEntryFile: './src/styles/global.css', // Kiva components are designed on a 14px rem (text-sm, text-base, …) polyfills: { rem: 14 } }); ``` ### 2. Create global CSS Create a `src/styles/global.css` file with Tailwind, Uniwind and the Kiva design tokens: ```css title="src/styles/global.css" @import "tailwindcss"; @import "uniwind"; @import "./kiva-native/index.css"; ``` The last line is **required**. Every native component is styled with semantic tokens (`bg-background`, `text-muted-foreground`, `border-field-border`, `bg-success-soft`, …) that are only defined by this file — without it components render transparent and unstyled. The CLI installs it with the first native component (the `@kivacore/rn-styles` item every `rn-*` component depends on) at `src/styles/kiva-native/index.css` (`styles/kiva-native/` in the project root when there is no `src/`). It defines spacing, radius, font and light/dark color tokens; Uniwind follows the device appearance automatically. See [Theming](/docs/native/guide/theming#design-tokens) for the token list, overrides and the optional color schemes. The tokens set `--font-sans` to Inter (`Inter_400Regular`, `Inter_500Medium`, …). Load those fonts with `@expo-google-fonts/inter` (`useFonts`), or override `--font-sans*` in an `@theme` block after the import. ### 3. Import in your app entry Import the global CSS at the top of your root layout: ```tsx title="app/_layout.tsx" import '../styles/global.css'; import { KivaThemeProvider } from '@/lib/kiva/theme'; export default function RootLayout() { return ( ); } ``` ## Set up the theme Wrap your app with `KivaThemeProvider` at the root level. See the [Theming](/docs/native/guide/theming) guide for full configuration options. ```tsx title="app/_layout.tsx" import { KivaThemeProvider } from '@/lib/kiva/theme'; export default function RootLayout() { return ( ); } ``` ## Keyboard handling (recommended) Form components like Input, Textarea, and Modal work best with `react-native-keyboard-controller`. It prevents inputs from being hidden behind the keyboard and provides smooth animated transitions. ```bash npx expo install react-native-keyboard-controller ``` Wrap your app with `KeyboardProvider` at the root level: ```tsx title="app/_layout.tsx" import '../styles/global.css'; import { KeyboardProvider } from 'react-native-keyboard-controller'; import { KivaThemeProvider } from '@/lib/kiva/theme'; export default function RootLayout() { return ( ); } ``` Once the provider is active, all screens — including modals with `KeyboardAvoidingView` — automatically benefit from improved keyboard behavior. ## Set up the Kiva data layer Skip this section if you only use presentational components. Kiva-connected components (data grid, form view, calendar, kanban, composers, …) and the [native hooks](/docs/native/hooks) need a few providers near the root: ```tsx title="app/_layout.tsx" import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { GestureHandlerRootView } from 'react-native-gesture-handler'; import Storage from 'expo-sqlite/kv-store'; import { KivaStorageProvider, type KivaKeyValueStore } from '@/lib/kiva/storage'; import { UiTranslationProvider } from '@/hooks/kiva-native/use-ui-translation'; import { KivaTenantProvider } from '@/hooks/kiva-native/use-kiva-tenant'; const queryClient = new QueryClient(); // Synchronous key-value backend for view-parameter persistence, saved views, recents, … const store: KivaKeyValueStore = { getItem: key => Storage.getItemSync(key), setItem: (key, value) => Storage.setItemSync(key, value), removeItem: key => Storage.removeItemSync(key) }; export function KivaProviders({ client, authReady, t, children }) { return ( ); } ``` - **`QueryClientProvider`** — required by every `use-kiva-*` hook. - **`KivaTenantProvider`** — tenant date / number formats for every grid cell, value renderer and calendar ([docs](/docs/native/hooks/use-kiva-tenant)). - **`KivaStorageProvider`** — persistent backend for `persistState` and the active saved view ([docs](/docs/native/hooks/use-parameter-persistence)). Without it state lives in memory for the process lifetime. - **`UiTranslationProvider`** — optional; without it components render their English fallbacks ([docs](/docs/native/hooks/use-ui-translation)). - **`GestureHandlerRootView`** — required by the calendar, notification stack, tree view drag and image editor. - Warm the shared inventory cache after sign-in with [`useKivaInventoryLoader`](/docs/native/hooks/use-kiva-inventory). Some optional peers need a development build (they are not in Expo Go): `react-native-enriched-html` (email composer rich body) and `expo-speech-recognition` (add its config plugin to `app.config.ts`). `react-native-maps` works in Expo Go, but an Android development build needs a Google Maps API key (`android.config.googleMaps.apiKey`). ## Import and use Once installed, import native components and use them in your screens. All components accept a `className` prop for Tailwind-based styling: ```tsx title="app/index.tsx" import { View } from 'react-native'; import { Button } from '@/components/kiva-native/button'; export default function Home() { return ( ); } ``` Components are installed as source code — you can freely modify, extend, or restyle them to fit your needs. --- # Releases URL: /docs/native/guide/releases Latest releases and updates for Kiva UI Native components. Track the latest changes, features, and bug fixes for the `@kivacore/ui-native` React Native component library. ## Migration guide The web-parity release of `@kivacore/ui-native` is a breaking (major) release. The [migration guide](https://github.com/Kivacore/kiva-ui/blob/alpha/packages/ui-native/MIGRATION.md) covers the required app setup, peer dependencies, the i18n change and the breaking changes per component. --- # RN Assistant URL: /docs/native/guide/rn-assistant Install, configure, and integrate KivaRNAssistant in an Expo or React Native app. [npm version](https://www.npmjs.com/package/@kivacore/rn-assistant) `@kivacore/rn-assistant` is a standalone React Native assistant package for Kiva-compatible backends. It is designed to be embedded into an existing host app without depending on app-local aliases, project-specific folders, or direct `.env` reads inside the package. The package includes: - Chat UI with streaming responses - Session/thread management - Model and reasoning selection - File attachments and voice recording - Built-in theme surface ## Installation ```bash tab="pnpm" pnpm add @kivacore/rn-assistant pnpm add react react-native expo react-native-keyboard-controller react-native-safe-area-context react-native-svg ``` ```bash tab="npm" npm install @kivacore/rn-assistant react react-native expo react-native-keyboard-controller react-native-safe-area-context react-native-svg ``` | Dependency | Version | |---|---| | React | 19+ | | React Native | 0.83+ | | Expo | 55+ | | `react-native-keyboard-controller` | 1.20.7+ | | `react-native-safe-area-context` | 5.6.2+ | | `react-native-svg` | 15.15.3+ | ### Root providers Wrap your app root with these providers: ```tsx title="app/_layout.tsx" import { SafeAreaProvider } from 'react-native-safe-area-context'; import { KeyboardProvider } from 'react-native-keyboard-controller'; export default function RootLayout() { return ( ); } ``` ## Configuration ### Environment variables The package does not read env values itself. Your host app should read env variables and turn them into props/config. ```txt EXPO_PUBLIC_API_BASE_URL= EXPO_PUBLIC_ASSISTANT_AGENT_ID= EXPO_PUBLIC_ASSISTANT_DATA_SOURCE_ID= EXPO_PUBLIC_OAUTH2_CLIENT_ID= EXPO_PUBLIC_OAUTH2_SCOPES=openid profile offline_access User.Read Users.Read.All DS.Read.All DS.ReadWrite.All AI.Read.All AI.ReadWrite.All EXPO_PUBLIC_OAUTH2_CALLBACK_URL=appName://auth/callback ``` ### Create assistant config ```tsx import { createKivaRNAssistantConfig } from '@kivacore/rn-assistant'; const assistantConfig = createKivaRNAssistantConfig({ baseUrl: process.env.EXPO_PUBLIC_API_BASE_URL || '', getToken: async () => auth.tokens?.accessToken || null, }); ``` You can also pass a direct `token`, but `getToken` is better for host-managed auth refresh. ### Authentication and scopes The assistant requires a valid authenticated token from the host app. Recommended scope set: - `User.Read`, `Users.Read.All` - `DS.Read.All`, `DS.ReadWrite.All` - `AI.Read.All`, `AI.ReadWrite.All` At minimum, assistant deployment loading requires `AI.Read.All` or `AI.ReadWrite.All`. > If you change OAuth scopes, the user must **sign out and sign in again**. Changing env values alone does not upgrade an already-issued token. ## Usage The host app should choose one presentation path at a time. Avoid rendering a page assistant and opening a second assistant sheet on top of it. ## iOS Permissions If voice recording or media attachments are enabled, define native permission strings in the **host app**: ```ts title="app.config.ts" export default { expo: { ios: { infoPlist: { NSMicrophoneUsageDescription: 'Uses the microphone for voice prompts.', NSCameraUsageDescription: 'Uses the camera to attach photos.', NSPhotoLibraryUsageDescription: 'Uses your photo library to attach images.', } } } }; ``` - These keys belong to the host app, not the package - After changing permission strings, rebuild with `run:ios` - Microphone permission is requested when recording starts, not on first render ## API Reference ## Troubleshooting ### 403 on deployment fetch ```txt Client is not authorized to access this resource. One of the following scopes is required: AI.Read.All, AI.ReadWrite.All ``` Fix: add `AI.Read.All` or `AI.ReadWrite.All` to your OAuth scopes, sign out, and sign in again. ### iOS crashes on microphone access Fix: add the required `ios.infoPlist` keys in the host app and rebuild with `run:ios`. ### Env changes do not apply For Expo apps, restart the dev server after changing `EXPO_PUBLIC_*` values. ## Related - [Native Installation](/docs/native/guide/installation) - [Native Theming](/docs/native/guide/theming) - [API Reference](/docs/guide/api-reference) --- # Theming URL: /docs/native/guide/theming Customize the look and feel of Kiva UI Native components with KivaThemeProvider, color schemes, and Tailwind CSS. ## Overview Kiva UI Native uses **Tailwind CSS v4** via Uniwind for component styling. Static styles are expressed as `className` using Tailwind utility classes and semantic color tokens (`bg-card`, `text-foreground`, `border-border`). Dynamic values that can't be expressed as className (KivaIcon colors, platform shadows, runtime color lookups) are accessed via the `useKivaTheme()` hook. Two sources of truth, kept in sync by value: - **CSS tokens** (`styles/kiva-native/index.css`, installed by the CLI) — what every `className` resolves against. Required; see [Design Tokens](#design-tokens). - **JS palette** (`useKivaTheme().colors`) — the same colors as raw strings, for props that need one. ## Setup Import the design tokens from your Uniwind CSS entry (see [Installation](/docs/native/guide/installation#2-create-global-css)): ```css title="src/styles/global.css" @import "tailwindcss"; @import "uniwind"; @import "./kiva-native/index.css"; ``` Then wrap your app root with `KivaThemeProvider`: ```tsx title="app/_layout.tsx" import '../src/styles/global.css'; import { KivaThemeProvider } from '@/lib/kiva/theme'; export default function RootLayout() { return ( ); } ``` ### Provider Props | Prop | Type | Default | Description | |------|------|---------|-------------| | `colorScheme` | `ColorScheme` | — | Controlled color scheme | | `mode` | `ThemeMode` | — | Controlled theme mode | | `lang` | `ThemeLanguage` | — | Controlled language | | `defaultColorScheme` | `ColorScheme` | `'kiva'` | Initial color scheme | | `defaultMode` | `ThemeMode` | `'system'` | Initial theme mode | | `defaultLang` | `ThemeLanguage` | `'en'` | Initial language | | `brand` | `Record` | — | Custom brand colors | | `fontFamily` | `ThemeFontFamily` | System fonts | Custom font family | | `messages` | `Record` | — | App-level message bag exposed through `useKivaTheme()`. Kiva components no longer read it — translate component copy with ` ); } ``` ### className vs style Decision Guide | Use Case | Approach | Example | |----------|----------|---------| | Static layout/colors | `className` | `className="flex-1 p-4 bg-card rounded-lg"` | | Semantic colors | `className` | `className="text-foreground bg-primary/10"` | | Dark mode | `className` | `className="bg-muted dark:bg-background"` | | Pressable states | `className` | `className="active:opacity-70 active:scale-95"` | | Animated values | `style` | `style={{ opacity: fadeAnim }}` | | Platform shadows | `style` | `style={cardShadow(isDark, colors.border)}` | | KivaIcon color | `color` prop | `color={colors.primary}` | | Dynamic theme lookup | `style` | `style={{ backgroundColor: colors[key] }}` | ## useKivaTheme Hook Access theme values for **dynamic use cases only** — static styling should use Tailwind className: ```tsx import { useKivaTheme } from '@/lib/kiva/theme'; import { KivaIcon } from '@/components/kiva-native/kiva-icon'; function MyComponent() { const { colors, isDark } = useKivaTheme(); return ( ); } ``` ### Theme Object ```tsx const theme = useKivaTheme(); theme.colors // ThemeColors — semantic + Tailwind palette theme.spacing // ThemeSpacing — numeric scale theme.borderRadius // ThemeBorderRadius theme.fieldHeight // ThemeFieldHeight theme.fontFamily // ThemeFontFamily theme.isDark // boolean — for conditional logic theme.colorScheme // 'kiva' | 'slate' | 'gray' | 'zinc' | ... theme.mode // 'light' | 'dark' | 'system' theme.lang // 'en' | 'tr' theme.brand // Custom brand object theme.messages // i18n messages ``` ## Color Schemes Kiva UI Native ships with **13 color schemes**, each providing light and dark variants: ### Base Schemes (Neutral) | Scheme | Description | |--------|-------------| | `slate` | Blue-gray neutral tones | | `gray` | Pure gray neutral tones | | `zinc` | Warm gray neutral tones | | `stone` | Warm beige neutral tones | | `neutral` | True neutral (no hue) | ### Accent Schemes | Scheme | Primary Color | Base | |--------|--------------|------| | `kiva` | Slate + Blue accent | Slate | | `red` | Red 600 | Zinc | | `rose` | Rose 600 | Zinc | | `orange` | Orange 500 | Stone | | `green` | Green 600 | Zinc | | `blue` | Blue 500 | Slate | | `yellow` | Yellow 500 | Stone | | `violet` | Violet 500 | Gray | ```tsx ``` `colorScheme` switches the **JS palette** (`useKivaTheme().colors`). The `className` tokens come from CSS: `index.css` ships only the default `kiva` scheme. The other 12 are opt-in Uniwind custom themes in `color-schemes.css` (installed next to `index.css`), named `-light` / `-dark`, with the same variable set: 1. Import it after `index.css`, **by relative path**: ```css title="src/styles/global.css" @import "tailwindcss"; @import "uniwind"; @import "./kiva-native/index.css"; @import "./kiva-native/color-schemes.css"; ``` 2. Register the theme names in Metro — Tailwind rejects an `@variant` it doesn't know, so every scheme in the file must be listed. Restart Metro with `--clear` afterwards: ```js title="metro.config.js" const schemes = ['slate', 'gray', 'zinc', 'stone', 'neutral', 'red', 'rose', 'orange', 'green', 'blue', 'yellow', 'violet']; module.exports = withUniwindConfig(config, { cssEntryFile: './src/styles/global.css', polyfills: { rem: 14 }, extraThemes: schemes.flatMap(scheme => [`${scheme}-light`, `${scheme}-dark`]) }); ``` 3. Switch at runtime, keeping the JS palette in step: ```tsx import { Uniwind } from 'uniwind'; const { setColorScheme, isDark } = useKivaTheme(); function applyScheme(scheme: ColorScheme) { setColorScheme(scheme); Uniwind.setTheme(scheme === 'kiva' ? 'system' : `${scheme}-${isDark ? 'dark' : 'light'}`); } ``` A custom theme is not adaptive — switch between `-light` and `-dark` yourself when the appearance changes, and note that `dark:` utilities only apply under the built-in `dark` theme. Core colors in `color-schemes.css` mirror the JS palettes; the extended surface / field tokens reuse the default Kiva values. ## Semantic Color Tokens Every color scheme provides these semantic tokens, available as both Tailwind classes and `colors.*` values (the full class-only list is in [Design Tokens](#design-tokens)): | Token | Tailwind Class | JS Access | Description | |-------|---------------|-----------|-------------| | `background` | `bg-background` | `colors.background` | App background | | `foreground` | `text-foreground` | `colors.foreground` | Primary text | | `card` | `bg-card` | `colors.card` | Card surfaces | | `primary` | `bg-primary` | `colors.primary` | Primary actions | | `secondary` | `bg-secondary` | `colors.secondary` | Secondary surfaces | | `muted` | `bg-muted` | `colors.muted` | Muted backgrounds | | `destructive` | `bg-destructive` | `colors.destructive` | Destructive actions | | `border` | `border-border` | `colors.border` | Borders | | `success` | `bg-success` | `colors.success` | Success states | | `warning` | `bg-warning` | `colors.warning` | Warning states | | `info` | `bg-info` | `colors.info` | Info states | **Use Tailwind classes for static colors** (`className="bg-card text-foreground"`). **Use `colors.*` only when a raw color string is needed** (KivaIcon, chart libraries, `cardShadow()`, runtime lookups). ### Tailwind Color Palette In addition to semantic tokens, `colors` includes the full Tailwind palette (50–950 shades): ```tsx const { colors } = useKivaTheme(); // Only needed for dynamic runtime lookups — prefer className for static colors colors.blue[500] // '#3b82f6' colors.red[600] // '#dc2626' colors.emerald[400] // '#34d399' ``` Available palettes: `red`, `orange`, `amber`, `yellow`, `lime`, `green`, `emerald`, `teal`, `cyan`, `sky`, `blue`, `indigo`, `violet`, `purple`, `fuchsia`, `pink`, `rose`. ## Dark Mode ### With Tailwind Classes Components support dark mode variants via Tailwind: ```tsx ``` ### System-Based (Default) ```tsx ); } ``` ### Checking Dark Mode Use `isDark` for logic that can't be expressed as className (platform shadows, conditional rendering): ```tsx const { isDark, colors } = useKivaTheme(); // Platform shadows need style prop — no Tailwind equivalent ); } ``` ## Brand Colors Add custom brand-specific colors available throughout the theme: ```tsx type MyBrand = { accentBlue: string; accentGold: string; headerBg: string; }; brand={{ accentBlue: '#1E90FF', accentGold: '#FFD700', headerBg: '#0A1128', }} > ``` Access brand colors in components: ```tsx const { brand } = useKivaTheme(); // Brand colors are dynamic — use style prop ``` ## Localization The provider stores the active language (`lang` / `defaultLang`) and an optional `messages` bag for your own app code: ```tsx ``` ```tsx const { lang, messages } = useKivaTheme(); ``` Kiva native components do **not** read `lang` or `messages` for their built-in copy. Every component renders an English fallback and looks up `ui..` through [``](/docs/native/hooks/use-ui-translation) — the same keys as the web package, so one translation catalog covers both platforms. Explicit copy props (`label`, `cancelLabel`, `messages`, …) always win. ## Web vs Native Comparison | Feature | Web (CSS Variables) | Native (Tailwind + Theme) | |---------|--------------------|-----------------------| | Static styling | `className="bg-primary p-4"` | `className="bg-primary p-4"` | | Token access | `var(--primary)` in CSS | `className="bg-primary"` or `colors.primary` | | Dark mode | `.dark` class + CSS | `className="dark:bg-background"` or `isDark` | | Color scheme | CSS variable swap | `colorScheme` prop on provider | | Custom colors | CSS variable override | `brand` prop | | Fonts | CSS `font-family` | `fontFamily` prop | | Animated values | CSS transitions / motion | `style` prop with Animated/Reanimated | | 3rd-party colors | CSS variable reference | `colors.*` from `useKivaTheme()` | --- # Troubleshooting URL: /docs/native/guide/troubleshooting Common issues and solutions when using Kiva UI native components. ## Verify your versions Make sure your environment meets or exceeds these minimum versions. | Dependency | Minimum Version | |---|---| | React | 19 | | React Native | 0.79 | | Expo SDK | 53 | | Node.js | 18 | ## Components look transparent or unstyled Surfaces, borders and text colors come from the Kiva design tokens (`bg-background`, `border-field-border`, `bg-sheet-surface`, …). If they render transparent, your Uniwind CSS entry is missing the tokens import — add it after Tailwind and Uniwind, with a path relative to that file: ```css title="src/styles/global.css" @import "tailwindcss"; @import "uniwind"; @import "./kiva-native/index.css"; ``` The file is installed by the CLI with any `rn-*` component (`kiva-ui add rn-styles` installs it alone). Restart Metro with `npx expo start --clear` after changing the CSS entry. `Theme X is missing variable …` means a token you override is declared in one `@variant` but not the other; `Cannot use @variant with unknown variant` means `color-schemes.css` is imported without its themes in Metro `extraThemes` (or through a package path instead of a relative one) — see [Theming](/docs/native/guide/theming#color-schemes). ## Theme not applying Make sure your app is wrapped with `KivaThemeProvider` at the root level. Without this provider, components will fall back to default styles. If using Expo Router, wrap it in your root `_layout.tsx`. ```tsx title="app/_layout.tsx" import { KivaThemeProvider } from '@/lib/kiva/theme'; export default function RootLayout() { return ( ); } ``` ## Expo Go compatibility Some native components require a development build and won't work in Expo Go. Check the component's documentation for Expo Go compatibility. Components that use native modules require `npx expo prebuild` and a custom dev client: ```bash npx expo prebuild npx expo run:ios ``` ## Missing peer dependencies Native components declare peer dependencies for packages like `react-native-svg`, `expo-document-picker`, and `expo-localization`. If you see module resolution errors, install the required dependency: ```bash npx expo install react-native-svg npx expo install expo-document-picker npx expo install expo-localization ``` ## Font Awesome icons not loading If `KivaIcon` is not rendering icons, make sure you've configured the icon CDN path correctly. Native icons are loaded from the Kiva CDN — verify your network connectivity and that the icon name matches the registry. ## React Native Reanimated errors If you see errors related to Reanimated, make sure you've added the Babel plugin: ```js title="babel.config.js" module.exports = function(api) { api.cache(true); return { presets: ['babel-preset-expo'], plugins: ['react-native-reanimated/plugin'], }; }; ``` ## Metro bundler cache issues If you're seeing stale code or unexpected errors after installing new components, clear the Metro cache: ```bash npx expo start --clear ``` ## Still having issues? If none of the above solutions resolve your problem, please [open an issue on GitHub](https://github.com/Kivacore/kiva-ui/issues) with a description of what you're experiencing and your environment details. --- # Overview URL: /docs/native/hooks Reusable React Native hooks for Kiva-connected mobile applications. Browse all available Kiva UI native hooks. ## Available Hooks | Hook | Description | |-----------|-------------| | [useAdaptiveCard](/docs/native/hooks/use-adaptive-card) | Headless state, validation, visibility and action dispatch for the native Adaptive Cards renderer. Drives the AdaptiveCard component and is exported so apps can wire custom toolbars or server-side validation. | | [useDataExport](/docs/native/hooks/use-data-export) | Client-side export of already-loaded rows to CSV, JSON, Markdown or Excel on React Native. Projects rows through a column list, writes the file into the cache directory and opens the share sheet. API-aligned with the web useDataExport. | | [useDateFormat](/docs/native/hooks/use-date-format) | Provider-agnostic date, datetime and time formatting context for Kiva native components. Wired automatically by KivaTenantProvider, but works with any date library. | | [useDynamicFormView](/docs/native/hooks/use-dynamic-form-view) | Backend-agnostic form engine for React Native. Renders an IField schema with sections, tabs, collapsible panels, computed fields, field and form actions, validation tokens and a submit payload builder, with no network I/O. | | [useKivaAdaptiveCardItemDetail](/docs/native/hooks/use-kiva-adaptive-card-item-detail) | Generate an Adaptive Card JSON payload from a Kiva field list + a single record — mapping Kiva field types onto the Adaptive Cards element vocabulary — and render it with the shared native AdaptiveCard renderer. | | [useKivaAdaptiveCardItemList](/docs/native/hooks/use-kiva-adaptive-card-item-list) | Generate an array of Adaptive Card JSON payloads from a Kiva field list + many records, and render them as a responsive grid, a stacked list, a single Carousel card or a single Table card with the shared native AdaptiveCard renderer. | | [useKivaAgentAttachments](/docs/native/hooks/use-kiva-agent-attachments) | Uploads chat attachments to a Kiva agent thread (creating the thread on first use) and returns the storage paths for the chat request. | | [useKivaAgentChat](/docs/native/hooks/use-kiva-agent-chat) | The complete streaming chat runtime for a Kiva AI agent — AI SDK transport, threads, attachment uploads and client-side tool execution — ready to drive KivaAgent. | | [useKivaAgentInfo](/docs/native/hooks/use-kiva-agent-info) | Fetches a Kiva AI agent's profile, suggestions and capabilities from the agent-deployment endpoint and maps them onto the KivaAgent props. | | [useKivaAgentMemories](/docs/native/hooks/use-kiva-agent-memories) | Backend glue for the KivaAgent memory manager — list, create, update and delete /v1/ai/memories with optimistic local state. | | [useKivaAgentMemoryCandidates](/docs/native/hooks/use-kiva-agent-memory-candidates) | Backend glue for the KivaAgent memory-extraction dialog — extract candidates from a thread, then save or skip them. | | [useKivaAgentProjects](/docs/native/hooks/use-kiva-agent-projects) | Lists, creates, renames and deletes Kiva AI projects scoped to an agent. | | [useKivaAgentThreads](/docs/native/hooks/use-kiva-agent-threads) | Lists, renames, deletes and loads the messages of Kiva AI assistant chat threads. | | [useKivaCalendar](/docs/native/hooks/use-kiva-calendar) | Calendar backed by a Kiva data source. Detects the date, title, color, description and user fields, turns records into events, and wires create, update, delete and drag to the API. | | [useKivaContactActivity](/docs/native/hooks/use-kiva-contact-activity) | Merges a record's audit log, comments, related events and tasks, and status updates into one typed timeline for ContactActivityPanel, with upcoming items, a relationship summary and comment and status mutations. | | [useKivaContactChannels](/docs/native/hooks/use-kiva-contact-channels) | React Query wiring for the Contact Channels & Consent API — a record's channels, consent and validation ledgers, tenant brands and every channel / consent / validation mutation. | | [useKivaDataExport](/docs/native/hooks/use-kiva-data-export) | Server-side export of a Kiva data source on React Native. POSTs the column list, filters and keyword to the query-export endpoint, writes the returned xlsx or csv file into the cache directory and opens the share sheet. | | [useKivaDataGallery](/docs/native/hooks/use-kiva-data-gallery) | Kiva-backed card gallery for React Native — composes useKivaDataGrid for schema, saved views, server filters / sort / search / paging and pivot / side filters, and adds gallery-owned card + display config, a toolbar and props for the native DataGallery. | | [useKivaDataGrid](/docs/native/hooks/use-kiva-data-grid) | Everything a Kiva-backed native DataGrid needs in one hook — columns from the schema, server-side filters / sort / search / paging, saved views, pivot filters, advanced AND/OR filter, borrowed relation columns, inline edit, status updates, bulk actions, exports and persisted view parameters. | | [useKivaDataImportWizard](/docs/native/hooks/use-kiva-data-import-wizard) | One-call wiring of a Kiva data source to the native DataImportWizard. Picks a spreadsheet, uploads and analyses it on the server, auto-maps columns, imports the rows and returns a ready-to-render wizard element plus imperative helpers. | | [useKivaDataSourceFields](/docs/native/hooks/use-kiva-data-source-fields) | Lightweight schema hook for one Kiva data source on React Native. Returns the data source and its field list (including inline enum options), served cache-first from the shared inventory so no extra request is made after the post-sign-in warm-up. | | [useKivaDataSourceJsonSchema](/docs/native/hooks/use-kiva-data-source-json-schema) | Generate a JSON Schema (object schema, properties keyed by field slug) from a Kiva data source field list. | | [useKivaDataTable](/docs/native/hooks/use-kiva-data-table) | Headless Kiva-backed table for the native DataTable — schema columns rendered with the value renderers, server filters / sort / search / paging, saved views, bulk actions, exports and a table ↔ gallery view node. | | [useKivaDataViewSelect](/docs/native/hooks/use-kiva-data-view-select) | Load a Kiva data source's fields, saved views and forms, and wire them into the native DataGridViewSelect with one hook — view CRUD, reorder, hidden views and persisted active view included. | | [useKivaDummyDataGeneratorWizard](/docs/native/hooks/use-kiva-dummy-data-generator-wizard) | One-call wiring of a Kiva data source to the native DummyDataGenerator. Loads the schema, seeds per-field strategies, generates seeded sample rows, previews and exports them, and inserts them into the data source. Returns an inline wizard element plus imperative helpers. | | [useKivaEmailComposer](/docs/native/hooks/use-kiva-email-composer) | Wires the native EmailComposer to the Kiva messaging API — sender accounts, @ mention users and the send mutation, with composer state managed for you. | | [useKivaFieldComponent](/docs/native/hooks/use-kiva-field-component) | Resolve the native form field, value renderer or inline editor for a Kiva field type — plus the shared FORM_FIELD_MAP / VALUE_RENDERER_MAP registries and IField helpers. | | [useKivaFormView](/docs/native/hooks/use-kiva-form-view) | Create, edit and view forms bound to a Kiva data source on React Native. Loads the schema, record and options, uploads files to Kiva storage and creates or updates the record through the shared form-view engine. | | [useKivaInstantMessageComposer](/docs/native/hooks/use-kiva-instant-message-composer) | Wires the native InstantMessageComposer to the Kiva SMS and WhatsApp messaging API. | | [useKivaInventory](/docs/native/hooks/use-kiva-inventory) | Shared app-utils inventory cache for Kiva metadata (apps, data sources with fields, enums, views and forms, users, brands, preferences) plus a post-sign-in warm-up hook that drives a loading screen. | | [useKivaKanban](/docs/native/hooks/use-kiva-kanban) | Kanban board backed by a Kiva data source. Groups records by an enum, user or date field, and saves a card's move to the API when it is dropped. Enum options marked final become drop zones. | | [useKivaLogActivity](/docs/native/hooks/use-kiva-log-activity) | Kiva data engine for LogActivityForm. Fetches comments, users, task and event options and the record's status field, and runs the comment, task, event and two-call status mutations. | | [useKivaMapView](/docs/native/hooks/use-kiva-map-view) | Map backed by a Kiva data source. Detects the location field and builds markers from logos, icons or the default pin, with clustering, a viewport filter, basemaps and drag-to-move with reverse geocoding. | | [useKivaPivotCalendar](/docs/native/hooks/use-kiva-pivot-calendar) | PivotCalendar backed by a Kiva data source. Aggregates per day or month in the database through a pivot matrix, optionally grouped by a relation, and turns a tapped value into a ready-to-run drilldown query. | | [useKivaPivotFilter](/docs/native/hooks/use-kiva-pivot-filter) | Connects a Kiva data source to a native PivotFilter strip. It detects the field type, runs a pivot aggregate query, builds pill items and date buckets, and emits filter rules. KivaPivotFilterGroup stacks several strips that cross-filter each other. | | [useKivaPivotGrid](/docs/native/hooks/use-kiva-pivot-grid) | Pivot grid backed by a Kiva data source. Aggregates on the device from raw records, or in the database through a pivot matrix and calculations, and returns a controller for the native PivotGrid components. | | [useKivaTenant](/docs/native/hooks/use-kiva-tenant) | Tenant integration for Kiva native apps. Fetches tenant preferences, builds dateUtils and numberUtils, and wires DateFormatProvider and NumberFormatProvider so every native component picks up the tenant's date and number formats. | | [useLocalDataSource](/docs/native/hooks/use-local-data-source) | Create an in-memory Kiva-compatible data source from a JSON array, with local CRUD and Kiva-style query parameters. | | [useLocalDataSourceDataGrid](/docs/native/hooks/use-local-data-source-data-grid) | Run the full useKivaDataGrid workflow — views, search, filters, grouping, sort, inline save, bulk delete — over an in-memory LocalDataSource. No backend, no sign-in. | | [useNumberFormat](/docs/native/hooks/use-number-format) | Provider-agnostic number formatting context for Kiva native components. Mirror of useDateFormat, wired automatically by KivaTenantProvider. | | [useParameterPersistence](/docs/native/hooks/use-parameter-persistence) | Persist a serializable view-parameter snapshot (search, filters, sort, column layout, …) per saved view and restore it on the next mount, backed by a synchronous native key-value store. | | [useSpeechRecognition](/docs/native/hooks/use-speech-recognition) | Live speech-to-text for React Native with the same API as the web hook, backed by the optional expo-speech-recognition module. | | [useUiTranslation](/docs/native/hooks/use-ui-translation) | Provider-agnostic i18n bridge for Kiva native components. Same ui.``.`` keys as the web package, English fallback when no provider is mounted. | --- # useAdaptiveCard URL: /docs/native/hooks/use-adaptive-card Headless state, validation, visibility and action dispatch for the native Adaptive Cards renderer. Drives the AdaptiveCard component and is exported so apps can wire custom toolbars or server-side validation. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-adaptive-card ``` **Dependencies:** - [react](https://react.dev) The hook ships with the [rn-adaptive-card](/docs/native/kiva/adaptive-card) component (it imports the card's types and `lib/` helpers). It is also re-exported from `@/components/kiva-native/adaptive-card`, and the old `components/adaptive-card/use-adaptive-card` path still resolves. ## Overview `useAdaptiveCard` owns the runtime state of one card. The public API matches web `@kivacore/ui` 1:1. - **Inputs.** Every visible `Input.*` element is registered by `id`, with its live value and validation state. - **Visibility overrides.** `Action.ToggleVisibility` results are layered on top of the static `isVisible` defaults. - **Show-card state.** Each `Action.ShowCard` button has an open or closed flag. - **Action dispatch.** `submit`, `execute`, `openUrl`, `toggleVisibility`, `showCard` and `resetInputs` are emitted as typed events. - **Submit payload assembly.** The hook walks the visible tree, honours `associatedInputs: 'auto' | 'none'` and merges `action.data`. - **Focus on the first invalid input.** When a submit or execute fails validation, the hook focuses the first invalid input. The native equivalent of the web `[aria-invalid]` DOM lookup is a focus registry: `Input.Text` and `Input.Number` register their `TextInput` ref, so the keyboard opens on that field and the enclosing scroll view brings it into view. `` uses this hook internally. Call it yourself only when you need one of these: - Trigger actions programmatically, for example from a native header button. - Read input state from outside the card. - Wire server-side validation that returns errors per input id. ## Usage ### Custom integration ```tsx import { Button, View } from 'react-native'; import { AdaptiveCardView, useAdaptiveCard, type AdaptiveCardActionEvent, type AdaptiveCardPayload } from '@/components/kiva-native/adaptive-card'; export function CardWithToolbar({ payload }: { payload: AdaptiveCardPayload }) { function handleAction(event: AdaptiveCardActionEvent) { console.log(event); } const adaptive = useAdaptiveCard(payload, { onAction: handleAction }); return ( ); } ``` ### Reading the current input state ```tsx const adaptive = useAdaptiveCard(payload); console.log(adaptive.state.inputs.email); console.log(adaptive.state.validations.email); ``` ### Submitting programmatically ```tsx const submitAction = payload.actions?.find(a => a.type === 'Action.Submit'); if (submitAction && submitAction.type === 'Action.Submit') { adaptive.controls.submit(submitAction); } ``` ### Resetting after a successful save ```tsx async function handleAction(event: AdaptiveCardActionEvent) { if (event.type !== 'submit') return; await api.post('/forms', event.data); adaptive.controls.reset(); // clears inputs, visibility overrides and show-card state } ``` ## API Reference ```ts function useAdaptiveCard(card: AdaptiveCardPayload, options?: UseAdaptiveCardOptions): UseAdaptiveCardReturn; ``` ### `UseAdaptiveCardOptions` | Option | Type | Default | Description | |--------|------|---------|-------------| | `onAction` | `(event: AdaptiveCardActionEvent) => void \| Promise` | — | Receives every dispatched action. | | `hostConfig` | `AdaptiveCardHostConfigOverride` | — | Deep-merged onto `defaultHostConfig`. | | `customElements` | `Record` | `{}` | Renderers for unknown `type` strings. | | `onChoiceQuery` | `(request: AdaptiveCardChoiceQueryRequest) => Promise>` | — | Async resolver for a filtered `Input.ChoiceSet` whose `choices.data` is a `Data.Query`. The input is debounced, and the returned choices are merged with the static `choices`. A throwing resolver yields `[]`. | ### `AdaptiveCardChoiceQueryRequest` | Field | Type | Description | |-------|------|-------------| | `dataset` | `string` | The `Data.Query` dataset name. | | `search` | `string` | The current filter text. | | `inputId` | `string` | The `Input.ChoiceSet` id. | ### `UseAdaptiveCardReturn` | Field | Type | Description | |-------|------|-------------| | `card` | `AdaptiveCardPayload` | The payload passed in. | | `hostConfig` | `AdaptiveCardHostConfig` | The resolved host config: the default deep-merged with your override. | | `state.inputs` | `Record` | Live input values, keyed by `id`. | | `state.validations` | `Record` | Validation for each input (`{ isValid, errorMessage? }`), recomputed on every change. | | `state.visibilityOverrides` | `Record` | `Action.ToggleVisibility` overrides, keyed by element `id`. | | `state.showCardOpen` | `Record` | Open flags for `Action.ShowCard`, keyed by the action's `id` or `title`. | | `state.hasSubmittedOnce` | `boolean` | Becomes `true` after the first failed submit, which is when per-input errors start to show. | | `controls.setInput(id, value)` | `(id, value) => void` | Sets an input imperatively. | | `controls.submit(action)` | `(action: AdaptiveCardActionSubmit) => void` | Validates, then dispatches `'submit'`. On failure, focuses the first invalid input instead. | | `controls.execute(action)` | `(action: AdaptiveCardActionExecute) => void` | Validates, then dispatches `'execute'` with `verb`. On failure, focuses the first invalid input instead. | | `controls.openUrl(action)` | `(action: AdaptiveCardActionOpenUrl) => void` | Dispatches `'openUrl'`. | | `controls.toggleVisibility(action)` | `(action: AdaptiveCardActionToggleVisibility) => void` | Applies the visibility overrides, then dispatches `'toggleVisibility'`. | | `controls.toggleShowCard(action)` | `(action: AdaptiveCardActionShowCard) => void` | Flips a show-card, then dispatches `'showCard'`. | | `controls.resetInputs(action)` | `(action: AdaptiveCardActionResetInputs) => void` | Clears the target inputs (all of them when `targetInputIds` is empty), then dispatches `'resetInputs'`. | | `controls.validateAll()` | `() => { ok; firstInvalidId?; errors }` | Runs validation immediately. It does not dispatch or change focus. | | `controls.reset()` | `() => void` | Clears inputs, visibility overrides and show-card state. | | `cardProps` | `AdaptiveCardContextValue` | The value `` consumes. On native it also carries `registerInputFocus` for the focus registry. | ## When validation runs - **The first submit** validates silently. If any input fails, the hook sets `state.hasSubmittedOnce = true`, focuses the first invalid focusable input, and does **not** dispatch. - **After that failed submit**, validation re-renders live, so each error message clears once the user fixes the field. - **Date, time, toggle, choice-set and rating inputs** have no text caret to focus. They show their error state but are not focused. ## The `associatedInputs` contract `Action.Submit` and `Action.Execute` build the submit payload from the **currently visible** card tree: - **`'auto'` (default):** collects every `Input.*` that is visible under the current `visibilityOverrides`. Hidden inputs are left out. - **`'none'`:** skips inputs and emits only the literal `action.data`. ## Type Exports | Type | Description | |------|-------------| | `UseAdaptiveCardOptions` | The hook options. | | `UseAdaptiveCardReturn` | The full hook return value. | | `AdaptiveCardChoiceQueryRequest` | The request passed to `onChoiceQuery`. | | `AdaptiveCardInputValue` | `string \| Array \| boolean \| number \| null`. | --- # useDataExport URL: /docs/native/hooks/use-data-export Client-side export of already-loaded rows to CSV, JSON, Markdown or Excel on React Native. Projects rows through a column list, writes the file into the cache directory and opens the share sheet. API-aligned with the web useDataExport. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-data-export ``` **Dependencies:** - [expo-file-system (optional)](https://www.npmjs.com/package/expo-file-system) - [expo-sharing (optional)](https://www.npmjs.com/package/expo-sharing) The hook needs no Kiva client. It works on rows you already hold, such as the rows of a list, a grid page or generated sample data. For a full server-side export of a data source, use [`useKivaDataExport`](/docs/native/hooks/use-kiva-data-export). `expo-file-system` (SDK 54+ `File` / `Paths` API) and `expo-sharing` are **optional peers**, loaded lazily through the internal `lib/native-export` helpers. Without `expo-file-system`, `exportData` resolves `null` and writes nothing. Without `expo-sharing`, the file is written but the share sheet does not open. ## Usage ```tsx import { Button } from '@/components/kiva-native/button'; import { useDataExport, type DataExportColumn } from '@/hooks/kiva-native/use-data-export'; type Contact = { id: string; name: string; email: string; company?: { name: string } }; const columns: DataExportColumn ); } ``` ### Formats | Format | Extension | Output | |--------|-----------|--------| | `csv` | `.csv` | RFC 4180 quoting, CRLF line endings, UTF-8 BOM by default (`csvBom`). | | `json` | `.json` | Array of projected objects keyed by column `id`, pretty-printed. | | `markdown` | `.md` | GitHub table. Pipes and backslashes are escaped and newlines become `
`. | | `xlsx` | `.xlsx` | Single sheet with a bold, frozen header row. Numbers, booleans and dates are typed cells, and objects are JSON strings. | Without a `formatter`, primitives are written as they are, dates as ISO strings, and objects / arrays through `JSON.stringify`. ## API Reference ### Options (`UseDataExportOptions`) | Option | Type | Default | Description | |--------|------|---------|-------------| | `columns` | `DataExportColumn[]` | — | Column projection. Order is kept in the output (required). | | `fileName` | `string` | `'export'` | File name without extension. Invalid characters are removed. | | `sheetName` | `string` | `'Sheet1'` | Sheet name for `xlsx`. | | `csvBom` | `boolean` | `true` | Prepend a UTF-8 BOM to CSV output so Excel detects the encoding. | | `share` | `boolean` | `true` | Native: open the share sheet after writing. `false` only writes the file and returns its `uri`. | | `dialogTitle` | `string` | the file name | Native: title of the Android share chooser. | ### DataExportColumn<TData> | Field | Type | Description | |-------|------|-------------| | `id` | `string` | Stable column id, also the JSON key (required). | | `header` | `string` | Header label for CSV, Markdown and Excel (required). | | `accessor` | `(row: TData) => unknown` | Raw value. Defaults to `row[id]`. | | `formatter` | `(value: unknown, row: TData) => string` | Runs after `accessor` to produce the written value. | ### Result (`UseDataExportResult`) | Field | Type | Description | |-------|------|-------------| | `exportData` | `(rows: TData[], format: DataExportFormat) => Promise` | Project, write and share. Resolves `null` when `expo-file-system` is missing. | | `isExporting` | `boolean` | True while a file is being written. | ### DataExportResult | Field | Type | Description | |-------|------|-------------| | `mimeType` | `string` | MIME type of the file. | | `extension` | `string` | Extension including the leading dot. | | `fileName` | `string` | ``. | | `uri` | `string` | Native: local `file://` URI in the cache directory. | ## Differences from web - Web builds a `Blob` and clicks an ``. Native writes the file into the cache directory and opens the share sheet, so the user can save it to Files, send it or open it in another app. - Web writes Excel with `exceljs`, which needs Node `Buffer` / `stream` polyfills that Metro does not ship. Native uses a zero-dependency OOXML writer (`buildSimpleXlsx` in the internal `lib/native-export`), which is also used by the pivot-grid exporter. - Native adds the `share` and `dialogTitle` options and the `uri` field on the result. `exportData` can resolve `null`. ## Type Exports | Type | Description | |------|-------------| | `UseDataExportOptions` | Hook options. | | `UseDataExportResult` | Hook result. | | `DataExportColumn` | Column projection entry. | | `DataExportFormat` | `'csv' \| 'json' \| 'markdown' \| 'xlsx'`. | | `DataExportResult` | Written file metadata. | --- # useDateFormat URL: /docs/native/hooks/use-date-format Provider-agnostic date, datetime and time formatting context for Kiva native components. Wired automatically by KivaTenantProvider, but works with any date library. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-date-format ``` The module exports `useDateFormat()` (hook), `; } ``` ### Custom provider (date-fns) ```tsx import { format } from 'date-fns'; import { DateFormatProvider } from '@/hooks/kiva-native/use-date-format'; export function AppProviders({ children }: { children: React.ReactNode }) { return ( ); } ``` ## API Reference ### `useDateFormat()` Takes no parameters. **Returns:** `DateFormatContextValue`. | Field | Type | Description | |-------|------|-------------| | `formatDate` | `(value: unknown) => string` | Date-only output. | | `formatDateTime` | `(value: unknown) => string` | Date and time output. | | `formatTime` | `(value: unknown) => string` | Time-only output. | ### `` | Prop | Type | Default | Description | |------|------|---------|-------------| | `formatDate` | `DateFormatFn` | — | Required. Backs `formatDate` inside the tree. | | `formatDateTime` | `DateFormatFn` | — | Required. Backs `formatDateTime` inside the tree. | | `formatTime` | `DateFormatFn` | — | Required. Backs `formatTime` inside the tree. | | `children` | `ReactNode` | — | Tree to wrap. | ### `isDefaultDateFormatContext(ctx)` | Parameter | Type | Description | |-----------|------|-------------| | `ctx` | `DateFormatContextValue` | A value returned by `useDateFormat()`. | **Returns:** `boolean`. `true` when `ctx` is the no-provider sentinel rather than a real provider. Listing hooks use it so they don't shadow a cell's own fallback formatting when no provider is mounted. ### `DateFormatContext` The raw context (`DateFormatContextValue | null`, `null` without a provider). Native-only export: the native data-grid cell reads it directly. Prefer `useDateFormat()` in app code. ## Type Exports | Type | Description | |------|-------------| | `DateFormatFn` | `(value: unknown) => string`. | | `DateFormatContextValue` | Shape returned by `useDateFormat()`. | --- # useDynamicFormView URL: /docs/native/hooks/use-dynamic-form-view Backend-agnostic form engine for React Native. Renders an IField schema with sections, tabs, collapsible panels, computed fields, field and form actions, validation tokens and a submit payload builder, with no network I/O. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-dynamic-form-view ``` **Dependencies:** - [jsonata](https://www.npmjs.com/package/jsonata) - [@react-querybuilder/core](https://www.npmjs.com/package/@react-querybuilder/core) The native port of the web hook with the same signature. It drives the shared form-view engine (the same one behind [`useKivaFormView`](/docs/native/hooks/use-kiva-form-view)) but fetches nothing: you pass the `IField[]` schema, the values, static option lists, upload handlers and an `onSubmit` sink. Fields render through the native `KivaFieldDynamic` controls; view mode renders the value renderers, or `EditableRecordDetail` with `clickToEdit`. ## Usage ```tsx import { ScrollView } from 'react-native'; import { Alert } from '@/components/kiva-native/alert'; import { Button } from '@/components/kiva-native/button'; import { type IField } from '@/components/kiva-native/form-fields'; import { useDynamicFormView } from '@/hooks/kiva-native/use-dynamic-form-view'; const fields: IField[] = [ { id: '1', name: 'Title', slug: 'title', type: 'field-text', validations: ['required', 'minLength:3'] }, { id: '2', name: 'Quantity', slug: 'quantity', type: 'field-number' }, { id: '3', name: 'Unit price', slug: 'unit_price', type: 'field-money' }, { id: '4', name: 'Total', slug: 'total', type: 'field-number', readOnly: true } ]; export function OrderForm() { const view = useDynamicFormView({ fields, validationTokens: 'all', layout: [ { id: 'main', variant: 'fieldset', title: 'Order', items: [{ type: 'field', slug: 'title', colSpan: 'full' }, 'quantity', 'unit_price', 'total'] } ], fieldLayout: { total: { computedFormula: '$number(quantity) * $number(unit_price)' } }, onSubmit: payload => saveOrder(payload) }); return ( ); } ``` ## Uploads `onImageUpload` / `onFileUpload` receive the picked asset as a `NativeFile` (`{ uri, name, type, size? }` from `expo-image-picker` / `expo-document-picker`) instead of a DOM `File`. Upload it and resolve to a `StoredFileValue`: ```tsx onImageUpload: async (file) => { const formData = new FormData(); formData.append('file', { uri: file.uri, name: file.name, type: file.type } as never); return uploadToStorage(formData); // → { file_name, source, signed_url, file_type, file_size } } ``` Per-field async option loaders are wired through `fieldLayout[slug].fieldProps` (`onSearch` / `searching` / `onLoadMore` / `hasMore` / `onExpand`). ## Layout `layout` is a tree of field slugs, `{ type: 'field', slug, colSpan }` items and sections: | Section | Native rendering | Keys | |---------|------------------|------| | `fieldset` | Bordered panel; with `collapsible` the title toggles a native `Collapsible` | `id`, `title`, `description`, `items`, `columns`, `collapsible`, `defaultCollapsed`, `colSpan`, `className`, `contentClassName` | | `tabpanel` | Bordered panel with scrollable underline `Tabs` | `id`, `title`, `description`, `items: tab[]`, `defaultTabId`, `colSpan` | | `tab` | One tab page (inside a `tabpanel`) | `id`, `title`, `description`, `items`, `className`, `contentClassName` | Fields not placed in the layout are appended after it. The grid is a flex-wrap grid: **phones render one column**, tablets honor `gridColumns` / `columns` (capped at 2 below 900pt) and `colSpan` (`1`–`4` or `'full'`). Sections span the full row unless they carry a `colSpan`. ## Form-level styling `labelAlign` / `labelWidth` / `fieldSize` / `fieldVariant` are resolved into field props (`getFormLayoutFieldProps` in `form-fields/lib/form-layout`) instead of the web descendant CSS selectors (Uniwind has none): `labelAlign: 'left'` → `labelAlignment: 'left'` + a fixed label column (`sm` w-24 / `md` w-40 / `lg` w-56), `fieldSize` → field `size`, `fieldVariant: 'outline' | 'filled'` → `'outlined' | 'filled'`. Explicit `fieldLayout[slug].fieldProps` win. ## Computed fields, actions and validation - **Computed** (`fieldLayout[slug]` or `IField`): `computedHidden` / `computedRequired` (JSONata string or query-builder JSON), `computedLabel` / `computedDescription` (JSONata → string), `computedFormula` (JSONata → value written back into the field). Expressions evaluate against the live values (`quantity * unit_price`). - **Field actions** (`fieldActions`, trigger `onFieldChange`): blocks of IF / ELSE IF (`conditionalItems`) / ELSE (`elseActions`) / ALWAYS (`unconditionalActions`) with the 8 step methods `setFieldValue`, `setFieldValues`, `clearFieldValue`, `showField`, `hideField`, `setFieldRequired`, `setFieldDisabled`, `setFieldReadOnly`. - **Form actions** (`formActions`): the same blocks on `onFormLoad`, `onFormBeforeSubmit` and `onFormAfterSubmit` (`$result` bound). - **Priority**: computed formulas > field-action overrides > form-action overrides > `fieldLayout` callbacks > `IField` defaults. - **Validation order per field**: `required` (always) → tokens (`validationTokens`: `'off'` advisory, `'form'` only `fieldLayout.validations`, `'all'` also the field's own tokens; resolved list on `field.enforcedValidations`, also used for the fields' live hints) → JSONata `customValidations` (`value` + `values` bound). Form-level `formCustomValidations` run once every field passes. - **Payload**: read-only and disabled fields are excluded; companion columns (`___currency`, `___country`, status sub-fields, avatar mapping) are submitted with their field. ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `fields` | `IField[]` | required | Field schema (already normalized to IField) | | `mode` | `'create' \| 'edit' \| 'view'` | `'create' (no values) / 'edit' (with values)` | Form mode | | `initialValues` | `Record` | — | Uncontrolled seed — merged over field defaults; re-seeds when its content changes | | `values` | `Record` | — | Controlled values — the form re-seeds whenever its content changes | | `onValuesChange` | `(values: Record) => void` | — | Fires on every field change (controlled and uncontrolled) | | `disabled` | `boolean` | `false` | Disable every field | | `clickToEdit` | `boolean` | `false` | In view mode, render through EditableRecordDetail (inline edit + save) | | `includeReadOnlyFields` | `boolean` | `mode !== 'create'` | Render read-only fields as values | | `unsupportedFieldBehavior` | `'skip' \| 'value'` | `create ? 'skip' : 'value'` | Field types without a native editor: skip or render as a value | | `gridColumns` | `1 \| 2 \| 3 \| 4` | `2` | Form grid columns (phones render 1 column; tablets up to 2 below 900pt) | | `validationTokens` | `'off' \| 'form' \| 'all'` | `'off'` | Enforce minLength / maxLength / pattern / min / max tokens on submit (required is always enforced) | | `labelAlign` | `'top' \| 'left'` | `'top'` | Form-level label placement | | `labelWidth` | `'sm' \| 'md' \| 'lg'` | `'md'` | Label column width when labelAlign is left | | `fieldSize` | `'sm' \| 'md' \| 'lg'` | — | Form-level field density | | `fieldVariant` | `'outline' \| 'filled'` | — | Form-level input style | | `fieldSlugs` | `string[]` | — | Whitelist of field slugs to render | | `fieldOrder` | `string[]` | — | Explicit field order (unlisted fields sort by name) | | `hiddenFieldSlugs` | `string[]` | — | Field slugs to hide | | `fieldLayout` | `Record` | — | Per-field overrides: hidden / required fns, readOnly, disabled, colSpan, label, description, fieldProps, valueProps, computed*, fieldActions, customValidations, validations | | `layout` | `KivaFormViewLayoutItem[]` | — | Section tree: fieldset (columns, collapsible, defaultCollapsed) / tabpanel / tab, field items with colSpan | | `enumOptions` | `Record` | — | Option lists keyed by field slug (overrides inline enums) | | `onImageUpload` | `(file: NativeFile) => Promise` | — | Upload handler for `field-image` **and** `field-avatar` (asset from expo-image-picker). Without it a picked avatar is never uploaded. | | `onFileUpload` | `(file: NativeFile) => Promise` | — | File field upload handler (asset from expo-document-picker) | | `onSubmit` | `(payload, context) => unknown` | — | Persistence handler — omitted: submit() returns the built payload | | `transformSubmit` | `(payload, context) => Record` | — | Rewrite the built payload before persistence | | `onSubmitSuccess` | `(result, payload) => void` | — | Called after a successful submit | | `onSubmitError` | `(error, payload) => void` | — | Called when validation or persistence fails | | `formActions` | `FormAction[] \| null` | — | Form lifecycle actions (onFormLoad / onFormBeforeSubmit / onFormAfterSubmit) | | `formCustomValidations` | `FormCustomValidationRule[] \| null` | — | Form-level JSONata validations — errors land in formValidationErrors | | `client` | `RestApiClient` | — | Optional passthrough to field / value components (never used for fetching) | ## Return Value | Key | Type | Description | |-----|------|-------------| | `mode` | `KivaFormViewMode` | Resolved mode | | `item` / `values` | `Record` | Live form values | | `defaultValues` | `Record` | Initial values (field defaults + record) | | `form` | `{ Field }` | Render-prop `form.Field` for custom field UI (`{ name, state: { value, meta }, handleChange, handleBlur }`) | | `fields` / `allFields` | `KivaFormViewField[]` | Resolved, visible fields (required / hidden / readOnly / disabled / renderMode / enforcedValidations / submitKeys …) | | `unsupportedFields` | `KivaFormViewField[]` | Fields rendered as values because no native editor exists | | `validationErrors` | `Map` | Per-field errors from the last `validate()` | | `formValidationErrors` | `string[]` | Form-level `formCustomValidations` errors — render them as an `Alert` banner | | `isDirty` | `boolean` | Values differ from the baseline (empty values normalized) | | `isLoading` | `boolean` | Data still loading | | `isSubmitting` | `boolean` | A submit is in flight | | `error` | `Error \| null` | Load / submit error | | `setValue` | `(slug, value) => void` | Programmatic write | | `validate` | `() => Promise` | required → tokens → JSONata `customValidations`, then form-level validations | | `reset` | `() => void` | Restore the baseline | | `submit` | `() => Promise` | Validate → `onFormBeforeSubmit` → build payload → persist → `onFormAfterSubmit` | | `resetActionOverrides` | `() => void` | Clear field-action and form-action property overrides | | `renderField` | `(slug, options?) => ReactNode` | Render one field (form or value mode) | | `renderLayout` | `(options?) => ReactNode` | Render the whole layout (sections / tabs / grid, or `EditableRecordDetail` with `clickToEdit`) | ## Type Exports | Type | Description | |------|-------------| | `UseDynamicFormViewOptions` | Hook options | | `UseDynamicFormViewResult` | Hook result | | `DynamicFormViewCallbackContext` | `onSubmit` / `transformSubmit` context (`mode`, `itemId`, `values`, `fields`) | | `DynamicFormViewMode` / `DynamicFormViewRenderMode` / `DynamicFormViewValidationTokenMode` | Mode unions | | `DynamicFormViewLayoutItem` / `DynamicFormViewSection` / `DynamicFormViewFieldsetSection` / `DynamicFormViewTabPanelSection` / `DynamicFormViewTabSection` / `DynamicFormViewLayoutFieldItem` / `DynamicFormViewColSpan` | Layout tree types | | `DynamicFormViewFieldLayout` | Per-field overrides | | `DynamicFormViewField` | Resolved field | | `DynamicFormViewRenderFieldOptions` / `DynamicFormViewRenderLayoutOptions` | `renderField` / `renderLayout` options | | `DynamicFormViewSubmitContext` | Engine submit context | --- # useKivaAdaptiveCardItemDetail URL: /docs/native/hooks/use-kiva-adaptive-card-item-detail Generate an Adaptive Card JSON payload from a Kiva field list + a single record — mapping Kiva field types onto the Adaptive Cards element vocabulary — and render it with the shared native AdaptiveCard renderer. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-adaptive-card-item-detail ``` **Dependencies:** - [react](https://react.dev) Installing the hook also installs [rn-adaptive-card](/docs/native/kiva/adaptive-card) and the pure mapper helpers (`_internal/kiva-adaptive-card*.ts`). The signature is identical to web `@kivacore/ui`, so the same field list and record produce the same card JSON on both platforms. ## Overview `useKivaAdaptiveCardItemDetail` is the bridge between **Kiva field types** (`field-select`, `field-money`, `field-image`, …) and the **Adaptive Cards** element vocabulary (`TextBlock`, `FactSet`, `Image`, `Badge`, `CodeBlock`, …). You hand it a field list + one record and it **generates an Adaptive Card JSON payload** (`card`) — the primary output. The card is then drawn by the shared [rn-adaptive-card](/docs/native/kiva/adaptive-card) renderer; the hook also returns a ready-to-render `view` and the full [`useAdaptiveCard`](/docs/native/hooks/use-adaptive-card) runtime (state / controls / `cardProps`) so you can wire actions. It is **backend-agnostic** — no network I/O. Pass any Kiva-shaped field list (`IField[]`, `DataSourceField[]`, or the loose `KivaAdaptiveCardField[]`) and a plain record object. When a [`KivaTenantProvider`](/docs/native/hooks/use-kiva-tenant) is mounted, date / number / currency values are formatted with the tenant's preferences automatically. ## Usage ### Generate + render a detail card ```tsx import { ScrollView } from 'react-native'; import { useKivaAdaptiveCardItemDetail } from '@/hooks/kiva-native/use-kiva-adaptive-card-item-detail'; export function DealDetail({ fields, record }) { const { view } = useKivaAdaptiveCardItemDetail({ fields, record }); return ; } ``` ### Use the generated JSON directly The `card` field is a plain Adaptive Card payload — persist it, post it to Teams, or render it yourself with ``. ```tsx import { AdaptiveCard } from '@/components/kiva-native/adaptive-card'; import { useKivaAdaptiveCardItemDetail } from '@/hooks/kiva-native/use-kiva-adaptive-card-item-detail'; const { card } = useKivaAdaptiveCardItemDetail({ fields, record }); // `card` === { type: 'AdaptiveCard', version: '1.5', body: [...] } await client.post('/teams/notify', card); return ; ``` ### Pin slots, add actions, react to clicks ```tsx const { view } = useKivaAdaptiveCardItemDetail({ fields, record, slots: { titleField: 'name', badgeField: 'status', coverImageField: 'cover', subtitleField: 'description' }, actions: [ { type: 'Action.OpenUrl', title: 'Open record', url: `myapp://records/${record.id}` } ], onAction: (event) => { // Action.OpenUrl also opens the URL via Linking; route in-app links yourself. if (event.type === 'openUrl') router.push(event.url); } }); ``` ## Field-type → Adaptive Card element mapping The card body is assembled from three regions: a header (cover / avatar / title / subtitle / status badge), a `FactSet` of scalar fields, and standalone blocks for rich fields. Slots are auto-detected from field type + slug (see [Slot detection](#slot-detection)); everything else lands in the body. | Kiva field type | Adaptive Card representation | |--------------------|------------------------------| | `field-text`, `field-email`, `field-url`, `field-phone`, `field-currency`, `field-color`, `field-icon`, `field-formula`, `field-identity` | Header title **or** `FactSet` value (`TextBlock`) | | `field-number`, `field-autonumber`, `field-money`, `field-percent`, `field-duration`, `field-rating` | `FactSet` value — formatted (currency, `%`, `★`, `hh:mm:ss`) | | `field-checkbox`, `field-switch` | `FactSet` value — `Yes`/`No`, `On`/`Off` | | `field-date`, `field-dateTime`, `field-time`, `field-dateRange` | `FactSet` value — tenant-formatted date/time | | `field-select`, `field-radioGroup`, `field-enum`, `field-systemEnum`, `field-status`, `field-approvalStatus` | Header status `Badge` (semantic color) **or** `FactSet` value (option name) | | `field-multiSelect`, `field-tagSelect` | `FactSet` value — comma-joined option names | | `field-userSelect` | `FactSet` value — user display name | | `field-userMultiSelect` | `FactSet` value — joined user names | | `field-relation`, `field-relatedField` | `FactSet` value — related record label | | `field-image`, `field-avatar` | Cover / avatar `Image`, or an `Image` / `ImageSet` body block | | `field-textarea`, `field-markdown`, `field-htmlEditor`, `field-emailEditor`, `field-docEditor` | Wrapped `TextBlock` block (HTML stripped) | | `field-json`, `field-jsonSchema`, `field-jsonata`, `field-handlebars`, `field-code`, `field-codeEditor`, `field-queryBuilder`, `field-dsql` | `CodeBlock` block (language-tagged) | | `field-file` | `FactSet` value — file name | | `field-locationSelect` | `FactSet` value — address label | | `field-taskList`, `field-todo` | `FactSet` value — `done / total` summary | | `field-adaptiveCard`, `field-button`, `field-password`, `field-inlineForm`, `field-schema*`, `field-inlineData`, `field-dynamic`, `field-conversationChannel`, `field-fileStorageFolder`, `field-system*` | Skipped (no meaningful card representation) | Enum / status colors (Tailwind families or hex) are classified to the nearest Adaptive Card badge style: green → `good`, red → `attention`, amber → `warning`, blue/purple → `accent`, otherwise `informative`. ## Slot detection When you don't pin slots, bindings are auto-detected from the field list using the same heuristics as the web data gallery (slug hints first, then type; system audit columns such as `id`, `created_by` and `record_owner` are never picked). Override any slot with a slug, or `null` to disable a detected binding: | Slot | Auto-detected from | |------|--------------------| | `titleField` | slug `name` / `title` / `subject` / `label`, then a text/identity field | | `subtitleField` | slug `description` / `summary` / `subtitle`, then a textarea field | | `coverImageField` | slug `cover` / `image` / `thumbnail` / `banner`, then a `field-image` | | `avatarField` | slug `avatar` / `profile_photo`, then a `field-avatar` | | `badgeField` | slug `status` / `priority` / `stage`, then a status/select field | | `timelineField` | slug `due` / `deadline` / `start`, then a `field-date` (leads the facts) | | `bodyFields` | every remaining non-system field | ## API Reference ### `UseKivaAdaptiveCardItemDetailOptions` | Option | Type | Default | Description | |--------|------|---------|-------------| | `fields` | `KivaAdaptiveCardField[]` | — | Field metadata (accepts `IField` / `DataSourceField` / `KivaFieldLike`). | | `record` | `Record \| null` | — | The record to render. | | `enumOptions` | `Record` | — | Per-field-slug enum options. Falls back to each field's inline `enums`. | | `slots` | `KivaAdaptiveCardSlotOverrides` | — | Pin (`string`) or disable (`null`) individual slot bindings. | | `includeFields` | `string[]` | — | Explicit, ordered body field list (replaces auto-detected body). | | `excludeFields` | `string[]` | — | Field slugs to drop from the body. | | `title` | `string` | — | Force the header title text. | | `actions` | `AdaptiveCardAction[]` | — | Card-level actions appended to `payload.actions`. | | `hideEmpty` | `boolean` | `true` | Drop empty fields instead of rendering an em-dash. | | `factLayout` | `'facts' \| 'stacked'` | `'facts'` | Scalar layout — a `FactSet` or stacked label/value blocks. | | `version` | `string` | `'1.5'` | Adaptive Card schema version. | | `formatDate` | `(value) => string` | tenant context | Override the date formatter. | | `formatDateTime` | `(value) => string` | tenant context | Override the datetime formatter. | | `formatNumber` | `(value, opts?: { variant?: 'number' \| 'currency' \| 'percent'; currency?: string; decimalPrecision?: number; thousandSeparator?: string }) => string` | tenant context | Override the number/currency/percent formatter. | | `className` | `string` | — | `className` forwarded to the rendered `view` (``). | | `onAction` | `(event: AdaptiveCardActionEvent) => void \| Promise` | — | Forwarded to `useAdaptiveCard`. | | `hostConfig` | `AdaptiveCardHostConfigOverride` | — | Forwarded to `useAdaptiveCard`. | | `customElements` | `Record` | — | Forwarded to `useAdaptiveCard`. | | `onChoiceQuery` | `(request: AdaptiveCardChoiceQueryRequest) => Promise` | — | Forwarded to `useAdaptiveCard`. | ### `UseKivaAdaptiveCardItemDetailReturn` Extends [`UseAdaptiveCardReturn`](/docs/native/hooks/use-adaptive-card) (`state`, `controls`, `cardProps`, `hostConfig`) with: | Field | Type | Description | |-------|------|-------------| | `card` | `AdaptiveCardPayload` | The generated Adaptive Card JSON — the primary output. | | `slots` | `KivaAdaptiveCardSlots` | The resolved slot bindings. | | `view` | `ReactNode` | Ready-to-render `` for the generated card. | ## Type Exports | Type | Description | |------|-------------| | `UseKivaAdaptiveCardItemDetailOptions` | Hook options. | | `UseKivaAdaptiveCardItemDetailReturn` | Hook return. | | `KivaAdaptiveCardField` | Minimal field shape (`slug` + `name` + `type`, optional `enums`). | | `KivaAdaptiveCardSlots` | Resolved slot bindings. | | `KivaAdaptiveCardSlotOverrides` | Slot override map (`string` to pin, `null` to disable). | | `KivaAdaptiveCardFactLayout` | `'facts' \| 'stacked'`. | ## See also - [`useKivaAdaptiveCardItemList`](/docs/native/hooks/use-kiva-adaptive-card-item-list) — the same mapping, for a list of records. - [rn-adaptive-card](/docs/native/kiva/adaptive-card) — the renderer. - [`useAdaptiveCard`](/docs/native/hooks/use-adaptive-card) — the underlying runtime. --- # useKivaAdaptiveCardItemList URL: /docs/native/hooks/use-kiva-adaptive-card-item-list Generate an array of Adaptive Card JSON payloads from a Kiva field list + many records, and render them as a responsive grid, a stacked list, a single Carousel card or a single Table card with the shared native AdaptiveCard renderer. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-adaptive-card-item-list ``` **Dependencies:** - [react](https://react.dev) The signature is identical to web `@kivacore/ui`. Only the rendered `view` differs: it is built from React Native `View`s. ## Overview `useKivaAdaptiveCardItemList` is the list companion of [`useKivaAdaptiveCardItemDetail`](/docs/native/hooks/use-kiva-adaptive-card-item-detail). You hand it a **Kiva field list + a list of records** and it **generates one Adaptive Card JSON payload per record** (`cards`) — mapping Kiva field types onto the Adaptive Cards element vocabulary — then renders them with the shared [rn-adaptive-card](/docs/native/kiva/adaptive-card) renderer. Both hooks share the same backend-agnostic mapper, so a card looks identical whether it's shown alone (detail) or in a list. Four layouts are supported: - **`grid`** (default) — rows of equal-width cards. With `columns: 'flex'` the column count is derived from the **window width** (`useWindowDimensions`): `floor((width + gap) / (minCardWidth + gap))`, at least 1. A phone therefore gets one column and a tablet gets two or more. A fixed number pins the count. - **`list`** — a single stacked column of cards. - **`carousel`** — one combined Adaptive Card whose `Carousel` pages are the per-record bodies. - **`table`** — one combined Adaptive Card whose `Table` has a field-label header row and one row per record (scalar fields become columns; images / rich-text / code are excluded). The native `Table` element gives every column a fixed width (`3` × 50 = 150 px) and scrolls horizontally inside a `ScrollView` when the columns are wider than the card. When a [`KivaTenantProvider`](/docs/native/hooks/use-kiva-tenant) is mounted, dates / numbers / currency are formatted with the tenant's preferences. See [`useKivaAdaptiveCardItemDetail`](/docs/native/hooks/use-kiva-adaptive-card-item-detail#field-type--adaptive-card-element-mapping) for the full field-type → element mapping and slot-detection rules. ## Usage ### Render a responsive grid of cards ```tsx import { ScrollView } from 'react-native'; import { useKivaAdaptiveCardItemList } from '@/hooks/kiva-native/use-kiva-adaptive-card-item-list'; export function DealGallery({ fields, records }) { const { view } = useKivaAdaptiveCardItemList({ fields, records, layout: 'grid', columns: 'flex', minCardWidth: 340 }); return ; } ``` The `view` is a plain, non-virtualized `View` tree, so it can sit inside a `ScrollView`. For hundreds of records, render `items` yourself in a `FlashList` (`numColumns`) with one `` per cell. ### Per-card actions + scoped click handler `onItemAction` receives the originating record and index, so one handler routes every card (not applied in `carousel` or `table` layout). ```tsx const { view } = useKivaAdaptiveCardItemList({ fields, records, getItemActions: (record) => [ { type: 'Action.OpenUrl', title: 'Open', url: `myapp://deals/${record.id}` } ], onItemAction: (event, record) => { if (event.type === 'openUrl') router.push(event.url); } }); ``` ### Use the generated JSON array directly ```tsx const { cards, items } = useKivaAdaptiveCardItemList({ fields, records }); // `cards` is AdaptiveCardPayload[] — one per record // `items` is [{ id, record, card }] if you need the record alongside its card await syncToTeams(cards); ``` ### Carousel ```tsx const { view, carouselCard } = useKivaAdaptiveCardItemList({ fields, records, layout: 'carousel' }); // `carouselCard` is the single combined AdaptiveCardPayload (a Carousel). return view; ``` ### Table ```tsx const { view, tableCard } = useKivaAdaptiveCardItemList({ fields, records, layout: 'table' }); // `tableCard` is the single combined AdaptiveCardPayload (a Table: // header row = field labels, one row per record). Scrolls horizontally // when wider than its container. return view; ``` ## API Reference ### `UseKivaAdaptiveCardItemListOptions` | Option | Type | Default | Description | |--------|------|---------|-------------| | `fields` | `KivaAdaptiveCardField[]` | — | Field metadata (accepts `IField` / `DataSourceField` / `KivaFieldLike`). | | `records` | `Record[] \| null` | — | Records to render as cards. | | `enumOptions` | `Record` | — | Per-field-slug enum options. Falls back to each field's inline `enums`. | | `slots` | `KivaAdaptiveCardSlotOverrides` | — | Slot bindings shared by every card. | | `includeFields` | `string[]` | — | Explicit, ordered body field list. | | `excludeFields` | `string[]` | — | Field slugs to drop from every card body. | | `hideEmpty` | `boolean` | `true` | Drop empty fields instead of rendering an em-dash. | | `factLayout` | `'facts' \| 'stacked'` | `'facts'` | Scalar layout — a `FactSet` or stacked label/value blocks. | | `version` | `string` | `'1.5'` | Adaptive Card schema version. | | `getRecordId` | `(record, index) => string` | `record.id` → index | Stable key per record. | | `getItemTitle` | `(record, index) => string \| undefined` | — | Per-card title override. | | `getItemActions` | `(record, index) => AdaptiveCardAction[] \| undefined` | — | Per-card actions. | | `onItemAction` | `(event: AdaptiveCardActionEvent, record, index) => void \| Promise` | — | Action handler scoped to the record. Not applied in `carousel` / `table`. | | `layout` | `'grid' \| 'list' \| 'carousel' \| 'table'` | `'grid'` | Rendered layout. `carousel` / `table` produce one combined card. | | `columns` | `number \| 'flex'` | `'flex'` | Grid columns. `'flex'` derives the count from the window width and `minCardWidth`. | | `minCardWidth` | `number` | `320` | Minimum card width (px) for the `'flex'` grid. | | `gap` | `number` | `16` | Gap (px) between cards. | | `className` | `string` | — | `className` for the list container `View` (or the combined carousel / table card). | | `cardClassName` | `string` | — | `className` for each card (`grid` / `list`). | | `emptyContent` | `ReactNode` | built-in | Shown when there are no records. The built-in state reads `ui.adaptiveCard.noRecords` (fallback "No records to display.") through `useUiTranslation`. | | `formatDate` | `(value: unknown) => string` | tenant context | Override the date formatter. | | `formatDateTime` | `(value: unknown) => string` | tenant context | Override the datetime formatter. | | `formatNumber` | `KivaAdaptiveCardFormatters['formatNumber']` | tenant context | Override the number / currency / percent formatter. | | `hostConfig` | `AdaptiveCardHostConfigOverride` | — | Forwarded to every rendered card. | | `customElements` | `Record` | — | Forwarded to every rendered card. | ### `UseKivaAdaptiveCardItemListReturn` | Field | Type | Description | |-------|------|-------------| | `cards` | `AdaptiveCardPayload[]` | The generated Adaptive Card JSON payloads — the primary output. | | `items` | `KivaAdaptiveCardListItem[]` | `{ id, record, card }` per record. | | `slots` | `KivaAdaptiveCardSlots` | Slot bindings shared by every card. | | `carouselCard` | `AdaptiveCardPayload \| null` | Combined `Carousel` card in `carousel` layout, else `null`. | | `tableCard` | `AdaptiveCardPayload \| null` | Combined `Table` card in `table` layout (header row = field labels, one row per record), else `null`. | | `view` | `ReactNode` | Ready-to-render list element. | ## Type Exports | Type | Description | |------|-------------| | `UseKivaAdaptiveCardItemListOptions` | Hook options. | | `UseKivaAdaptiveCardItemListReturn` | Hook return. | | `KivaAdaptiveCardListItem` | `{ id, record, card }`. | | `KivaAdaptiveCardListLayout` | `'grid' \| 'list' \| 'carousel' \| 'table'`. | | `KivaAdaptiveCardField` | Minimal field shape. | | `KivaAdaptiveCardSlots` / `KivaAdaptiveCardSlotOverrides` | Slot bindings / overrides. | | `KivaAdaptiveCardFactLayout` | `'facts' \| 'stacked'`. | ## See also - [`useKivaAdaptiveCardItemDetail`](/docs/native/hooks/use-kiva-adaptive-card-item-detail) — single-record detail card + the full mapping table. - [rn-adaptive-card](/docs/native/kiva/adaptive-card) — the renderer. --- # useKivaAgentAttachments URL: /docs/native/hooks/use-kiva-agent-attachments Uploads chat attachments to a Kiva agent thread (creating the thread on first use) and returns the storage paths for the chat request. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-agent-attachments ``` **Dependencies:** - [ai](https://www.npmjs.com/package/ai) Port of the web hook with one native change: the web hook fetches each file's `blob:` URL; on React Native `FileUIPart.url` is the local `file://` / `content://` URI returned by the picker, so the upload appends the RN FormData file shape `{ uri, name, type }` instead. Thread state is **controlled**: pass the active `threadId` (`null` for a new chat) and capture the created id with `onThreadCreated`. [`useKivaAgentChat`](/docs/native/hooks/use-kiva-agent-chat) already embeds it. Endpoints: `POST /v1/apps/base/data-sources/thread/items` (create thread, `thread_type: 'assistant'`) and `POST /v1/apps/base/data-sources/thread/items/{threadId}/files/upload` (multipart `file`). ## Usage ```tsx const [threadId, setThreadId] = useState(null); const { resolveFilePaths, ensureThread } = useKivaAgentAttachments({ client, agentId: AGENT_ID, threadId, onThreadCreated: setThreadId }); const onSendMessage = async ({ text, files }: AgentMessagePayload) => { await ensureThread(text); const { filePaths } = files?.length ? await resolveFilePaths(files, text) : { filePaths: [] }; await sendMessage({ text }, { body: { files: filePaths, supportFiles: filePaths.length > 0 } }); }; ``` ## API Reference ### UseKivaAgentAttachmentsArgs | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `KivaAgentAttachmentsClient \| null \| undefined` | - | Client with `post(url, body)` | | `agentId` | `string` | - | Tenant AI agent ID (required) | | `threadId` | `string \| null` | - | Current thread; `null` → first call creates one (required) | | `onThreadCreated` | `(threadId: string) => void` | - | Fires when a new thread is created | | `projectId` | `string \| null` | `null` | Project scope of new threads | | `deploymentId` | `string \| null` | `null` | Deployment scope of new threads | | `senderName` | `string` | `'User'` | `sender_name` of new threads | | `threadSubject` | `(messageText: string) => string` | first 100 chars | Subject of new threads | ### UseKivaAgentAttachmentsResult | Field | Type | Description | |-------|------|-------------| | `resolveFilePaths` | `(files: FileUIPart[], messageText: string) => Promise<{ filePaths: string[]; threadId: string \| null }>` | Uploads every file, returns storage paths | | `ensureThread` | `(messageText: string) => Promise` | Returns the current thread id or creates one | --- # useKivaAgentChat URL: /docs/native/hooks/use-kiva-agent-chat The complete streaming chat runtime for a Kiva AI agent — AI SDK transport, threads, attachment uploads and client-side tool execution — ready to drive KivaAgent. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-agent-chat ``` **Dependencies:** - [ai](https://www.npmjs.com/package/ai) - [@ai-sdk/react](https://www.npmjs.com/package/@ai-sdk/react) - [zod](https://www.npmjs.com/package/zod) - [@tanstack/react-query](https://www.npmjs.com/package/@tanstack/react-query) Native-first hook (platform-neutral name, so web can adopt it later) that extracts the transport and tool loop the web `EditorAgent` builds inline. It wires `@ai-sdk/react` `useChat` + `ai` `DefaultChatTransport` to `${apiBaseUrl}/ai/agents/${agentId}/chat` with a per-request bearer token, embeds [`useKivaAgentThreads`](/docs/native/hooks/use-kiva-agent-threads) and [`useKivaAgentAttachments`](/docs/native/hooks/use-kiva-agent-attachments), sends the last `maxHistoryLength` messages (file parts stripped) with `threadId`, `modelId`, `files`, `supportFiles`, `featureFlags`, `pageDataSourceId`, `additionalContext` and your `extraBody`, and auto-executes registered **client tools** (results go back with `addToolOutput`; `sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls` continues the turn). ### Streaming on React Native No polyfills are needed on **Expo SDK 57**: its WinterCG runtime (`expo/src/winter`) replaces the global `fetch` with the streaming `expo/fetch` and installs `TextDecoderStream`, `TextEncoderStream` and `structuredClone` (Metro injects `ReadableStream`). If your app sets `EXPO_PUBLIC_USE_RN_FETCH=1` or is a bare React Native app, pass a streaming implementation through the `fetch` option (e.g. `import { fetch } from 'expo/fetch'`) and install those globals yourself (`@ungap/structured-clone`, `@stardazed/streams-text-encoding`). ### Host singletons `ai` and `@ai-sdk/react` are **not** host singletons: the `Chat` instance lives inside the hook and only plain `UIMessage` data crosses the boundary (the same classification as on web), so the CLI installs them as regular dependencies. `ai` needs `zod` (`^3.25.76 || ^4.1.8`) as a peer. ## Usage ```tsx import { useKivaAuth } from '@kivacore/signin/react-native'; import { KivaAgent, KivaAgentThreadsSidebar } from '@/components/kiva-native/kiva-agent'; import { useKivaAgentChat } from '@/hooks/kiva-native/use-kiva-agent-chat'; import { useKivaAgentInfo } from '@/hooks/kiva-native/use-kiva-agent-info'; export function AssistantScreen() { const { client, user } = useKivaAuth(); const info = useKivaAgentInfo({ client, agentId: AGENT_ID }); const chat = useKivaAgentChat({ agentId: AGENT_ID, apiBaseUrl: 'https://api.kiva.app/v1', getAccessToken: () => client?.getAccessToken() ?? null, client, userId: user?.id, clientTools: [{ name: 'open_record', execute: input => router.push(`/records/${(input as { id: string }).id}`) }] }); if (!info.agent) return null; return ( ); } ``` ## API Reference ### UseKivaAgentChatArgs | Option | Type | Default | Description | |--------|------|---------|-------------| | `agentId` | `string` | - | Tenant AI agent ID (required) | | `apiBaseUrl` | `string` | - | API base URL **including** `/v1` (required) | | `getAccessToken` | `() => string \| null \| undefined \| Promise<…>` | - | Bearer token, called on every request | | `client` | `KivaAgentChatClient \| null \| undefined` | - | REST client (`get` / `post` / `patch` / `delete`) for threads + uploads (required) | | `userId` | `string \| null` | `null` | Restrict the thread list to this user | | `projectId` | `string \| null` | `null` | Scope new threads + the thread list to a project | | `deploymentId` | `string \| null` | `null` | Scope new threads to a deployment | | `senderName` | `string` | `'User'` | `sender_name` of new threads | | `extraBody` | `() => Record \| null \| undefined` | - | Extra request-body fields (called per send) | | `additionalContext` | `() => string \| null \| undefined` | - | Per-turn system-prompt context (called per send) | | `dataSourceId` | `string \| null` | `null` | Sent as `pageDataSourceId` | | `clientTools` | `ReadonlyArray` | - | `{ name, execute(input) }` tools run on the device | | `modelId` | `string` | `'default'` | Model id sent to the backend | | `maxHistoryLength` | `number` | `10` | Trailing messages sent as history | | `fetch` | `typeof fetch` | global `fetch` | Streaming fetch implementation | | `throttle` | `number` | `50` | `useChat` UI update throttle (ms) | | `enableThreads` | `boolean` | `true` | Load the thread list | ### UseKivaAgentChatResult | Field | Type | Description | |-------|------|-------------| | `messages` | `UIMessage[]` | Chat messages | | `chatStatus` | `ChatStatus` | `'ready' \| 'submitted' \| 'streaming' \| 'error'` | | `error` | `Error \| undefined` | Last transport error | | `sendMessage` | `(payload: AgentMessagePayload) => Promise` | Ensures a thread, uploads files, sends — pass to `onSendMessage` | | `stop` | `() => void` | Abort the stream — pass to `onStopGeneration` | | `regenerate` | `() => Promise` | Regenerate the last reply | | `newThread` | `() => void` | Clear and start a new thread | | `selectThread` | `(thread \| id) => Promise` | Load a thread's messages (its tool calls are never re-executed) | | `deleteThread` | `(thread \| id) => Promise` | Delete; resets when it was active | | `renameThread` | `(thread \| id, subject) => Promise` | Rename | | `activeThreadId` | `string \| null` | Current thread | | `setMessages` | `(messages: UIMessage[]) => void` | Replace messages | | `threads` | `UseKivaAgentThreadsResult` | Thread list + loading flags (for `KivaAgentThreadsSidebar`) | ### KivaAgentClientTool | Field | Type | Description | |-------|------|-------------| | `name` | `string` | Tool key — must match the `tenant_ai_tool.key` registered to the agent | | `execute` | `(input: unknown) => unknown \| Promise` | Local handler; a thrown error is returned as `{ ok: false, error: { message } }` | --- # useKivaAgentInfo URL: /docs/native/hooks/use-kiva-agent-info Fetches a Kiva AI agent's profile, suggestions and capabilities from the agent-deployment endpoint and maps them onto the KivaAgent props. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-agent-info ``` **Dependencies:** - [@tanstack/react-query](https://www.npmjs.com/package/@tanstack/react-query) A verbatim port of the web hook. It reads `GET /v1/ai/agent-deployments/base/{agentId}` (or `/v1/ai/agent-deployments/{deploymentId}`) and returns an `AgentProfile` (name, description, welcome message, avatar), the agent's standard suggestions, and its feature capabilities, ready to spread onto [rn-kiva-agent](/docs/native/kiva/kiva-agent). A `QueryClientProvider` must be mounted above it. ## Usage ```tsx import { KivaAgent } from '@/components/kiva-native/kiva-agent'; import { useKivaAgentInfo } from '@/hooks/kiva-native/use-kiva-agent-info'; function Assistant({ client }) { const { agent, suggestions, capabilities } = useKivaAgentInfo({ client, agentId: AGENT_ID }); if (!agent) return null; return ; } ``` ## API Reference ### UseKivaAgentInfoArgs | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `KivaAgentInfoClient \| null \| undefined` | - | Client with a `get(url, params?)` method (e.g. `RestApiClient`) | | `agentId` | `string \| null` | `null` | Tenant AI agent ID (base deployment) | | `deploymentId` | `string \| null` | `null` | Read a specific deployment instead of the base record | | `enabled` | `boolean` | `!!client && (agentId \|\| deploymentId)` | Toggle the query | ### UseKivaAgentInfoResult | Field | Type | Description | |-------|------|-------------| | `agent` | `AgentProfile \| null` | Mapped profile, `null` until loaded | | `suggestions` | `string[]` | `standardSuggestions` of the agent | | `capabilities` | `AgentCapabilities` | `supportFiles`, `supportWebSearch`, `supportDocumentSearch` (backend `documentSearch`), `supportThinking`, `supportDeepResearch`, `supportWorkCanvas` (backend `featureWorks`), `supportMultipleModels`, `promptOptimizationChoice` | | `raw` | `KivaAgentDeploymentEnvelope \| null` | Raw deployment payload | | `isLoading` | `boolean` | Query loading flag | | `error` | `Error \| null` | Query error | | `refresh` | `() => Promise` | Refetch | Query key: `['kiva-agent', 'info', deploymentId ?? 'base:']` (same as web). --- # useKivaAgentMemories URL: /docs/native/hooks/use-kiva-agent-memories Backend glue for the KivaAgent memory manager — list, create, update and delete /v1/ai/memories with optimistic local state. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-agent-memories ``` A verbatim port of the web hook (no React Query — plain local state with optimistic updates). Feed its result into [`KivaAgentMemoriesView`](/docs/native/kiva/kiva-agent#memories). ## Usage ```tsx import { KivaAgentMemoriesView } from '@/components/kiva-native/kiva-agent'; import { useKivaAgentMemories } from '@/hooks/kiva-native/use-kiva-agent-memories'; const memories = useKivaAgentMemories({ client, agentId: AGENT_ID, userId: user?.id }); ``` ## API Reference ### UseKivaAgentMemoriesArgs | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `KivaAgentMemoriesClient \| null \| undefined` | - | Client with `get` / `post` / `patch` / `delete` | | `enabled` | `boolean` | `true` | Run the initial fetch | | `agentId` | `string` | - | Agent scope of created memories | | `projectId` | `string \| null` | `null` | Project scope of created memories | | `userId` | `string \| null` | `null` | User scope of created memories | | `listParams` | `Record` | - | Extra query params for the list call | ### UseKivaAgentMemoriesResult | Field | Type | Description | |-------|------|-------------| | `memories` | `ReadonlyArray` | Current list | | `isLoading` / `isSaving` | `boolean` | Fetch / save state | | `deletingId` | `string \| null` | Memory being deleted | | `error` | `string \| null` | Last error message | | `refresh` | `() => Promise` | Re-fetch `GET /v1/ai/memories` | | `create` | `(form: KivaAgentMemoryFormState) => Promise` | `POST /v1/ai/memories` | | `update` | `(memory, form) => Promise` | `PATCH /v1/ai/memories/{id}` | | `remove` | `(memory) => Promise` | `DELETE /v1/ai/memories/{id}` | --- # useKivaAgentMemoryCandidates URL: /docs/native/hooks/use-kiva-agent-memory-candidates Backend glue for the KivaAgent memory-extraction dialog — extract candidates from a thread, then save or skip them. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-agent-memory-candidates ``` A verbatim port of the web hook. `extract()` calls `GET /v1/ai/memory-candidates` for the thread; `save` / `saveAll` write through `POST /v1/ai/memories`; skipping and level changes are local. Drive [`KivaAgentMemoryExtractionDialog`](/docs/native/kiva/kiva-agent#memories) with it. ## Usage ```tsx const candidates = useKivaAgentMemoryCandidates({ client, threadId: activeThreadId, agentId: AGENT_ID }); ``` ## API Reference ### UseKivaAgentMemoryCandidatesArgs | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `KivaAgentMemoryCandidatesClient \| null \| undefined` | - | Client with `get` / `post` | | `threadId` | `string \| null` | - | Thread to extract from (required to extract / save) | | `agentId` | `string` | - | Agent the memories belong to (required to save) | | `projectId` | `string \| null` | `null` | Project scope of saved memories | | `userId` | `string \| null` | `null` | User scope of saved memories | | `defaultImportance` | `number` | `3` | Importance when a candidate has none | | `defaultLevel` | `string` | `'user_agent'` | Level when a candidate has none | ### UseKivaAgentMemoryCandidatesResult | Field | Type | Description | |-------|------|-------------| | `candidates` | `ReadonlyArray` | Current candidates | | `isLoading` / `isSaving` | `boolean` | Extract / save state | | `error` | `string \| null` | Last error | | `extract` | `() => Promise` | Fetch candidates for `threadId` | | `save` | `(candidate) => Promise` | Save one | | `skip` | `(candidate) => void` | Skip one (local) | | `saveAll` | `() => Promise` | Save every candidate | | `skipAll` | `() => void` | Clear the list (local) | | `setLevel` | `(candidate, level: string) => void` | Change a candidate's level (local) | | `setCandidates` | `(candidates) => void` | Replace the list | | `reset` | `() => void` | Reset all state | --- # useKivaAgentProjects URL: /docs/native/hooks/use-kiva-agent-projects Lists, creates, renames and deletes Kiva AI projects scoped to an agent. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-agent-projects ``` **Dependencies:** - [@tanstack/react-query](https://www.npmjs.com/package/@tanstack/react-query) A verbatim port of the web hook. Endpoints: `GET /v1/ai/projects`, `POST /v1/ai/projects` (`{ name, description?, tenant_ai_agent_id }`), `PATCH /v1/ai/projects/{id}` (`{ name }`), `DELETE /v1/ai/projects/{id}`. The list is filtered client-side to the agent (and to `userId` when given). Pair it with `KivaAgentProjectsView` / `KivaAgentSidebarProjectsSection`. ## Usage ```tsx import { KivaAgentProjectsView } from '@/components/kiva-native/kiva-agent'; import { useKivaAgentProjects } from '@/hooks/kiva-native/use-kiva-agent-projects'; const { projects, createProject, deleteProject } = useKivaAgentProjects({ client, agentId: AGENT_ID }); ``` ## API Reference ### UseKivaAgentProjectsArgs | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `KivaAgentProjectsClient \| null \| undefined` | - | Client with `get` / `post` / `patch` / `delete` | | `agentId` | `string` | - | Tenant AI agent ID (required) | | `userId` | `string \| null` | `null` | Only projects owned by / shared with this user | | `enabled` | `boolean` | `!!client` | Toggle the list query | ### UseKivaAgentProjectsResult | Field | Type | Description | |-------|------|-------------| | `projects` | `KivaAgentProject[]` | `{ id, name, description?, agentId?, deploymentId?, createdBy?, sharedTo? }` | | `isLoading` / `error` | `boolean` / `Error \| null` | List query state | | `refresh` | `() => Promise` | Invalidate the list | | `createProject` | `(input: CreateProjectInput) => Promise` | `{ name, description? }` | | `isCreating` | `boolean` | Create pending | | `renameProject` | `(projectId, name) => Promise` | Rename | | `isRenaming` | `boolean` | Rename pending | | `deleteProject` | `(projectId) => Promise` | Delete | | `isDeleting` | `boolean` | Delete pending | --- # useKivaAgentThreads URL: /docs/native/hooks/use-kiva-agent-threads Lists, renames, deletes and loads the messages of Kiva AI assistant chat threads. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-agent-threads ``` **Dependencies:** - [@tanstack/react-query](https://www.npmjs.com/package/@tanstack/react-query) - [ai](https://www.npmjs.com/package/ai) A verbatim port of the web hook. It manages the `thread` records (`thread_type: 'assistant'`) of an agent and turns stored messages into AI SDK `UIMessage[]`, ready for `useChat().setMessages`. [`useKivaAgentChat`](/docs/native/hooks/use-kiva-agent-chat) already embeds it. Endpoints: `GET /v1/apps/base/data-sources/thread/items` (list), `PATCH …/thread/items/{id}` (rename), `DELETE …/thread/items/{id}` (delete), `GET /v1/apps/base/data-sources/message/items` (messages, max 200). ## Usage ```tsx import { KivaAgentThreadsSidebar } from '@/components/kiva-native/kiva-agent'; import { useKivaAgentThreads } from '@/hooks/kiva-native/use-kiva-agent-threads'; const threads = useKivaAgentThreads({ client, agentId: AGENT_ID, userId: user?.id }); setMessages(await threads.loadMessages(thread.id))} onRenameThread={(thread, subject) => threads.renameThread(thread.id, subject)} onDeleteThread={thread => threads.deleteThread(thread.id)} /> ``` ## API Reference ### UseKivaAgentThreadsArgs | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `KivaAgentThreadsClient \| null \| undefined` | - | Client with `get` / `post` / `patch` / `delete` | | `agentId` | `string` | - | Tenant AI agent ID (required) | | `userId` | `string \| null` | `null` | Only threads owned by / shared with this user | | `projectId` | `string \| null` | `null` | Only threads of this project | | `deploymentId` | `string \| null` | `null` | Filter by deployment instead of agent | | `enabled` | `boolean` | `!!client` | Toggle the list query | ### UseKivaAgentThreadsResult | Field | Type | Description | |-------|------|-------------| | `threads` | `KivaAgentThread[]` | `{ id, title, createdAt, updatedAt, bodyText?, createdBy?, createdByName?, projectId? }`, newest first | | `isLoading` / `error` | `boolean` / `Error \| null` | List query state | | `refresh` | `() => Promise` | Invalidate the list | | `loadMessages` | `(threadId) => Promise` | Messages as `UIMessage[]` (from `body_json.parts`, else `body_text`) | | `isLoadingMessages` | `boolean` | `loadMessages` pending | | `renameThread` | `(threadId, subject) => Promise` | Rename | | `isRenaming` | `boolean` | Rename pending | | `deleteThread` | `(threadId) => Promise` | Delete | | `isDeleting` | `boolean` | Delete pending | --- # useKivaCalendar URL: /docs/native/hooks/use-kiva-calendar Calendar backed by a Kiva data source. Detects the date, title, color, description and user fields, turns records into events, and wires create, update, delete and drag to the API. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-calendar ``` **Dependencies:** - [@kivacore/api-client](https://www.npmjs.com/package/@kivacore/api-client) - [@kivacore/app-utils](https://www.npmjs.com/package/@kivacore/app-utils) - [@tanstack/react-query](https://tanstack.com/query/latest) This is a port of the web hook with the same signature. It builds on [`useKivaDataGrid`](/docs/native/hooks/use-kiva-data-grid), which supplies saved views, the toolbar, filters, search and field metadata. Its own items query then requests only the columns the calendar needs. `calendarProviderProps` is ready to spread onto the native [rn-calendar](/docs/native/kiva/calendar), which supports all eight views (including `year-timeline`, `quarter` and `13weeks`). It passes: - `isRefreshing` (from `itemsQuery.isFetching`) - the timeline options - the user `filterItems` - `onEventCreate` / `onEventUpdate` / `onEventDelete` / `onEventDrop`, each calling the Kiva API With `enableDateRangeFilter`, the query adds an overlap rule (`start <= rangeEnd AND end >= rangeStart`) and refetches whenever the visible range changes. The hook needs an authenticated `RestApiClient` and a `QueryClientProvider` above it. ## Usage ```tsx import { useKivaClient } from '@kivacore/signin/react-native'; import { Calendar } from '@/components/kiva-native/calendar'; import { useKivaCalendar } from '@/hooks/kiva-native/use-kiva-calendar'; export function EventsCalendar() { const client = useKivaClient(); const cal = useKivaCalendar({ client: client!, appSlug: 'base', dataSourceSlug: 'event', startDateFieldSlug: 'start_date', endDateFieldSlug: 'end_date', titleFieldSlug: 'subject', descriptionFieldSlug: 'description', enableDateRangeFilter: true, persistState: true }); // Render a skeleton only on the very first load — passing `isLoading` on // every refetch would unmount the calendar and reset its view + date. if (!cal.hasLoadedOnce) return null; return ( <> {cal.toolbar} ); } ``` ## API Reference ### Options (`UseKivaCalendarOptions`) Extends every [`useKivaDataGrid`](/docs/native/hooks/use-kiva-data-grid) option except `data`, `enableItemsQuery`, `showSelectColumn`, `enableRowMarkers` and `collection`, which the calendar owns. | Prop | Type | Default | Description | |------|------|---------|-------------| | `client` | `RestApiClient` | — | Authenticated Kiva API client (required) | | `appSlug` | `string` | — | App slug (required) | | `dataSourceSlug` | `string` | — | Data source slug (required) | | `collection` | `KivaCalendarCollection` | — | Custom `list` / `create` / `update` / `delete` adapter | | `startDateFieldSlug` | `string` | first `field-date` / `field-dateTime` | Event start field | | `endDateFieldSlug` | `string` | `end_date`, `end_time`, `due_date`, … or the second date field | Event end field | | `titleFieldSlug` | `string` | `name`, `title`, `label`, `subject`, … | Event title field | | `colorFieldSlug` | `string` | `color` / `colour` | Event color field | | `descriptionFieldSlug` | `string` | `description`, `notes`, `content`, … | Event description field | | `userFieldSlug` | `string` | first user field, then `record_owner` | User field that fills the user filter | | `colorMap` | `Record` | — | Maps field values to event colors | | `defaultEventDurationMinutes` | `number` | `60` | Event length when the end date is missing | | `getEvent` | `(item, context) => KivaCalendarEvent \| null` | — | Replaces the built-in event builder. Return `null` to skip a record | | `defaultView` | `TCalendarView` | `'month'` | Initial view | | `enableDateRangeFilter` | `boolean` | `false` | Limits the query to the visible range. Native wires `onVisibleRangeChange` for you | | `timelineMaxLanes` | `number` | `3` | Lanes shown in each timeline row before `+N more` | | `defaultYearTimelineMode` | `'continuous' \| 'single'` | `'continuous'` | Initial pagination mode of the year timeline | | `defaultQuarterMode` | `'continuous' \| 'single'` | `'continuous'` | Initial pagination mode of the quarter view | | `staleTime` | `number` | `30000` | React Query stale time in ms | | `enableGroupMenu` | `boolean` | `false` | Shows the group menu in the grid toolbar | | `enableRowHeightMenu` | `boolean` | `false` | Shows the row-height menu in the grid toolbar | | `enableDisplayMenu` | `boolean` | `false` | Shows the display menu in the grid toolbar | | `onReload` | `() => void` | — | Called after a toolbar reload | | `persistState` | `boolean \| { storage?: 'session' \| 'local'; key?: string }` | — | Saves the grid's view parameters for each saved view | ### Result (`UseKivaCalendarResult`) | Key | Type | Description | |-----|------|-------------| | `calendarProviderProps` | `Omit` | Ready to spread onto `` / `` | | `events` | `KivaCalendarEvent[]` | Transformed events | | `users` | `IUser[]` | Unique event users | | `filterItems` | `CalendarFilterItem[]` | User filter items | | `items` | `TData[]` | Raw records | | `startDateField` / `endDateField` / `titleField` / `colorField` / `descriptionField` / `userField` | `DataSourceField \| null` | Resolved fields | | `hasDateField` | `boolean` | Whether a start-date field was found | | `requestedColumns` | `string` | `columns` sent to the items endpoint | | `resolvedListParams` | `KivaDataGridListParams` | Full query payload | | `createRecord` | `(start, end, extra?) => Promise` | Creates a record | | `updateRecord` | `(recordId, data) => Promise` | Updates a record | | `deleteRecord` | `(recordId) => Promise` | Deletes a record | | `moveRecord` | `(recordId, newStart, newEnd) => Promise` | Updates the start and end fields | | `visibleRange` / `setVisibleRange` | `{ start: Date; end: Date } \| null` / setter | The range that drives the date-range filter | | `isLoading` / `isFetching` / `hasLoadedOnce` | `boolean` | Loading flags | | `error` | `Error \| null` | Error from the schema or items request | | `reload` | `() => void` | Refetches the schema and the items | | `table` / `toolbar` / `views` / `fields` / `dataSource` / `activeViewId` / `setActiveViewId` | — | Passed through from `useKivaDataGrid` | ## Native deltas - `toolbar` / `table` come from the native `useKivaDataGrid`, which stacks the toolbar for small screens. - With `enableDateRangeFilter`, `calendarProviderProps.onVisibleRangeChange` is already wired to `setVisibleRange`. On web you wire it yourself. Pass your own `onVisibleRangeChange` after the spread to override it. Identical ranges are ignored. - The items query keeps the previous result while a new range loads (`keepPreviousData`). Navigating shows the `isRefreshing` spinner over the current events instead of clearing the calendar. ## Type Exports | Type | Description | |------|-------------| | `UseKivaCalendarOptions` | Hook options | | `UseKivaCalendarResult` | Hook result | | `KivaCalendarEvent` | `IEvent` plus `recordId` and `item` | | `KivaCalendarCollection` | Collection adapter | | `KivaCalendarEventBuilderContext` | Context passed to `getEvent` | | `IEvent`, `IUser`, `TCalendarView`, `TEventColor`, `CalendarFilterItem` | Re-exported calendar types | --- # useKivaContactActivity URL: /docs/native/hooks/use-kiva-contact-activity Merges a record's audit log, comments, related events and tasks, and status updates into one typed timeline for ContactActivityPanel, with upcoming items, a relationship summary and comment and status mutations. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-contact-activity ``` **Dependencies:** - [@tanstack/react-query](https://www.npmjs.com/package/@tanstack/react-query) The hook needs a `QueryClientProvider` above it. It is also re-exported from `@/components/kiva-native/contact-activity-panel`. ## Usage ```tsx import { useKivaClient } from '@kivacore/signin/react-native'; import { ContactActivityPanel } from '@/components/kiva-native/contact-activity-panel'; import { useKivaContactActivity } from '@/hooks/kiva-native/use-kiva-contact-activity'; export function ContactActivity({ contactId, meId }: { contactId: string; meId: string }) { const client = useKivaClient(); const { panelProps } = useKivaContactActivity({ client, appSlug: 'base', dataSourceSlug: 'contact', recordId: contactId, relationSlug: 'contact', currentUserId: meId }); return ; } ``` ### Sources | Source | Request | Becomes | |--------|---------|---------| | `audit` | `GET {record}/activities` | `record_create`, `record_update`, `file`, `trace`, … rows (comment operations are skipped) | | `comments` | `GET {record}/comments` | `comment` cards. Replies stay off the timeline and are served by `onLoadReplies` | | `events` | `GET /v1/apps/{eventApp}/data-sources/{eventDs}/items` filtered by `eventRelationSlug ?? relationSlug` | `call` or `meeting` cards, classified by `classifyEvent` or `eventTypeNames` | | `tasks` | `GET /v1/apps/{taskApp}/data-sources/{taskDs}/items` filtered by `taskRelationSlug ?? relationSlug` | `task` rows plus open-task counts and upcoming tasks | | `statusUpdates` | `GET /v1/apps/{activityApp}/data-sources/{activityDs}/items` for this record | `status_update` rows | | `files` | `GET {record}/files` | `file` rows carrying a real `PostAttachment` (name, size, MIME, signed URL). With this on, the audit log's bare `UPLOAD_FILE` traces are dropped — same upload, less information | `{record}` is `/v1/apps/:appSlug/data-sources/:dataSourceSlug/items/:recordId`. Users come from `/v1/users` unless you pass `users`. Events and tasks are only fetched when a relation slug is set. Every query lives under the `['kiva-contact-activity', {record}]` prefix, which [`useKivaLogActivity`](/docs/native/hooks/use-kiva-log-activity) invalidates after each log, so a mounted timeline refreshes by itself. `CreatePostPayload.attachments` are `NativeFile`s on native. Like web, the hook currently posts only `message` and `parentId`. ## API Reference ### UseKivaContactActivityOptions | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `ContactActivityClient` | - | REST client with `get` / `post` / `patch` / `delete`. `RestApiClient` fits (required) | | `appSlug` | `string` | - | Owning record's app (required) | | `dataSourceSlug` | `string` | - | Owning record's data source (required) | | `recordId` | `string` | - | Owning record id (required) | | `relationSlug` | `string` | - | Back-relation slug on events and tasks. Without it those sources stay off | | `eventRelationSlug` | `string` | `relationSlug` | Event back-relation override | | `taskRelationSlug` | `string` | `relationSlug` | Task back-relation override | | `sources` | `ContactActivitySources` | all `true` | Toggle `audit`, `comments`, `events`, `tasks`, `statusUpdates`, `files` | | `eventAppSlug` | `string` | `'base'` | Events app | | `eventDataSourceSlug` | `string` | `'event'` | Events data source | | `taskAppSlug` | `string` | `'base'` | Tasks app | | `taskDataSourceSlug` | `string` | `'task'` | Tasks data source | | `activityAppSlug` | `string` | `'base'` | Status-activity app | | `activityDataSourceSlug` | `string` | `'activity'` | Status-activity data source | | `users` | `ChatUser[]` | - | Users instead of fetching `/v1/users` | | `currentUserId` | `string` | - | Current user id | | `activityTypes` | `ActivityType[]` | - | Passed to the panel's type filter | | `eventTypeNames` | `EventTypeNameHints` | `{ call: ['call', 'phone'], meeting: ['meeting', 'visit', 'demo'] }` | Name substrings used to classify events | | `classifyEvent` | `(event: Record) => 'call' \| 'meeting'` | - | Custom classifier (wins over `eventTypeNames`) | | `relatedColumns` | `{ events?: string[]; tasks?: string[] }` | - | Extra relation columns fetched on the event / task sources and surfaced as related chips in the detail sheet. Relation slugs are per-tenant and an unknown column fails the whole request, so nothing is requested unless you name it | | `limit` | `number` | `100` | Page size per source | | `enabled` | `boolean` | `true` | Toggle every query | ### UseKivaContactActivityResult | Field | Type | Description | |-------|------|-------------| | `activities` | `ContactActivity[]` | Merged timeline, newest first | | `upcoming` | `UpcomingActivity[]` | Future tasks and events, soonest first | | `relationshipSummary` | `RelationshipSummary` | Last contact, next activity, open tasks | | `users` | `ChatUser[]` | Resolved users | | `currentUser` | `ChatUser \| undefined` | Resolved current user | | `panelProps` | `ContactActivityPanelData` | Spread onto `` | | `isLoading` | `boolean` | Any source loading | | `error` | `Error \| null` | First source error | | `isMutating` | `boolean` | Any mutation pending | | `mutationError` | `Error \| null` | First mutation error | | `refetch` | `() => Promise` | Invalidate every source | | `createComment` | `(payload: CreatePostPayload) => Promise` | Post a comment or reply | | `deleteComment` | `(commentId: string) => Promise` | Delete a comment | | `updateStatus` | `(input: UpdateStatusInput) => Promise` | `PATCH` the record, then log a status update | | `isUpdatingStatus` | `boolean` | Status mutation pending | ### UpdateStatusInput | Field | Type | Description | |-------|------|-------------| | `statusFieldSlug` | `string` | Status field slug (required) | | `value` | `string` | New status option id (required) | | `secondaryValue` | `string \| null` | Sub-status option id | | `description` | `string \| null` | Note | | `followupDate` | `string \| null` | Follow-up date | | `writeCompanions` | `boolean` | Also `PATCH` the `___*` companion columns. Default `true`. Set `false` for a plain `field-select` | ## Notes - **Files are on by default.** The documents source adds one request per record; pass `sources={{ files: false }}` to keep the previous behaviour (uploads then stay as bare audit traces). - **Related chips.** A comment's `assigned_to` becomes a related chip automatically (resolved against the users list). Everything else is opt-in through `relatedColumns` — the hook never guesses a tenant's relation slugs. ## Type Exports | Type | Description | |------|-------------| | `UseKivaContactActivityOptions` / `UseKivaContactActivityResult` | Options and result | | `ContactActivityClient` | Minimal REST client interface | | `ContactActivitySources` | Source toggles | | `EventTypeNameHints` | Call / meeting name hints | | `UpdateStatusInput` | Status mutation input | | `ContactActivityPanelData` | The panel props the hook fills | --- # useKivaContactChannels URL: /docs/native/hooks/use-kiva-contact-channels React Query wiring for the Contact Channels & Consent API — a record's channels, consent and validation ledgers, tenant brands and every channel / consent / validation mutation. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-contact-channels ``` **Dependencies:** - [@tanstack/react-query](https://www.npmjs.com/package/@tanstack/react-query) A verbatim port of the web hook. It takes a structural `ContactChannelsClient` (`get` / `post` / `patch` / `delete`), which `RestApiClient` satisfies. Queries share the web keys (`['kiva-contact-channels', , …]`, `['kiva-tenant-brands']`) and every mutation invalidates the record's channel queries. Read endpoints need `DS.Read.All`, write endpoints `DS.ReadWrite.All`. [rn-contact-channels-panel](/docs/native/kiva/contact-channels-panel) uses it internally. ## Usage ```tsx import { useKivaContactChannels } from '@/hooks/kiva-native/use-kiva-contact-channels'; const { channels, brands, createChannel, recordConsent, runValidation } = useKivaContactChannels({ client, appSlug: 'base', dataSourceSlug: 'contact', recordId }); await createChannel({ channelKind: 'email', channelType: 'email', value: 'erin@acme.com', isPrimary: true }); await recordConsent(channelId, { purpose: 'marketing', action: 'opt_in', consentStatus: 'opted_in', consentChannel: 'email' }); ``` ## API Reference ### UseKivaContactChannelsOptions | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `ContactChannelsClient` | - | REST client (required) | | `appSlug` / `dataSourceSlug` / `recordId` | `string` | - | Owning record (required) | | `includeArchived` | `boolean` | `false` | Include archived channels | | `enabled` | `boolean` | `Boolean(recordId)` | Toggle every query | | `loadBrands` | `boolean` | `true` | Fetch `/v1/tenant/brands` | ### UseKivaContactChannelsResult | Field | Type | Description | |-------|------|-------------| | `channels` / `brands` / `consentHistory` / `validationHistory` | arrays | Loaded data | | `isLoading` / `error` / `isMutating` / `mutationError` | | State | | `refetch` | `() => Promise` | Invalidate the record's queries | | `createChannel(input)` / `updateChannel(id, input)` | `Promise` | `POST` / `PATCH …/channels` | | `makePrimary(id)` / `archiveChannel(id, reason?)` / `unarchiveChannel(id)` / `deleteChannel(id)` | `Promise` | Channel actions | | `recordConsent(id, entry)` / `bulkRecordConsent(id, items)` / `bulkRecordRecordConsent(items)` | `Promise` | Consent ledger writes | | `listChannelConsent(id)` | `Promise` | Per-channel consent ledger | | `recordValidation(id, entry)` / `runValidation(id)` | `Promise` | Validation writes / engine run | | `listChannelValidations(id)` | `Promise` | Per-channel validation ledger | ### Types | Type | Description | |------|-------------| | `ContactChannelsClient` | `{ get, post, patch, delete }` | | `ContactChannelsPanelData` | Read part of the result | | `ConsentEntryWithChannel` | `ConsentEntryInput & { channelId }` | --- # useKivaDataExport URL: /docs/native/hooks/use-kiva-data-export Server-side export of a Kiva data source on React Native. POSTs the column list, filters and keyword to the query-export endpoint, writes the returned xlsx or csv file into the cache directory and opens the share sheet. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-data-export ``` **Dependencies:** - [@kivacore/api-client](https://www.npmjs.com/package/@kivacore/api-client) - [@react-querybuilder/core](https://www.npmjs.com/package/@react-querybuilder/core) - [expo-file-system (optional)](https://www.npmjs.com/package/expo-file-system) - [expo-sharing (optional)](https://www.npmjs.com/package/expo-sharing) The hook needs an authenticated `RestApiClient`. Unlike [`useDataExport`](/docs/native/hooks/use-data-export), which projects rows you already loaded, the server runs the full query and streams back the whole result set as a file. Pair it with [rn-kiva-data-export-menu](/docs/native/kiva/kiva-data-export-menu) for the column picker. `expo-file-system` and `expo-sharing` are **optional peers**, loaded lazily through the internal `lib/native-export` helpers. Without `expo-file-system`, `exportData` resolves `null`. Without `expo-sharing`, the file is written but not shared. ## Usage ```tsx import { useKivaClient } from '@kivacore/signin/react-native'; import { Button } from '@/components/kiva-native/button'; import { useKivaDataExport } from '@/hooks/kiva-native/use-kiva-data-export'; export function ExportTasks({ dataSourceId, query, keyword }: Props) { const client = useKivaClient(); const { exportData, isExporting, error } = useKivaDataExport({ client: client!, fileName: 'tasks' }); return ( ); } ``` ### Request body `exportData(payload)` sends `POST /v1/edge/run/query-export` (or `endpoint`) with `responseType: 'arrayBuffer'` and this body: | Key | Value | |-----|-------| | `dataSourceId` | From the payload. | | `columns` | `'*'` when omitted, `'*'` or empty. Otherwise the slugs joined with `,` (inline projections such as `country(id,name)` are kept). | | `filters` | The `RuleGroupType`, or `null` when it has no rules. | | `limit` | `payload.limit` when it is a positive number, otherwise `defaultLimit`. | | `filterKeyword` | Only sent when non-empty. | | any other key | Forwarded as is (for example `format`). | The response bytes are written to `/.xlsx` (or `.csv` when `payload.format === 'csv'`) and handed to the share sheet. Errors are stored in `error` and re-thrown. ## API Reference ### Options (`UseKivaDataExportOptions`) | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `RestApiClient` | — | Authenticated REST client (required). | | `defaultLimit` | `number` | `10000` | Row cap when `payload.limit` is omitted. | | `endpoint` | `string` | `'/v1/edge/run/query-export'` | Export endpoint path. | | `fileName` | `string` | `export-` | Native: file name without extension. The server's `Content-Disposition` is not reachable through `client.post`, so the name is chosen on the device. | | `share` | `boolean` | `true` | Native: open the share sheet after writing. | ### KivaDataExportPayload | Field | Type | Description | |-------|------|-------------| | `dataSourceId` | `string` | Target data source id (required). | | `columns` | `'*' \| ReadonlyArray` | `'*'` (or omitted) for every exportable field, or field slugs with optional inline projections. | | `filters` | `RuleGroupType \| null` | Filter group of the items query. | | `filterKeyword` | `string` | Free-text keyword search. | | `limit` | `number` | Maximum rows. Defaults to `defaultLimit`. | | `format` | `'xlsx' \| 'csv'` | Export format (server-controlled, default `xlsx`). | | `[key: string]` | `unknown` | Extra keys forwarded to the endpoint. | ### Result (`UseKivaDataExportResult`) | Field | Type | Description | |-------|------|-------------| | `exportData` | `(payload: KivaDataExportPayload) => Promise` | Run the export and share the file. Resolves `null` when `expo-file-system` is missing. | | `isExporting` | `boolean` | True while the request runs. | | `error` | `Error \| null` | Last error (cleared on every new attempt). | ### KivaDataExportFileResult | Field | Type | Description | |-------|------|-------------| | `uri` | `string` | Local `file://` URI in the cache directory. | | `fileName` | `string` | File name including the extension. | | `mimeType` | `string` | MIME type. | ## Differences from web - Web calls `client.download()`, which saves through the browser. Native POSTs with `responseType: 'arrayBuffer'`, writes the bytes with `expo-file-system` and shares them with `expo-sharing`. - `exportData` resolves the written file (`KivaDataExportFileResult`) instead of `void`. - Native adds the `fileName` and `share` options. ## Type Exports | Type | Description | |------|-------------| | `UseKivaDataExportOptions` | Hook options. | | `UseKivaDataExportResult` | Hook result. | | `KivaDataExportPayload` | Request payload. | | `KivaDataExportFileResult` | Written file metadata. | --- # useKivaDataGallery URL: /docs/native/hooks/use-kiva-data-gallery Kiva-backed card gallery for React Native — composes useKivaDataGrid for schema, saved views, server filters / sort / search / paging and pivot / side filters, and adds gallery-owned card + display config, a toolbar and props for the native DataGallery. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-data-gallery ``` **Dependencies:** - [@kivacore/app-utils](https://www.npmjs.com/package/@kivacore/app-utils) - [@kivacore/api-client](https://www.npmjs.com/package/@kivacore/api-client) - [@tanstack/react-query](https://tanstack.com/query/latest) - [@tanstack/react-table](https://tanstack.com/table/latest) - [@shopify/flash-list](https://shopify.github.io/flash-list/) A port of the web hook with the same options and result. It composes [`useKivaDataGrid`](/docs/native/hooks/use-kiva-data-grid) (read-only, grid toolbar switched off) for the data layer and adds what a gallery owns: the card field bindings (auto-detected from the schema, or the saved view's `galleryCardConfig`), the display config (variant, columns, density, cover …), a debounced search that becomes the server `filterKeyword`, and a toolbar. Spread `galleryProps` onto the native [rn-data-gallery](/docs/native/kiva/data-gallery). ## Usage ```tsx import { View } from 'react-native'; import { useKivaClient } from '@kivacore/signin/react-native'; import { DataGallery } from '@/components/kiva-native/data-gallery'; import { useKivaDataGallery } from '@/hooks/kiva-native/use-kiva-data-gallery'; export function ContactGallery() { const client = useKivaClient(); const { toolbar, galleryProps, sideFilters } = useKivaDataGallery ); } ``` Saving or creating a view from the toolbar's view picker injects the current `galleryCardConfig` / `galleryDisplayConfig` into the payload, so the gallery layout travels with the view (and is shared with the grid's gallery display mode). ## API Reference ### Options (`UseKivaDataGalleryOptions`) Every [`useKivaDataGrid`](/docs/native/hooks/use-kiva-data-grid#options-usekivadatagridoptionstdata) option is accepted and forwarded (`client`, `appSlug`, `dataSourceSlug`, `listParams`, `pivotFilters`, `enableSideFilters` / `sideFiltersConfig`, `persistState`, `onCardClick`, `users`, `formatDate`, …) **except** the grid-only `enableSearch`, `enableRowHeightMenu`, `enableRowMarkers`, `trackChanges`, `onSaveChanges`, `onRowAdd`, `readOnly` (always read-only) and the grid's `cardConfig`. Gallery options: | Option | Type | Default | Description | |--------|------|---------|-------------| | `cardConfig` | `DataGalleryCardConfigSerializable` | auto-detected | Initial card bindings (saved view → this → `detectCardConfigFromFields`). | | `onCardConfigChange` | `(config) => void` | — | Fires on every card-config change. | | `displayConfig` | `Partial` | defaults | Initial display config (merged with the view's `galleryDisplayConfig`). | | `onDisplayConfigChange` | `(config: DataGalleryDisplayConfig) => void` | — | Fires on every display change. | | `showSelectColumn` | `boolean` | `true` | Keep row selection (long-press a card). | | `enableSearchInput` | `boolean` | `true` | Search input (debounced 250 ms → `filterKeyword`). | | `enableFilterMenu` | `boolean` | `true` | Filter chip. | | `enableSortMenu` | `boolean` | `true` | Sort chip. | | `enableGroupMenu` | `boolean` | `true` | Group chip. | | `enableDisplayMenu` | `boolean` | `true` | Display sheet. | | `enableCardConfigMenu` | `boolean` | `true` | Card fields sheet. | | `enableViewSelect` | `boolean` | `true` | Saved-view picker. | | `enableReloadButton` | `boolean` | `true` | Reload button. | | `viewSelectVariant` | `'horizontal-tabs' \| 'dropdown' \| 'vertical-tabs'` | `'horizontal-tabs'` | View picker variant. | | `onAdd` / `addLabel` | `() => void` / `string` | — / `'Add'` | Toolbar add button. | | `minCardWidth` | `number` | `260` | Card width floor for the column clamp. | | `estimatedCardHeight` / `overscan` | `number` | — | Accepted for parity; ignored. | ### Result (`UseKivaDataGalleryResult`) Everything `useKivaDataGrid` returns except `gridProps`, `toolbar` and `sidePanel` (`table`, `items`, `fields`, `views`, `forms`, `activeViewId`, `setActiveViewId`, `activeViewForm`, `formViewProps`, `resolvedListParams`, `pagingMode`, `pivotFilterRule`, `pivotFiltersStrip`, `sideFilters`, `sideFiltersExpanded`, `setSideFiltersExpanded`, `sideFiltersQuery`, `selectedRows`, `selectedRowCount`, `reload`, `refetch`, `isLoading`, `error`, `hasNoViews`, `dataSource`, `gridViewSelectProps` — wrapped to inject the gallery config on save), plus: | Field | Type | Description | |-------|------|-------------| | `galleryProps` | `KivaDataGalleryProps` | Spread onto `` (below). | | `toolbar` | `ReactNode` | Pivot strips → view picker → search → scrollable chips (filter, sort, group, display, card fields, reload, add). | | `cardConfig` / `setCardConfig` | `DataGalleryCardConfigSerializable` / setter (value or updater) | Card bindings. | | `displayConfig` / `setDisplayConfig` | `DataGalleryDisplayConfig` / setter | Display config. | | `searchInput` / `setSearchInput` | `string` / `(value) => void` | Immediate search value. | | `searchKeyword` | `string` | Debounced keyword sent as `filterKeyword`. | `KivaDataGalleryProps`: | Field | Type | Description | |-------|------|-------------| | `table` / `tableMeta` | TanStack | Grid table + meta. | | `displayConfig` | `DataGalleryDisplayConfig` | Current display config. | | `onClearFilters` / `hasActiveFilters` | `() => void` / `boolean` | Empty-state reset (toolbar chips + search; side filters count as active). | | `selectedRowCount` / `getSelectedRows` | `number` / `() => TData[]` | Selection. | | `columnsPerRow` | `number` | Measured column count. | | `onContainerLayout` | `(event) => void` | **Native.** Width measurement (web: `containerRef`). | | `minCardWidth` | `number` | **Native.** Column clamp. | | `pagingMode` | `'standard' \| 'virtual-scroll'` | Resolved paging mode. | | `isReloading` | `boolean` | Background refetch. | | `onRefresh` | `() => void` | **Native.** Pull-to-refresh → `reload`. | ## Native deltas - `galleryProps` drops web `containerRef` / `virtualizer` (FlashList + `onLayout`) and adds `onContainerLayout`, `minCardWidth`, `onRefresh`. - `estimatedCardHeight` / `overscan` are accepted and ignored. - The toolbar uses the grids' stacked native layout (chips open bottom sheets). - `persistState` stores the gallery layer (search, card, display config) under the `…:gallery` key in `lib/storage`, next to the grid's own entry. ## Exports | Export | Description | |--------|-------------| | `useKivaDataGallery` | The hook. | | `detectCardConfigFromFields(fields)` | Re-exported card-slot auto-detection. | ## Type Exports | Type | Description | |------|-------------| | `UseKivaDataGalleryOptions` / `UseKivaDataGalleryResult` | Options / result. | | `KivaDataGalleryProps` | `galleryProps` shape. | --- # useKivaDataGrid URL: /docs/native/hooks/use-kiva-data-grid Everything a Kiva-backed native DataGrid needs in one hook — columns from the schema, server-side filters / sort / search / paging, saved views, pivot filters, advanced AND/OR filter, borrowed relation columns, inline edit, status updates, bulk actions, exports and persisted view parameters. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-data-grid ``` **Dependencies:** - [@kivacore/app-utils](https://www.npmjs.com/package/@kivacore/app-utils) - [@kivacore/api-client](https://www.npmjs.com/package/@kivacore/api-client) - [@tanstack/react-query](https://tanstack.com/query/latest) - [@tanstack/react-table](https://tanstack.com/table/latest) - [@react-querybuilder/core](https://react-querybuilder.js.org) A port of the web hook with the **same option and result names**. It composes [`useKivaDataViewSelect`](/docs/native/hooks/use-kiva-data-view-select) (schema, views, forms) with the native [rn-data-grid](/docs/native/kiva/data-grid) controller, and returns `table` + `gridProps` for ` ); } ``` ### Bulk update / compose dialogs Like web, the `update` / `email` / `message` bulk actions open the native `BulkUpdateDialog` / `EmailComposeDialog` / `InstantMessageComposeDialog` out of the box, and email / phone cells open the compose dialogs through `tableMeta.emailClient` / `messageClient`. Override any of them: ```tsx const { toolbar, table, gridProps } = useKivaDataGrid({ client, appSlug: 'base', dataSourceSlug: 'contact', // optional overrides — omit to use the built-in native dialogs renderBulkUpdateDialog: props => , onBulkMessage: phones => openWhatsApp(phones) }); ``` The dialogs are rendered inside `toolbar`, so render `toolbar` even when you hide its controls. ### Side filters and the vertical-tabs side panel ```tsx const { toolbar, table, gridProps, sideFilters, sidePanel } = useKivaDataGrid({ client, appSlug: 'base', dataSourceSlug: 'contact', viewSelectVariant: 'vertical-tabs', enableSideFilters: true, sideFiltersConfig: { columnsConfig: [ { id: 'status', accessor: row => row.status, displayName: 'Status', type: 'option', options: statusOptions }, { id: 'created_on', accessor: row => row.created_on, displayName: 'Created', type: 'date' } ] } }); return ( ); ``` `sideFilters` defaults to `presentation: 'sheet'`: the node is a "Filters (n)" trigger that opens the panel as a bottom sheet. `sideFiltersConfig.presentation: 'inline'` renders web's collapsible column in place (tablets), bound to `sideFiltersExpanded`. The emitted rule group is ANDed into the items query. ## API Reference ### Options (`UseKivaDataGridOptions`) Every [`useKivaDataViewSelect`](/docs/native/hooks/use-kiva-data-view-select#options-usekivadataviewselectoptions) option (`client`, `appSlug`, `dataSourceSlug`, `appId`, `dataSource`, `overrideFields`, `mapField`, `staleTime`, `enabled`, `enableDataViews`, `dataSourceExpand`, `enableForms`, `persistActiveView`, `persistKey`, `activeViewStorage`, `defaultRowGroupingColumn`, `systemViews`) is accepted and forwarded, plus: #### Data & query | Option | Type | Default | Description | |--------|------|---------|-------------| | `data` | `TData[]` | — | Pre-resolved rows; skips the items query (search then filters client-side). | | `collection` | `KivaDataGridCollection` | — | `{ list, updateMany?, deleteMany? }` — drives fetch, inline save and bulk delete. | | `listParams` | `KivaDataGridListParams` | — | Extra items params; `filters` is AND-merged, every other key overrides. | | `pivotFilters` | `KivaPivotFilterGroupField[]` | — | Pivot strips stacked on top of `toolbar`; their rule is ANDed into the query and they cross-filter against the grid's filters. | | `defaultLimit` | `number` | `100` | Page size when neither the view nor `listParams` set one. | | `enableItemsQuery` | `boolean` | `data === undefined` | Toggle the internal items query. | | `defaultPagingMode` | `'standard' \| 'virtual-scroll'` | `'virtual-scroll'` | Paging mode when the view carries none. | | `excludeFieldSlugs` | `string[]` | — | Slugs dropped from the schema before anything uses it. | | `fieldEnums` | `Record` | — | Enum options for fields the API returns without any. | | `enableRelationColumns` | `boolean` | `false` | Offer columns borrowed from related data sources. | | `relationIconFields` | `Record` | — | Relation slug → icon / image field on the related data source (projected and shown in the cell). | | `users` | `CellUserOption[]` | — | Tenant users for user cells and the user filter (filtered client-side). | | `persistState` | `boolean \| { storage?: 'session' \| 'local'; key?: string }` | — | Persist manually edited view parameters per active view (`true` → in-memory session store). | #### Columns | Option | Type | Default | Description | |--------|------|---------|-------------| | `showSelectColumn` | `boolean` | `true` | Leading select column (pinned left). | | `enableRowMarkers` | `boolean` | `true` | Row numbers on the select column. | | `selectColumn` | `ColumnDef` | — | Replace the select column. | | `actionsColumn` | `ColumnDef` | — | Column after the select column (pinned left). | | `extraColumns` | `ColumnDef[]` | — | Columns before the field columns. | | `getRowId` | `(row, index, parent?) => string` | — | Row identity. | | `mapColumn` | `(field, defaultColumn) => ColumnDef \| null` | — | Per-field override; `null` skips the field. | | `dynamicLabelTranslator` | `(label: string) => string` | — | Translate string headers + `meta.label` (and borrowed-column labels). | | `dynamicEnumOptionTranslator` | `(option: EnumOption, field: IField) => string` | — | Translate static enum option names (cells, filters, group headers). | #### Grid behaviour (forwarded to `useDataGrid`) | Option | Type | Default | Description | |--------|------|---------|-------------| | `readOnly` | `boolean` | `true` | Editing is also switched on by a view's `inlineEditingEnabled`. | | `trackChanges` | `boolean` | `true` | Save / discard bar (forced on while inline editing). | | `onSaveChanges` | `(changes: RowChange[], data: TData[]) => void \| Promise` | bulk PATCH | Custom save handler. | | `enableSearch` | `boolean` | `false` | Grid in-cell search. | | `enableGrouping` | `boolean` | `true` | Row grouping. | | `rowColorRules` / `cellColorRules` | `DataGridRowColorRule[]` / `DataGridCellColorRule[]` | — | Color rules. | | `getRowLabel` | `(row, rowIndex) => string` | — | Row label (a11y + save bar). | | `onRowAdd` / `onRowsAdd` / `onRowsDelete` / `onDataChange` | `useDataGrid` handlers | — | Forwarded. | | `meta` | `TableMeta` | — | Extra table meta; the hook's own wiring wins. | | `initialState` | `InitialTableState` | — | One-time TanStack defaults. | | `getRelationHref` | `(args) => string \| undefined` | — | URL for a relation cell (opened with `Linking`). | | `onOpenRelation` | `(args) => void` | — | In-app navigation for a relation cell (wins). | | `formatDate` / `formatDateTime` / `formatNumber` | formatters | context | Explicit formatters; default to `DateFormatProvider` / `NumberFormatProvider` when a real provider is mounted. | #### Toolbar | Option | Type | Default | Description | |--------|------|---------|-------------| | `enableViewSelect` | `boolean` | `true` | View picker. | | `viewSelectVariant` | `DataGridViewSelectVariant` | `'horizontal-tabs'` | Picker variant (`'vertical-tabs'` has no native side panel — the picker is omitted). | | `viewSelectMaxVisible` | `number` | — | Max inline tabs. | | `enableSearchInput` | `boolean` | `true` | Search input (debounced into `filterKeyword`). | | `searchPlaceholder` | `string` | `t('ui.common.search', 'Search…')` | Placeholder. | | `searchDebounceMs` | `number` | `300` | Search debounce. | | `enableFilterMenu` | `boolean` | `true` | Filter chips + (server-driven grids) the advanced filter. | | `enableGroupMenu` / `enableSortMenu` / `enableRowHeightMenu` / `enableFieldsMenu` / `enableDisplayMenu` | `boolean` | `true` | Menu triggers. | | `enableGalleryMenus` | `boolean` | `true` | Card-fields + display menus in gallery mode. | | `enableServerExportMenu` | `boolean` | `true` | Server export (`POST /v1/edge/run/query-export`, written + shared). | | `enableClientExportMenu` | `boolean` | `false` | Client export of loaded rows (only when the server export is off). | | `serverExportLimit` | `number` | `10000` | Server export row cap. | | `serverExportExcludedFieldTypes` / `serverExportExcludedSlugs` | `string[]` | internal lists | Server export exclusions. | | `enableReloadButton` | `boolean` | `true` | Records-only reload. | | `onReload` | `() => void` | — | After a reload. | | `toolbarClassName` | `string` | — | Toolbar root classes. | | `toolbarStartContent` / `toolbarEndContent` | `ReactNode` | — | Custom toolbar content. | #### Bulk actions & compose | Option | Type | Default | Description | |--------|------|---------|-------------| | `bulkActions` | `false \| KivaDataGridBulkAction[]` | `['update', 'delete', 'export', 'email', 'message']` | Built-in selection actions (`email` / `message` schema-gated). | | `extraBulkActions` | `DataGridAction[]` | — | Appended selection actions. | | `exportColumns` | `'visible' \| 'all' \| string[]` | `'visible'` | Columns of the bulk / client export. | | `exportFileName` | `string` | `dataSourceSlug` | Export file name. | | `renderBulkUpdateDialog` | `(props: KivaBulkUpdateDialogRenderProps) => ReactNode` | `BulkUpdateDialog` | **Native.** Replace the default bulk-update dialog. | | `renderEmailComposeDialog` | `(props: KivaEmailComposeDialogRenderProps) => ReactNode` | `EmailComposeDialog` | **Native.** Replace the composer for the `email` action and email cells. | | `renderMessageComposeDialog` | `(props: KivaMessageComposeDialogRenderProps) => ReactNode` | `InstantMessageComposeDialog` | **Native.** Replace the composer for the `message` action and phone cells. | | `onBulkEmail` | `(addresses: string[], rows: TData[]) => void` | — | **Native.** Handle email yourself (wins over the slot and the default dialog). | | `onBulkMessage` | `(phones: string[], rows: TData[]) => void` | — | **Native.** Handle messages yourself (wins over the slot and the default dialog). | #### Side filters | Option | Type | Default | Description | |--------|------|---------|-------------| | `enableSideFilters` | `boolean` | `false` | Render `sideFilters` and AND its rule group into the items query. Needs `sideFiltersConfig`. | | `sideFiltersConfig` | `KivaDataGridSideFiltersConfig` | — | Panel configuration (below). | | `sideFiltersDefaultExpanded` | `boolean` | `true` | Initial expanded state of the inline panel. | | `sideFiltersExpanded` / `onSideFiltersExpandedChange` | `boolean` / `(expanded) => void` | — | Controlled expanded state (inline). | | `sideFiltersWidth` | `number \| string` | `280` | Width of the expanded inline panel; ignored for the sheet. | `KivaDataGridSideFiltersConfig`: | Field | Type | Default | Description | |-------|------|---------|-------------| | `columnsConfig` | `ColumnConfig[]` | — | Filter columns (required). | | `strategy` | `'server' \| 'client'` | `'server'` | Filter strategy. | | `defaults` | `SideFilterDefaults` | — | Per-column UI hints. | | `sections` | `SideFilterSectionGroup[]` | — | Named section groups. | | `variant` | `'default' \| 'bordered' \| 'compact'` | `'default'` | Panel variant. | | `title` | `ReactNode` | `'Filters'` | Header title (`null` hides it). | | `showActiveChips` / `showClearAll` | `boolean` | `true` | Active chips / "Clear all". | | `searchable` | `boolean \| string` | — | Search input (column id drives a specific column). | | `clearAllLabel` / `clearLabel` | `string` | — | Label overrides. | | `locale` | `Locale` | `'en'` | Filter UI locale. | | `className` | `string` | — | Panel classes. | | `collapseAriaLabel` / `expandAriaLabel` | `string` | — | Inline collapse / expand labels. | | `collapsedWidth` | `number \| string` | — | Accepted for parity (collapsed bar is full-width). | | `presentation` | `'sheet' \| 'inline'` | `'sheet'` | **Native.** Trigger + bottom sheet, or the inline collapsible panel. | | `triggerLabel` | `string` | `title` → `'Filters'` | **Native.** Sheet trigger label. | #### Gallery, forms, accepted-for-parity | Option | Type | Default | Description | |--------|------|---------|-------------| | `cardConfig` | `DataGalleryCardConfig` | auto-detected | Initial card bindings + render hooks. | | `galleryDisplayConfig` | `Partial` | defaults | Initial display config. | | `onCardClick` | `(record, rowIndex) => void` | — | Card tap. | | `defaultFormLayout` | `Record \| null` | — | Form layout when the view has no bound form. | | `enableColumnReorder`, `showDropdownChevron`, `enablePaste` | `boolean` | — | Desktop affordances, accepted and ignored. | ### Result (`UseKivaDataGridResult`) Everything [`useKivaDataViewSelect`](/docs/native/hooks/use-kiva-data-view-select#result-usekivadataviewselectresult) returns (`gridViewSelectProps` wraps the gallery config into view save / create; `fields` honour `excludeFieldSlugs`), plus: | Field | Type | Description | |-------|------|-------------| | `table` | `Table` | TanStack table — `` and the menus. | | `gridProps` | `object` | Spread onto ``: the `useDataGrid` result + `actions`, `isReloading`, `isLoading`, `onClearFilters`, `onRefresh` (pull-to-refresh), `galleryCardConfig`, `galleryDisplayConfig`, `onCardClick`. | | `toolbar` | `ReactNode` | Pivot strips → view picker → search → scrollable menu row, plus the bulk dialogs. | | `pivotFilterRule` | `PivotFilterRule[] \| null` | Combined pivot rule. | | `pivotFiltersStrip` | `ReactNode` | The pivot strip alone (`null` without `pivotFilters`). | | `selectedRows` / `selectedRowCount` | `TData[]` / `number` | Reactive selection. | | `activeViewFormId` / `activeViewForm` | `string \| undefined` / `DataForm \| undefined` | Form bound to the active view. | | `formViewProps` | `KivaDataGridFormViewProps` | `{ formLayout, gridColumns?, dataSource }` for `useKivaFormView`. | | `items` | `TData[]` | Rows passed to the grid. | | `resolvedListParams` | `KivaDataGridListParams` | Params actually sent. | | `pagingMode` | `'standard' \| 'virtual-scroll' \| undefined` | Pass to ``. | | `reload` | `() => void` | Schema + views + items refetch, then `onReload`. | | `sidePanel` | `ReactNode` | `DataGridSidePanel` with the vertical-tabs view picker when `viewSelectVariant === 'vertical-tabs'`, else `null`. | | `sideFilters` | `ReactNode` | `DataTableSideFilters` (sheet trigger by default), `null` unless `enableSideFilters` + config. | | `sideFiltersExpanded` / `setSideFiltersExpanded` | `boolean` / `(v) => void` | Inline panel expanded state. | | `sideFiltersQuery` | `RuleGroupType \| undefined` | Rule group emitted by the side filters. | ## Native deltas - **Toolbar layout** — stacked (pivot strips, view picker, search, one horizontally scrollable row of compact triggers + `toolbarEndContent`) instead of web's single wrapping row. - **Email / phone cells** — tapping opens an action sheet (web: on-hover icons). Like web, `tableMeta.emailClient` / `messageClient` = `client`, so "Compose email" / "Send message" open the grid's own compose dialogs. When `renderEmailComposeDialog` / `onBulkEmail` (resp. message) is supplied, the cells route to that override through `tableMeta.onComposeEmail` / `onSendMessage`. - **Bulk `update` / `email` / `message`** — open the native `BulkUpdateDialog` / `EmailComposeDialog` / `InstantMessageComposeDialog` (bottom sheets). Precedence for email / message: `onBulkEmail` / `onBulkMessage` → `render*ComposeDialog` → default dialog → `Linking` (`mailto:` / `sms:`, only without a client). - **Bulk `export`** — ActionSheet (CSV / Excel / JSON / Markdown); the file is written to the cache directory and shared (optional `expo-file-system` + `expo-sharing`). - **Side filters** — `sideFilters` is the native `DataTableSideFilters`, `presentation: 'sheet'` by default (web: a collapsible column; available as `'inline'`). - **Vertical tabs** — `sidePanel` is a `DataGridSidePanel`: a strip whose view list opens as a bottom sheet on phones, a side column on tablets (≥ 768 dp). - **UUID copy** — uses the optional `expo-clipboard` peer, falling back to the share sheet. - **Storage** — `persistState` uses `lib/storage` (`'session'` = in-memory for the process, `'local'` = the registered persistent store). - **`gridProps.onRefresh`** — pull-to-refresh runs the records-only reload. - `enableColumnReorder`, `showDropdownChevron`, `enablePaste` are ignored; column order / pinning live in the Fields sheet. - New i18n keys: `ui.dataGrid.bulkUpdate`, `ui.dataGrid.bulkDelete`, `ui.dataGrid.bulkEmail`, `ui.dataGrid.bulkMessage`, `ui.dataGrid.reload`, `ui.dataGrid.exportFormatCsv|Xlsx|Json|Markdown` (web hard-codes these labels). ## Exports | Export | Description | |--------|-------------| | `useKivaDataGrid` | The hook. | | `collectFieldSlugsByType(fields, types)` | Slugs of fields whose type is in `types`. | | `collectRecipientValues(rows, slugs)` | De-duplicated string values of `slugs` across `rows`. | | `EMAIL_FIELD_TYPES` / `PHONE_FIELD_TYPES` | `Set(['field-email'])` / `Set(['field-phone'])`. | ## Type Exports | Type | Description | |------|-------------| | `UseKivaDataGridOptions` / `UseKivaDataGridResult` | Options / result. | | `KivaDataGridListParams` | Items query params. | | `KivaDataGridCollection` | `{ list, updateMany?, deleteMany? }`. | | `KivaDataGridBulkAction` | `'update' \| 'delete' \| 'export' \| 'email' \| 'message'`. | | `KivaDataGridFormViewProps` | `formViewProps` shape. | | `KivaDataGridSideFiltersConfig` | Side-filter config (see Side filters). | | `DataGridPersistSnapshot` | Persisted parameter snapshot. | | `KivaBulkUpdateDialogRenderProps` | `renderBulkUpdateDialog` props (`open`, `onOpenChange`, `client`, `appSlug`, `dataSourceSlug`, `records`, `onSuccess`). | | `KivaEmailComposeDialogRenderProps` / `KivaMessageComposeDialogRenderProps` | Compose slot props (`client`, `trigger: null`, `open`, `onOpenChange`, `to`). | --- # useKivaDataImportWizard URL: /docs/native/hooks/use-kiva-data-import-wizard One-call wiring of a Kiva data source to the native DataImportWizard. Picks a spreadsheet, uploads and analyses it on the server, auto-maps columns, imports the rows and returns a ready-to-render wizard element plus imperative helpers. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-data-import-wizard ``` **Dependencies:** - [@kivacore/api-client](https://www.npmjs.com/package/@kivacore/api-client) - [@kivacore/app-utils](https://www.npmjs.com/package/@kivacore/app-utils) - [@tanstack/react-query](https://tanstack.com/query/latest) - [expo-document-picker (optional)](https://www.npmjs.com/package/expo-document-picker) This is a port of the web hook with the same options and result. It needs an authenticated `RestApiClient` and a `QueryClientProvider` above it. The file is picked with the optional `expo-document-picker` peer and **parsed on the server**, so no spreadsheet library runs on the device. The hook renders [rn-data-import-wizard](/docs/native/kiva/data-import-wizard). ## How it works 1. **Fields.** Target fields come from [`useKivaDataSourceFields`](/docs/native/hooks/use-kiva-data-source-fields) while the wizard is open (cache-first through the shared inventory), unless you pass `fields`. 2. **Upload.** Picking a file POSTs multipart `FormData` with a React Native file part (`{ uri, name, type }`) to `…/import/upload`. `RestApiClient` detects `FormData` and leaves the `Content-Type` to `fetch`. Pass `uploadFile` to replace this phase. 3. **Analyse.** `GET …/import/details?fileName=…` returns the columns, rows (`data` is normalized to `rows`) and unique-field hints. The mapping is seeded from `initialMapping` or `buildAutoMapping(columns, fields)`. If the fields load after the analysis, auto-mapping runs again. 4. **Import.** Enum-like columns are resolved to option ids on the device and sent as `uniqueData`. Relation lookups are left to the server. The hook POSTs `{ fileName, options }` to `…/import`, where `options` comes from `buildImportOptions(mapping, fields, upsertUniqueFields, uniqueData)`. All three endpoints default to `/v1/apps/{appSlug}/data-sources/{dataSourceSlug}/import/…` and can be overridden with `endpoints`. Closing the wizard resets the run, so the next open starts fresh. ### Deployments without an upload route When the API has no `POST …/import/upload`, the raw file must already be in tenant storage under `tenant-{tenantNo}/tmp/import/{fileName}`. Pass `uploadFile` to put it there yourself and return the `UploadedFileInfo`. The returned `fileName` is what the analyse and import phases use. ## Usage ```tsx import { useKivaClient } from '@kivacore/signin/react-native'; import { Button } from '@/components/kiva-native/button'; import { useKivaDataImportWizard } from '@/hooks/kiva-native/use-kiva-data-import-wizard'; export function ImportContacts({ onDone }: { onDone: () => void }) { const client = useKivaClient(); const { wizard, openWizard, isImporting } = useKivaDataImportWizard({ client: client!, appSlug: 'base', dataSourceSlug: 'contact', requiredFieldSlugs: ['name'], onImported: () => onDone(), onError: (error, phase) => console.warn(phase, error.message) }); return ( <> {wizard} ); } ``` ### Imperative usage `uploadAsync` and `analyseAsync` call the endpoints directly and resolve their responses without changing the wizard state. They are useful for custom flows and tests. `importAsync` imports the file the wizard has already analysed, using the current mapping. It throws when no file has been analysed yet, and it skips the on-device `uniqueData` pre-resolution. ```tsx const importer = useKivaDataImportWizard({ client, appSlug, dataSourceSlug }); const uploaded = await importer.uploadAsync(file); // DataImportFile const analysed = await importer.analyseAsync(uploaded.fileName); // …after the user went through the mapping step: const result = await importer.importAsync(); ``` ## API Reference ### Options (`UseKivaDataImportWizardOptions`) | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `RestApiClient` | — | Authenticated REST client (required). | | `appSlug` | `string` | — | App slug (required). | | `dataSourceSlug` | `string` | — | Data source slug (required). | | `appId` | `string` | — | Accepted for web parity (web scopes its saved-view lookup by app id). | | `fields` | `ReadonlyArray` | — | Pre-resolved target fields. Skips the schema fetch. | | `requiredFieldSlugs` | `ReadonlyArray` | `[]` | Slugs that must be mapped before leaving the mapping step. | | `uniqueFieldSlugs` | `ReadonlyArray` | from the analyse response | Slugs covered by unique indexes. | | `endpoints` | `{ upload?: string; analyse?: string; import?: string }` | `…/import/upload`, `…/import/details`, `…/import` | Endpoint overrides. | | `uploadFile` | `(file: DataImportFile) => Promise` | — | Replace the upload phase (see above). | | `previewRowCount` | `number` | `10` | Rows shown in the preview step. | | `maxFileSizeBytes` | `number` | `20 * 1024 * 1024` | Maximum file size (20 MB). | | `acceptedExtensions` | `ReadonlyArray` | `['xlsx', 'xls', 'csv']` | Accepted extensions. | | `initialMapping` | `WizardMappingMap` | — | Mapping seed that overrides auto-mapping. | | `enabled` | `boolean` | `true` | `false` returns `wizard: null` (feature flag). | | `open` | `boolean` | — | Controlled open state. When omitted, the hook owns it. | | `onOpenChange` | `(open: boolean) => void` | — | Called whenever the open state changes. | | `onImported` | `(result: ImportResultPayload) => void` | — | Called after a successful import. | | `onError` | `(error: Error, phase: 'upload' \| 'analyse' \| 'import') => void` | — | Called when any phase throws. | | `title` | `ReactNode` | — | Wizard header title. | | `description` | `ReactNode` | — | Wizard header description. | ### Result (`UseKivaDataImportWizardResult`) | Field | Type | Description | |-------|------|-------------| | `open` | `boolean` | Current open state. | | `openWizard` / `closeWizard` | `() => void` | Open or close (closing resets the run). | | `resetWizard` | `() => void` | Back to the upload step with a clean state. | | `step` | `ImportWizardStep` | Current step. | | `setStep` | `(next: ImportWizardStep) => void` | Change the step. | | `wizard` | `ReactElement \| null` | The wired `DataImportWizard`. Render it once next to your trigger. | | `uploadAsync` | `(file: DataImportFile) => Promise` | Imperative upload. | | `analyseAsync` | `(fileName: string) => Promise` | Imperative analyse. | | `importAsync` | `() => Promise` | Imperative import with the current mapping. | | `uploadedFile` | `UploadedFileInfo \| null` | Upload response. | | `analysedFile` | `AnalysedFile \| null` | Analyse response. | | `importResult` | `ImportResultPayload \| null` | Import response. | | `fields` | `ReadonlyArray` | Resolved target fields. | | `isUploading` / `isAnalysing` / `isImporting` | `boolean` | Phase flags. | | `error` | `Error \| null` | First error of the upload, analyse or import phase. | ## Differences from web - `File` becomes `DataImportFile` (`NativeFile`: `{ uri, name, type, size? }`), and the upload sends a React Native `FormData` file part. - Target fields come from the lightweight `useKivaDataSourceFields` schema hook instead of `useKivaDataViewSelect`. - The wizard is a full-height bottom sheet, and the file comes from the system document picker instead of drag-and-drop. ## Type Exports | Type | Description | |------|-------------| | `UseKivaDataImportWizardOptions` | Hook options. | | `UseKivaDataImportWizardResult` | Hook result. | The wizard types (`DataImportFile`, `ImportWizardStep`, `WizardMappingMap`, `UploadedFileInfo`, `AnalysedFile`, `ImportResultPayload`, …) are exported from [`data-import-wizard`](/docs/native/kiva/data-import-wizard#type-exports). --- # useKivaDataSourceFields URL: /docs/native/hooks/use-kiva-data-source-fields Lightweight schema hook for one Kiva data source on React Native. Returns the data source and its field list (including inline enum options), served cache-first from the shared inventory so no extra request is made after the post-sign-in warm-up. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-data-source-fields ``` **Dependencies:** - [@kivacore/api-client](https://www.npmjs.com/package/@kivacore/api-client) - [@kivacore/app-utils](https://www.npmjs.com/package/@kivacore/app-utils) - [@tanstack/react-query](https://tanstack.com/query/latest) This hook is **native-only**. Web components that only need the field list (bulk update, import wizard, dummy-data generator) take it from the much larger `useKivaFormView` / `useKivaDataViewSelect` hooks. On native, [rn-bulk-update-dialog](/docs/native/kiva/bulk-update-dialog), [`useKivaDataImportWizard`](/docs/native/hooks/use-kiva-data-import-wizard) and [`useKivaDummyDataGeneratorWizard`](/docs/native/hooks/use-kiva-dummy-data-generator-wizard) use this hook instead. It needs a `QueryClientProvider` above it. The fetch runs through `createDataSourceClient(client, { inventory: getSharedKivaInventory(client) })`: 1. `getBySlug(appSlug, dataSourceSlug)` is served from the [shared inventory](/docs/native/hooks/use-kiva-inventory) with `fields` and inline enum options. 2. On a cache miss the scoped GET has no fields (system data sources), so the hook fetches again with `{ expand: 'enums' }`. All consumers share the query key `['kiva', 'dataSourceFields', appSlug, dataSourceSlug]` (exported as `kivaDataSourceFieldsQueryKey`), so mounting the hook in several places causes a single request. ## Usage ```tsx import { useKivaClient } from '@kivacore/signin/react-native'; import { useKivaDataSourceFields } from '@/hooks/kiva-native/use-kiva-data-source-fields'; export function TaskFieldList() { const client = useKivaClient(); const { fields, isLoading, error } = useKivaDataSourceFields({ client, appSlug: 'base', dataSourceSlug: 'task' }); if (isLoading) return ; if (error) return ; return fields.map(field => ); } ``` ### Gating and pre-resolved fields ```tsx // Only fetch while a sheet is open useKivaDataSourceFields({ client, appSlug, dataSourceSlug, enabled: open }); // Reuse fields you already have: the fetch is skipped entirely useKivaDataSourceFields({ client, appSlug, dataSourceSlug, fields: gridFields }); ``` ## API Reference ### Options (`UseKivaDataSourceFieldsOptions`) | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `RestApiClient \| null \| undefined` | — | Authenticated REST client. The query waits while it is missing (required). | | `appSlug` | `string` | — | App slug (required). | | `dataSourceSlug` | `string` | — | Data source slug (required). | | `enabled` | `boolean` | `true` | Gate the fetch (for example only while a dialog is open). | | `fields` | `ReadonlyArray` | — | Pre-resolved fields. When set, nothing is fetched and these are returned. | | `staleTime` | `number` | `300000` (5 minutes) | React Query stale time (ms). | ### Result (`UseKivaDataSourceFieldsResult`) | Field | Type | Description | |-------|------|-------------| | `dataSource` | `DataSource \| null` | The data source record from `@kivacore/app-utils`. | | `fields` | `ReadonlyArray` | Its fields, or the `fields` option. Empty while loading. | | `isLoading` | `boolean` | First load in progress (always `false` with pre-resolved `fields`). | | `error` | `Error \| null` | Fetch error. | | `refetch` | `() => void` | Refetch the schema. | ### KivaFieldLike | Field | Type | Description | |-------|------|-------------| | `id` | `string` | Field id. | | `slug` | `string` | Field slug. | | `name` | `string` | Display name. | | `type` | `IFieldType \| string` | Field type (`field-text`, `field-select`, …). | | `options` | `unknown` | Raw field options. | | `enums` | `unknown` | Inline enum options. | | `[key: string]` | `unknown` | Any other schema keys. | ## Exports | Export | Description | |--------|-------------| | `useKivaDataSourceFields(options)` | The hook. | | `kivaDataSourceFieldsQueryKey(appSlug, dataSourceSlug)` | Shared query key, for example to invalidate the schema after a studio change. | ## Type Exports | Type | Description | |------|-------------| | `UseKivaDataSourceFieldsOptions` | Hook options. | | `UseKivaDataSourceFieldsResult` | Hook result. | --- # useKivaDataSourceJsonSchema URL: /docs/native/hooks/use-kiva-data-source-json-schema Generate a JSON Schema (object schema, properties keyed by field slug) from a Kiva data source field list. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-data-source-json-schema ``` This hook is distributed as source. It is fully standalone — it ships its own `JsonSchema` type and a Kiva field-type → JSON Schema mapping, so it has no runtime dependency beyond React. The only import is the `IFieldType` union from the native form-fields types (type-only). ## Overview `useKivaDataSourceJsonSchema` turns an array of Kiva field descriptors into a standard **object JSON Schema** (Draft 2020-12 / Draft-07 compatible). Each field becomes one property: - `field.slug` → the property **key** (machine name). - `field.name` → the property `title` (user-facing label). - `field.type` → the property `type` / `format` (via the built-in field-type map). - `field.description` → the property `description`. Use it to drive AI Structured Outputs / tool definitions, runtime validation (Ajv, Zod-from-JSON-Schema, etc.), form generation, or any flow that needs a machine-readable contract for a data source. The hook is a pure, memoized transform — no state, no effects, no fetching. ## Usage ```tsx import { Text } from 'react-native'; import { useKivaDataSourceJsonSchema, type DataSourceFieldDescriptor } from '@/hooks/kiva-native/use-kiva-data-source-json-schema'; // Module scope keeps the reference stable, so the schema is built once. const fields: DataSourceFieldDescriptor[] = [ { slug: 'full_name', name: 'Full Name', type: 'field-text', description: 'Contact full name' }, { slug: 'email', name: 'Email', type: 'field-email' }, { slug: 'status', name: 'Status', type: 'field-status', description: 'Pipeline stage' }, { slug: 'tags', name: 'Tags', type: 'field-tagSelect' }, { slug: 'revenue', name: 'Annual Revenue', type: 'field-money' }, ]; export function ContactSchema() { const schema = useKivaDataSourceJsonSchema(fields, { title: 'Contact', description: 'A CRM contact record', }); return ; } ``` Produces: ```json { "type": "object", "properties": { "full_name": { "type": "string", "title": "Full Name", "description": "Contact full name" }, "email": { "type": "string", "format": "email", "title": "Email" }, "status": { "type": "string", "title": "Status", "description": "Pipeline stage" }, "tags": { "type": "array", "items": { "type": "string" }, "title": "Tags" }, "revenue": { "type": "number", "title": "Annual Revenue" } }, "additionalProperties": true, "title": "Contact", "description": "A CRM contact record" } ``` ### OpenAI Structured Outputs (strict mode) Set `strict: true` to constrain the output to OpenAI Structured Outputs rules — `additionalProperties: false` plus every field slug listed in `required`: ```tsx const schema = useKivaDataSourceJsonSchema(fields, { title: 'Contact', strict: true }); // schema.additionalProperties === false // schema.required === ['full_name', 'email', 'status', 'tags', 'revenue'] ``` ### Marking fields required ```tsx // every field required useKivaDataSourceJsonSchema(fields, { required: true }); // only specific slugs required useKivaDataSourceJsonSchema(fields, { required: ['full_name', 'email'] }); ``` ### Refining individual fields with `overrides` The built-in mapping uses pragmatic defaults (single-choice / reference fields → `string`, multi-choice → `array` of `string`, structured fields → open `object`). When a field needs a tighter shape, deep-merge an override keyed by slug: ```tsx const schema = useKivaDataSourceJsonSchema(fields, { overrides: { // narrow an enum/status field to a fixed set of option ids status: { enum: ['lead', 'qualified', 'won', 'lost'] }, // describe the shape of a relation reference owner: { type: 'object', properties: { id: { type: 'string' }, name: { type: 'string' } } }, }, }); ``` Overrides are deep-merged onto the generated property (override wins; nested objects merge recursively), so `title`/`description` derived from the field metadata are preserved unless you replace them explicitly. ### Outside React Both `buildDataSourceJsonSchema` and `fieldToJsonSchema` are pure and can be called outside React (background tasks, tests, AI tool-definition builders): ```ts import { buildDataSourceJsonSchema } from '@/hooks/kiva-native/use-kiva-data-source-json-schema'; const schema = buildDataSourceJsonSchema(fields, { strict: true }); ``` ## API Reference ### `useKivaDataSourceJsonSchema(fields, options?)` | Parameter | Type | Description | |-----------|------|-------------| | `fields` | `DataSourceFieldDescriptor[]` | Field list. Each entry: `{ slug, name, type, description? }`. | | `options` | `UseKivaDataSourceJsonSchemaOptions` | Generation options (see below). | Returns a memoized `JsonSchema` object. Memoization keys on `fields` and each option — pass a stable `fields` reference to avoid rebuilding on every render. ### `DataSourceFieldDescriptor` | Field | Type | Description | |-------|------|-------------| | `slug` | `string` | Machine name → JSON Schema **property key**. Fields without a slug are skipped. | | `name` | `string` | User-facing label → property `title`. | | `type` | `IFieldType` | Kiva field type (e.g. `field-text`, `field-email`, `field-status`). Drives `type` / `format`. | | `description` | `string \| null` | Optional → property `description`. | ### `UseKivaDataSourceJsonSchemaOptions` | Option | Type | Default | Description | |--------|------|---------|-------------| | `title` | `string` | `—` | `title` for the root object schema. | | `description` | `string` | `—` | `description` for the root object schema. | | `required` | `boolean \| string[]` | `—` | `true` → all slugs required; `string[]` → listed slugs required; omitted → no `required` array. | | `strict` | `boolean` | `false` | OpenAI Structured Outputs mode: forces `additionalProperties: false` + all slugs `required`. Overrides `required` and `additionalProperties`. | | `additionalProperties` | `boolean` | `true` | Root-level `additionalProperties`. Ignored when `strict`. | | `includeTitles` | `boolean` | `true` | Emit each property's `title` from `field.name`. | | `includeDescriptions` | `boolean` | `true` | Emit each property's `description` from `field.description`. | | `includeDialect` | `boolean` | `false` | Include the `$schema` dialect keyword on the root. | | `dialect` | `string` | `DEFAULT_JSON_SCHEMA_DIALECT` | Dialect URI used when `includeDialect` is set. | | `overrides` | `Record` | `—` | Per-slug schema overrides, deep-merged onto the generated property. | ### Exports | Export | Type | Purpose | |--------|------|---------| | `useKivaDataSourceJsonSchema` | `(fields, options?) => JsonSchema` | React hook (memoized). | | `buildDataSourceJsonSchema` | `(fields, options?) => JsonSchema` | Pure builder — usable outside React. | | `fieldToJsonSchema` | `(field, options?) => JsonSchema` | Pure single-field → property converter. | | `FIELD_TYPE_SCHEMA_MAP` | `Partial>` | Field type → base schema fragment map. | | `DEFAULT_JSON_SCHEMA_DIALECT` | `string` | Default dialect (`https://json-schema.org/draft/2020-12/schema`). | | `JsonSchema` | `interface` | Self-contained JSON Schema type returned by the hook. | | `DataSourceFieldDescriptor` | `interface` | Field descriptor input type. | | `UseKivaDataSourceJsonSchemaOptions` | `interface` | Options type. | ## Field type mapping The defaults below are intentionally pragmatic. Refine any field with `overrides`. | JSON Schema output | Kiva field types | |--------------------|---------------------| | `string` | `field-text`, `field-textarea`, `field-password`, `field-phone`, `field-color`, `field-icon`, `field-currency`, `field-display`, `field-htmlEditor`, `field-emailEditor`, `field-codeEditor`, `field-markdown`, `field-formula`, `field-code`, `field-identity`, `field-handlebars`, `field-fileStorageFolder`, `field-systemEnum` | | `string` + `format` | `field-email` (`email`), `field-url` (`uri`), `field-date` (`date`), `field-dateTime` (`date-time`), `field-time` (`time`) | | `number` | `field-number`, `field-money`, `field-percent`, `field-duration`, `field-rating` | | `integer` | `field-autonumber` | | `boolean` | `field-checkbox`, `field-switch`, `field-todo` | | `string` (id of choice / reference) | `field-enum`, `field-select`, `field-radioGroup`, `field-status`, `field-approvalStatus`, `field-userSelect`, `field-relation`, `field-locationSelect`, `field-button` | | `array` of `string` | `field-multiSelect`, `field-tagSelect`, `field-userMultiSelect`, `field-list`, `field-systemTextArray`, `field-systemUuidArray` | | `array` of `object` | `field-taskList`, `field-schemaRepeater` | | open `object` | `field-json`, `field-jsonSchema`, `field-jsonata`, `field-adaptiveCard`, `field-schema`, `field-dynamic`, `field-inlineData`, `field-inlineForm`, `field-conversationChannel`, `field-queryBuilder`, `field-systemBuffer`, `field-systemVector` | | stored-file `object` | `field-file`, `field-image`, `field-avatar` | | date-range `object` (`{ from, to }`) | `field-dateRange` | | `string` (fallback) | any unmapped / unknown type | ## How It Works The hook reads `FIELD_TYPE_SCHEMA_MAP` for each field's base fragment, layers on `title` / `description` from the field metadata, deep-merges any per-slug `overrides`, and assembles the property bag under a root `object` schema. `strict` and `required` only affect the root `additionalProperties` / `required` keywords — they never mutate individual property shapes. The whole transform is pure and memoized against `fields` + options. ### Out of scope - Fetching the field list — pass the data source's fields in yourself (e.g. from `@kivacore/app-utils` `DataSourceField` metadata). - Resolving enum options or relation targets into concrete schemas — supply those via `overrides` when you need them. - Validation — feed the returned schema to your validator of choice (Ajv, etc.). --- # useKivaDataTable URL: /docs/native/hooks/use-kiva-data-table Headless Kiva-backed table for the native DataTable — schema columns rendered with the value renderers, server filters / sort / search / paging, saved views, bulk actions, exports and a table ↔ gallery view node. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-data-table ``` **Dependencies:** - [@kivacore/app-utils](https://www.npmjs.com/package/@kivacore/app-utils) - [@kivacore/api-client](https://www.npmjs.com/package/@kivacore/api-client) - [@tanstack/react-query](https://tanstack.com/query/latest) - [@tanstack/react-table](https://tanstack.com/table/latest) - [@react-querybuilder/core](https://react-querybuilder.js.org) A port of the web hook with the same options and result. It builds its own `useReactTable` instance (no grid editing controller) whose cells render through the native value renderers, and returns `table` + `tableProps` for the headless native [rn-data-table](/docs/native/kiva/data-table), a `toolbar`, and a `view` node that switches between the table and a card gallery. It shares the saved views, list-params, export and bulk-action engine with [`useKivaDataGrid`](/docs/native/hooks/use-kiva-data-grid). ## Overview - **Columns** — one column per schema field whose cell is the field's value renderer (`VALUE_RENDERER_MAP`); object values group by a stable key. `inferColumnsFromData` derives columns from the rows when there is no schema. - **Items query** — `GET /v1/apps/{appSlug}/data-sources/{dataSourceSlug}/items` (or `collection.list`) with a flat `columns` list, `expand`, `orderBy` (sorting is manual for server data), `filters` (saved view + toolbar chips + `listParams.filters`), debounced `filterKeyword`, `limit` / `offset` / `fullCount` in standard paging. - **Saved views** — `DataGridViewSelect` in the toolbar; the active view is applied like the grid hook (reserved columns pinned left). `pinLeadingColumns` pins `select` / `actions` / `__*` columns on view-less tables. - **Display mode** — `enableDisplayMenu` adds the table / gallery toggle; `view` renders `DataTable` or the native `DataGridGallery` (legacy `cardConfig` adapted with `adaptLegacyCardConfig`, pull-to-refresh → records reload). - **Bulk actions** — selection bar inside `toolbar` (`update` / `delete` / `export` / `email` / `message` + `extraBulkActions`). - **Persistence** — `persistState` per active view (search, filters, sort, grouping, display mode, column layout, page size). ## Usage ```tsx import { View } from 'react-native'; import { useKivaClient } from '@kivacore/signin/react-native'; import { useKivaDataTable } from '@/hooks/kiva-native/use-kiva-data-table'; export function OrganizationsTable() { const client = useKivaClient(); const { toolbar, view } = useKivaDataTable({ client: client!, appSlug: 'base', dataSourceSlug: 'organization', enableDisplayMenu: true, persistState: true, cardConfig: { titleField: 'name', descriptionField: 'email' }, onRowClick: row => console.log(row.original) }); return ( ); } ``` Render `` yourself instead of `view` when you don't need the gallery toggle. ## API Reference ### Options (`UseKivaDataTableOptions`) Every [`useKivaDataViewSelect`](/docs/native/hooks/use-kiva-data-view-select#options-usekivadataviewselectoptions) option is accepted and forwarded, plus: | Option | Type | Default | Description | |--------|------|---------|-------------| | `data` | `TData[]` | — | Pre-resolved rows (skips the items query; search filters client-side). | | `collection` | `KivaDataGridCollection` | — | `{ list, updateMany?, deleteMany? }`. | | `listParams` | `KivaDataGridListParams` | — | Extra items params (`filters` AND-merged). | | `defaultLimit` | `number` | `100` | Default page size. | | `enableItemsQuery` | `boolean` | `data === undefined` | Toggle the items query. | | `pagingMode` | `'standard' \| 'virtual-scroll'` | view | Force the paging mode. | | `pageSize` | `number` | view / `defaultLimit` | Standard-paging page size without a view. | | `showSelectColumn` | `boolean` | `true` | Leading select column. | | `enableRowNumbers` | `boolean` | `true` | Row numbers on the select column. | | `selectColumn` / `actionsColumn` | `ColumnDef` | — | Replace the select column / add an actions column. | | `extraColumns` | `ColumnDef[]` | — | Columns before the field columns. | | `pinLeadingColumns` | `boolean` | `false` | Pin utility columns left when no view is active. | | `mapColumn` | `(field, defaultColumn) => ColumnDef \| null` | — | Per-field override. | | `inferColumnsFromData` | `boolean` | `false` | Columns from row keys when there's no schema. | | `onRowClick` | `(row: Row) => void` | — | Row press (table) / card press (gallery). | | `users` | `CellUserOption[]` | — | Users for the user filter options. | | `getRelationHref` / `onOpenRelation` | relation navigation | — | Forwarded to `tableMeta`. | | `formatDate` / `formatDateTime` / `formatNumber` | formatters | context | Tenant formatters (default: providers when mounted). | | `initialState` | `Partial<{ sorting; columnFilters; columnVisibility; rowSelection; expanded; grouping; pagination }>` | — | Initial TanStack state. | | `enableViewSelect` / `viewSelectVariant` / `viewSelectMaxVisible` | view picker | `true` / `'horizontal-tabs'` | View picker (`'vertical-tabs'` omits it on native). | | `enableSearchInput` | `boolean` | `true` | Search input. | | `searchPlaceholder` / `searchDebounceMs` | `string` / `number` | `t('ui.common.search', 'Search...')` / `300` | Search config. | | `enableFilterMenu` / `enableGroupMenu` / `enableSortMenu` | `boolean` | `true` | Menu triggers. | | `enableDisplayMenu` | `boolean` | `false` | Table / gallery toggle. | | `defaultDisplayMode` | `'table' \| 'gallery'` | `'table'` | Initial display mode. | | `displayMode` / `onDisplayModeChange` | controlled display mode | — | Controlled pair. | | `cardConfig` | `DataGridCardConfig` | — | Gallery card config (`titleField`, `descriptionField`, `imageField`, `bodyFields`, `renderCard`). | | `galleryHeight` | `number \| 'auto'` | `'auto'` | Gallery height (`'auto'` fills the parent). | | `galleryClassName` | `string` | — | Gallery container classes. | | `enableReloadButton` / `onReload` | reload | `true` | Records-only reload. | | `enableServerExportMenu` | `boolean` | `true` | Server export menu. | | `serverExportLimit` / `serverExportExcludedFieldTypes` / `serverExportExcludedSlugs` | export config | `10000` / internal | Server export. | | `toolbarClassName` / `toolbarStartContent` / `toolbarEndContent` | toolbar | — | Toolbar customization. | | `bulkActions` | `false \| KivaDataGridBulkAction[]` | all five | Selection actions. | | `extraBulkActions` | `DataGridAction[]` | — | Appended selection actions. | | `exportColumns` / `exportFileName` | export | `'visible'` / `dataSourceSlug` | Bulk export columns / file name. | | `renderBulkUpdateDialog` / `renderEmailComposeDialog` / `renderMessageComposeDialog` | render slots | native dialogs | **Native.** Replace the default `BulkUpdateDialog` / `EmailComposeDialog` / `InstantMessageComposeDialog`. | | `onBulkEmail` / `onBulkMessage` | callbacks | — | **Native.** Same as the grid hook; also used by email / phone cells. | | `tableClassName` / `tableContainerClassName` / `emptyText` | `DataTable` props | — | Forwarded through `tableProps`. | | `persistState` | `boolean \| { storage?; key? }` | — | Persist view parameters. | | `enableSideFilters` | `boolean` | `false` | Render `sideFilters` and AND its rule group into the items query. | | `sideFiltersConfig` | `KivaDataTableSideFiltersConfig` | — | Same shape as the grid hook's [`KivaDataGridSideFiltersConfig`](/docs/native/hooks/use-kiva-data-grid#side-filters) (incl. native `presentation: 'sheet' \| 'inline'`). | | `sideFiltersDefaultExpanded` | `boolean` | `true` | Initial expanded state of the inline panel. | | `sideFiltersExpanded` / `onSideFiltersExpandedChange` | controlled state | — | Inline panel expanded state. | | `sideFiltersWidth` | `number \| string` | `280` | Expanded inline panel width. | ### Result (`UseKivaDataTableResult`) All `useKivaDataViewSelect` result fields except `gridViewSelectProps`, plus: | Field | Type | Description | |-------|------|-------------| | `table` | `Table` | TanStack table (`useReactTable`). | | `tableProps` | `object` | `className`, `containerClassName`, `emptyText`, `pagination`, `isLoading`, `isReloading`, `onRowClick` — spread onto `DataTable` (minus `isReloading`). | | `toolbar` | `ReactNode` | Controls + selection bar + bulk dialogs. | | `view` | `ReactNode` | `DataTable` or the card gallery. | | `displayMode` / `setDisplayMode` | `'table' \| 'gallery'` / setter | Current display mode. | | `items` | `TData[]` | Rows. | | `resolvedListParams` | `KivaDataGridListParams` | Params sent. | | `pagingMode` | `'standard' \| 'virtual-scroll' \| undefined` | Resolved paging mode. | | `reload` | `() => void` | Full refetch. | | `sidePanel` | `ReactNode` | `DataGridSidePanel` with the vertical-tabs view picker (`viewSelectVariant === 'vertical-tabs'`), else `null`. | | `sideFilters` | `ReactNode` | `DataTableSideFilters` (sheet trigger by default), or `null`. | | `sideFiltersExpanded` / `setSideFiltersExpanded` | `boolean` / setter | Inline panel state. | | `sideFiltersQuery` | `RuleGroupType \| undefined` | Rule group emitted by the side filters. | ## Native deltas - `view` renders the native headless `DataTable` or the native `DataGridGallery` (FlashList of `DataGalleryCard`s, pull-to-refresh wired to the records reload). - Email / phone value renderers open the native compose dialogs from `client` (like web); a host override (`onBulkEmail` / `renderEmailComposeDialog`, or the message pair) wins through `onComposeEmail` / `onSendMessage`. - Bulk actions: same native engine as the grid hook (`update` / `email` / `message` open the native dialogs; `export` via ActionSheet + share sheet). - User / relation option loaders resolve relation targets through the shared inventory (web table fetches `/v1/apps/data-sources`). - Side filters default to a sheet trigger (`presentation: 'inline'` for the web column); the vertical-tabs `sidePanel` opens its view list as a bottom sheet on phones. ## Type Exports | Type | Description | |------|-------------| | `UseKivaDataTableOptions` / `UseKivaDataTableResult` | Options / result. | | `KivaDataTableSideFiltersConfig` | Side-filter config (parity). | --- # useKivaDataViewSelect URL: /docs/native/hooks/use-kiva-data-view-select Load a Kiva data source's fields, saved views and forms, and wire them into the native DataGridViewSelect with one hook — view CRUD, reorder, hidden views and persisted active view included. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-data-view-select ``` **Dependencies:** - [@kivacore/app-utils](https://www.npmjs.com/package/@kivacore/app-utils) - [@kivacore/api-client](https://www.npmjs.com/package/@kivacore/api-client) - [@tanstack/react-query](https://tanstack.com/query/latest) - [@react-querybuilder/core](https://react-querybuilder.js.org) A 1:1 port of the web hook (same options, same result). It needs an authenticated `RestApiClient` and a `QueryClientProvider` above it. Schema, saved views and forms are served from the shared inventory cache ([`useKivaInventoryLoader`](/docs/native/hooks/use-kiva-inventory)), so a warmed app pays no per-mount request. ## Overview - Loads the data source (cache-first, then a scoped `getBySlug` with `expand` for data sources outside the inventory) and maps its fields to query-builder `FullField`s — enum / status / select options become `values`, relation fields get their first 200 records (`id, name, autonumber_id`) as picker values. - Loads saved views (`createDataViewClient`) sorted by `sort_order` then name, prepends developer-defined `systemViews`, and wires create / save / delete / reorder with list invalidation (reorder is optimistic, one PATCH per moved view). - Loads active forms (`createDataFormClient`), default form first, so the view editor can bind a form to each view. - Owns the active view: current selection → persisted id → backend `isDefault` → first view. - Keeps a per-user **hidden views** list (`onViewHide` / `onViewUnhide`). ## Usage ```tsx import { useKivaClient } from '@kivacore/signin/react-native'; import { DataGridViewSelect } from '@/components/kiva-native/data-grid-view-select'; import { useKivaDataViewSelect } from '@/hooks/kiva-native/use-kiva-data-view-select'; export function OrganizationViews({ table }) { const client = useKivaClient(); const { gridViewSelectProps, hasNoViews } = useKivaDataViewSelect({ client: client!, appSlug: 'base', dataSourceSlug: 'organization' }); return ( ); } ``` The hook does not take `table` — spread `gridViewSelectProps` and pass `table` separately. [`useKivaDataGrid`](/docs/native/hooks/use-kiva-data-grid) and [`useKivaDataTable`](/docs/native/hooks/use-kiva-data-table) call this hook for you. ## API Reference ### Options (`UseKivaDataViewSelectOptions`) | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `RestApiClient` | — | Authenticated Kiva API client. | | `appSlug` | `string` | — | App slug of the data source. | | `dataSourceSlug` | `string` | — | Data source slug. | | `appId` | `string` | — | App id filter for views scoped to another app; also part of the storage keys. | | `overrideFields` | `FullField[]` | — | Replace the derived query-builder fields entirely. | | `dataSource` | `DataSource \| null` | — | Pre-resolved schema — skips the schema fetch; fields, relation targets and the returned `dataSource` come from it. | | `mapField` | `(field: DataSourceField, defaultMapped: FullField) => FullField \| null` | — | Per-field transform after the default mapping. `null` drops the field. | | `staleTime` | `number` | `30_000` | TanStack Query `staleTime` for every query. | | `enabled` | `boolean` | `true` | Disable every query. | | `enableDataViews` | `boolean` | `true` | Fetch / manage saved views. `false` for data sources without a view backend — only `systemViews` are shown. | | `dataSourceExpand` | `string \| false` | `'enums'` | `expand` for the scoped schema fetch. `false` / `''` omits it. | | `enableForms` | `boolean` | `true` | Fetch the data source's saved forms (`forms` result + `gridViewSelectProps.forms`). | | `persistActiveView` | `boolean` | `true` | Persist the last-selected view. | | `persistKey` | `string` | `docyrus:data-grid-view::[:]` | Storage key override for the active view. | | `activeViewStorage` | `'session' \| 'local'` | `'local'` | `lib/storage` backend for the active-view id. The data-listing hooks thread `persistState.storage` here. | | `defaultRowGroupingColumn` | `string` | — | Default row-grouping column for views without a `grouping` (applied by the grid / table hooks). | | `systemViews` | `SavedDataGridView[]` | — | Developer-defined views shown before the saved views; marked `isSystem` (no edit / delete). | ### Result (`UseKivaDataViewSelectResult`) | Field | Type | Description | |-------|------|-------------| | `gridViewSelectProps` | `Pick` | Spread onto `DataGridViewSelect`: `views`, `activeViewId`, `fields`, `forms`, `onViewChange`, `onViewCreate`, `onViewSave`, `onViewDelete`, `onViewHide`, `onViewUnhide`, `onViewReorder`, `hiddenViewIds`, `disabled`, `defaultRowGroupingColumn`, `isSaving`, `isLoading`. | | `views` | `SavedDataGridView[]` | System views + saved views (mapped from the backend shape). | | `fields` | `FullField[]` | Query-builder fields (from `@react-querybuilder/core`). | | `forms` | `DataForm[]` | Active saved forms, default first. | | `dataSource` | `DataSource \| undefined` | Resolved schema (injected or fetched). | | `activeViewId` | `string` | Active view id (`''` while loading / no views). | | `setActiveViewId` | `(viewId: string) => void` | Switch views programmatically. | | `isLoading` | `boolean` | Schema or views query loading. | | `error` | `Error \| null` | First error of the schema / views queries. | | `refetch` | `() => void` | Refetch schema + views. | | `hasNoViews` | `boolean` | The view list loaded and is empty (the grid then uses the raw field order — a dev warning is logged). | ## How It Works ### View shape mapping | `DataView` field | `SavedDataGridView` fields | |------------------|----------------------------| | `columns` | `columnVisibility`, `columnOrder`, `columnPinning`, `grouping`, `rowHeight`, `displayMode`, `pagingEnabled`, `pagingMode`, `pageSize`, `inlineEditingEnabled`, `readOnlyColumns`, `columnOptions`, `formId`, `galleryCardConfig`, `galleryDisplayConfig` | | `filters` | `columnFilters`, `filterQuery` | | `sort` | `sorting` | | `color_rules` | `rowColorRules`, `cellColorRules` | ### Active view & persistence The id is persisted under `persistKey` in the `lib/storage` store picked by `activeViewStorage` (`'local'` = the store registered through `` / `setKivaLocalStore()`; `'session'` = in-memory for the app process). With `persistState` on a data-listing hook, the key becomes `docyrus:view-params::[:]:__active-view__`. The hidden-views list always lives in the `'local'` store under `docyrus:data-grid-view-hidden::[:]`. ## Native deltas - `FullField` comes from `@react-querybuilder/core` (no DOM `react-querybuilder`). - Storage goes through `lib/storage` (`getKivaStore('local')` / `getPersistStore`) instead of `window.localStorage` / `sessionStorage`. Register a synchronous persistent store (e.g. `expo-sqlite/kv-store`) to survive restarts. - The "no saved view" warning is gated on `__DEV__`. ## Type Exports | Type | Description | |------|-------------| | `UseKivaDataViewSelectOptions` | Hook options. | | `UseKivaDataViewSelectResult` | Hook result. | --- # useKivaDummyDataGeneratorWizard URL: /docs/native/hooks/use-kiva-dummy-data-generator-wizard One-call wiring of a Kiva data source to the native DummyDataGenerator. Loads the schema, seeds per-field strategies, generates seeded sample rows, previews and exports them, and inserts them into the data source. Returns an inline wizard element plus imperative helpers. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-dummy-data-generator-wizard ``` **Dependencies:** - [@kivacore/api-client](https://www.npmjs.com/package/@kivacore/api-client) - [@kivacore/app-utils](https://www.npmjs.com/package/@kivacore/app-utils) - [@tanstack/react-query](https://tanstack.com/query/latest) - [expo-file-system (optional)](https://www.npmjs.com/package/expo-file-system) - [expo-sharing (optional)](https://www.npmjs.com/package/expo-sharing) This is a port of the web hook with the same options and result. It needs an authenticated `RestApiClient` and a `QueryClientProvider` above it. It renders [rn-dummy-data-generator](/docs/native/kiva/dummy-data-generator). `expo-file-system` and `expo-sharing` are optional peers used only by the preview step's export menu. ## How it works 1. **Fields.** Target fields come from [`useKivaDataSourceFields`](/docs/native/hooks/use-kiva-data-source-fields) (cache-first through the shared inventory), unless you pass `fields`. Whenever the field list changes, strategies are rebuilt with `buildInitialStrategyMap`, keeping the ones the user already edited. 2. **Generate.** **Preview rows** generates `count` rows with a fresh random seed through the pure `generateDummyRows`. **Regenerate sample** re-rolls the seed. User fields draw from `users`, and relation fields draw from `relationOptionsByFieldSlug`. The hook does not fetch either pool, so relation fields stay empty without it. 3. **Insert.** **Save to data source** inserts every generated row with, in order of preference, `insertRecords`, `collection.createMany({ records })`, per-row `collection.create(row)`, or per-row `POST /v1/apps/{appSlug}/data-sources/{dataSourceSlug}/items`. Per-row failures are collected into the result. With `previewOnly`, nothing is posted and **Finish** produces a result with `totalCreated: 0`. ## Usage ```tsx import { useKivaClient } from '@kivacore/signin/react-native'; import { AwesomeDialog, AwesomeDialogBody, AwesomeDialogContent } from '@/components/kiva-native/awesome-dialog'; import { useKivaDummyDataGeneratorWizard } from '@/hooks/kiva-native/use-kiva-dummy-data-generator-wizard'; export function SeedTasks({ open, onOpenChange, users }: Props) { const client = useKivaClient(); const { wizard } = useKivaDummyDataGeneratorWizard({ client: client!, appSlug: 'base', dataSourceSlug: 'task', requiredFieldSlugs: ['name'], defaultCount: 25, users, enabled: open, onGenerated: result => console.log(`${result.totalCreated} created`) }); return ( ); } ``` The wizard is an inline element, so wrap it in your own dialog or sheet for modal use. ## API Reference ### Options (`UseKivaDummyDataGeneratorWizardOptions`) | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `RestApiClient` | — | Authenticated REST client (required). | | `appSlug` | `string` | — | App slug (required). | | `dataSourceSlug` | `string` | — | Data source slug (required). | | `appId` | `string` | — | Accepted for web parity (web scopes its saved-view lookup by app id). | | `fields` | `ReadonlyArray` | — | Pre-resolved target fields. Skips the schema fetch. | | `requiredFieldSlugs` | `ReadonlyArray` | `[]` | Slugs that must stay enabled. | | `defaultCount` | `number` | `10` | Initial number of records. | | `maxCount` | `number` | `1000` | Hard cap for the record count. | | `previewRowCount` | `number` | `10` | Rows shown in the preview step. | | `collection` | `{ create?: (input) => Promise; createMany?: (input: { records }) => Promise }` | — | Collection wrapper. `createMany` is preferred for batch inserts. | | `users` | `ReadonlyArray` | — | Tenant users for user fields. | | `relationOptionsByFieldSlug` | `Record>` | — | Relation pools keyed by field slug. Without them, relation fields are not generated. | | `previewOnly` | `boolean` | `false` | Never POST; the preview step ends with **Finish** (download-only flows). | | `enabled` | `boolean` | `true` | `false` returns `wizard: null` and skips the schema fetch. | | `onGenerated` | `(result: DummyGenerationResult, rows: ReadonlyArray>) => void` | — | Called after the insert (or **Finish**) completes. | | `onError` | `(error: Error, rowIndex: number) => void` | — | Called when a per-row insert throws. | | `insertRecords` | `(rows) => Promise<{ errors: ReadonlyArray<{ rowIndex: number; message: string }> }>` | — | Replace the insert logic. | | `title` | `ReactNode` | — | Wizard header title. | | `description` | `ReactNode` | — | Wizard header description. | | `icon` | `string` | — | Wizard header icon. | | `exportFileName` | `string` | `'-dummy-data'` | File name (without extension) for exports. | ### Result (`UseKivaDummyDataGeneratorWizardResult`) | Field | Type | Description | |-------|------|-------------| | `wizard` | `ReactElement \| null` | The wired inline `DummyDataGenerator`. | | `resetWizard` | `() => void` | Back to the configure step. Clears the generated rows and the result. | | `step` | `DummyDataGeneratorStep` | Current step. | | `setStep` | `(next: DummyDataGeneratorStep) => void` | Change the step. | | `generateAsync` | `() => ReadonlyArray>` | Generate rows with a new seed (synchronous) and store them. | | `insertAsync` | `(rows) => Promise` | Insert rows and resolve the result. | | `fields` | `ReadonlyArray` | Resolved target fields. | | `strategies` | `DummyStrategyMap` | Current strategies. | | `setStrategies` | `(next: DummyStrategyMap) => void` | Replace the strategies. | | `count` | `number` | Current record count. | | `setCount` | `(next: number) => void` | Change the count. | | `generatedRows` | `ReadonlyArray>` | Rows of the latest generation. | | `result` | `DummyGenerationResult \| null` | Result of the latest insert. | | `isGenerating` | `boolean` | Always `false`, because generation is synchronous. Kept for web parity. | | `isCreating` | `boolean` | Insert in progress. | | `error` | `Error \| null` | Insert error. | ## Differences from web - Target fields come from the lightweight `useKivaDataSourceFields` schema hook instead of `useKivaDataViewSelect`. - The preview step exports CSV, Excel, JSON and Markdown through the share sheet ([`useDataExport`](/docs/native/hooks/use-data-export)) instead of browser downloads. ## Type Exports | Type | Description | |------|-------------| | `UseKivaDummyDataGeneratorWizardOptions` | Hook options. | | `UseKivaDummyDataGeneratorWizardResult` | Hook result. | The generator types (`DummyStrategyMap`, `DummyGenerationResult`, `DummyUserOption`, `DummyRelationOption`, …) are exported from [`dummy-data-generator`](/docs/native/kiva/dummy-data-generator#type-exports). --- # useKivaEmailComposer URL: /docs/native/hooks/use-kiva-email-composer Wires the native EmailComposer to the Kiva messaging API — sender accounts, @ mention users and the send mutation, with composer state managed for you. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-email-composer ``` **Dependencies:** - [@tanstack/react-query](https://www.npmjs.com/package/@tanstack/react-query) - [@kivacore/api-client](https://www.npmjs.com/package/@kivacore/api-client) A verbatim port of the web hook (same options, result and query keys). It fetches `GET /v1/messaging/email/accounts` for the From picker and auto-selects the first user-accessible account, fetches `GET /v1/users` once for `@` mentions (client-side filtering), and sends through `POST /v1/messaging/email/accounts/{accountId}/send`. It returns `composerProps` to spread onto [rn-email-composer](/docs/native/kiva/email-composer). Both endpoints need the `Messaging.Email.Send` scope, and a `QueryClientProvider` must be mounted above it. ## Usage ```tsx import { EmailComposer } from '@/components/kiva-native/email-composer'; import { useKivaEmailComposer } from '@/hooks/kiva-native/use-kiva-email-composer'; function ReplyComposer({ client, to }) { const { composerProps, send, attachments } = useKivaEmailComposer({ client, initialTo: to }); return ( { const result = await send({ attachments: [{ filePath: uploaded.fullPath, fileName: 'quote.pdf' }] }); console.log(result.accepted, result.rejected); }} /> ); } ``` `send(overrides)` takes storage-backed attachments (`{ filePath, fileName?, mimeType? }`) — upload the picked `NativeFile` to Kiva storage first. The composer's own `attachments` (`{ name, size }`) are display metadata only. ## API Reference ### UseKivaEmailComposerOptions | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `RestApiClient` | - | Authenticated REST client (required) | | `initialTo` / `initialCc` / `initialBcc` / `initialReplyTo` | `string[]` | `[]` | Initial recipients | | `initialSubject` | `string` | `''` | Initial subject | | `initialBody` | `string` | `''` | Initial HTML body | | `initialAccountId` | `string` | first accessible | Account to preselect | | `resetOnSendSuccess` | `boolean` | `true` | Clear recipients / subject / body / attachments after a send | | `enabled` | `boolean` | `true` | Toggle the queries | | `sendAsUser` | `boolean` | - | Default `sendAsUser` for every send | | `listAccountsEndpoint` | `string` | `/v1/messaging/email/accounts` | Accounts endpoint | | `sendEndpoint` | `string` | `/v1/messaging/email/accounts/{accountId}/send` | Send endpoint | | `mentions` | `boolean` | `true` | Fetch `/v1/users` for mentions | | `mentionUsers` | `EmailComposerMentionUser[]` | - | Explicit mention users (skips the fetch) | | `listUsersEndpoint` | `string` | `/v1/users` | Users endpoint | | `slashCommands` | `EmailComposerSlashCommand[]` | - | Passed through to the composer | ### UseKivaEmailComposerResult | Field | Type | Description | |-------|------|-------------| | `composerProps` | `Pick` | accounts, selection, to / cc / bcc, subject, body, mentionUsers, slashCommands, onSend, sending | | `accounts` / `selectedAccount` | `KivaEmailAccount[]` / `KivaEmailAccount \| null` | Raw account DTOs | | `setSelectedAccountId` | `(id: string) => void` | Change the account | | `isLoadingAccounts` / `accountsError` / `refetchAccounts` | | Accounts query state | | `mentionUsers` | `EmailComposerMentionUser[]` | Resolved mention users | | `to` / `cc` / `bcc` / `replyTo` / `subject` / `body` / `attachments` + setters | | Composer state | | `send` | `(overrides?: KivaEmailSendOverrides) => Promise` | Send | | `isSending` / `sendError` / `lastSendResult` | | Mutation state | | `reset` | `() => void` | Restore the initial values | ### Types | Type | Description | |------|-------------| | `KivaEmailAccount` | Account DTO (`kind`, `provider`, `providerSlug`, `isUserAccessible`, `allowOverrideName`, `allowOverrideEmail`, `createdOn`) | | `KivaEmailAttachment` | `{ filePath, fileName?, mimeType? }` | | `KivaEmailSendOverrides` | Per-send `to`, `cc`, `bcc`, `replyTo`, `subject`, `body`, `sendAsUser`, `attachments`, `accountId` | | `KivaEmailSendResult` | `{ messageId, provider, accepted, rejected }` | | `KivaEmailProvider` | `'aws' \| 'smtp' \| 'mailgun' \| 'resend' \| 'microsoft-graph' \| 'gmail'` | --- # useKivaFieldComponent URL: /docs/native/hooks/use-kiva-field-component Resolve the native form field, value renderer or inline editor for a Kiva field type — plus the shared FORM_FIELD_MAP / VALUE_RENDERER_MAP registries and IField helpers. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-field-component ``` Depends on `@kivacore/rn-form-fields`, `@kivacore/rn-value-renderers` and `@kivacore/rn-editable-value` (installed with it). ## Overview Native port of the web `useKivaFieldComponent`. The registries map every `IFieldType` to native components: - **`form-field`** — the IField adapter `KivaFieldDynamic`, typed as `ComponentType` (`field`, `value`, `onChange`, `record`, `onCompanionChange`, …). `null` for types without a native editor mapping (computed / system types). - **`value-renderer`** — the `KivaValue*` renderer; unknown types fall back to `KivaValueText`. - **`editable-value`** — always `EditableValue`, which dispatches by field type. The web-only kinds `data-grid-cell-variant` and `tanstack-column-def` live with the native data-grid package. ## Usage ```tsx import { useKivaFieldComponent } from '@/hooks/kiva-native/use-kiva-field-component'; function FieldRow({ field, record, onChange }) { const Form = useKivaFieldComponent(field.type, 'form-field'); const Value = useKivaFieldComponent(field.type, 'value-renderer'); if (!Form) return ; return (
onChange(field.slug, value)} onCompanionChange={onChange} /> ); } ``` ```tsx import { extractEnumOptions, toIField } from '@/hooks/kiva-native/use-kiva-field-component'; // DataSourceField (app-utils) → IField + inline options const field = toIField(dataSourceField); const options = extractEnumOptions(dataSourceField); ``` ## API Reference ### useKivaFieldComponent(fieldType, kind) | Param | Type | Description | |------|------|-------------| | `fieldType` | `IFieldType` | Field type | | `kind` | `'form-field' \| 'value-renderer' \| 'editable-value'` | Render context | Returns `KivaFieldComponentResult` — `ComponentType \| null`, `ComponentType` or `typeof EditableValue`. ### Exports | Export | Description | |------|-------------| | `FORM_FIELD_MAP` | `IFieldType` → controlled `KivaField*` component | | `VALUE_RENDERER_MAP` | `IFieldType` → `KivaValue*` renderer | | `GROUPABLE_FIELD_TYPES` | Field types usable for row grouping | | `extractEnumOptions(field)` | Inline options from `field.enums` / `options.options` (camel + snake case metadata, user names from `firstname lastname`) | | `toIField(field)` | Loose `KivaFieldLike` → `IField` | | `getFieldValue(row, slug)` | Safe value read | | `readFieldFormat(field)` | `KivaFieldFormat` from `field.format` with flat fallbacks | | `KivaValueDynamic` | Dynamic value renderer (re-export) | ### Types | Type | Description | |------|-------------| | `KivaFieldComponentKind` | `'form-field' \| 'value-renderer' \| 'editable-value'` | | `KivaFieldComponentResult` | Resolved component type | | `KivaFieldLike` | Loose field shape (IField or DataSourceField) | | `KivaFieldFormat` | `{ currency?, decimalPrecision?, thousandSeparator?, symbolPosition?, ratingMax?, ratingIcon? }` | --- # useKivaFormView URL: /docs/native/hooks/use-kiva-form-view Create, edit and view forms bound to a Kiva data source on React Native. Loads the schema, record and options, uploads files to Kiva storage and creates or updates the record through the shared form-view engine. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-form-view ``` **Dependencies:** - [@kivacore/api-client](https://www.npmjs.com/package/@kivacore/api-client) - [@kivacore/app-utils](https://www.npmjs.com/package/@kivacore/app-utils) - [@tanstack/react-query](https://tanstack.com/query/latest) - [jsonata](https://www.npmjs.com/package/jsonata) The native port of the web hook with the same signature. It is a thin Kiva adapter over the shared form-view engine (see [`useDynamicFormView`](/docs/native/hooks/use-dynamic-form-view) for the backend-agnostic sibling): - **Schema** through the shared inventory cache ([`useKivaInventory`](/docs/native/hooks/use-kiva-inventory)), with a scoped `expand` fetch on a cache miss. Enum options come from the fields' inline `enums`, with a one-off `/v1/apps/enums` fallback when a field has none. - **Record** from `/v1/apps/{app}/data-sources/{ds}/items/{itemId}` (companion columns included; a missing column is stripped and retried). - **Options**: `/v1/users` for user fields, the related data source's items for relation fields. - **Uploads**: image and file fields upload to `/v1/apps/{app}/data-sources/{ds}/files/upload` as an RN `FormData` part (`{ uri, name, type }`) and store the returned `StoredFileValue`. - **Persistence**: `create` → `POST …/items`, `edit` (and inline click-to-edit saves) → `PATCH …/items/{itemId}`, or your `collection` / `onSubmit`. - **Saved forms**: pass `formLayout` (a saved form's `layout`) to derive the layout, per-field overrides, validation tokens, form actions and label styling. It needs an authenticated `RestApiClient` and a `QueryClientProvider` above it. ## Usage ```tsx import { ScrollView } from 'react-native'; import { useKivaClient } from '@kivacore/signin/react-native'; import { Button } from '@/components/kiva-native/button'; import { useKivaFormView } from '@/hooks/kiva-native/use-kiva-form-view'; export function ContactForm({ contactId }: { contactId?: string }) { const client = useKivaClient(); const view = useKivaFormView({ client: client!, appSlug: 'base', dataSourceSlug: 'contact', itemId: contactId, validationTokens: 'form', onSubmitSuccess: () => navigation.goBack() }); if (view.isLoading) return null; return ( ); } ``` Read-only detail screen with inline editing: ```tsx const view = useKivaFormView({ client, appSlug: 'base', dataSourceSlug: 'contact', itemId, mode: 'view', clickToEdit: true }); return view.renderLayout(); // EditableRecordDetail — each save PATCHes the record ``` ## Layout `layout` is a tree of field slugs, `{ type: 'field', slug, colSpan }` items and sections: | Section | Native rendering | Keys | |---------|------------------|------| | `fieldset` | Bordered panel; with `collapsible` the title toggles a native `Collapsible` | `id`, `title`, `description`, `items`, `columns`, `collapsible`, `defaultCollapsed`, `colSpan`, `className`, `contentClassName` | | `tabpanel` | Bordered panel with scrollable underline `Tabs` | `id`, `title`, `description`, `items: tab[]`, `defaultTabId`, `colSpan` | | `tab` | One tab page (inside a `tabpanel`) | `id`, `title`, `description`, `items`, `className`, `contentClassName` | Fields not placed in the layout are appended after it. The grid is a flex-wrap grid: **phones render one column**, tablets honor `gridColumns` / `columns` (capped at 2 below 900pt) and `colSpan` (`1`–`4` or `'full'`). Sections span the full row unless they carry a `colSpan`. ## Form-level styling `labelAlign` / `labelWidth` / `fieldSize` / `fieldVariant` are resolved into field props (`getFormLayoutFieldProps` in `form-fields/lib/form-layout`) instead of the web descendant CSS selectors (Uniwind has none): `labelAlign: 'left'` → `labelAlignment: 'left'` + a fixed label column (`sm` w-24 / `md` w-40 / `lg` w-56), `fieldSize` → field `size`, `fieldVariant: 'outline' | 'filled'` → `'outlined' | 'filled'`. Explicit `fieldLayout[slug].fieldProps` win. ## Computed fields, actions and validation - **Computed** (`fieldLayout[slug]` or `IField`): `computedHidden` / `computedRequired` (JSONata string or query-builder JSON), `computedLabel` / `computedDescription` (JSONata → string), `computedFormula` (JSONata → value written back into the field). Expressions evaluate against the live values (`quantity * unit_price`). - **Field actions** (`fieldActions`, trigger `onFieldChange`): blocks of IF / ELSE IF (`conditionalItems`) / ELSE (`elseActions`) / ALWAYS (`unconditionalActions`) with the 8 step methods `setFieldValue`, `setFieldValues`, `clearFieldValue`, `showField`, `hideField`, `setFieldRequired`, `setFieldDisabled`, `setFieldReadOnly`. - **Form actions** (`formActions`): the same blocks on `onFormLoad`, `onFormBeforeSubmit` and `onFormAfterSubmit` (`$result` bound). - **Priority**: computed formulas > field-action overrides > form-action overrides > `fieldLayout` callbacks > `IField` defaults. - **Validation order per field**: `required` (always) → tokens (`validationTokens`: `'off'` advisory, `'form'` only `fieldLayout.validations`, `'all'` also the field's own tokens; resolved list on `field.enforcedValidations`, also used for the fields' live hints) → JSONata `customValidations` (`value` + `values` bound). Form-level `formCustomValidations` run once every field passes. - **Payload**: read-only and disabled fields are excluded; companion columns (`___currency`, `___country`, status sub-fields, avatar mapping) are submitted with their field. ## Native differences - Upload handlers receive a `NativeFile` instead of a DOM `File`. - The in-form enum option editor (`enumEditor`, `canManageEnumOptions`, `enumEditorAdminRoleIds`) injects the native `KivaEnumOptionEditor` (bottom sheet) as a "Manage options" footer (`ui.enumEditor.manageOptions`) inside the picker sheet of every `field-enum` / `field-systemEnum` field, via `fieldProps.renderOptionsEditor`. Permission is read from `/v1/users/me` (ADMIN / ARCHITECT) unless `canManageEnumOptions` is passed; saving refreshes the schema so the picker shows the new options. ## API Reference | Prop | Type | Default | Description | |------|------|---------|-------------| | `client` | `RestApiClient` | required | Authenticated Kiva API client | | `appSlug` | `string` | required | App slug of the data source | | `dataSourceSlug` | `string` | required | Data source slug | | `itemId` | `string` | — | Record id — loads the record (edit / view) and is the PATCH target | | `mode` | `'create' \| 'edit' \| 'view'` | `itemId ? 'edit' : 'create'` | Form mode | | `item` | `Record \| null` | — | Pre-loaded record — skips the item fetch | | `collection` | `KivaFormViewCollection` | — | Generated collection (get / create / update) used instead of the raw items endpoint | | `dataSource` | `DataSource \| null` | — | Pre-resolved schema — skips the schema fetch | | `enabled` | `boolean` | `true` | Enable the queries | | `staleTime` | `number` | `30000` | react-query stale time (ms) | | `schemaExpand` | `string \| false` | `'enums'` | `expand` for the cache-miss schema fetch | | `defaultValues` | `Record` | — | Extra defaults merged under the record | | `itemQueryParams` | `KivaFormViewGetParams` | — | Extra params / columns for the record GET | | `disabled` | `boolean` | `false` | Disable every field | | `clickToEdit` | `boolean` | `false` | In view mode, render through EditableRecordDetail (inline edit + save) | | `includeReadOnlyFields` | `boolean` | `mode !== 'create'` | Render read-only fields as values | | `unsupportedFieldBehavior` | `'skip' \| 'value'` | `create ? 'skip' : 'value'` | Field types without a native editor: skip or render as a value | | `gridColumns` | `1 \| 2 \| 3 \| 4` | `2` | Form grid columns (phones render 1 column; tablets up to 2 below 900pt) | | `validationTokens` | `'off' \| 'form' \| 'all'` | `'off'` | Enforce minLength / maxLength / pattern / min / max tokens on submit (required is always enforced) | | `labelAlign` | `'top' \| 'left'` | `'top'` | Form-level label placement | | `labelWidth` | `'sm' \| 'md' \| 'lg'` | `'md'` | Label column width when labelAlign is left | | `fieldSize` | `'sm' \| 'md' \| 'lg'` | — | Form-level field density | | `fieldVariant` | `'outline' \| 'filled'` | — | Form-level input style | | `fieldSlugs` | `string[]` | — | Whitelist of field slugs to render | | `fieldOrder` | `string[]` | — | Explicit field order (unlisted fields sort by name) | | `hiddenFieldSlugs` | `string[]` | — | Field slugs to hide | | `fieldLayout` | `Record` | — | Per-field overrides: hidden / required fns, readOnly, disabled, colSpan, label, description, fieldProps, valueProps, computed*, fieldActions, customValidations, validations | | `layout` | `KivaFormViewLayoutItem[]` | — | Section tree: fieldset (columns, collapsible, defaultCollapsed) / tabpanel / tab, field items with colSpan | | `enumOptions` | `Record` | — | Option lists keyed by field slug (overrides inline enums) | | `formLayout` | `Record \| null` | — | Saved Kiva form layout — converted into layout / fieldLayout / fieldSlugs / columns | | `mapField` | `(field: DataSourceField, mapped: IField) => IField \| null` | — | Customize (or drop) each mapped field | | `dynamicLabelTranslator` | `(label: string) => string` | — | Translate field labels | | `dynamicEnumOptionTranslator` | `(option: EnumOption, field: IField) => string` | — | Translate enum option labels | | `resolveUserOptions` | `boolean` | `true` | Fetch /v1/users for user fields | | `resolveRelationOptions` | `boolean` | `true` | Fetch related records for relation fields | | `optionLimit` | `number` | `100` | Relation option window size | | `onSubmit` | `(payload, context) => unknown` | — | Custom persistence — default: POST (create) / PATCH (edit) the items endpoint | | `transformSubmit` | `(payload, context) => Record` | — | Rewrite the built payload before persistence | | `onSubmitSuccess` | `(result, payload) => void` | — | Called after a successful submit | | `onSubmitError` | `(error, payload) => void` | — | Called when validation or persistence fails | | `formActions` | `FormAction[] \| null` | — | Form lifecycle actions (onFormLoad / onFormBeforeSubmit / onFormAfterSubmit) | | `formCustomValidations` | `FormCustomValidationRule[] \| null` | — | Form-level JSONata validations — errors land in formValidationErrors | | `enumEditor` | `boolean` | `true` | Permission-gated "Manage options" footer on enum fields (opens `KivaEnumOptionEditor`) | | `canManageEnumOptions` | `boolean` | — | Enum-editor permission override — skips the `/v1/users/me` fetch | | `enumEditorAdminRoleIds` | `string[]` | — | Role ids allowed to manage options (default ADMIN + ARCHITECT) | ## Return Value | Key | Type | Description | |-----|------|-------------| | `mode` | `KivaFormViewMode` | Resolved mode | | `item` / `values` | `Record` | Live form values | | `defaultValues` | `Record` | Initial values (field defaults + record) | | `form` | `{ Field }` | Render-prop `form.Field` for custom field UI (`{ name, state: { value, meta }, handleChange, handleBlur }`) | | `fields` / `allFields` | `KivaFormViewField[]` | Resolved, visible fields (required / hidden / readOnly / disabled / renderMode / enforcedValidations / submitKeys …) | | `unsupportedFields` | `KivaFormViewField[]` | Fields rendered as values because no native editor exists | | `validationErrors` | `Map` | Per-field errors from the last `validate()` | | `formValidationErrors` | `string[]` | Form-level `formCustomValidations` errors — render them as an `Alert` banner | | `isDirty` | `boolean` | Values differ from the baseline (empty values normalized) | | `isLoading` | `boolean` | Data still loading | | `isSubmitting` | `boolean` | A submit is in flight | | `error` | `Error \| null` | Load / submit error | | `setValue` | `(slug, value) => void` | Programmatic write | | `validate` | `() => Promise` | required → tokens → JSONata `customValidations`, then form-level validations | | `reset` | `() => void` | Restore the baseline | | `submit` | `() => Promise` | Validate → `onFormBeforeSubmit` → build payload → persist → `onFormAfterSubmit` | | `resetActionOverrides` | `() => void` | Clear field-action and form-action property overrides | | `renderField` | `(slug, options?) => ReactNode` | Render one field (form or value mode) | | `renderLayout` | `(options?) => ReactNode` | Render the whole layout (sections / tabs / grid, or `EditableRecordDetail` with `clickToEdit`) | | `dataSource` | `DataSource \| undefined` | Resolved schema | | `columns` | `string[]` | Columns requested for the record | | `refetch` | `() => void` | Refetch schema, record and options | ## Type Exports | Type | Description | |------|-------------| | `UseKivaFormViewOptions` | Hook options | | `UseKivaFormViewResult` | Hook result | | `KivaFormViewCollection` | Generated collection shape (`get` / `create` / `update`) | | `KivaFormViewGetParams` | Record GET params | | `KivaFormViewMode` / `KivaFormViewRenderMode` / `KivaFormViewValidationTokenMode` | Mode unions | | `KivaFormViewLayoutItem` / `KivaFormViewSection` / `KivaFormViewFieldsetSection` / `KivaFormViewTabPanelSection` / `KivaFormViewTabSection` / `KivaFormViewLayoutFieldItem` / `KivaFormViewColSpan` | Layout tree types | | `KivaFormViewFieldLayout` | Per-field overrides | | `KivaFormViewField` | Resolved field | | `KivaFormViewRenderFieldOptions` / `KivaFormViewRenderLayoutOptions` | `renderField` / `renderLayout` options | | `LocalFormShape` | `form.Field` render-prop shape | --- # useKivaInstantMessageComposer URL: /docs/native/hooks/use-kiva-instant-message-composer Wires the native InstantMessageComposer to the Kiva SMS and WhatsApp messaging API. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-instant-message-composer ``` **Dependencies:** - [@tanstack/react-query](https://www.npmjs.com/package/@tanstack/react-query) - [@kivacore/api-client](https://www.npmjs.com/package/@kivacore/api-client) A verbatim port of the web hook. It loads `GET /v1/messaging/sms/accounts` and `GET /v1/messaging/whatsapp/accounts` (only for the `availableChannels`), auto-selects the first account per channel, and sends through `POST …/sms/accounts/{accountId}/send` or `…/whatsapp/accounts/{accountId}/send`. WhatsApp supports `text` and pre-approved `template` messages. A `QueryClientProvider` must be mounted above it. ## Usage ```tsx import { InstantMessageComposer } from '@/components/kiva-native/instant-message-composer'; import { useKivaInstantMessageComposer } from '@/hooks/kiva-native/use-kiva-instant-message-composer'; const { composerProps } = useKivaInstantMessageComposer({ client, initialRecipients: ['+905551234567'] }); ``` ```tsx // WhatsApp template await send({ channel: 'whatsapp', type: 'template', templateName: 'order_shipped', templateLanguage: 'en_US', templateParams: ['#1042'] }); ``` ## API Reference ### UseKivaInstantMessageComposerOptions | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `RestApiClient` | - | Authenticated REST client (required) | | `initialChannel` | `'sms' \| 'whatsapp'` | `'sms'` | Initial channel | | `availableChannels` | `ReadonlyArray` | `['sms', 'whatsapp']` | Channels offered (and queried) | | `initialRecipients` | `string[]` | `[]` | Initial recipients | | `initialBody` | `string` | `''` | Initial body | | `initialSmsAccountId` / `initialWhatsAppAccountId` | `string` | first account | Accounts to preselect | | `resetOnSendSuccess` | `boolean` | `true` | Clear recipients / body / attachments after a send | | `enabled` | `boolean` | `true` | Toggle the queries | | `defaultFrom` | `string` | - | Default sender override | | `defaultPhoneNumberId` | `string` | - | Default Meta WhatsApp Cloud phone number id | | `listSmsAccountsEndpoint` / `listWhatsAppAccountsEndpoint` | `string` | `/v1/messaging/{sms,whatsapp}/accounts` | Account endpoints | | `sendSmsEndpoint` / `sendWhatsAppEndpoint` | `string` | `…/accounts/{accountId}/send` | Send endpoints | ### UseKivaInstantMessageComposerResult | Field | Type | Description | |-------|------|-------------| | `composerProps` | `Pick` | channel, availableChannels, recipients, body, attachments + handlers, onSend, sending | | `channel` / `setChannel` | | Active channel | | `smsAccounts` / `whatsAppAccounts` | `KivaSmsAccount[]` / `KivaWhatsAppAccount[]` | Account DTOs | | `selectedSmsAccount` / `selectedWhatsAppAccount` / `selectedAccountId` | | Selection | | `setSelectedSmsAccountId` / `setSelectedWhatsAppAccountId` | `(id: string) => void` | Change the account | | `isLoadingAccounts` / `accountsError` / `refetchAccounts` | | Accounts query state | | `recipients` / `body` / `attachments` + setters | | Composer state | | `send` | `(overrides?: KivaInstantMessageSendOverrides) => Promise` | Send | | `isSending` / `sendError` / `lastSendResult` / `reset` | | Mutation state | ### Types | Type | Description | |------|-------------| | `KivaSmsAccount` / `KivaWhatsAppAccount` | Account DTOs | | `KivaInstantMessageSendOverrides` | `channel`, `to`, `body`, `from`, `accountId`, `type`, `phoneNumberId`, `templateName`, `templateLanguage`, `templateParams` | | `KivaInstantMessageSendResult` | `{ messageId, provider, accepted, rejected }` | | `WhatsAppMessageType` | `'text' \| 'template'` | --- # useKivaInventory URL: /docs/native/hooks/use-kiva-inventory Shared app-utils inventory cache for Kiva metadata (apps, data sources with fields, enums, views and forms, users, brands, preferences) plus a post-sign-in warm-up hook that drives a loading screen. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-inventory ``` **Dependencies:** - [@kivacore/app-utils](https://www.npmjs.com/package/@kivacore/app-utils) - [@kivacore/api-client](https://www.npmjs.com/package/@kivacore/api-client) The module exports: - `getSharedKivaInventory(client)`: returns the process-wide shared `InventoryClient` for a `RestApiClient`, creating it on first use. Instances are memoized in a `WeakMap` keyed by client. `null` in gives `null` out. - `useKivaInventoryLoader(options)`: headless hook that runs `inventory.load()` once per client after sign-in and reports progress, so the app can show a loading screen before the home screen. ## Why this exists `createInventoryClient` from `@kivacore/app-utils` caches the metadata a Kiva app needs at startup: apps, data sources (with embedded `views`, `forms`, `fields` and field `enums`), users, brands and tenant preferences. The data sources come from one `GET /v1/apps/data-sources?expand=views,forms,fields` request. The cache lives inside the returned client, so everything must share **one** instance. Then a single warm-up fills the cache, and every inventory-backed Kiva hook reads from it instead of fetching again on mount. `getSharedKivaInventory` hands out that instance; the Kiva hooks call it internally. A new client identity (for example after a tenant switch that rebuilds the client) gets a fresh inventory. If you reuse the same client across a tenant switch, call `inventory.refresh()`. ## `getSharedKivaInventory(client)` ```ts import { createDataSourceClient } from '@kivacore/app-utils'; import { getSharedKivaInventory } from '@/hooks/kiva-native/use-kiva-inventory'; const inventory = getSharedKivaInventory(apiClient); const dataSources = createDataSourceClient(apiClient, { inventory }); // Served from the shared cache (fields, enums, views and forms embedded) const contacts = await dataSources.getBySlug('crm', 'contacts'); ``` | Parameter | Type | Description | |-----------|------|-------------| | `client` | `RestApiClient \| null \| undefined` | The authenticated API client. | **Returns:** `InventoryClient` for a client, `null` when `client` is nullish. Overloaded so a non-null client returns a non-null `InventoryClient` type. ## `useKivaInventoryLoader(options)` Runs `inventory.load()` once as soon as `enabled` is true and a `client` exists. It is StrictMode-safe and re-runs automatically when the client identity changes. Failures do not throw: `status` becomes `'error'` and `reload()` retries. The app still works on error, because inventory-backed reads fall back to the API. ```tsx import { ActivityIndicator, Text, View } from 'react-native'; import { useKivaAuth, useKivaClient } from '@kivacore/signin/react-native'; import { Button } from '@/components/kiva-native/button'; import { Progress } from '@/components/kiva-native/progress'; import { useKivaInventoryLoader } from '@/hooks/kiva-native/use-kiva-inventory'; const APP_ID = process.env.EXPO_PUBLIC_KIVA_APP_ID; // Keep array options stable (module scope or useMemo). const CONFIG_APP_IDS = APP_ID ? [APP_ID] : []; export function InventoryGate({ children }: { children: React.ReactNode }) { const { status } = useKivaAuth(); const client = useKivaClient(); const { status: loadStatus, progress, reload } = useKivaInventoryLoader({ client, enabled: status === 'authenticated', configAppIds: CONFIG_APP_IDS }); if (loadStatus === 'ready') return children; return ( ) : ( <> )} ); } ``` ### Options (`UseKivaInventoryLoaderOptions`) | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `RestApiClient \| null \| undefined` | — | The authenticated API client. The loader waits until it is set. | | `enabled` | `boolean` | `true` | Gate the warm-up (e.g. only once authenticated). A non-null `client` is still required. | | `include` | `InventoryLoadStepId[]` | app-utils default: `['apps', 'data-sources', 'users', 'brands', 'preferences']` | Tenant-wide steps to warm. Drop `'users'` when the user may lack the `Users.Read.All` scope. | | `configAppIds` | `string[]` | app-utils default | App ids whose config and user-config to warm. app-utils defaults to the `VITE_APP_ID` env var, which does not exist under Metro, so pass ids explicitly on native. `[]` skips config steps. | | `force` | `boolean` | app-utils default: `true` | Invalidate caches before loading so the warm-up makes fresh network calls. | ### Result (`KivaInventoryLoaderState`) | Field | Type | Description | |-------|------|-------------| | `inventory` | `InventoryClient \| null` | The shared inventory for the current client. | | `status` | `'idle' \| 'loading' \| 'ready' \| 'error'` | Warm-up lifecycle. | | `progress` | `InventoryLoadProgress \| null` | Latest progress event. `progress.ratio` (0 to 1) drives a determinate bar; `progress.message` is an English label. | | `error` | `unknown` | The load error when `status === 'error'`. | | `result` | `InventoryLoadResult \| null` | The loaded payload once ready. | | `isLoading` | `boolean` | `true` while warming. | | `isReady` | `boolean` | `true` once warmed successfully. | | `reload` | `() => void` | Re-run the warm-up (Retry button, tenant switch). | ## Type Exports | Type | Description | |------|-------------| | `KivaInventoryLoadStatus` | `'idle' \| 'loading' \| 'ready' \| 'error'`. | | `UseKivaInventoryLoaderOptions` | Options of `useKivaInventoryLoader`. | | `KivaInventoryLoaderState` | Return value of `useKivaInventoryLoader`. | --- # useKivaKanban URL: /docs/native/hooks/use-kiva-kanban Kanban board backed by a Kiva data source. Groups records by an enum, user or date field, and saves a card's move to the API when it is dropped. Enum options marked final become drop zones. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-kanban ``` **Dependencies:** - [@kivacore/api-client](https://www.npmjs.com/package/@kivacore/api-client) - [@kivacore/app-utils](https://www.npmjs.com/package/@kivacore/app-utils) - [@tanstack/react-query](https://tanstack.com/query/latest) This is a port of the web hook with the same signature. It builds on [`useKivaDataViewSelect`](/docs/native/hooks/use-kiva-data-view-select) for the schema and saved views. The items request uses the active view's filters and sort, the search keyword and `listParams` (whose `filters` are AND-merged with the view's filters). It returns a pre-wired `toolbar` and `board`. The board is the native [rn-kanban](/docs/native/kiva/kanban) in grouped-`value` mode. **Supported group fields:** `field-select`, `field-radioGroup`, `field-status`, `field-userSelect` (one column per user or per team) and `field-date` / `field-dateTime` (bucketed by day, week or month; the time part is ignored). **Moving cards:** long-press a card to drag it. The hook sends a single PATCH of the group field when you drop the card, never during the drag. Only enum and user columns can be changed this way. Date buckets and team columns are derived, so a card dropped there snaps back. ## Usage ```tsx import { useKivaClient } from '@kivacore/signin/react-native'; import { useKivaKanban } from '@/hooks/kiva-native/use-kiva-kanban'; export function TasksBoard() { const client = useKivaClient(); const { toolbar, board } = useKivaKanban({ client: client!, appSlug: 'base', dataSourceSlug: 'task', groupByFieldSlug: 'status', titleColumn: 'subject', descriptionColumn: 'description', userColumn: 'created_by', persistState: true, onCardOpen: row => router.push(`/tasks/${row.id}`), cardMenuItems: (row, defaults) => [ { key: 'duplicate', label: 'Duplicate', icon: 'fal copy', onAction: duplicate }, ...defaults ] }); return ( ); } ``` ## API Reference ### Options (`UseKivaKanbanOptions`) Extends every [`useKivaDataViewSelect`](/docs/native/hooks/use-kiva-data-view-select) option (`appId`, `staleTime`, `systemViews`, `persistKey`, `activeViewStorage`, …). | Prop | Type | Default | Description | |------|------|---------|-------------| | `client` | `RestApiClient` | — | Authenticated Kiva API client (required) | | `appSlug` | `string` | — | App slug (required) | | `dataSourceSlug` | `string` | — | Data source slug (required) | | `groupByFieldSlug` | `string` | — | Field whose values become the columns (required) | | `data` | `TData[]` | — | Pre-loaded rows. When set, the items query is skipped | | `collection` | `KivaKanbanCollection` | — | Custom `list` / `update` / `remove` adapter | | `listParams` | `KivaKanbanListParams` | — | Extra query params. `filters` is AND-merged; every other key overrides | | `defaultLimit` | `number` | `200` | Page size | | `enableItemsQuery` | `boolean` | `data === undefined` | Runs the internal items query | | `dateGroupBy` | `'day' \| 'week' \| 'month'` | `'day'` | Initial date bucket | | `userGroupBy` | `'user' \| 'team'` | `'user'` | Initial user grouping | | `showAllColumns` | `boolean` | `true` | Enum grouping: also shows options with no cards | | `avatarColumn` | `string` | — | Field for the card avatar (icon, color or image) | | `titleColumn` | `string` | — | Field for the card title | | `descriptionColumn` | `string` | — | Field for the card description | | `userColumn` | `string` | — | User field shown in the card footer | | `cardContent` | `(ctx: KivaKanbanCardContext) => ReactNode` | — | Extra card content | | `cardMenuItems` | `KivaKanbanCardMenuItem[] \| (row, defaults) => KivaKanbanCardMenuItem[]` | Open / Edit / Delete | Items of the card's action sheet | | `cardActions` | `ReadonlyArray<'open' \| 'edit' \| 'delete'>` | `['open', 'edit', 'delete']` | Built-in actions to keep | | `onCardOpen` | `(row) => void` | — | Open action. Also handles card taps when `onCardClick` is not set | | `onCardEdit` | `(row) => void` | — | Edit action | | `onCardDelete` | `(row) => void \| Promise` | API delete | Custom delete, run after the confirmation dialog | | `onCardClick` | `(row) => void` | `onCardOpen` | Card tap | | `enableViewSelect` | `boolean` | `true` | Saved-view picker (shown when views exist) | | `enableSearchInput` | `boolean` | `true` | Search input | | `enableDateGroupMenu` | `boolean` | `true` | Date-bucket picker (date grouping only) | | `enableUserGroupMenu` | `boolean` | `true` | User / team picker (user grouping only) | | `enableShowAllColumnsSwitch` | `boolean` | `true` | "Show all" switch (enum grouping only) | | `enableReloadButton` | `boolean` | `true` | Reload button | | `onReload` | `() => void` | — | Called after a reload | | `searchPlaceholder` | `string` | `t('ui.kanban.search', 'Search…')` | Search placeholder | | `searchDebounceMs` | `number` | `300` | Search debounce in ms | | `toolbarClassName` | `string` | — | Classes for the toolbar root | | `toolbarStartContent` | `ReactNode` | — | Content before the view picker | | `toolbarEndContent` | `ReactNode` | — | Content at the end of the control row | | `onItemMove` | `(params: { row, fromColumnId, toColumnId, column }) => void` | — | Called after a drop into another column. The built-in PATCH still runs | | `onItemMoveCommit` | `(params: { row, fromColumnId, toColumnId, column, payload }) => void \| Promise` | — | Takes over saving the move. Throw or reject to roll the board back | | `persistState` | `boolean \| { storage?: 'session' \| 'local'; key?: string }` | — | Saves search, date / user grouping and "show all" for each saved view (`…:kanban`). The active view follows the same store | ### KivaKanbanCardMenuItem | Field | Type | Description | |-------|------|-------------| | `key` | `string` | Stable key | | `label` | `string` | Row label (native: string) | | `icon` | `string` | `KivaIcon` string, e.g. `'fal pen'` (native: string) | | `destructive` | `boolean` | Red row | | `disabled` | `boolean \| (row) => boolean` | Disables the row | | `onAction` | `(row) => void` | Runs after the sheet closes | ### Result (`UseKivaKanbanResult`) | Key | Type | Description | |-----|------|-------------| | `toolbar` | `ReactNode` | Toolbar plus the delete dialog and card action sheet. Always render it | | `board` | `ReactNode` | The board. Shows a spinner while loading and an empty state for an unsupported field | | `items` | `TData[]` | Rows on the board | | `resolvedListParams` | `KivaKanbanListParams` | Query payload | | `groupByField` | `DataSourceField \| undefined` | Group field metadata | | `columns` | `KivaKanbanColumnMeta[]` | Visible columns (`id`, `label`, `color`, `icon`, `imageUrl`, `isFinal`, `count`) | | `columnsItems` | `Record` | Rows grouped by column id | | `dateGroupBy` / `setDateGroupBy` | `KivaKanbanDateGroupBy` / setter | Date bucket | | `userGroupBy` / `setUserGroupBy` | `KivaKanbanUserGroupBy` / setter | User grouping | | `showAllColumns` / `setShowAllColumns` | `boolean` / setter | "Show all" switch | | `reload` / `refetch` | `() => void` | Refetches the views and the items | | `views` / `fields` / `forms` / `dataSource` / `activeViewId` / `setActiveViewId` / `isLoading` / `error` / `hasNoViews` | — | From `useKivaDataViewSelect` | ### Exports `KIVA_KANBAN_SUPPORTED_FIELD_TYPES` (`Set`) and `readUserMeta(value, mode)`, which normalizes a user or team payload to `{ id, label, imageUrl }`. ## Native deltas - The card `⋮` button (and the info icon) opens an **action sheet** with the menu items. The created / modified audit trail is the sheet message, where web uses a hover tooltip. `label` and `icon` are strings. - Delete asks for confirmation in the native `RecordDeleteConfirmDialog`. - If a move fails (the built-in PATCH rejects or `onItemMoveCommit` throws), the board returns to the server's distribution. - The toolbar is stacked: start content and view picker, then search, then a horizontal row with the group pickers, "Show all", reload and end content. ## Translation Keys | Key | Fallback | |-----|----------| | `ui.kanban.search` | Search… | | `ui.kanban.view` | View | | `ui.kanban.groupBy` | Group by | | `ui.kanban.day` / `week` / `month` | Day / Week / Month | | `ui.kanban.user` / `team` | User / Team | | `ui.kanban.showAll` | Show all | | `ui.kanban.uncategorized` | Uncategorized | | `ui.kanban.weekOf` | Week of | | `ui.kanban.open` / `edit` / `delete` | Open / Edit / Delete | | `ui.kanban.cardActions` | Card actions | | `ui.kanban.recordInfo` | Record info | | `ui.kanban.created` / `modified` | Created / Modified | | `ui.kanban.configureGroupBy` | Configure a group-by field that points to … | | `ui.kanban.unsupportedField` | This field is not supported as a kanban group column: | ## Type Exports | Type | Description | |------|-------------| | `UseKivaKanbanOptions` / `UseKivaKanbanResult` | Hook options and result | | `KivaKanbanCollection` | Collection adapter | | `KivaKanbanListParams` | Query params | | `KivaKanbanColumnMeta` | Column metadata | | `KivaKanbanCardMenuItem` / `KivaKanbanCardAction` / `KivaKanbanCardContext` | Card types | | `KivaKanbanDateGroupBy` / `KivaKanbanUserGroupBy` | Grouping modes | --- # useKivaLogActivity URL: /docs/native/hooks/use-kiva-log-activity Kiva data engine for LogActivityForm. Fetches comments, users, task and event options and the record's status field, and runs the comment, task, event and two-call status mutations. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-log-activity ``` **Dependencies:** - [@tanstack/react-query](https://www.npmjs.com/package/@tanstack/react-query) - [@kivacore/api-client](https://www.npmjs.com/package/@kivacore/api-client) The hook owns all network I/O for the presentational [rn-log-activity-form](/docs/native/kiva/log-activity-form) and returns a `logActivityProps` bag to spread onto it. It needs a `QueryClientProvider` above it. ## Usage ```tsx import { useKivaClient } from '@kivacore/signin/react-native'; import { LogActivityForm } from '@/components/kiva-native/log-activity-form'; import { useKivaLogActivity } from '@/hooks/kiva-native/use-kiva-log-activity'; export function ContactLogActivity({ contactId, meId }: { contactId: string; meId: string }) { const client = useKivaClient(); const { logActivityProps } = useKivaLogActivity({ client, appSlug: 'base', dataSourceSlug: 'contact', recordId: contactId, relationSlug: 'contact', currentUserId: meId, callEventTypeName: 'Call', meetingEventTypeName: 'Meeting' }); return ; } ``` ### What it calls | Tab | Requests | |-----|----------| | Comment | `GET {record}/comments`, `POST {record}/comments`, `DELETE {record}/comments/:id`, users from `/v1/users` | | Task | `GET /v1/apps/{taskApp}/data-sources/{taskDs}?expand=fields,enums` (status + priority enums), `POST …/{taskDs}/items` linked through `taskRelationSlug ?? relationSlug` | | Call / Meeting | `GET /v1/apps/{eventTypeApp}/data-sources/{eventTypeDs}/items` (event types), `POST /v1/apps/{eventApp}/data-sources/{eventDs}/items` linked through `eventRelationSlug ?? relationSlug` | | Status | `GET {dataSource}?expand=fields,enums` (status field), `GET {record}?columns=…` (current value), then `PATCH {record}` followed by `POST {dataSource}/status-update/:slug` | `{record}` is `/v1/apps/:appSlug/data-sources/:dataSourceSlug/items/:recordId`. Queries for tabs that are not in `activityTypes` never run. If the `PATCH` succeeds but logging the status update fails, the mutation rejects with an error carrying `partial: true`. The status was still changed. Every successful mutation invalidates the record-scoped `['kiva-contact-activity', {record}]` prefix. A mounted [`useKivaContactActivity`](/docs/native/hooks/use-kiva-contact-activity) timeline for the same record refreshes automatically. ### Email tab Like web, the hook embeds [`useKivaEmailComposer`](/docs/native/hooks/use-kiva-email-composer): sender accounts, `@` mention users and the send mutation, with recipients seeded from `emailTo`. Its queries only run while the `email` tab is enabled. Native-only: pass `emailComposerProps`, `onSendEmail` and `isSendingEmail` to replace it with your own email wiring. The embedded composer then stays idle. ## API Reference ### UseKivaLogActivityOptions | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `RestApiClient` | - | Authenticated Kiva REST client (required) | | `appSlug` | `string` | - | Owning record's app (required) | | `dataSourceSlug` | `string` | - | Owning record's data source (required) | | `recordId` | `string` | - | Owning record id (required). Queries wait until it is set | | `relationSlug` | `string` | - | Back-relation slug linking new tasks and events to the record | | `eventRelationSlug` | `string` | `relationSlug` | Event back-relation override | | `taskRelationSlug` | `string` | `relationSlug` | Task back-relation override | | `statusFieldSlug` | `string` | first `field-status` | Status field on the record's data source | | `activityTypes` | `LoggableActivityType[]` | all six | Tabs shown. Also gates the queries | | `taskAppSlug` | `string` | `'base'` | Tasks app | | `taskDataSourceSlug` | `string` | `'task'` | Tasks data source | | `taskStatusFieldSlug` | `string` | `'status'` | Task status field | | `taskPriorityFieldSlug` | `string` | `'priority'` | Task priority field | | `eventAppSlug` | `string` | `'base'` | Events app | | `eventDataSourceSlug` | `string` | `'event'` | Events data source | | `eventTypeAppSlug` | `string` | `'base'` | Event type (calendar) app | | `eventTypeDataSourceSlug` | `string` | `'calendar'` | Event type (calendar) data source | | `callEventTypeId` | `string` | - | Preset event type for Call | | `meetingEventTypeId` | `string` | - | Preset event type for Meeting | | `callEventTypeName` | `string` | - | Resolve the Call event type by name (case-insensitive) when no id is given | | `meetingEventTypeName` | `string` | - | Resolve the Meeting event type by name when no id is given | | `users` | `CommentUser[]` | - | Users to use instead of fetching `/v1/users` | | `currentUserId` | `string` | - | Current user id (own comments) | | `usersLimit` | `number` | `1000` | Max users fetched | | `listUsersEndpoint` | `string` | `'/v1/users'` | Users endpoint override | | `emailTo` | `string[]` | - | Seed the Email tab recipients | | `emailComposerProps` | `Partial` | - | Native-only: overrides the embedded `useKivaEmailComposer` props | | `onSendEmail` | `() => void \| Promise` | - | Native-only: overrides the embedded send | | `isSendingEmail` | `boolean` | `false` | Native-only: pending send state when you override the email wiring | | `enabled` | `boolean` | `true` | Toggle every query | ### UseKivaLogActivityResult | Field | Type | Description | |-------|------|-------------| | `logActivityProps` | `KivaLogActivityProps` | Spread onto `` | | `createComment` | `(payload: LogActivityCommentPayload) => Promise` | Post a comment or reply | | `deleteComment` | `(commentId: string) => Promise` | Delete a comment | | `createTask` | `(input: LogTaskInput) => Promise` | Create a linked task | | `createEvent` | `(input: LogEventInput, kind: 'call' \| 'meeting') => Promise` | Create a linked event | | `updateStatus` | `(input: LogStatusInput) => Promise` | Two-call status change | | `isCreatingComment` | `boolean` | Comment mutation pending | | `isCreatingTask` | `boolean` | Task mutation pending | | `isCreatingEvent` | `boolean` | Event mutation pending | | `isUpdatingStatus` | `boolean` | Status mutation pending | | `refetch` | `() => Promise` | Invalidate the record-scoped activity cache | ## Type Exports | Type | Description | |------|-------------| | `UseKivaLogActivityOptions` | Hook options | | `UseKivaLogActivityResult` | Hook result | | `KivaLogActivityProps` | The subset of `LogActivityFormProps` the hook fills | --- # useKivaMapView URL: /docs/native/hooks/use-kiva-map-view Map backed by a Kiva data source. Detects the location field and builds markers from logos, icons or the default pin, with clustering, a viewport filter, basemaps and drag-to-move with reverse geocoding. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-map-view ``` **Dependencies:** - [@kivacore/api-client](https://www.npmjs.com/package/@kivacore/api-client) - [@kivacore/app-utils](https://www.npmjs.com/package/@kivacore/app-utils) - [@tanstack/react-query](https://tanstack.com/query/latest) - [react-native-maps](https://github.com/react-native-maps/react-native-maps) - [expo-location (optional)](https://docs.expo.dev/versions/latest/sdk/location/) This is a port of the web hook with the same signature. It builds on [`useKivaDataGrid`](/docs/native/hooks/use-kiva-data-grid) for the saved views, toolbar, filters and search, then requests only the columns the map needs. The rendering is rewritten for native. **`KivaMapView`** draws everything on the compound [rn-map](/docs/native/kiva/map), which uses react-native-maps. It includes: - clustered markers showing a logo, a Kiva icon or the default pin - callouts - drag-to-move - zoom and locate controls - a basemap switcher - a "Search this area" pill The web names `KivaLeafletMapView` and `KivaGoogleMapView` are exported as aliases. `KivaGoogleMapView` forces the Google provider. ## Usage ```tsx import { useKivaClient } from '@kivacore/signin/react-native'; import { KivaMapView, useKivaMapView } from '@/hooks/kiva-native/use-kiva-map-view'; export function OrganizationsMap() { const client = useKivaClient(); const mapView = useKivaMapView({ client: client!, appSlug: 'base', dataSourceSlug: 'organization', locationFieldSlug: 'map_location', titleFieldSlug: 'name', descriptionFieldSlugs: ['address', 'city', 'status'], markerImageFieldSlug: 'company_logo', markerIconFieldSlug: 'company_icon', enableViewportFilter: true, viewportFilterMode: 'manual', enableMarkerDrag: true, basemaps: ['street', 'satellite', 'hybrid', 'terrain'], googleMapsApiKey: process.env.EXPO_PUBLIC_GOOGLE_MAPS_API_KEY, persistState: true }); return ( <> {mapView.toolbar} ); } ``` ## API Reference ### Options (`UseKivaMapViewOptions`) Extends every [`useKivaDataGrid`](/docs/native/hooks/use-kiva-data-grid) option except `data`, `enableItemsQuery`, `showSelectColumn` and `enableRowMarkers`. | Prop | Type | Default | Description | |------|------|---------|-------------| | `client` | `RestApiClient` | — | Authenticated Kiva API client (required) | | `appSlug` | `string` | — | App slug (required) | | `dataSourceSlug` | `string` | — | Data source slug (required) | | `data` | `TData[]` | — | Pre-loaded rows. When set, the items query is skipped | | `collection` | `KivaDataGridCollection` | — | Custom `list` adapter | | `locationFieldSlug` | `string` | first `field-locationSelect` | Location field | | `titleFieldSlug` | `string` | `name`, `title`, … or the first text field | Marker title field | | `descriptionFieldSlugs` | `string[]` | `description`, `details`, `address`, `city`, … | Fields for the callout description | | `markerImageFieldSlug` | `string` | — | Image / file field used as the marker image | | `markerIconFieldSlug` | `string` | `field-icon` / `icon` | Kiva icon field | | `markerIconColorFieldSlug` | `string` | — | Icon color field (hex, `rgb()` or a Tailwind token) | | `markerIconColor` | `string` | — | Icon color when the color field is empty | | `markerPriority` | `'image' \| 'icon'` | `'image'` | Which one to show when a record has both | | `enableViewportFilter` | `boolean` | `false` | Limits `markers` / `mappedItems` to the viewport | | `viewportFilterMode` | `'auto' \| 'manual'` | `'auto'` | `manual` waits for `searchThisArea()` | | `enableMarkerDrag` | `boolean` | `false` | Makes markers draggable (long-press, then drag) | | `onMarkerMove` | `(marker, newPosition) => void \| Promise` | PATCH location | Replaces the default PATCH | | `markerTemplate` | `string` | — | `{{field_slug}}` template for the callout text | | `getMarker` | `(item, context) => KivaMapMarker \| null` | — | Replaces the built-in marker builder | | `defaultCenter` | `KivaMapPoint` | `{ lat: 39.9334, lng: 32.8597 }` | Center when there are no markers | | `defaultZoom` | `number` | `6` | Zoom when there are no markers | | `focusedZoom` | `number` | `14` | Zoom for a single marker | | `fitBoundsPadding` | `number` | `48` | Padding in px for the one-time fit to all markers | | `autoSelectSingleMarker` | `boolean` | `true` | Selects the marker automatically when there is only one | | `googleMapsApiKey` | `string \| null` | — | Enables Google reverse geocoding. There is no env fallback on native | | `onMapClick` | `(position: KivaMapPoint) => void` | — | Called on a tap on the map, then again with `address` once it resolves | | `basemaps` | `Array \| false` | — | Basemaps in the picker. Omit to hide the picker | | `defaultBasemap` | `string` | first entry | Initial basemap | | `enableGroupMenu` / `enableRowHeightMenu` / `enableDisplayMenu` | `boolean` | `false` | Grid toolbar menus | | `staleTime` | `number` | `30000` | React Query stale time in ms | | `onReload` | `() => void` | — | Called after a toolbar reload | | `persistState` | `boolean \| { storage?: 'session' \| 'local'; key?: string }` | — | Saves the grid's view parameters and the basemap (`…:map`) for each saved view | ### Result (`UseKivaMapViewResult`) | Key | Type | Description | |-----|------|-------------| | `markers` / `allMarkers` | `KivaMapMarker[]` | Markers after / before the viewport filter | | `items` / `mappedItems` / `unmappedItems` | `TData[]` | All records / records with a location / records without one | | `counts` | `{ total, mapped, unmapped }` | Record counts | | `viewportBounds` / `setViewportBounds` | `KivaMapBounds \| null` / setter | Last settled bounds. Wire the setter to `onViewportChange` | | `isViewportStale` | `boolean` | Manual mode: the map has moved since the last search | | `searchThisArea` / `clearViewportFilter` | `() => void` | Applies / clears the viewport filter | | `enableMarkerDrag` / `handleMarkerMove` | `boolean` / `(marker, pos) => Promise` | Drag-to-move | | `availableBasemaps` / `activeBasemap` / `setActiveBasemap` | — | Basemap state | | `locationField` / `titleField` / `descriptionFields` | `DataSourceField` | Resolved fields | | `hasLocationField` | `boolean` | Whether a location field was found | | `requestedColumns` / `resolvedListParams` | — | Query payload | | `center` / `bounds` / `defaultZoom` / `focusedZoom` / `fitBoundsPadding` | — | Camera inputs for `KivaMapView` | | `selectedMarkerId` / `selectedMarker` / `setSelectedMarkerId` / `selectMarker` / `clearSelectedMarker` | — | Selection | | `googleMapsApiKey` | `string \| null` | The resolved key | | `onMapClick` | `(position) => void \| undefined` | Passed through from options | | `isLoading` / `error` / `reload` | — | Loading, error and reload | | `table` / `toolbar` / `views` / `fields` / `dataSource` / `activeViewId` / `setActiveViewId` | — | Passed through from `useKivaDataGrid` | ### KivaMapView props | Prop | Type | Default | Description | |------|------|---------|-------------| | `markers` | `KivaMapMarker[]` | — | Markers to render (required) | | `center` | `KivaMapPoint` | — | Initial center (required) | | `bounds` | `KivaMapBounds \| null` | — | The map fits these bounds once, the first time they are available | | `defaultZoom` | `number` | `6` | Initial zoom without bounds | | `focusedZoom` | `number` | `14` | Zoom used for a single point | | `fitBoundsPadding` | `number` | `48` | Fit padding in px | | `selectedMarkerId` | `string \| null` | — | Highlighted marker | | `onSelectMarker` | `(id \| null) => void` | — | Called on a marker press, and with `null` when the map is tapped | | `onMapClick` | `(position) => void` | — | Called on a tap on empty map, then again with `address` | | `renderPopup` | `(marker) => ReactNode` | — | Custom callout content | | `onEditMarker` | `(marker) => void` | — | Called when the callout is pressed | | `onViewportChange` | `(bounds) => void` | — | Called when the map settles | | `draggableMarkers` | `boolean` | — | Makes markers draggable | | `onMarkerMove` | `(marker, position) => void \| Promise` | — | Called when a marker is dropped | | `allMarkersCount` | `number` | — | Keeps the map mounted when the viewport has no markers | | `basemaps` / `activeBasemap` / `onBasemapChange` | — | — | Layers control; shown when there are 2 or more basemaps | | `renderMarkerIcon` | `(marker, isSelected) => ReactNode` | — | Custom marker view | | `emptyState` | `ReactNode` | `t('ui.mapView.emptyMarkers')` | Shown when there is no data | | `className` | `string` | `h-[420px]` | Container classes. Give it a height | | `provider` | `'default' \| 'google'` | `'default'` | Map provider (native-only) | | `isViewportStale` / `onSearchThisArea` | `boolean` / `() => void` | — | "Search this area" pill (native-only) | | `enableClustering` | `boolean` | `true` | Clusters nearby markers (native-only) | | `showZoomControl` / `showLocateControl` | `boolean` | `true` | Map controls (native-only) | | `googleMapsApiKey` | `string \| null` | — | Reverse-geocoding key for `onMapClick` (native-only) | `KivaGoogleMapView` also accepts `apiKey`, `defaultMapType` (`'roadmap' | 'satellite' | 'hybrid' | 'terrain'`) and `getMarkerIcon(marker, isSelected) => string | { url, size } | null`. ### Helpers - `reverseGeocode(lat, lng, apiKey?)` returns `Promise`. It tries the optional `expo-location` peer first, then the Google Geocoding REST API when a key is given, then OpenStreetMap Nominatim. It never throws. - `getExpoLocationModule()` returns the optional `expo-location` module, or `null`. - `DEFAULT_KIVA_BASEMAPS` holds the built-in `street` / `satellite` / `hybrid` / `terrain` definitions. ## Native deltas - There is ONE `KivaMapView` on react-native-maps instead of the web Leaflet and Google Maps views. Both web names are exported as aliases. - `KivaBasemapDefinition` adds `mapType` (`'standard' | 'satellite' | 'hybrid' | 'terrain'`). The Leaflet tile fields are optional and ignored. - `KivaMapMarker` adds `icon` (the raw Kiva icon id), which is rendered with `KivaIcon`. - The map fits to the markers only once, like web, so refetches and drags never move the user's viewport. The viewport is not persisted. - `expo-location` is an **optional peer**. Without it, reverse geocoding uses Google REST (with a key) or Nominatim. ## Translation Keys | Key | Fallback | |-----|----------| | `ui.mapView.emptyMarkers` | No mapped records yet. | | `ui.mapView.searchThisArea` | Search this area | | `ui.mapView.tapToEdit` | Tap to edit | ## Type Exports | Type | Description | |------|-------------| | `UseKivaMapViewOptions` / `UseKivaMapViewResult` | Hook options and result | | `KivaMapMarker` / `KivaMapMarkerBuilderContext` / `KivaMapMarkerIcon` | Marker types | | `KivaMapPoint` / `KivaMapBounds` / `KivaLocationValue` / `KivaNormalizedLocation` | Geometry types | | `KivaBasemapId` / `KivaBasemapDefinition` / `KivaGoogleMapType` / `KivaMapProvider` | Basemap types | | `KivaMapViewProps` / `KivaGoogleMapViewProps` | View props | --- # useKivaPivotCalendar URL: /docs/native/hooks/use-kiva-pivot-calendar PivotCalendar backed by a Kiva data source. Aggregates per day or month in the database through a pivot matrix, optionally grouped by a relation, and turns a tapped value into a ready-to-run drilldown query. ## Installation ```bash pnpm dlx @kivacore/ui-cli add @kivacore/rn-hooks-use-kiva-pivot-calendar ``` **Dependencies:** - [@kivacore/api-client](https://www.npmjs.com/package/@kivacore/api-client) - [@tanstack/react-query](https://tanstack.com/query/latest) - [date-fns](https://www.npmjs.com/package/date-fns) A straight port of the web hook, with the same signature. It sends a `pivot.matrix` + `calculations` request to `GET /v1/apps/{appSlug}/data-sources/{dataSourceSlug}/items` through TanStack Query: - The date axis is `bucket:to_char[YYYY-MM-DD]@` (`YYYY-MM` for the year view) over a `dateRange` covering the active period. - With `groupBy`, a second matrix entry adds `groupLabel:` (plus `groupId:` when `idField` is set). The response is mapped into `cells` + `groups`, and `pivotCalendarProps` is ready to spread onto the native [rn-pivot-calendar](/docs/native/kiva/pivot-calendar). It needs an authenticated `RestApiClient` and a `QueryClientProvider` above it. Only the first **2** measures are requested, same as web. ## Usage ```tsx import { useState } from 'react'; import { useKivaClient } from '@kivacore/signin/react-native'; import { PivotCalendar } from '@/components/kiva-native/pivot-calendar'; import { useKivaPivotCalendar, type KivaPivotDrilldownQuery } from '@/hooks/kiva-native/use-kiva-pivot-calendar'; const toHours = (seconds: number) => seconds / 3600; export function TimeEntriesCalendar() { const client = useKivaClient(); const [drilldown, setDrilldown] = useState(null); const { pivotCalendarProps, buildDrilldownQuery } = useKivaPivotCalendar({ client: client!, appSlug: 'base', dataSourceSlug: 'time_entry', dateField: 'date', measures: [ { id: 'logged', label: 'Logged', field: 'duration', func: 'sum', transform: toHours, formatValue: v => `${v.toFixed(1)}h`, color: '#10b981' }, { id: 'billable', label: 'Billable', field: 'duration_billable', func: 'sum', transform: toHours, formatValue: v => `${v.toFixed(1)}h`, color: '#6366f1' } ], groupBy: { field: 'record_owner', label: 'User', labelField: 'name', idField: 'user_id' }, persistState: true, // `drilldown.filters` / `columns` / `orderBy` → fetch the underlying records. onCellClick: info => setDrilldown(buildDrilldownQuery(info)) }); return ; } ``` ## API Reference ### Options | Option | Type | Default | Description | |--------|------|---------|-------------| | `client` | `RestApiClient` | — | **Required.** Authenticated Kiva API client. | | `appSlug` | `string` | — | **Required.** App slug of the data source. | | `dataSourceSlug` | `string` | — | **Required.** Data source slug. | | `dateField` | `string` | — | **Required.** Date field that is bucketed per day or month (e.g. `created_on`, `due_date`). | | `measures` | `KivaPivotMeasure[]` | — | **Required.** Measures to aggregate. Only the first 2 are requested and rendered. | | `groupBy` | `KivaPivotGroupBy` | — | Optional grouping dimension (relation, user or select field). | | `columns` | `string` | — | Extra `columns` segment for the request. Defaults to a relation spread (`...()`) or `id`. | | `filters` | `unknown` | — | Filters applied to the aggregated records. They are also merged into the drilldown query. | | `defaultView` | `TPivotCalendarView` | `'month-calendar'` | Initial view. | | `view` | `TPivotCalendarView` | — | Controlled view. | | `onViewChange` | `(view: TPivotCalendarView) => void` | — | Called when the view changes. | | `defaultDate` | `Date` | `new Date()` | Initial reference date. | | `date` | `Date` | — | Controlled reference date. | | `onDateChange` | `(date: Date) => void` | — | Called when the reference date changes. | | `hideViewSwitcher` | `boolean` | — | Pass-through to `PivotCalendar`. | | `hideSidebar` | `boolean` | — | Pass-through to `PivotCalendar` (hides the group filter sheet). | | `visibleViews` | `TPivotCalendarView[]` | — | Pass-through to `PivotCalendar`. | | `enabled` | `boolean` | `true` | Enables or disables the query. | | `staleTime` | `number` | `30000` | TanStack Query `staleTime` (ms). | | `showEmptyCells` | `boolean` | `true` | When `false`, sends `pivot.hideEmptyRows: true`. | | `onCellClick` | `(info: IPivotCalendarCellClick) => void` | — | Fires when a value is tapped. Pair it with `buildDrilldownQuery`. | | `persistState` | `boolean \| { storage?: 'session' \| 'local'; key?: string }` | — | Persists the uncontrolled view and focused date under `docyrus:view-params:::pivot-calendar`. `true` / `'session'` is in-memory for the JS runtime. `'local'` uses the store registered with `` / `setKivaLocalStore()` and survives restarts. Controlled `view` / `date` always win. | ### KivaPivotMeasure | Field | Type | Description | |-------|------|-------------| | `id` | `string` | Stable id; also the calculation name in the response. | | `label` | `string` | Visible label. | | `shortLabel` | `string` | Compact label for headers. | | `field` | `string` | Field slug to aggregate (`'id'` for `count`). | | `func` | `'sum' \| 'count' \| 'avg' \| 'min' \| 'max'` | Aggregation function. | | `transform` | `(value: number) => number` | Applied to the API value (e.g. seconds → hours). | | `formatValue` | `(value: number) => string` | Cell formatter. | | `color` | `string` | Accent colour. | | `description` | `string` | Shown in the day sheet. | ### KivaPivotGroupBy | Field | Type | Description | |-------|------|-------------| | `field` | `string` | Grouping relation / select field slug. | | `label` | `string` | Label for the filter sheet and the grid's group column. | | `labelField` | `string` | Sub-field used as the group label. Default `'name'`. | | `idField` | `string` | Non-join sub-field used as a stable group id (e.g. `'user_id'` for users). With it, drilldown filters use ` = `; without it, they use `rel_/ =