Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Astrolabe Apps Astrolabe Common
https://github.com/astrolabe-apps/astrolabe-common
Admin
missing description
Tokens:
54,972
Snippets:
338
Trust Score:
1.5
Update:
1 year ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Run Development Server (Bash) Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.TestTemplate/ClientApp/sites/formServer/README.md Commands to start the development server for the Next.js project using different package managers. Ensure you have Node.js installed. The server will be accessible at http://localhost:3000. ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` -------------------------------- ### Install Dependencies - Bash Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.TestTemplate/ClientApp/expoapp/README.md Installs all necessary project dependencies using npm. This is a prerequisite for starting the development server or running other project scripts. ```bash npm install ``` -------------------------------- ### ASP.NET Core API Example for ProductsController Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.SearchState/README.md Demonstrates a basic ASP.NET Core API controller for searching products. It utilizes dependency injection for ProductService and handles search queries via GET requests. This controller is designed to return search results using the `SearchResults<ProductDto>` type. ```csharp [ApiController] [Route("api/[controller]")] public class ProductsController : ControllerBase { private readonly ProductService _productService; public ProductsController(ProductService productService) { _productService = productService; } [HttpGet] public async Task<ActionResult<SearchResults<ProductDto>>> Search([FromQuery] SearchOptions options) { var results = await _productService.SearchProducts(options); return Ok(results); } } ``` -------------------------------- ### Start Development Server - Bash Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.TestTemplate/ClientApp/expoapp/README.md Starts the Expo development server, enabling the application to be run on emulators, simulators, or Expo Go. This command also provides options to open the app in various development environments. ```bash npx expo start ``` -------------------------------- ### Install @react-typed-forms/core using npm Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/core/README.md Installs the core package for React Typed Forms. This package provides the necessary hooks and components for creating type-safe forms with validation. ```bash npm install @react-typed-forms/core ``` -------------------------------- ### FormStateNode Initialization: Add Validation Setup (C#) Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/VALIDATION_IMPLEMENTATION_PLAN.md This snippet demonstrates how to integrate validation setup into the FormStateNode constructor. It should be called after InitializeDataNode() to ensure the dataNode is reactive. The pattern follows existing Initialize*() methods. ```csharp private void InitializeValidation(ControlDefinition originalDefinition) { if (originalDefinition is not DataControlDefinition dcd) return; // Create validation enabled control based on visibility var validationEnabledField = _stateControl.Field(x => x.ValidationEnabled); _editor.SetComputed(validationEnabledField, tracker => { var visible = tracker.TrackValue(_stateControl, x => x.Visible); return visible == true; }); // Setup validators... (similar to TypeScript setupValidation) } // Add after line 61 in FormStateNode constructor: // InitializeValidation(definition); ``` -------------------------------- ### Reset Project - Bash Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.TestTemplate/ClientApp/expoapp/README.md Resets the project to a fresh state by moving existing starter code to 'app-example' and creating a new, blank 'app' directory for development. This is useful for starting development from scratch. ```bash npm run reset-project ``` -------------------------------- ### Install Astrolabe.Web.Common via .NET CLI Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.Web.Common/README.md Command to add the Astrolabe.Web.Common NuGet package to a .NET project. This is the primary method for integrating the library's functionalities. ```shell dotnet add package Astrolabe.Web.Common ``` -------------------------------- ### C# Example Usage of Setting DontClearError in Validation Setup Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/VALIDATION_IMPLEMENTATION_PLAN.md Demonstrates how to use the `SetDontClearError` method within the validation setup process. This ensures that validation errors are managed solely by the validation system and not cleared inadvertently by control value changes. ```csharp // In InitializeValidation() method private void InitializeValidation(ControlDefinition originalDefinition) { if (originalDefinition is not DataControlDefinition dcd) return; // Get the control from dataNode var control = _dataNodeControl.Value?.Control; if (control != null) { // Set DontClearError flag so validation owns error management _editor.SetDontClearError(control, true); } // ... rest of validation setup } ``` -------------------------------- ### Manage Dependencies and Development with Rush Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/CLAUDE.md Commands for updating dependencies and running development scripts within the Rush monorepo. This includes installing/updating packages and starting development servers. ```bash # Install dependencies for all packages rush update # Development mode cd astrolabe-storybook && rushx dev # Next.js dev server cd astrolabe-storybook && rushx storybook # Storybook on port 6007 # Linting rush lint ``` -------------------------------- ### ControlEditor RunWithMutator Pattern in C# Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.Controls/CONTROL-PRINCIPLES.md Provides an internal C# implementation example of the RunWithMutator pattern used by ControlEditor. This pattern ensures modifications are managed within transactions, supporting change tracking and listener notifications, and only applies to controls implementing IControlMutation. ```csharp // Internal ControlEditor pattern private void RunWithMutator(IControl control, Func<IControlMutation, bool> action) { RunInTransaction(() => { if (control is not IControlMutation mutator) return; if (action(mutator)) { _modifiedControls.Add(control); } }); } public void SetValue(IControl control, object? value) { RunWithMutator(control, x => x.SetValueInternal(this, value)); } ``` -------------------------------- ### URL Helper Functions for Routing Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/BEST-PRACTICES.md Provides examples of creating URL helper functions for generating navigation links, such as for editing or viewing items, which simplifies route construction. ```typescript // Create URL helper functions export function itemEditUrl(id: string) { return `/edit?id=${id}`; } export function adminItemViewUrl(id: string) { return `/admin/view?id=${id}`; } ``` -------------------------------- ### Example Switch Renderer Implementation - TypeScript Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/schemas/FORM_EXTENSIONS_GUIDE.md Provides an example of a custom switch renderer component. It uses `createDataRenderer` to create a checkbox input that toggles a boolean value and conditionally displays a label. ```typescript const SwitchRenderer = createDataRenderer( (props, renderer) => { const { renderOptions, control } = props; const { displayLabel } = renderOptions as ExtendedSwitch & RenderOptions; return ( <label className="inline-flex items-center cursor-pointer"> <input type="checkbox" checked={control.value ?? false} onChange={() => control.setValue((x) => !x)} className="sr-only peer" disabled={control.disabled} /> <div className="..." /> {displayLabel && ( <span className="ms-3 subhead"> {control.value ?? false ? "On" : "Off"} </span> )} </label> ); }, { renderType: SwitchOptions.value, } ); ``` -------------------------------- ### Install Astrolabe.FileStorage.Azure NuGet Package Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.FileStorage.Azure/README.md Instructions for adding the Astrolabe.FileStorage.Azure NuGet package to your .NET project. This package enables Azure Blob Storage integration and automatically installs its dependency, Astrolabe.FileStorage. ```bash dotnet add package Astrolabe.FileStorage.Azure ``` -------------------------------- ### ControlEditor Transaction Batching: C# Example Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/VALIDATION_IMPLEMENTATION_PLAN.md Illustrates how ControlEditor.RunInTransaction() in C# batches changes to optimize performance. This method ensures that listeners are only triggered after all batched changes are complete. ```csharp public void RunInTransaction(Action action) { _inTransaction = true; try { action(); } finally { _inTransaction = false; // Listeners run AFTER transaction completes _runListenerList(); } } ``` -------------------------------- ### Basic Setup for BlobContainerFileStorage in C# Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.FileStorage.Azure/README.md Demonstrates how to create an instance of `BlobContainerFileStorage` for a specific entity type `FileEntity`. This setup involves configuring the Azure Blob Container client, defining functions for path generation and domain object creation from uploads, and specifying options like maximum file length. ```csharp using Azure.Storage.Blobs; using Astrolabe.FileStorage.Azure; // Create blob container client var containerClient = new BlobContainerClient(connectionString, containerName); // Create file storage instance var fileStorage = BlobContainerFileStorage.CreateContainerStorage<FileEntity>( containerClient: containerClient, newUploadPath: request => $"uploads/{Guid.NewGuid()}/{request.FileName}", newUpload: async uploadInfo => { // Create your domain object from the upload result return new FileEntity { Id = Guid.NewGuid(), FileName = uploadInfo.Request.FileName, BlobPath = uploadInfo.BlobPath, ContentType = uploadInfo.ContentType, Size = uploadInfo.ContentLength, UploadedAt = DateTime.UtcNow }; }, getPath: file => file.BlobPath, options: new FileStorageOptions { MaxLength = 5 * 1024 * 1024 } // 5MB limit ); ``` -------------------------------- ### Astrolabe Custom Searcher with Mapping in C# Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.SearchState/README.md Demonstrates creating a fully customized search function using `SearchHelper.CreateSearcher`. This example includes a projection to transform `Product` entities into `ProductDto` objects and specifies a `maxLength` for the query. It allows for fine-grained control over data retrieval and transformation. ```csharp // Create a custom searcher with transformation var searcherWithMapping = SearchHelper.CreateSearcher<Product, ProductDto>( query => query.Select(p => new ProductDto { Id = p.Id, Name = p.Name, DisplayPrice = "$" + p.Price.ToString("F2") }).ToListAsync(), query => query.CountAsync(), maxLength: 100 // Override default max page size ); ``` -------------------------------- ### Database Integration Example with FileService in C# Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.FileStorage.Azure/README.md Presents a `FileService` class that integrates with `IFileStorage<FileEntity>` and a `DbContext` to handle file saving operations. The `SaveFileAsync` method uploads a file and then saves the corresponding `FileEntity` to the database. ```csharp public class FileService { private readonly IFileStorage<FileEntity> _fileStorage; private readonly DbContext _context; public FileService(IFileStorage<FileEntity> fileStorage, DbContext context) { _fileStorage = fileStorage; _context = context; } public async Task<FileEntity> SaveFileAsync(UploadRequest request) { var fileEntity = await _fileStorage.UploadFile(request); _context.Files.Add(fileEntity); await _context.SaveChangesAsync(); return fileEntity; } } ``` -------------------------------- ### DTO Naming Conventions for REST APIs (C#) Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/BEST-PRACTICES.md Defines naming patterns for DTOs used in REST APIs: {Entity}Edit for POST/PUT, {Entity}Info for list GETs, and {Entity}View for detailed GETs. These conventions ensure clarity and consistency for different API operations. ```csharp public class GroupEdit { public string Name { get; set; } public Guid? ParentId { get; set; } public int OrderIndex { get; set; } } public class GroupInfo { public Guid Id { get; set; } public string Name { get; set; } public int OrderIndex { get; set; } } public class GroupView : GroupEdit { public Guid Id { get; set; } public DateTime CreatedAt { get; set; } public DateTime UpdatedAt { get; set; } public GroupInfo? Parent { get; set; } public List<GroupInfo> Children { get; set; } = new(); } ``` -------------------------------- ### Create Custom Password Hasher in C# Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.LocalUsers/README.md Implement the `IPasswordHasher` interface to create a custom password hashing mechanism. The example shows how to implement a `BcryptPasswordHasher` using the BCrypt.Net library for secure password storage. ```csharp public class BcryptPasswordHasher : IPasswordHasher { public string Hash(string password) { return BCrypt.Net.BCrypt.HashPassword(password); } } ``` -------------------------------- ### Customizing Filtering in C# with Astrolabe.SearchState Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.SearchState/README.md Demonstrates how to implement custom filterers for dynamic filtering with `Astrolabe.SearchState`. This example includes filters for a 'priceRange' and a general 'search' text filter, falling back to default property filtering. Requires `Astrolabe.SearchState` and LINQ. ```csharp // Create a custom filterer var filterer = SearchHelper.MakeFilterer<Product>(field => { // Handle price range filtering if (field == "priceRange") { return (query, values) => { if (values.Count != 2) return query; if (!decimal.TryParse(values[0], out var min)) return query; if (!decimal.TryParse(values[1], out var max)) return query; return query.Where(p => p.Price >= min && p.Price <= max); }; } // Handle text search if (field == "search") { return (query, values) => { var search = values.FirstOrDefault(); if (string.IsNullOrEmpty(search)) return query; return query.Where(p => p.Name.Contains(search)); }; } // Fall back to default property-based filtering return null; }); // Use the custom filterer var searcher = SearchHelper.CreateSearcher<Product, Product>( query => query.ToListAsync(), query => query.CountAsync(), null, // Use default sorter filterer ); ``` -------------------------------- ### Perform Batch Control Operations (C#) Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.Controls/CONTROL-PRINCIPLES.md Illustrates how to execute multiple control modifications as a single atomic transaction using ControlEditor.RunInTransaction. This ensures that all changes within the lambda are applied together or none are, providing data consistency. Requires a 'ControlEditor' instance and control objects. ```csharp var editor = new ControlEditor(); editor.RunInTransaction(() => { editor.SetValue(control1, value1); editor.SetValue(control2, value2); editor.SetDisabled(control3, true); // All changes committed together when transaction completes }); ``` -------------------------------- ### Structure for Validator Unit Tests in C# Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/VALIDATION_IMPLEMENTATION_PLAN.md Outlines the structure for unit tests of validators in C#, using xUnit. It includes examples for testing required fields, length constraints, date validation, JSONata expression evaluation, and scenarios with multiple validators. ```csharp public class ValidatorTests { [Fact] public void RequiredValidator_EmptyValue_ReturnsError() { // Test required validation } [Theory] [InlineData(5, 10, 7, true)] // Within range [InlineData(5, 10, 3, false)] // Below min [InlineData(5, 10, 12, false)] // Above max public void LengthValidator_VariousLengths_ValidatesCorrectly( int min, int max, int length, bool expectedValid) { // Test length validation } [Fact] public void DateValidator_NotBefore_ValidatesCorrectly() { // Test date validation } [Fact] public async Task JsonataValidator_Expression_EvaluatesAsync() { // Test jsonata validation } [Fact] public void MultipleValidators_FirstErrorWins() { // Test error priority } } ``` -------------------------------- ### Create HTML Display Renderer (TypeScript) Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/schemas/FORM_EXTENSIONS_GUIDE.md A factory function `createHtmlRenderer` that generates an HTML display renderer. It utilizes `createDisplayRenderer` and expects a `makeOnClick` callback for handling click events within the HTML content. The renderer displays HTML content from `props.data.html`. ```typescript export function createHtmlRenderer( makeOnClick: (actionId: string, data: any) => () => void ) { return createDisplayRenderer( (props) => { return ( <HtmlDisplayRenderer {...props} html={(props.data as HtmlDisplay).html ?? ""} makeOnClick={makeOnClick} /> ); }, { renderType: DisplayDataType.Html } ); } ``` -------------------------------- ### Create Custom Label Renderer in TypeScript Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/schemas/FORM_EXTENSIONS_GUIDE.md Provides a way to customize how field labels are displayed using `createLabelRenderer`. This example defines a simple label renderer that wraps the label text in a `span` with a custom class. ```typescript import { createLabelRenderer, LabelType } from "@react-typed-forms/schemas"; export const MyLabelRenderer = createLabelRenderer( (props) => { return <span className="custom-label">{props.label}</span>; }, { labelType: LabelType.Text, } ); ``` ```typescript const HtmlLabelRenderer = createLabelRenderer( (p) => <HtmlLabel label={p.label} />, { labelType: LabelType.Text } ); function HtmlLabel({ label }: { label: ReactNode }) { const labelText = useMemo(() => { if (typeof label === "string") { return parse(label); // Parse HTML string } return label; }, [label]); return labelText; } ``` -------------------------------- ### Build .NET Solution and Projects Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/CLAUDE.md Commands to build the entire .NET solution or specific projects within the Astrolabe Common repository. These commands utilize the standard .NET CLI. ```bash # Build entire solution dotnet build Astrolabe.Common.sln # Build specific project dotnet build Astrolabe.Common/Astrolabe.Common.csproj ``` -------------------------------- ### Set Up Local User Controller (C#) Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.LocalUsers/README.md Shows how to set up a REST API controller in C# by extending the `AbstractLocalUserController` base class. This controller handles incoming user management requests and delegates them to the underlying user service. It requires implementation of a method to extract the current user's ID from claims. ```csharp [ApiController] [Route("api/users")] public class UserController : AbstractLocalUserController<NewUser, int> { public UserController(ILocalUserService<NewUser, int> userService) : base(userService) { } protected override int GetUserId() { // Extract user ID from the current authenticated user's claims return int.Parse(User.FindFirst("userId")?.Value ?? "0"); } } ``` -------------------------------- ### Access Form Control Values and Structure (TypeScript) Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/schemas/FORM_EXTENSIONS_GUIDE.md Demonstrates how to get the current value of a form control, set a new value, access parent data nodes, and retrieve values from child fields within an object control. ```typescript const value = control.value; control.setValue("new value"); const parentNode = getRootDataNode(dataNode); const rootControl = parentNode.control; const fields = control.fields; const childValue = fields.someField.value; ``` -------------------------------- ### Create Custom Data Renderer - TypeScript Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/schemas/FORM_EXTENSIONS_GUIDE.md Implements a custom data renderer component using `createDataRenderer` from `@react-typed-forms/schemas`. This example shows a basic text input field that updates its value and conditionally displays it based on configuration options. ```typescript import { createDataRenderer } from "@react-typed-forms/schemas"; import { MyExtensionOptions } from "./formExtensions"; export const MyDataRenderer = createDataRenderer( (props, renderer) => { const { control, renderOptions, className, id } = props; const options = renderOptions as MyExtensionOptions & RenderOptions; return ( <div className={className}> <input type="text" value={control.value ?? ''} onChange={(e) => control.setValue(e.target.value)} disabled={control.disabled} /> {options.displayLabel && <span>{control.value}</span>} </div> ); }, { renderType: MyExtensionOptions.value, // Must match the value from Step 1 } ); ``` -------------------------------- ### Run License Report with Solution File (Bash) Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/license-check/README.md Executes the license-report.sh script with a C# solution file (.sln) as input. This initiates a scan of .NET project dependencies to generate a license report. No external dependencies are explicitly managed by this command snippet itself, but the script relies on .NET SDK. ```bash # Run with a solution file ./license-report.sh path/to/your-project.sln ``` -------------------------------- ### Create Custom Display Renderer (TypeScript) Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/schemas/FORM_EXTENSIONS_GUIDE.md Defines a custom display renderer using `createDisplayRenderer`. This example shows how to create a renderer for a specific data type (`MyDisplay`) and render its content within a `div` element. It imports necessary types from `@react-typed-forms/schemas`. ```typescript import { createDisplayRenderer, DisplayDataType, HtmlDisplay } from "@react-typed-forms/schemas"; export const MyDisplayRenderer = createDisplayRenderer( (props) => { const data = props.data as MyDisplayData; return <div className="display">{data.content}</div>; }, { renderType: DisplayDataType.MyDisplay, } ); ``` -------------------------------- ### Host SPAs by Domain Prefix with UseDomainSpa (C#) Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.Web.Common/README.md An extension method for `IApplicationBuilder` that enables hosting multiple SPAs within a single ASP.NET Core application. Routing is determined by domain prefixes, path segments, or a custom matching function. It requires the web host environment and the directory containing SPA files. ```csharp public static IApplicationBuilder UseDomainSpa( this IApplicationBuilder app, IWebHostEnvironment env, string siteDir, string? domainPrefix = null, bool fallback = false, DomainSpaOptions? options = null, Func<HttpRequest, bool>? match = null, PathString? pathString = null ) // Usage // Match requests to admin.example.com app.UseDomainSpa(env, "admin"); // Match requests to /dashboard app.UseDomainSpa( env, "dashboard", domainPrefix: null, pathString: "/dashboard" ); // Custom matching function app.UseDomainSpa( env, "special", match: req => req.Headers["X-Special"].Any() ); ``` -------------------------------- ### Common Patterns for Reading Control Values in C# Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.Controls/CONTROL-PRINCIPLES.md Presents common C# code patterns for safely reading control properties. It includes examples for accessing the current value, checking if a control is dirty, and retrieving the value of a specific field within a control. ```csharp // Always safe to read var currentValue = control.Value; var isModified = control.IsDirty; var fieldValue = control["fieldName"]?.Value; ``` -------------------------------- ### Data Loading Patterns with useEffect and useControlEffect (TypeScript) Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/BEST-PRACTICES.md Demonstrates how to use useEffect for initial data loading and useControlEffect for reactive loading based on state changes. Includes async functions for fetching data. Dependencies: React hooks, a client for API calls. ```typescript import { useEffect } from "react"; import { useControlEffect } from "@react-typed-forms/core"; // Use useEffect for initial loading useEffect(() => { loadForms(); }, []); // Use useControlEffect for reactive loading useControlEffect( () => itemId.value, (v) => { if (!v) return; loadFormData(v); }, true ); // Async loading functions async function loadForms() { formList.value = await formClient.listForms(undefined, undefined); } ``` -------------------------------- ### Create Custom Adornment Renderer in TypeScript Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/schemas/FORM_EXTENSIONS_GUIDE.md Implements a custom adornment renderer using `createAdornmentRenderer`. This allows for adding decorative or functional elements to form controls. It uses markup manipulation functions like `wrapMarkup` and `appendMarkupAt`. The example shows wrapping children with a span for displaying adornment text. ```typescript import { createAdornmentRenderer, wrapMarkup, appendMarkupAt, AdornmentPlacement, ControlAdornment } from "@react-typed-forms/schemas"; export const MyAdornmentRenderer = createAdornmentRenderer( (props, renderers) => { const options = props.adornment as MyAdornmentOptions & ControlAdornment; return { apply: wrapMarkup("children", (children) => ( <div className="relative"> {children} <span className="adornment">{options.adornmentText}</span> </div> )), priority: 0, // Lower numbers render first (outer layers) adornment: props.adornment, }; }, { adornmentType: ControlAdornmentType.MyAdornment, } ); ``` ```typescript const createHelpTextRenderer = (container: HTMLElement | null) => { return createAdornmentRenderer( (p, renderers) => { const label = (p.adornment as ExtendedHelpText).helpLabel; const helpText = (p.adornment as HelpTextAdornment).helpText; return { apply: appendMarkupAt( (p.adornment as HelpTextAdornment).placement ?? AdornmentPlacement.LabelEnd, <Popover.Root> <Popover.Trigger asChild> <button className="..."> <i className="fa fa-info-circle mr-2" /> {renderers.renderLabelText(label)} </button> </Popover.Trigger> <Popover.Portal container={container}> <Popover.Content className="..."> <Div className="..." html={helpText} /> </Popover.Content> </Popover.Portal> </Popover.Root> ), priority: 0, adornment: p.adornment, }; }, { adornmentType: ControlAdornmentType.HelpText, } ); }; ``` -------------------------------- ### Key Rush Monorepo Commands Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/CLAUDE.md A summary of essential Rush commands for managing the TypeScript monorepo, including building, testing, dependency management, and executing custom scripts. ```bash # Build all TypeScript packages rush build # Run tests across all packages with coverage rush test # Install/update dependencies for all packages rush update # Run package-specific scripts (e.g., rushx dev, rushx storybook) rushx <command> ``` -------------------------------- ### Create Custom Group Renderer in TypeScript Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/schemas/FORM_EXTENSIONS_GUIDE.md Defines a custom group renderer using `createGroupRenderer`. It controls the layout of child fields within a form. Key props include `definition`, `dataContext`, `renderChild`, `formNode`, `className`, and `style`. The example demonstrates rendering children within a `div` element. ```typescript import { createGroupRenderer, GroupRendererProps } from "@react-typed-forms/schemas"; export const MyGroupRenderer = createGroupRenderer( (props, renderers) => { const { className, style, definition, dataContext, renderChild, formNode } = props; return ( <div className={className} style={style}> {formNode.children.map((child, i) => renderChild(child))} </div> ); }, { renderType: MyGroupOptions.value, } ); ``` ```typescript const topLevelGroupRenderer = createGroupRenderer( (p, renderers) => ( <div className={rendererClass(className, DefaultRenderOptions.group?.standardClassName)}> <AllErrors definition={definition} dataNode={dataContext.parentNode} labelRenderer={renderers.renderLabelText} /> {formNode.children.map((c, i) => renderChild(c))} </div> ), { renderType: TopLevelGroupOption.value, } ); ``` -------------------------------- ### Basic C# Search Implementation with Astrolabe.SearchState Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.SearchState/README.md Demonstrates a basic search implementation using Astrolabe.SearchState for a Product model. It utilizes `SearchHelper.CreateSearcher` to build a search function that handles data retrieval and count for pagination. Requires `Astrolabe.SearchState` and Entity Framework Core (`ToListAsync`, `CountAsync`). ```csharp using Astrolabe.SearchState; // Define your model public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public ProductCategory Category { get; set; } } // Define an enum if needed public enum ProductCategory { Electronics, Clothing, Food } // Define a DTO if needed public class ProductDto { public int Id { get; set; } public string Name { get; set; } } // Define a DbContext if needed (example) public abstract class DbContext { public IQueryable<Product> Products { get; set; } public abstract Task<int> CountAsync(); public abstract Task<List<Product>> ToToListAsync(); } // Create a search function public class ProductService { private readonly DbContext _dbContext; public ProductService(DbContext dbContext) { _dbContext = dbContext; } public Task<SearchResults<Product>> SearchProducts(SearchOptions options, bool includeTotal = true) { // Create the searcher with default sorters and filterers var searcher = SearchHelper.CreateSearcher<Product, Product>( query => query.ToListAsync(), query => query.CountAsync() ); // Execute the search return searcher(_dbContext.Products, options, includeTotal); } } ``` -------------------------------- ### Bidirectional Value and Unidirectional InitialValue Flow in C# Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.Controls/CONTROL-PRINCIPLES.md Demonstrates in C# how 'Value' synchronizes bidirectionally between parent and child controls, while 'InitialValue' only flows from parent to child. The example shows setting initial values and then modifying values, illustrating the expected synchronization behavior and the immutability of parent's InitialValue from child changes. ```csharp var editor = new ControlEditor(); var parent = Control.CreateStructured(new { Name = "John", Age = 30 }); var nameControl = parent["Name"]; // InitialValue flows down editor.SetInitialValue(parent, new { Name = "Jane", Age = 25 }); // nameControl.InitialValue is now "Jane" // Value flows up (lazy reconstruction) editor.SetValue(nameControl, "Bob"); // parent.Value will reconstruct to { Name = "Bob", Age = 30 } when accessed // InitialValue changes on child don't flow up editor.SetInitialValue(nameControl, "Alice"); // parent.InitialValue is unchanged - still { Name = "Jane", Age = 25 } ``` -------------------------------- ### Query Parameter Handling with useQueryControl and useSyncParam Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/BEST-PRACTICES.md Demonstrates how to manage query parameters in the URL using `useQueryControl` and `useSyncParam`. This allows for synchronization between URL parameters and component state, including optional string parameters. ```typescript import { useQueryControl, useSyncParam, makeOptStringParam } from "@astroapps/client"; // In component const queryControl = useQueryControl(); const itemId = useSyncParam(queryControl, "id", makeOptStringParam()); const formType = useSyncParam( queryControl, "formType", makeOptStringParam(), createData.fields.formType // Optional: sync with control ); ``` -------------------------------- ### React Simple Form Example with @react-typed-forms/core Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/core/README.md A basic React component demonstrating form input and submission using @react-typed-forms/core. It includes field validation for 'lastName' and displays the submitted form data. ```tsx import { Finput, notEmpty, useControl } from "@react-typed-forms/core"; import React, { useState } from "react"; interface SimpleForm { firstName: string; lastName: string; } export default function SimpleExample() { const formState = useControl( { firstName: "", lastName: "" }, { fields: { lastName: { validator: notEmpty("Required field") } } } ); const fields = formState.fields; const [formData, setFormData] = useState<SimpleForm>(); return ( <form onSubmit={(e) => { e.preventDefault(); setFormData(formState.current.value); }} > <label>First Name</label> <Finput id="firstName" type="text" state={fields.firstName} /> <label>Last Name *</label> <Finput id="lastName" type="text" state={fields.lastName} /> <div> <button id="submit">Validate and toObject()</button> </div> {formData && ( <pre className="my-2">{JSON.stringify(formData, undefined, 2)}</pre> )} </form> ); } ``` -------------------------------- ### AbstractLocalUserService Implementation Methods (C#) Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.LocalUsers/README.md Lists the abstract methods that must be implemented when extending `AbstractLocalUserService` in C#. These methods cover essential user management operations such as sending verification emails, creating accounts, handling authentication, managing password resets, and updating user profiles. Each method signature outlines the required parameters and return types. ```csharp // Send verification email with code protected abstract Task SendVerificationEmail(TNewUser newUser, string verificationCode); // Create unverified account in your database protected abstract Task CreateUnverifiedAccount(TNewUser newUser, string hashedPassword, string verificationCode); // Count existing users with the same email protected abstract Task<int> CountExistingForEmail(string email); // Verify email with code and return JWT token protected abstract Task<string?> VerifyAccountCode(string code); // MFA verification for account protected abstract Task<string?> MfaVerifyAccountForUserId(MfaAuthenticateRequest mfaAuthenticateRequest); // Authenticate with username/password and return JWT token protected abstract Task<string?> AuthenticatedHashed(AuthenticateRequest authenticateRequest, string hashedPassword); // Send an MFA code via SMS/phone protected abstract Task<bool> SendCode(MfaCodeRequest mfaCodeRequest); protected abstract Task<bool> SendCode(TUserId userId, string? number=null); // Verify MFA code and return JWT token protected abstract Task<string?> VerifyMfaCode(string token, string code, string? number); protected abstract Task<bool> VerifyMfaCode(TUserId userId, string code, string? number); // Set reset code for password reset protected abstract Task SetResetCodeAndEmail(string email, string resetCode); // Change email for a user protected abstract Task<bool> EmailChangeForUserId(TUserId userId, string hashedPassword, string newEmail); // Change password with appropriate methods protected abstract Task<(bool, Func<string, Task<string>>?)> PasswordChangeForUserId(TUserId userId, string hashedPassword); protected abstract Task<Func<string, Task<string>>?> PasswordChangeForResetCode(string resetCode); // Change MFA phone number protected abstract Task<bool> ChangeMfaNumberForUserId(TUserId userId, string hashedPassword, string newNumber); ``` -------------------------------- ### Run License Report with Project File (Bash) Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/license-check/README.md Executes the license-report.sh script with a C# project file (.csproj) as input. This allows for a more granular scan of specific .NET project dependencies. The script may automatically detect associated Rush projects if configured. ```bash # Run with a specific project file ./license-report.sh path/to/your-project.csproj ``` -------------------------------- ### Render Product Table with DataGrid Source: https://context7.com/astrolabe-apps/astrolabe-common/llms.txt Demonstrates how to use the DataGrid component to render a table of products. It includes defining product data, configuring columns with sorting and formatting options using ColumnBuilder, and setting up event handlers for row clicks and selection. The DataGrid supports features like sorting, filtering, row selection, and pagination. ```typescript import { DataGrid, ColumnBuilder } from "@astroapps/datagrid"; interface Product { id: string; name: string; category: string; price: number; inStock: boolean; createdAt: Date; } function ProductTable() { const products: Product[] = [ { id: "1", name: "Widget", category: "Hardware", price: 29.99, inStock: true, createdAt: new Date("2024-01-15") }, { id: "2", name: "Gadget", category: "Electronics", price: 49.99, inStock: false, createdAt: new Date("2024-02-20") }, { id: "3", name: "Doohickey", category: "Tools", price: 19.99, inStock: true, createdAt: new Date("2024-03-10") } ]; const columns = new ColumnBuilder<Product>() .addString("name", "Product Name", { sortable: true }) .addString("category", "Category", { sortable: true }) .addNumber("price", "Price", { format: (value) => `$${value.toFixed(2)}`, sortable: true }) .addBoolean("inStock", "In Stock", { render: (value) => value ? "✓" : "✗" }) .addDate("createdAt", "Created", { sortable: true }) .build(); const handleRowClick = (product: Product) => { console.log("Selected product:", product); }; const handleSelection = (selectedIds: string[]) => { console.log("Selected IDs:", selectedIds); }; return ( <DataGrid data={products} columns={columns} onRowClick={handleRowClick} selectable={true} onSelectionChange={handleSelection} pagination={{ pageSize: 10 }} /> ); } ``` -------------------------------- ### JSON SchemaField Definition Example Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/astrolabe-controls/README.md This example shows how to define a SchemaField using plain JSON. It illustrates the basic structure including 'type', 'field', and 'displayName', as well as optional properties like 'required' and 'defaultValue'. This method is an alternative to using the `buildSchema` function. ```json [ { "type": "String", "field": "firstName", "displayName": "First Name" }, { "type": "String", "field": "lastName", "displayName": "Last Name", "required": true }, { "type": "Int", "field": "yearOfBirth", "displayName": "Year of birth", "defaultValue": 1980 } ] ``` -------------------------------- ### Build TypeScript Packages with Rush Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/CLAUDE.md Commands for building TypeScript packages within the Rush monorepo. These commands are executed from the 'Astrolabe.TestTemplate/ClientApp' directory and allow for building all packages or specific ones. ```bash # Navigate to rush workspace cd Astrolabe.TestTemplate/ClientApp # Build all TypeScript packages rush build # Build specific package rush build --to <package-name> ``` -------------------------------- ### React Form Schema and UI Rendering Example Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/astrolabe-controls/README.md This example demonstrates how to define a form schema using buildSchema and render a form UI with the createFormRenderer. It showcases defining string and integer fields, setting default values and required properties, and integrating with react-typed-forms/core for state management. ```tsx import { useControl } from "@react-typed-forms/core"; import React from "react"; import { buildSchema, createDefaultRenderers, createFormRenderer, defaultFormEditHooks, defaultTailwindTheme, defaultValueForFields, FormRenderer, intField, renderControl, stringField, useControlDefinitionForSchema, } from "@react-typed-forms/schemas"; /** Define your form */ interface SimpleForm { firstName: string; lastName: string; yearOfBirth: number; } /* Build your schema fields. Importantly giving them Display Names for showing in a UI */ const simpleSchema = buildSchema<SimpleForm>({ firstName: stringField("First Name"), lastName: stringField("Last Name", { required: true }), yearOfBirth: intField("Year of birth", { defaultValue: 1980 }), }); /* Create a form renderer based on a simple tailwind css based theme */ const renderer: FormRenderer = createFormRenderer( [], createDefaultRenderers(defaultTailwindTheme), ); export default function SimpleSchemasExample() { /* Create a `Control` for collecting the data, the schema fields can be used to get a default value */ const data = useControl<SimpleForm>(() => defaultValueForFields(simpleSchema), ); /* Generate a ControlDefinition automatically from the schema */ const controlDefinition = useControlDefinitionForSchema(simpleSchema); return ( <div className="container my-4 max-w-2xl"> {/* Render the ControlDefinition using `data` for the form state */} {renderControl(controlDefinition, data, { fields: simpleSchema, renderer, hooks: defaultFormEditHooks, })} <pre>{JSON.stringify(data.value, null, 2)}</pre> </div> ); } ``` -------------------------------- ### Run .NET Tests Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/CLAUDE.md Command to execute unit tests for the .NET projects within the Astrolabe Common repository. The tests are typically written using xunit. ```bash # Run .NET tests (uses xunit) dotnet test ``` -------------------------------- ### Rebuild and Test TypeScript Packages with Rush Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/CLAUDE.md Commands for performing a clean rebuild of all TypeScript packages and running tests across the monorepo using Rush. Test execution includes coverage reporting. ```bash # Rebuild all packages (clean build) rush rebuild # Run tests across all packages rush test ``` -------------------------------- ### Controller for Entity Management (C#) Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/AbstractWorkflowExecutor-Guide.md Demonstrates a C# controller using ASP.NET Core for managing entities. It includes methods for creating, updating, and performing workflow actions on entities, along with retrieving user actions. It depends on a `MyEntityService` and utilizes `ControllerBase` and `ApiController` attributes. ```csharp using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Threading.Tasks; [ApiController] [Route("api/[controller]")] public class MyEntitiesController : ControllerBase { private readonly MyEntityService _entityService; public MyEntitiesController(MyEntityService entityService) { _entityService = entityService; } [HttpPost] public async Task<MyEntityView> CreateEntity(MyEntityEdit entityEdit) { var id = await _entityService.CreateEntity(entityEdit, User); return await GetEntity(id); } [HttpPut("{id}")] public async Task<MyEntityView> UpdateEntity(Guid id, MyEntityEdit entityEdit) { await _entityService.UpdateEntity(id, entityEdit, User); return await GetEntity(id); } // Generic workflow action endpoint [HttpPost("{id}/actions/{action}")] public async Task PerformWorkflowAction(Guid id, WorkflowAction action) { await _entityService.PerformWorkflowAction(id, action, User); } [HttpGet("{id}/actions")] public async Task<IEnumerable<WorkflowAction>> GetUserActions(Guid id) { return await _entityService.GetUserActions(id, User); } } ``` -------------------------------- ### Account Creation API Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/Astrolabe.LocalUsers/README.md Endpoint for creating a new user account. ```APIDOC ## POST /create ### Description Create a new account. ### Method POST ### Endpoint /create ### Parameters #### Request Body - **username** (string) - Required - The username for the new account. - **email** (string) - Required - The email address for the new account. - **password** (string) - Required - The password for the new account. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securePassword123" } ``` ### Response #### Success Response (200) - **userId** (string) - The unique identifier for the newly created user. #### Response Example ```json { "userId": "user-12345" } ``` ``` -------------------------------- ### Core Schema and Control Management Imports (TypeScript) Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/schemas/FORM_EXTENSIONS_GUIDE.md Lists the essential imports for schema functions, control management, and field type definitions from the '@react-typed-forms' libraries. ```typescript // Core schema functions import { createDataRenderer, createGroupRenderer, createAdornmentRenderer, createLabelRenderer, createDisplayRenderer, createFormRenderer, buildSchema, CustomRenderOptions, ControlDefinitionExtension, } from "@react-typed-forms/schemas"; // Control management import { Control, useControlEffect } from "@react-typed-forms/core"; // Field types import { boolField, stringField, intField, stringOptionsField, } from "@react-typed-forms/schemas"; ``` -------------------------------- ### Frontend Development with AppForms Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/BEST-PRACTICES.md Provides guidelines on using the AppForms library for frontend form development, including recommended implementation steps and form class structures. ```APIDOC ## Frontend Development with AppForms ### Description This section recommends the use of AppForms for implementing editable forms in the frontend. It outlines the preferred approach, including form class structure, registration, and scenarios where AppForms is most beneficial. ### When to Use AppForms - ✅ Pages with editable form fields - ✅ Create/Edit dialogs and pages - ✅ Settings and configuration pages - ✅ User input forms - ✅ Dashboard pages ### Form Class Structure **Preferred Approach**: Define a form class that includes a property for the edit DTO and any additional data needed for the form. ```csharp public class GroupEditorForm { public GroupEdit Group { get; set; } = new(); public List<UserInfo> AvailableUsers { get; set; } = new(); public List<UserInfo> AssignedUsers { get; set; } = new(); } ``` **Simple Approach**: Use the edit DTO directly if no additional form data is required. ### Form Registration Register the form definition in `Forms/AppForms.cs`. ```csharp // In AppForms.cs Form<GroupEditorForm>("GroupEditorForm", "Group Editor", "Admin") ``` ### When AppForms May Not Be Needed - Simple read-only display pages - Basic navigation pages - Pages with only buttons/links (no form inputs) ``` -------------------------------- ### MSAL Authentication Layout Integration Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/BEST-PRACTICES.md Shows how to integrate MSAL authentication by wrapping the root layout with `wrapWithMsalContext` and configuring `PublicClientApplication`. It also demonstrates using `useMsalSecurityService` for obtaining user data. ```typescript // Wrap root layout with MSAL context export default wrapWithMsalContext( RootLayout, new PublicClientApplication(msalConfig) ); // Use security services const security = useMsalSecurityService({ getUserData: async (fetch) => { const roles: string[] = []; return { roles }; } }); ``` -------------------------------- ### Controller - Throwing Exceptions for Errors (C#) Source: https://github.com/astrolabe-apps/astrolabe-common/blob/main/BEST-PRACTICES.md Demonstrates the recommended pattern for controller methods to throw exceptions when errors occur. This includes handling not found scenarios and returning business logic results. FluentValidation exceptions are automatically handled. ```csharp using Microsoft.AspNetCore.Mvc; using YourApp.Exceptions; // ... other usings [ApiController] [Route("api/[controller]")] public class GroupsController : ControllerBase { private readonly IGroupService _groupService; public GroupsController(IGroupService groupService) { _groupService = groupService; } [HttpGet("{id}")] public async Task<GroupView> GetGroup(Guid id) { var group = await _groupService.GetGroupById(id); if (group == null) { throw new NotFoundException($"Group with ID {id} not found."); } return group; } [HttpPost] public async Task<GroupView> CreateGroup(GroupEdit groupEdit) { // Validation exceptions are thrown by FluentValidation automatically return await _groupService.CreateGroup(groupEdit); } [HttpDelete("{id}")] public async Task DeleteGroup(Guid id) { // Service throws NotFoundException if not found // Service throws InvalidOperationException for business rule violations await _groupService.DeleteGroup(id); } } ```