إنتقل إلى المحتوى الرئيسي

Standard Library

Standard library behaviors for Almadar applications


1. Overview

The Standard Library provides 34 reusable behaviors (standard traits) for the Orbital system. Each behavior is a self-contained OrbitalSchema that can function as a standalone .orb file.

Behavior Categories

CategoryBehaviors
Game CoreGameLoop, Physics2D, Input, Collision
Game EntityHealth, Score, Movement, Combat, Inventory
Game UIGameFlow, Dialogue, LevelProgress
UI InteractionList, Detail, Form, Modal, Drawer, Tabs, Wizard, MasterDetail, Filter
Data ManagementPagination, Selection, Sort, Filter, Search
AsyncLoading, Fetch, Submit, Retry, Poll
FeedbackNotification, Confirmation, Undo

2. Behavior Structure (OrbitalSchema)

Each behavior is a complete OrbitalSchema (aliased as BehaviorSchema):

import type { BehaviorSchema } from '@almadar/std';

export const LIST_BEHAVIOR: BehaviorSchema = {
name: 'std-list',
version: '1.0.0',
description: 'Entity list with selection and actions',
orbitals: [{
name: 'ListOrbital',
entity: {
name: 'ListState',
persistence: 'runtime',
fields: [
{ name: 'id', type: 'string', required: true },
{ name: 'selectedId', type: 'string', default: null },
{ name: 'items', type: 'array', default: [] },
],
},
traits: [{
name: 'List',
linkedEntity: 'ListState',
category: 'interaction',
stateMachine: {
states: [
{ name: 'Empty', isInitial: true },
{ name: 'Loaded' },
{ name: 'ItemSelected' },
],
events: [/* ... */],
transitions: [/* ... */],
},
}],
pages: [],
}],
};

Key Structure Points

  • name: Kebab-case with std- prefix (e.g., std-list, std-gameloop)
  • orbitals: Array containing one orbital with entity, traits, and pages
  • entity: Runtime state fields
  • traits: Array of trait definitions with linkedEntity
  • pages: Empty array (required by type, can be populated for pages)

3. Type-Safe Pattern Validation

PatternType Union

The render-ui effect enforces valid pattern types at compile-time:

import type { PatternConfig } from '@almadar/core';

export interface PatternConfig {
type: PatternType; // 203 valid patterns
[key: string]: unknown;
}

The PatternType union includes all registered patterns:

export type PatternType =
| 'entity-table'
| 'card'
| 'form'
| 'button'
// ... 199 more patterns
;

Usage in Behaviors

// ✅ Valid - 'entity-table' with typed props
['render-ui', 'main', { patternType: 'entity-table', columns: ['name', 'email'] }]

// ❌ TypeScript error - 'fake-pattern' is not a valid PatternType
['render-ui', 'main', { patternType: 'fake-pattern' }]

// ❌ TypeScript error - missing required 'columns' prop
['render-ui', 'main', { patternType: 'entity-table' }]

4. Usage

Import Behaviors

import { 
LIST_BEHAVIOR,
FORM_BEHAVIOR,
LOADING_BEHAVIOR,
STANDARD_BEHAVIORS,
} from '@almadar/std';

// Access all 34 behaviors
console.log(STANDARD_BEHAVIORS.length); // 34

Type Imports

import type { 
BehaviorSchema, // OrbitalSchema alias
OrbitalSchema, // Full schema type
Orbital, // Single orbital
Entity, // Entity definition
} from '@almadar/std';

Registry Functions

import { 
getBehavior,
isKnownBehavior,
getAllBehaviorNames,
getBehaviorLibraryStats,
} from '@almadar/std';

// Get behavior by name
const list = getBehavior('std-list');

// Check if valid
if (isKnownBehavior('std-form')) { /* ... */ }

// Get stats
const stats = getBehaviorLibraryStats();
// { totalBehaviors: 34, totalStates: X, totalEvents: X, ... }

Complete Behavior Reference (34 Behaviors)

Game Behaviors (12)

