### Complete Setup Example (TypeScript) Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/technical-documentation-guide.md Demonstrates how to set up and combine multiple features of a library. This example shows a resource being created and configured with various features using a pipeable approach. It highlights how different components interact and become available after setup. ```markdown ### Complete Setup Shows how all features work together. ```typescript const resource = createResource().pipe( withFeature1(), withFeature2({ option: 'value' }), withFeature3() ) // Available after setup: // - resource.feature1Atom // - resource.feature2() // - resource.feature3.reset() ``` ``` -------------------------------- ### Content Strategy - Complete Setup Examples Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/technical-documentation-guide.md Provides guidance on using complete setup examples that offer full context, contrasting them with fragment examples that lack necessary information. ```APIDOC ### Complete Setup Examples #### Good: Full Context ```typescript const userResource = reatomResource(async (ctx) => { const id = ctx.spy(userIdAtom); return await ctx.schedule(() => fetch(`/api/users/${id}`).then((r) => r.json())); }).pipe( // Add data state management withDataAtom(null), // Add error handling withErrorAtom((ctx, error) => { if (error instanceof Response) return error.status; return error instanceof Error ? error : new Error(String(error)); }), // Add caching withCache({ staleTime: 5000, cacheTime: 30000, }), ); // Available features after setup: // - userResource.dataAtom // - userResource.errorAtom // - userResource.cacheAtom.invalidate(ctx) ``` #### Bad: Fragment Examples ```typescript const resource = userResource.pipe(withDataAtom(null)); // No context of what this provides or how to use it ``` ``` -------------------------------- ### Complete Setup Example (TypeScript) Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/technical-documentation-guide.md Provides a comprehensive example of setting up a resource with multiple features like data state management, error handling, and caching using TypeScript. This illustrates how to combine different operators for a full-featured resource. ```typescript const userResource = reatomResource(async (ctx) => { const id = ctx.spy(userIdAtom); return await ctx.schedule(() => fetch(`/api/users/${id}`).then((r) => r.json())); }).pipe( // Add data state management withDataAtom(null), // Add error handling withErrorAtom((ctx, error) => { if (error instanceof Response) return error.status; return error instanceof Error ? error : new Error(String(error)); }), // Add caching withCache({ staleTime: 5000, cacheTime: 30000, }), ); // Available features after setup: // - userResource.dataAtom // - userResource.errorAtom // - userResource.cacheAtom.invalidate(ctx) ``` -------------------------------- ### Multi-Provider Setup Example Source: https://github.com/konturio/disaster-ninja-fe/blob/main/src/core/map/MapPopover.md Example demonstrating how to register multiple content providers with varying priorities. ```APIDOC ## Multi-Provider Setup ### Description Register multiple providers with different priorities. ### Example ```tsx // Register multiple providers with different priorities const setupProviders = () => { // High priority tool mapPopoverRegistry.register('boundary-tool', new BoundarySelectProvider()); // Normal content providers mapPopoverRegistry.register('feature-info', new FeatureInfoProvider()); mapPopoverRegistry.register('layer-tooltip', new LayerTooltipProvider()); // Debug provider (lowest priority) mapPopoverRegistry.register('debug', new DebugProvider()); }; ``` ``` -------------------------------- ### Content Strategy - Practical Patterns Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/technical-documentation-guide.md Illustrates the use of practical, real-world usage examples for API patterns, distinguishing them from theoretical or abstract examples. ```APIDOC ### Practical Patterns #### Good: Real-World Usage ```typescript // Manual refresh button const refreshUser = action((ctx) => { userResource.cacheAtom.invalidate(ctx); }, 'refreshUser'); // Auto retry on error onConnect(userResource.errorAtom, (ctx) => { if (ctx.get(userResource.errorAtom)) { userResource.retry(ctx); } }); ``` #### Bad: Theoretical Examples ```typescript // Example usage resource.invalidate(); // No context of when/why to use this ``` ``` -------------------------------- ### Start Disaster Ninja Development Server Source: https://github.com/konturio/disaster-ninja-fe/blob/main/README.md This command installs project dependencies and starts the development server for Disaster Ninja. It allows for real-time development and testing of the front-end application. ```bash pnpm i pnpm run dev ``` -------------------------------- ### Usage Pattern Example (TypeScript) Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/technical-documentation-guide.md Illustrates a common usage pattern for a library feature. This example demonstrates how to create an instance with specific options and then use its methods. It's crucial for showing practical application and key considerations. ```markdown ### Pattern Name Description of when to use this pattern. ```typescript // Complete working example const example = createExample({ option1: 'value1', option2: 'value2' }) // Usage example.doSomething() ``` **Key points**: Important considerations **Alternatives**: When to use different approaches ``` -------------------------------- ### Registering Multiple Content Providers (TypeScript) Source: https://github.com/konturio/disaster-ninja-fe/blob/main/src/core/map/MapPopover.md Example demonstrating how to register multiple content providers with the `IMapPopoverContentRegistry`. This setup assigns different priorities to providers, such as a high-priority tool, normal content providers, and a low-priority debug provider. ```typescript // Register multiple providers with different priorities const setupProviders = () => { // High priority tool mapPopoverRegistry.register('boundary-tool', new BoundarySelectProvider()); // Normal content providers mapPopoverRegistry.register('feature-info', new FeatureInfoProvider()); mapPopoverRegistry.register('layer-tooltip', new LayerTooltipProvider()); // Debug provider (lowest priority) mapPopoverRegistry.register('debug', new DebugProvider()); }; ``` -------------------------------- ### Practical Pattern Example (TypeScript) Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/technical-documentation-guide.md Illustrates practical, real-world usage patterns for managing resources, such as implementing a manual refresh button and setting up auto-retry logic on error using TypeScript. This demonstrates how to interact with resource features in application code. ```typescript // Manual refresh button const refreshUser = action((ctx) => { userResource.cacheAtom.invalidate(ctx); }, 'refreshUser'); // Auto retry on error onConnect(userResource.errorAtom, (ctx) => { if (ctx.get(userResource.errorAtom)) { userResource.retry(ctx); } }); ``` -------------------------------- ### Creating a Simple Control Guide Source: https://github.com/konturio/disaster-ninja-fe/blob/main/src/core/toolbar/readme.md A step-by-step guide on how to create and initialize a simple control. ```APIDOC ## Guides ### Creating a Simple Control **Step 1:** Setup the control ```typescript export const locateControl = toolbar.setupControl({ id: 'LocateMe', type: 'button', typeSettings: { name: 'Locate Me', icon: 'Location24', preferredSize: 'medium', }, }); ``` **Step 2:** Add behavior ```typescript locateControl.onStateChange((ctx, state) => { if (state === 'active') { navigator.geolocation.getCurrentPosition(/* ... */); locateControl.setState('regular'); } }); ``` **Step 3:** Initialize ```typescript locateControl.init(); ``` **Step 4:** [Add to toolbar layout](#44-adding-to-toolbar-layout) ``` -------------------------------- ### CSS Styling Examples for PagesDocument Component Source: https://github.com/konturio/disaster-ninja-fe/blob/main/src/core/pages/customization.md Provides CSS examples for styling the PagesDocument component. It demonstrates how to target specific document IDs, markdown content wrappers, headings based on their level and ID, and nested elements. These styles leverage the default prefixes and structure provided by the component. ```css #app-pages-docid-about { /* styles for about page */ } .app-pages-element-markdown { /* styles for markdown sections */ } .wrap-hdr-1 { /* styles for content under h1 */ } .wrap-hdr-1-1 { /* styles for content under h2 within first h1 */ } #hdr-1 { /* styles for first h1 */ } #app-pages-docid-about .wrap-hdr-1 { /* styles for first h1 content in about page */ } .wrap-hdr-1 a[href^='#hdr-'] { /* styles for heading links within first section */ } ``` -------------------------------- ### Tool Integration Example Source: https://github.com/konturio/disaster-ninja-fe/blob/main/src/core/map/MapPopover.md Example showing how to integrate a tool with the popover system, including automatic popover closure on activation. ```APIDOC ## Tool Integration ### Description Tool activation with automatic popover closure. ### Example ```tsx // Tool activation with automatic popover closure const activateBoundarySelector = () => { // Registry automatically closes existing popovers when exclusive provider is registered mapPopoverRegistry.register('boundary-selector', boundarySelectorProvider); // Tool is now active - next map clicks will show only boundary selector }; const deactivateBoundarySelector = () => { mapPopoverRegistry.unregister('boundary-selector'); // Back to normal mode - all providers can respond to clicks }; ``` ``` -------------------------------- ### OIDC Client Initialization Example Source: https://github.com/konturio/disaster-ninja-fe/blob/main/src/core/auth/README.md JavaScript examples demonstrating how to initialize the OIDC Simple Client. Shows basic initialization with issuer URI and client ID, and advanced initialization with localStorage for cross-tab synchronization. ```javascript const client = new OidcSimpleClient(); await client.init('https://auth-server.com', 'client-id'); // With cross-tab synchronization: const clientWithSync = new OidcSimpleClient(localStorage, true); await clientWithSync.init('https://auth-server.com', 'client-id'); ``` -------------------------------- ### Complete UniLayout Flow Example Source: https://github.com/konturio/disaster-ninja-fe/blob/main/src/components/Uni/Layout/UniLayout.md Illustrates a complete UniLayout data flow, starting from a field definition in fieldsRegistry and a layout definition, showing the final component props including raw values and merged metadata. ```javascript // fieldsRegistry.ts projectId: { type: 'number', text: (v) => `#${v}`, } ``` ```json { "type": "Badge", "$props": { "value": "projectId", "status": "status" }, "overrides": { "value": { "icon": "Project16" } } } ``` ```javascript { value: 42, // raw value from projectId status: "active", // raw value from status $meta: { value: { type: "number", text: (v) => `#${v}`, icon: "Project16" // overridden }, status: { // metadata from fieldsRegistry for status } } } ``` -------------------------------- ### Parameter Documentation (TypeScript) Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/technical-documentation-guide.md Illustrates how to document function parameters effectively, using the example of an `atom` function. It provides a clear signature and detailed explanations for each parameter, including context and return values, which is crucial for understanding reducer functions. ```typescript function atom( initialState: T, reducer: (ctx: Ctx, state: T) => T ): AtomMut **Reducer signature**: `(ctx: Ctx, state: T) => T` - `ctx`: Context for accessing other atoms - `state`: Current atom state - **Returns**: New state value **Note**: Reducer is called on every atom access, not just updates. ``` -------------------------------- ### Build and Serve Disaster Ninja with pnpm Source: https://github.com/konturio/disaster-ninja-fe/blob/main/README.md These commands are used to build the Disaster Ninja front-end application and serve it using pnpm. First, it installs dependencies, then builds the project, and finally starts a local development server. ```bash pnpm i pnpm run build pnpm run serve ``` -------------------------------- ### OIDC Client Authentication Examples Source: https://github.com/konturio/disaster-ninja-fe/blob/main/src/core/auth/README.md JavaScript examples for using the OIDC Simple Client's authentication methods. Includes logging in with username and password, retrieving an access token, and logging out with or without page reload. ```javascript // Login const result = await client.authenticate('username', 'password'); // result can be true or error message string // Get access token const token = await client.getAccessToken(); // Logout await client.logout(); // Reloads by default await client.logout(false); // Does not reload ``` -------------------------------- ### New Documentation Template (Markdown) Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/technical-documentation-guide.md A template for creating new documentation pages. It outlines the standard sections, including Table of Contents, Overview, Core Concepts, API Reference, Usage Patterns, and Common Examples. This ensures a consistent structure across all documentation. ```markdown # Library Name Documentation ## Table of Contents - [Overview](#overview) - [Core Concepts](#core-concepts) - [API Reference](#api-reference) - [Usage Patterns](#usage-patterns) - [Common Examples](#common-examples) ## Overview Brief description of what the library does and its core principles. ## Core Concepts Explain the fundamental building blocks and how they work together. ## API Reference Complete function signatures with expanded options and behavioral notes. ## Usage Patterns Real-world examples showing how to combine features effectively. ## Common Examples Complete setup examples demonstrating typical use cases. ``` -------------------------------- ### Run Development Server with pnpm start Source: https://github.com/konturio/disaster-ninja-fe/blob/main/README.md Starts the application in development mode, enabling hot-reloading and displaying lint errors in the console. The app is accessible at http://localhost:3000. ```bash pnpm start ``` -------------------------------- ### Install Playwright Browsers Source: https://github.com/konturio/disaster-ninja-fe/blob/main/README.md Installs the necessary Playwright browsers for running end-to-end tests. This command should be run before executing any Playwright tests. ```bash npx playwright install ``` -------------------------------- ### Performance Optimization: Early Return and Optimized Queries Source: https://github.com/konturio/disaster-ninja-fe/blob/main/src/core/map/MapPopover.md Provides strategies for optimizing map performance. The first example shows using an early return in `renderContent` to avoid expensive operations for irrelevant events. The second example demonstrates optimizing feature queries by filtering by layer ID. ```tsx renderContent(mapEvent: MapMouseEvent): React.ReactNode | null { // Quick checks first if (!this.isEnabled || !this.shouldShow) return null; // Expensive operations only when needed const features = mapEvent.target.queryRenderedFeatures(mapEvent.point); return features.length ? : null; } ``` ```tsx // ✅ Good - filter by layer const features = mapEvent.target.queryRenderedFeatures(mapEvent.point, { layers: ['my-layer-id'], }); // ❌ Slower - query all layers const features = mapEvent.target.queryRenderedFeatures(mapEvent.point); ``` -------------------------------- ### useAction Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/reatom/reatom3-core-guide.md A React hook to get a dispatcher function for a Reatom action. ```APIDOC ## useAction(action) ### Description Hook to get an action dispatcher. ### Method `useAction(action: Action): [(...params: Params) => void]` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const dispatchUpdateUser = useAction(updateUserAction); const handleClick = () => { dispatchUpdateUser(userId, { name: 'New Name' }); }; ``` ### Response #### Success Response (200) N/A (This is a hook) #### Response Example N/A ``` -------------------------------- ### Setup and Initialize a Toolbar Control (TypeScript) Source: https://github.com/konturio/disaster-ninja-fe/blob/main/src/core/toolbar/readme.md Demonstrates how to set up a new toolbar control, define its properties, handle lifecycle events like initialization and state changes, and finally initialize it within a feature module. This is the primary method for integrating custom controls into the toolbar system. ```typescript import { toolbar } from '~core/toolbar'; import { i18n } from '~core/localization'; // 1. Setup control export const myControl = toolbar.setupControl({ id: 'MY_CONTROL_ID', type: 'button', borrowMapInteractions: true, // Set to true if control needs exclusive map access typeSettings: { name: 'My Control', hint: i18n.t('my_control.hint'), icon: 'MyIcon24', preferredSize: 'large', }, }); // 2. Add control logic myControl.onInit(() => { // Initialize control }); myControl.onStateChange((ctx, state, prevState) => { if (state === 'active') { // Control activated } else if (prevState === 'active') { // Control deactivated } }); // 3. Initialize in your feature module export function initMyFeature() { myControl.init(); } ``` -------------------------------- ### Create String Atom API (TypeScript) Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/reatom/reatom2-core-guide.md Defines the TypeScript function signature for creating a string atom, including methods for getting the state and updating the value. ```typescript function createStringAtom( initial: T, id?: string, ): { getState(): T; // Current state change(value: T): Action; // Update value }; ``` -------------------------------- ### Async Atom Dependency on Direct Atom Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/reatom/reatom2-core-guide.md Shows an example where an async atom (`weatherByCityAtom`) directly depends on a regular atom (`cityAtom`) to fetch data based on the city name. ```typescript const cityAtom = createAtom('London', 'cityAtom'); const weatherByCityAtom = createAsyncAtom( cityAtom, async (city: string) => { const response = await fetch(`/weather/${city}`); return response.json(); }, 'weatherByCityAtom', ); ``` -------------------------------- ### Content Provider Infrastructure Setup Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/architecture/ADR-001-MapPopover-Migration-Architecture.md Sets up the core infrastructure for the content provider system. This includes defining the provider interface, creating a registry for coordination, and enhancing the map interaction hook to support the new registry. ```typescript // 1. Define provider interface interface IMapPopoverContentProvider { renderContent(mapEvent: MapMouseEvent, onClose: () => void): React.ReactNode | null; } // 2. Create registry to coordinate providers class MapPopoverContentRegistry implements IMapPopoverContentRegistry { // Simple registration and first-match-wins content rendering } // 3. Enhanced map interaction hook useMapPopoverInteraction({ map, popoverService, registry, // Registry support alongside existing renderContent }); ``` -------------------------------- ### Create and Initialize a Simple Button Control (TypeScript) Source: https://github.com/konturio/disaster-ninja-fe/blob/main/src/core/toolbar/readme.md Demonstrates the process of creating a simple 'Locate Me' button control using `setupControl`, adding behavior via `onStateChange`, and initializing it with `init()`. ```typescript export const locateControl = toolbar.setupControl({ id: 'LocateMe', type: 'button', typeSettings: { name: 'Locate Me', icon: 'Location24', preferredSize: 'medium', }, }); locateControl.onStateChange((ctx, state) => { if (state === 'active') { navigator.geolocation.getCurrentPosition(/* ... */); locateControl.setState('regular'); } }); locateControl.init(); ``` -------------------------------- ### Implement Reatom Actions Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/reatom/reatom3-core-guide.md Shows how to define actions in Reatom for handling side effects and state mutations. Examples include simple actions, actions with payloads, and asynchronous actions. ```typescript import { action } from '@reatom/core'; // Simple action const increment = action((ctx) => { counterAtom(ctx, ctx.get(counterAtom) + 1); }); // Action with payload const setValue = action((ctx, value: number) => { counterAtom(ctx, value); }); // Async action with side effects const fetchData = action(async (ctx, id: string) => { const data = await ctx.schedule(() => fetch(`/api/data/${id}`).then((r) => r.json())); dataAtom(ctx, data); }); ``` -------------------------------- ### Build Static Site with pnpm run build Source: https://github.com/konturio/disaster-ninja-fe/blob/main/README.md Builds a static copy of the site, optimized for deployment, and places the output in the `dist/` folder. ```bash pnpm run build ``` -------------------------------- ### Get Action Dispatcher with useAction Hook Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/reatom/reatom3-core-guide.md A React hook that provides a dispatcher function for a given Reatom action. This allows components to trigger actions defined elsewhere in the application. ```typescript function useAction(action: Action): [(...params: Params) => void]; // Returns: [dispatcher] ``` -------------------------------- ### Create Number Atom API (TypeScript) Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/reatom/reatom2-core-guide.md Defines the TypeScript function signature for creating a number atom, including methods for getting the state, setting a specific value, incrementing, and decrementing. ```typescript function createNumberAtom( initial: number, id?: string, ): { getState(): number; // Current state change(n: number): Action; // Set specific value increment(n: number = 1): Action; // Add n (default: 1) decrement(n: number = 1): Action; // Subtract n (default: 1) }; ``` -------------------------------- ### Serve Static Site with pnpm run serve Source: https://github.com/konturio/disaster-ninja-fe/blob/main/README.md Runs a static server for the built application, allowing you to preview the production build locally. ```bash pnpm run serve ``` -------------------------------- ### Create Boolean Atom API (TypeScript) Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/reatom/reatom2-core-guide.md Defines the TypeScript function signature for creating a boolean atom, including methods for getting the state, toggling, setting true/false, and custom changes. ```typescript function createBooleanAtom( initial: boolean, id?: string, ): { getState(): boolean; // Current state toggle(): Action; // Flip current state setTrue(): Action; // Set to true setFalse(): Action; // Set to false change(fn: (state: boolean) => boolean): Action; // Custom update }; ``` -------------------------------- ### Run Postinstall Script Source: https://github.com/konturio/disaster-ninja-fe/blob/main/README.md This script is automatically executed after `pnpm install` completes, typically used for setting up project dependencies or performing initial configurations. ```bash pnpm postinstall ``` -------------------------------- ### Schedule Asynchronous Side Effects Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/reatom/reatom2-core-guide.md Queues a side effect function to be executed asynchronously after all current atom updates are complete. This is the only place where the `dispatch` function is available, but `get()` cannot be used within this effect. ```typescript function track.schedule(effect: (dispatch: Dispatch, ctx: any) => void): void // Usage: schedule(async (dispatch) => { const data = await fetch('/api/data'); dispatch(create('setData', data)); }); ``` -------------------------------- ### React to Atom State Changes Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/reatom/reatom2-core-guide.md Triggers a callback function after the state of a specified atom has been updated. Similar to `onAction`, the `get()` method within the callback only reads the state without establishing a subscription. ```typescript function track.onChange(atomKey: string, callback: (newState: any, prevState: any) => void): void // Usage: onChange('counter', (newState, prevState) => { console.log(`Counter changed from ${prevState} to ${newState}`); }); ``` -------------------------------- ### Handle Specific Action Synchronously Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/reatom/reatom2-core-guide.md Executes a callback function synchronously when a specific action type is dispatched. The `get()` method used within this callback only reads the state without creating subscriptions. ```typescript function track.onAction(type: string, callback: (payload: any) => void): void // Usage: onAction('increment', (amount) => { state += amount; }); ``` -------------------------------- ### Patch Flow Optimization Example Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/investigations/R013-MountedLayers-Reatom-Patches-Flow-Analysis.md Illustrates the optimized patch flow before and after implementing performance improvements for mount and enable operations. It highlights the reduction in recalculations and patch flows, especially when combined with mutual exclusion. ```text Before Mount: Layer A mounts → ALL layers recalculate → Multiple patch flows After Mount: Layer A mounts → Only Layer A processes → Single patch flow Before Enable: Layer A enables → ALL layers recalculate → Multiple patch flows + Mutual exclusion → Multiple enabledLayersAtom.delete() → MORE cascades After Enable: Layer A enables → Only Layer A processes → Single patch flow + Mutual exclusion → Clean targeted operations → No cascades ``` -------------------------------- ### Example Plugin Implementation in TypeScript Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/investigations/toolbar-system-architecture.md Demonstrates a concrete implementation of a `MapToolPlugin`, including initialization, activation, deactivation, and cleanup logic for boundary selection. ```typescript export default class BoundarySelectorPlugin extends MapToolPlugin { readonly id = 'boundary-selector'; readonly name = 'Boundary Selector'; readonly version = '1.0.0'; readonly category = 'tools'; readonly icon = 'SelectArea24'; readonly preferredSize = 'large'; async init(): Promise { // Plugin initialization this.setupBoundaryRegistry(); } async onMapActivate(map: MapInstance): Promise { // Enable boundary selection on map this.enableBoundarySelection(map); } async onMapDeactivate(map: MapInstance): Promise { // Clean up map interactions this.disableBoundarySelection(map); } async destroy(): Promise { // Plugin cleanup this.cleanupBoundaryRegistry(); } } ``` -------------------------------- ### Converting Reatom v3 Atom to v2 Compatibility Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/reatom/reatom2-core-guide.md Provides the signature and usage example for `v3toV2`, a utility function that converts a Reatom v3 atom into a v2 compatible atom, allowing for gradual migration. ```typescript import { v3toV2 } from '~utils/atoms/v3tov2'; function v3toV2( v3atom: v3.Atom, v3Actions?: V3Actions, store?: Store, ): AtomSelfBinded>; // Usage: // Create v3 atom const v3Atom = atom(0, 'counter'); const incrementAction = action((ctx) => { v3Atom(ctx, ctx.get(v3Atom) + 1); }, 'increment'); // Convert to v2 const v2Atom = v3toV2(v3Atom, { increment: incrementAction, }); // Use v2 API v2Atom.increment.dispatch(); const state = v2Atom.getState(); ``` -------------------------------- ### Track Interface Definition Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/reatom/reatom2-core-guide.md Defines the structure and methods of the Track object, which is central to atom interaction, dependency management, and handling side effects. It outlines methods for getting state, subscribing to changes, dispatching actions, and managing asynchronous operations. ```typescript interface Track { // Read dependency state with subscription management // - Outside handlers: READS + SUBSCRIBES // - Inside onAction/onChange: Only READS // - In async (schedule): Throws "Outdated track call" get(depsKey: string): any; // Handle specific action with payload // - Runs synchronously when action dispatched // - get() inside only READS state onAction(type: string, cb: (payload: any) => void); // React to state changes of dependency atom // - Runs after state updates // - get() inside only READS state onChange(atomKey: string, cb: (newState: any, prevState: any) => void); // Queue side effect for execution after computations // - Only place to get dispatch function // - Runs asynchronously after all atom updates // - Cannot use get() inside (will throw) schedule(effect: (dispatch: Dispatch, ctx: any) => void); // Create action from dependency mapper create(actionKey: string, ...args: any[]): Action; // Run callback only on first reducer execution onInit(cb: () => void); // Read external atom state without subscription getUnlistedState(atom: Atom): any; // V3 Integration context // - Allows interaction with Reatom v3 atoms // - spy() reads v3 atom state without subscription v3ctx: { spy(atom: V3Atom): any; }; } ``` -------------------------------- ### Registry-Based Map Component Setup (TypeScript) Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/architecture/ADR-001-MapPopover-Migration-Architecture.md Sets up a map component that utilizes a registry for managing popover content providers. It hooks into map interactions and registers providers for consistent popup behavior across different map elements. Dependencies include useMapInstance, useMapPopoverService, useMemo, and MapPopoverContentRegistry. ```typescript function MapComponent() { const map = useMapInstance(); const popoverService = useMapPopoverService(); const registry = useMemo(() => new MapPopoverContentRegistry(), []); useMapPopoverInteraction({ map, popoverService, registry, // Registry coordinates all renderer-managed providers }); return
; } ``` -------------------------------- ### Map Instantiation and Options in map-libre-adapter/index.tsx Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/investigations/maplibre-migration.md This section focuses on the instantiation of a MapLibre map and its associated options within the `map-libre-adapter/index.tsx` file. It specifically calls for a review of new or changed options such as projection and WebGL2 support. Additionally, custom layer and source handling, including `addSource` and `addLayer` methods, may need updates to slots or ordering. ```typescript new maplibre.Map({...}) ``` -------------------------------- ### Create Atom with Track Object - TypeScript Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/reatom/reatom2-core-guide.md Demonstrates creating an atom using the `createAtom` function, passing dependencies and a reducer function that utilizes the track object for state management and side effects. The track object provides methods like `get` and `onAction`. ```typescript import { createAtom } from '~utils/atoms'; // Track object provides all atom interaction methods const myAtom = createAtom( { counterAtom, increment: (n: number) => n }, ({ get, onAction, schedule }, state = 0) => { // Track methods for state management return state; }, ); ``` -------------------------------- ### SQL: Creating Database Migrations with Rollbacks Source: https://github.com/konturio/disaster-ninja-fe/blob/main/AGENTS.md When creating new database migrations, ensure that both an 'up' (forward) migration and a 'down' (rollback) migration are provided. This allows for safe reversibility of changes. ```sql -- Example 'up' migration: CREATE TABLE users ( id SERIAL PRIMARY KEY, username VARCHAR(255) UNIQUE NOT NULL ); -- Example 'down' migration: DROP TABLE users; ``` -------------------------------- ### Get Dependency State with Subscription Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/reatom/reatom2-core-guide.md Retrieves the state of a dependency atom, managing subscriptions based on the context. It requires string literals for dependency keys and behaves differently depending on whether it's called from outside handlers, inside onAction/onChange, or within an asynchronous schedule. ```typescript function track.get(depsKey: string): any // Usage: const myAtom = createAtom({ counter: counterAtom }, ({ get }) => { const value = get('counter'); // Must use string literal return value * 2; }); ``` -------------------------------- ### V2/V3 Integration with Reatom (TypeScript) Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/reatom/reatom2-core-guide.md Shows how to integrate Reatom v2 and v3 atoms seamlessly. This example utilizes `v3ctx` to access v3 atom state within a v2 atom and `schedule` to react to changes in the v3 state, dispatching updates to the v2 atom accordingly. ```typescript const bridgeAtom = createAtom({}, ({ v3ctx, schedule }, state = null) => { // Access v3 atom state const v3State = v3ctx.spy(someV3Atom); // React to v3 changes schedule((dispatch) => { if (v3State !== state) { dispatch(create('updateState', v3State)); } }); return state; }); ``` -------------------------------- ### Initialize Husky for Git Hooks Source: https://github.com/konturio/disaster-ninja-fe/blob/main/README.md This command initializes Husky, a tool for managing Git hooks, in your project. It should be run after cloning the project for the first time to set up pre-commit hooks for code quality and consistency. ```bash npx husky-init ``` -------------------------------- ### Action Handling in Reatom v2 (TypeScript) Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/reatom/reatom2-core-guide.md Illustrates proper action definition and handling patterns within Reatom v2. This example defines actions with typed payloads and demonstrates how to handle these actions within the atom's reducer, including updating nested state immutably. ```typescript const userAtom = createAtom( { // Action definitions with typed payloads setUser: (user: User) => user, updateName: (name: string) => name, clearUser: () => null, }, ({ onAction }, state = null) => { // Typed action handling onAction('setUser', (user: User) => { state = user; }); onAction('updateName', (name: string) => { if (state) { state = { ...state, name }; } }); onAction('clearUser', () => { state = null; }); return state; }, ); ``` -------------------------------- ### API Documentation - Function Signatures Source: https://github.com/konturio/disaster-ninja-fe/blob/main/docs/technical-documentation-guide.md Demonstrates best practices for documenting function signatures, emphasizing expanded inline options over interface references for better clarity. ```APIDOC ## Function Signatures ### Good: Expanded Inline Options ```typescript function withCache(options?: { // CacheOptions staleTime?: number; // Time before data is considered stale (ms) cacheTime?: number; // Time before cache entry is removed (ms) size?: number; // Maximum number of cached entries swr?: boolean; // Enable stale-while-revalidate ignoreAbort?: boolean; // Keep cache on abort }): (action: AsyncAction) => AsyncAction & { cacheAtom: CacheAtom }; ``` ### Bad: Interface References ```typescript function withCache(options?: CacheOptions): ... // Forces developers to hunt for interface definition ``` ```