### useUserInfo - React Authentication Hook Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt A React hook for managing user authentication state. It includes automatic refetch control and query caching for user information. Dependencies include authentication API functions. ```typescript import { useUserInfo, useLogout } from './src/api/auth'; function UserProfile() { const { data: userInfo, isLoading, error } = useUserInfo(); const logout = useLogout(); if (isLoading) return
Loading user info...
; if (error) return
Authentication error
; return (

User Profile

ID: {userInfo.id}

Email: {userInfo.email}

); } // Usage in component with conditional rendering function ProtectedContent() { const { data: user, isLoading } = useUserInfo(); if (isLoading) return null; if (!user?.id) { // User will be automatically redirected to login return
Redirecting to login...
; } return
Welcome, {user.email}!
; } ``` -------------------------------- ### AidboxCall - Simplified JSON API Requests Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt AidboxCall is a higher-level API wrapper that simplifies common CRUD operations by automatically handling JSON serialization and deserialization, providing typed responses. ```APIDOC ## AidboxCall - Simplified JSON API Requests ### Description A higher-level API wrapper that automatically handles JSON serialization/deserialization for simplified CRUD operations and typed responses. ### Method Any valid HTTP method (GET, POST, PUT, DELETE, etc.) ### Endpoint `/fhir/*` (and other Aidbox API endpoints) ### Parameters #### Path Parameters None specific to AidboxCall itself, depends on the endpoint. #### Query Parameters - **params** (object) - Optional - Query parameters to append to the URL. #### Request Body - **method** (string) - Required - The HTTP method for the request. - **url** (string) - Required - The endpoint URL. - **body** (object | string) - Optional - The request body, can be an object or a JSON string. ### Request Example ```typescript import { AidboxCall } from './src/api/auth'; interface Patient { resourceType: 'Patient'; id: string; name: Array<{ given: string[]; family: string; }>; birthDate: string; } const patient = await AidboxCall({ method: 'GET', url: '/fhir/Patient/patient-456' }); const newPatient = await AidboxCall({ method: 'POST', url: '/fhir/Patient', body: { resourceType: 'Patient', name: [{ given: ['John'], family: 'Doe' }], birthDate: '1990-01-01', gender: 'male' } }); const searchResults = await AidboxCall({ method: 'GET', url: '/fhir/Patient', params: { name: 'Doe', birthdate: 'gt1980-01-01', _count: '10', _sort: '-birthdate' } }); ``` ### Response #### Success Response (200) - The response body is automatically deserialized into the specified generic type (or `any` if not specified). #### Response Example ```json { "resourceType": "Patient", "id": "patient-456", "name": [ { "given": ["Jane"], "family": "Doe" } ], "birthDate": "1995-05-15" } ``` ``` -------------------------------- ### Transform FHIR Schema Snapshot to Tree - TypeScript Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt Transforms FHIR resource schema snapshots into hierarchical tree structures suitable for navigation and visualization. It takes an array of schema objects and returns a map representing the tree. Dependencies include the `transformSnapshotToTree` function from `./src/utils`. ```typescript import { transformSnapshotToTree } from './src/utils'; // FHIR Patient schema snapshot data const snapshotData = [ { type: 'root', name: 'Patient', path: 'Patient', short: 'Information about an individual' }, { type: 'complex', path: 'Patient.identifier', name: 'identifier', datatype: 'Identifier', min: 0, max: '*', short: 'An identifier for this patient' }, { type: 'primitive', path: 'Patient.active', name: 'active', datatype: 'boolean', min: 0, max: '1', short: 'Whether this patient's record is in active use' }, { type: 'complex', path: 'Patient.name', name: 'name', datatype: 'HumanName', min: 0, max: '*', short: 'A name associated with the patient', flags: ['summary'] }, { type: 'primitive', path: 'Patient.name.family', name: 'family', datatype: 'string', min: 0, max: '1', short: 'Family name' }, { type: 'primitive', path: 'Patient.name.given', name: 'given', datatype: 'string', min: 0, max: '*', short: 'Given names' } ]; const tree = transformSnapshotToTree(snapshotData); // Tree structure with hierarchical relationships console.log(tree['root']); // { name: 'Root', children: ['Patient'] } console.log(tree['Patient']); // { // name: 'Patient', // meta: { // type: 'Resource', // min: '0', // max: '*', // description: 'Information about an individual' // }, // children: ['Patient.identifier', 'Patient.active', 'Patient.name'] // } console.log(tree['Patient.name']); // { // name: 'name', // meta: { // type: 'HumanName', // min: '0', // max: '*', // short: 'A name associated with the patient', // description: 'A name associated with the patient', // isSummary: true // }, // children: ['Patient.name.family', 'Patient.name.given'] // } console.log(tree['Patient.name.given']); // { // name: 'given', // meta: { // type: 'string', // min: '0', // max: '*', // short: 'Given names', // description: 'Given names', // lastNode: true // Indicates leaf node // } // } // Use tree for navigation UI function renderTree(nodeId: string) { const node = tree[nodeId]; return (
{node.name} {node.meta?.type && : {node.meta.type}} {node.children && (
    {node.children.map(childId => (
  • {renderTree(childId)}
  • ))}
)}
); } ``` -------------------------------- ### Parse and Generate HTTP Requests - TypeScript Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt Parses raw HTTP request text into structured data and generates HTTP request strings from structured data. It handles methods, paths, headers, and bodies, with support for UI-specific empty header rows. Dependencies include the `parseHttpRequest` and `generateHttpRequest` functions from `./src/utils`. ```typescript import { parseHttpRequest, generateHttpRequest } from './src/utils'; // Parse raw HTTP request text const rawRequest = `POST /fhir/Patient Content-Type: application/json Authorization: Bearer token123 { "resourceType": "Patient", "name": [{"given": ["Jane"], "family": "Doe"}] }`; const parsed = parseHttpRequest(rawRequest); console.log(parsed.method); // 'POST' console.log(parsed.path); // '/fhir/Patient' console.log(parsed.headers); // [ // { id: 'uuid-1', name: 'Content-Type', value: 'application/json', enabled: true }, // { id: 'uuid-2', name: 'Authorization', value: 'Bearer token123', enabled: true }, // { id: 'uuid-3', name: '', value: '', enabled: true } // Empty row for UI // ] console.log(parsed.body); // '{ // "resourceType": "Patient", // "name": [{"given": ["Jane"], "family": "Doe"}] // }' // Generate HTTP request from structured data const tab = { method: 'GET', path: '/fhir/Patient?name=Doe&_count=10', headers: [ { id: '1', name: 'Accept', value: 'application/fhir+json', enabled: true }, { id: '2', name: 'X-Custom', value: 'test', enabled: false } // Disabled header ], body: '' }; const httpRequest = generateHttpRequest(tab); console.log(httpRequest); // GET /fhir/Patient?name=Doe&_count=10 // Accept: application/fhir+json // ``` -------------------------------- ### AidboxRequest - Core API Request Handler Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt AidboxRequest provides a low-level API request function with comprehensive error handling, authentication redirection, and detailed response metadata. It supports various HTTP methods, custom headers, query parameters, request bodies, and streaming responses. ```APIDOC ## AidboxRequest - Core API Request Handler ### Description Handles low-level API requests with built-in error handling, authentication redirection, and metadata retrieval. ### Method Any valid HTTP method (GET, POST, PUT, DELETE, etc.) ### Endpoint `/fhir/*` (and other Aidbox API endpoints) ### Parameters #### Path Parameters None specific to AidboxRequest itself, depends on the endpoint. #### Query Parameters - **params** (Array<[string, string]> | Record) - Optional - Query parameters to append to the URL. #### Request Body - **method** (string) - Required - The HTTP method for the request. - **url** (string) - Required - The endpoint URL. - **headers** (object) - Optional - Request headers. - **body** (string) - Optional - The request body, typically JSON stringified. - **streamBody** (boolean) - Optional - If true, indicates a streaming response. ### Request Example ```javascript import { AidboxRequest } from './src/api/auth'; const response = await AidboxRequest({ method: 'GET', url: '/fhir/Patient/patient-123', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); const createResponse = await AidboxRequest({ method: 'POST', url: '/fhir/Observation', params: [['_format', 'json'], ['_pretty', 'true']], body: JSON.stringify({ resourceType: 'Observation', status: 'final', code: { coding: [{ system: 'http://loinc.org', code: '15074-8', display: 'Glucose' }] } }) }); ``` ### Response #### Success Response (200) - **response** (object) - Contains the actual HTTP response details (status, headers, body). - **meta** (object) - Contains metadata about the request (e.g., duration). #### Response Example ```json { "response": { "status": 200, "body": "{\"resourceType\": \"Patient\", \"id\": \"patient-123\", ...}" }, "meta": { "duration": 142 } } ``` #### Error Handling - Automatically redirects on 401/403 errors. - Errors contain a `cause` property with full response details. ``` -------------------------------- ### useUIHistory - React Request History Hook Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt A hook for accessing and displaying recent HTTP request history. It supports pagination and sorting, automatically fetching the last 100 HTTP-type entries sorted by `_lastUpdated` in descending order. ```typescript import { useUIHistory } from './src/api/auth'; function RequestHistory() { const { data: history, isLoading, refetch } = useUIHistory(); if (isLoading) return
Loading history...
; return (

Recent Requests ({history.total})

    {history.entry.map(item => (
  • {item.resource.command} {new Date(item.resource.meta.createdAt).toLocaleString()}
  • ))}
); } // The hook automatically fetches last 100 HTTP-type history entries // Sorted by _lastUpdated in descending order // Stale time: 30 seconds (won't refetch if data is fresh) ``` -------------------------------- ### Retrieve Aidbox Base URL - TypeScript Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt Retrieves the Aidbox server base URL by checking cookies, environment variables, or defaulting to the current window's location. This utility is crucial for configuring API requests. Dependencies include the `getAidboxBaseURL` function from `./src/utils`. ```typescript import { getAidboxBaseURL } from './src/utils'; // Get base URL for API requests const baseURL = getAidboxBaseURL(); console.log(baseURL); // 'https://my-aidbox.instance.com' or 'http://localhost:8080' // Priority order: // 1. Cookie: 'aidbox-base-url' // 2. Environment variable: VITE_AIDBOX_BASE_URL // 3. Current window location // Use in custom API calls async function customRequest(endpoint: string) { const url = `${getAidboxBaseURL()}${endpoint}`; const response = await fetch(url, { credentials: 'include', headers: { 'Content-Type': 'application/json' } }); return response.json(); } // Set base URL via cookie (typically done by backend) document.cookie = `aidbox-base-url=${encodeURIComponent('https://custom.aidbox.app')}; path=/`; ``` -------------------------------- ### useDebounce - React Debounce Hook Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt A custom React hook for debouncing rapid function calls. It is ideal for search inputs and API calls triggered by user input, delaying execution until a specified time has passed without new calls. ```typescript import { useDebounce } from './src/hooks/useDebounce'; import { useState } from 'react'; function PatientSearch() { const [results, setResults] = useState([]); const [searchTerm, setSearchTerm] = useState(''); // Debounce search API call by 500ms const debouncedSearch = useDebounce(async (term: string) => { if (term.length < 2) { setResults([]); return; } const response = await AidboxCall({ method: 'GET', url: '/fhir/Patient', params: { name: term, _count: '20' } }); setResults(response.entry || []); }, 500); const handleSearchChange = (e: React.ChangeEvent) => { const value = e.target.value; setSearchTerm(value); debouncedSearch(value); // API call delayed until typing stops }; return (
    {results.map(patient => (
  • {patient.resource.name?.[0]?.family}
  • ))}
); } ``` -------------------------------- ### FHIR Resource CRUD Operations Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt Provides functions for creating, reading, updating, deleting, and fetching the history of FHIR resources. It ensures consistent error handling and type safety for all operations. ```typescript import { fetchResource, createResource, updateResource, deleteResource, fetchResourceHistory } from './src/components/ResourceEditor/api'; // Fetch a single resource const observation = await fetchResource('Observation', 'obs-789'); console.log(observation.resourceType); // 'Observation' // Create a new resource const newCondition = await createResource('Condition', { resourceType: 'Condition', clinicalStatus: { coding: [{ system: 'http://terminology.hl7.org/CodeSystem/condition-clinical', code: 'active' }] }, code: { coding: [{ system: 'http://snomed.org/sct', code: '73211009', display: 'Diabetes mellitus' }] }, subject: { reference: 'Patient/patient-123' } }); console.log(newCondition.id); // Auto-generated ID // Update existing resource const updatedCondition = await updateResource('Condition', newCondition.id, { ...newCondition, clinicalStatus: { coding: [{ system: 'http://terminology.hl7.org/CodeSystem/condition-clinical', code: 'resolved' }] }, abatementDateTime: '2024-01-15T10:30:00Z' }); // Fetch resource history (version timeline) const history = await fetchResourceHistory('Condition', newCondition.id); console.log(history.total); // Number of versions history.entry.forEach(entry => { console.log(`Version ${entry.resource.meta.versionId}: ${entry.resource.meta.lastUpdated}`); }); // Delete resource await deleteResource('Condition', newCondition.id); ``` -------------------------------- ### useLocalStorage Hook: React Persistent State with Cross-Tab Sync Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt A React hook for managing state persisted in localStorage. It supports basic string storage, complex object storage with type safety, and synchronization across browser tabs. Custom serialization and deserialization functions can also be provided. ```typescript import { useLocalStorage } from './src/hooks/useLocalStorage'; function ThemeSettings() { // Basic usage with string const [theme, setTheme, removeTheme] = useLocalStorage({ key: 'app-theme', defaultValue: 'light' }); return (
); } // Complex object storage with type safety interface EditorSettings { fontSize: number; tabSize: number; wordWrap: boolean; } function EditorConfig() { const [settings, setSettings] = useLocalStorage({ key: 'editor-settings', defaultValue: { fontSize: 14, tabSize: 2, wordWrap: true }, sync: true // Sync across browser tabs }); const updateFontSize = (size: number) => { setSettings(prev => ({ ...prev, fontSize: size })); }; return (
); } // With custom serialization/deserialization const [data, setData] = useLocalStorage({ key: 'custom-data', serialize: (value) => btoa(JSON.stringify(value)), // Base64 encode deserialize: (value) => value ? JSON.parse(atob(value)) : null }); ``` -------------------------------- ### AidboxCall: Simplified Typed FHIR API Requests (TypeScript) Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt AidboxCall is a higher-level API wrapper that simplifies common CRUD operations by automatically handling JSON serialization and deserialization. It provides typed responses, enhancing type safety and developer experience when interacting with FHIR resources. ```typescript import { AidboxCall } from './src/api/auth'; // Fetch resource with automatic JSON parsing and type inference interface Patient { resourceType: 'Patient'; id: string; name: Array<{ given: string[]; family: string; }>; birthDate: string; } const patient = await AidboxCall({ method: 'GET', url: '/fhir/Patient/patient-456' }); console.log(patient.name[0].family); // Access typed properties // Create resource with object body (auto-serialized) const newPatient = await AidboxCall({ method: 'POST', url: '/fhir/Patient', body: { resourceType: 'Patient', name: [{ given: ['John'], family: 'Doe' }], birthDate: '1990-01-01', gender: 'male' } }); // Search with query parameters const searchResults = await AidboxCall({ method: 'GET', url: '/fhir/Patient', params: { name: 'Doe', birthdate: 'gt1980-01-01', _count: '10', _sort: '-birthdate' } }); // Update resource with PUT const updated = await AidboxCall({ method: 'PUT', url: `/fhir/Patient/${patient.id}`, body: { ...patient, active: true, telecom: [{ system: 'phone', value: '+1-555-0123' }] } }); ``` -------------------------------- ### diff Utility: Deep Object Comparison for FHIR Resources and Arrays Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt A utility function designed for deep comparison of objects, arrays, or primitives. It returns three distinct structures: items only in the original, items only in the updated, and items that remain unchanged. This is particularly useful for comparing complex data structures like FHIR resources. ```typescript import { diff } from './src/utils/diff'; // Compare FHIR resource versions const originalPatient = { resourceType: 'Patient', id: 'patient-123', name: [{ given: ['John'], family: 'Doe' }], birthDate: '1990-01-01', active: true, address: [{ city: 'Boston', state: 'MA' }] }; const updatedPatient = { resourceType: 'Patient', id: 'patient-123', name: [{ given: ['John'], family: 'Smith' }], // Changed birthDate: '1990-01-01', active: false, // Changed address: [{ city: 'Boston', state: 'MA', country: 'USA' }], // Added field telecom: [{ system: 'email', value: 'john@example.com' }] // New field }; const [onlyInOriginal, onlyInUpdated, unchanged] = diff(originalPatient, updatedPatient); console.log(onlyInOriginal); // { // name: [{ family: 'Doe' }], // active: true, // address: [{}] // } console.log(onlyInUpdated); // { // name: [{ family: 'Smith' }], // active: false, // address: [{ country: 'USA' }], // telecom: [{ system: 'email', value: 'john@example.com' }] // } console.log(unchanged); // { // resourceType: 'Patient', // id: 'patient-123', // name: [{ given: ['John'] }], // birthDate: '1990-01-01', // address: [{ city: 'Boston', state: 'MA' }] // } // Array comparison const [addedItems, removedItems, commonItems] = diff( ['apple', 'banana', 'cherry'], ['banana', 'cherry', 'date'] ); console.log(addedItems); // [null, null, 'date'] console.log(removedItems); // ['apple', null, null] console.log(commonItems); // [null, 'banana', 'cherry'] ``` -------------------------------- ### AidboxRequest: Low-level FHIR API Request Handler (TypeScript) Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt AidboxRequest is a fundamental function for making API calls to Aidbox. It handles authentication, error redirection for 401/403 errors, and provides detailed metadata about the request, including duration and response headers. It supports various HTTP methods, request bodies, query parameters, and streaming responses. ```typescript import { AidboxRequest } from './src/api/auth'; // Fetch a FHIR Patient resource with full metadata const response = await AidboxRequest({ method: 'GET', url: '/fhir/Patient/patient-123', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); // Response structure includes both response data and metadata console.log(response.response.status); // 200 console.log(response.response.body); // '{"resourceType": "Patient", "id": "patient-123", ...}' console.log(response.meta.duration); // 142 (milliseconds) // Create a new resource with POST and query parameters const createResponse = await AidboxRequest({ method: 'POST', url: '/fhir/Observation', params: [['_format', 'json'], ['_pretty', 'true']], body: JSON.stringify({ resourceType: 'Observation', status: 'final', code: { coding: [{ system: 'http://loinc.org', code: '15074-8', display: 'Glucose' }] } }) }); // Streaming response for large datasets const streamResponse = await AidboxRequest({ method: 'GET', url: '/fhir/Patient', params: [['_count', '1000']], streamBody: true }); // Error handling - automatically redirects on 401/403 try { await AidboxRequest({ method: 'DELETE', url: '/fhir/Patient/invalid-id' }); } catch (error) { // Error contains cause with full response details console.error(error.message); // "HTTP 404: Not Found" console.error(error.cause.response.body); // Full error response } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.