BehaviorDescriptionStatesEvents
GAME_LOOP_BEHAVIORMain game loop with update/renderPaused, RunningSTART, PAUSE, RESUME
PHYSICS_2D_BEHAVIOR2D physics simulationStatic, DynamicCOLLISION, APPLY_FORCE
INPUT_BEHAVIORInput handling (keyboard, mouse, touch)Idle, ActiveKEY_DOWN, KEY_UP, CLICK
COLLISION_BEHAVIORCollision detectionClear, CollidingENTER, EXIT
HEALTH_BEHAVIORHealth/damage systemHealthy, Damaged, DeadDAMAGE, HEAL, REVIVE
SCORE_BEHAVIORPoints/scoring systemIdle, UpdatingADD_POINTS, RESET
MOVEMENT_BEHAVIOREntity movementIdle, MovingMOVE, STOP, TELEPORT
COMBAT_BEHAVIORCombat mechanicsPeaceful, InCombat, CooldownATTACK, DEFEND, DODGE
INVENTORY_BEHAVIORItem inventoryEmpty, HasItemsADD_ITEM, REMOVE_ITEM
GAME_FLOW_BEHAVIORGame state managementMenu, Playing, Paused, GameOverSTART, PAUSE, RESUME, END
DIALOGUE_BEHAVIORNPC dialogue systemIdle, ActiveSTART_DIALOGUE, ADVANCE, END
LEVEL_PROGRESS_BEHAVIORLevel/quest trackingInProgress, CompletedCOMPLETE_OBJECTIVE, UNLOCK

UI Interaction Behaviors (9)

BehaviorDescriptionUse Case
LIST_BEHAVIOREntity list with selectionData tables, lists
DETAIL_BEHAVIORSingle entity displayItem detail, profile
FORM_BEHAVIORInput form handlingCreate/edit forms
MODAL_BEHAVIORModal dialogAlerts, confirmations
DRAWER_BEHAVIORSide panel drawerNavigation, filters
TABS_BEHAVIORTab interfaceContent sections
WIZARD_BEHAVIORMulti-step wizardOnboarding, checkout
MASTER_DETAIL_BEHAVIORMaster-detail layoutEmail, file explorer
FILTER_BEHAVIORData filteringSearch results, lists

Data Management Behaviors (5)

BehaviorDescriptionFeatures
PAGINATION_BEHAVIORPage through dataPage size, navigation
SELECTION_BEHAVIORMulti-select itemsSelect all, range select
SORT_BEHAVIORSort data columnsMulti-column sort
SEARCH_BEHAVIORFull-text searchDebounced, filters

Async Behaviors (5)

BehaviorDescriptionStates
LOADING_BEHAVIORLoading statesIdle, Loading, Success, Error
FETCH_BEHAVIORData fetchingFresh, Stale, Refreshing
SUBMIT_BEHAVIORForm submissionReady, Submitting, Submitted
RETRY_BEHAVIORRetry with backoffFailed, Retrying, Recovered
POLL_BEHAVIORPolling updatesPolling, Stopped

Feedback Behaviors (3)

BehaviorDescriptionFeatures
NOTIFICATION_BEHAVIORToast notificationsAuto-dismiss, actions
CONFIRMATION_BEHAVIORConfirm actionsOK/Cancel, custom buttons
UNDO_BEHAVIORUndo/redo stackTime-limited undo

API Reference

Behavior Registry

// Get single behavior
import { getBehavior } from '@almadar/std';

// Check if exists
import { isKnownBehavior } from '@almadar/std';

// List all
import { getAllBehaviorNames, getAllBehaviors } from '@almadar/std';

// Metadata
import { getAllBehaviorMetadata } from '@almadar/std';

// Find by use case
import { findBehaviorsForUseCase } from '@almadar/std';

// Event filtering
import { getBehaviorsForEvent } from '@almadar/std';

// State filtering
import { getBehaviorsWithState } from '@almadar/std';

// Validation
import { validateBehaviorReference } from '@almadar/std';

Standard Library Operators

// Math operations
import { MATH_OPERATORS } from '@almadar/std';

// String operations
import { STR_OPERATORS } from '@almadar/std';

// Array operations
import { ARRAY_OPERATORS } from '@almadar/std';

// Object operations
import { OBJECT_OPERATORS } from '@almadar/std';

// Time operations
import { TIME_OPERATORS } from '@almadar/std';

// Validation
import { VALIDATE_OPERATORS } from '@almadar/std';

// Formatting
import { FORMAT_OPERATORS } from '@almadar/std';

// Async utilities
import { ASYNC_OPERATORS } from '@almadar/std';

Registry Access

// All operators lookup
import {
STD_OPERATORS,
STD_OPERATORS_BY_MODULE,
getStdOperatorMeta,
isKnownStdOperator,
} from '@almadar/std';

// Module queries
import {
getModuleOperators,
getAllStdOperators,
getStdOperatorsByModule,
} from '@almadar/std';

// Classification
import {
getLambdaOperators,
getStdEffectOperators,
getStdPureOperators,
} from '@almadar/std';

// Validation
import {
validateStdOperatorArity,
isStdGuardOperator,
isStdEffectOperator,
} from '@almadar/std';

Documentation Generation

import {
generateOperatorDoc,
generateModuleDoc,
generateBehaviorDoc,
generateModulesDocs,
generateBehaviorsDocs,
generateStdLibDocs,
} from '@almadar/std';