### ts2lang.json Configuration Example Source: https://github.com/outsystems/reactview/blob/master/ViewGenerator/readme.txt Configure input/output paths, namespace, and base component class for code generation. ```json { "tasks": [ { "input": Path where the declaration of the UI (typescript) files live, "output": Path where the generated C# class files will be written, "template": Leave empty, "parameters": { "namespace": Namespace to be used in the generated C# classes, "baseComponentClass": Name of the base class of the UI component. Use this if you need to inherit from a base component other than the default, "javascriptDistPath": Place where the typescript compiler will place the compiled js files } } ] } ``` -------------------------------- ### Async External Resource Handling Source: https://context7.com/outsystems/reactview/llms.txt Handle external resource requests asynchronously. This example demonstrates fetching data from the network and responding with the fetched data and content type. ```csharp // Async external resource example: view.ExternalResourceRequested += handler => { handler.BeginAsyncResponse(() => { var data = FetchDataFromNetwork(handler.Url); handler.RespondWith(data, "json"); }); }; ``` -------------------------------- ### Wire Edit Commands to Menu Items Source: https://context7.com/outsystems/reactview/llms.txt Connect standard text-editing clipboard operations to application menu items or keyboard shortcuts. This example shows how to wire these commands in an Avalonia application. ```csharp public MainWindow() { var view = new MainView(); CutCommand = ReactiveCommand.Create(() => view.EditCommands.Cut()); CopyCommand = ReactiveCommand.Create(() => view.EditCommands.Copy()); PasteCommand = ReactiveCommand.Create(() => view.EditCommands.Paste()); UndoCommand = ReactiveCommand.Create(() => view.EditCommands.Undo()); RedoCommand = ReactiveCommand.Create(() => view.EditCommands.Redo()); SelectAllCommand = ReactiveCommand.Create(() => view.EditCommands.SelectAll()); DeleteCommand = ReactiveCommand.Create(() => view.EditCommands.Delete()); } ``` -------------------------------- ### React Component TypeScript Definition Example Source: https://github.com/outsystems/reactview/blob/master/ViewGenerator/readme.txt Define component properties, behaviors, and export the default component. Ensure all types are exported for C# binding generation. ```typescript import * as React from "react"; import "third-party-lib"; /// import third-party lib modules import "./LocalModule"; /// import local js modules import "./Styles.scss"; /// import local sass export interface ISomeType { name: string; } /// This interface will contain all the component events that can be subscribed on the C# code. /// Use the Properties interface expose an API to get data from C#. export interface IExampleProperties { click(arg: ISomeType): void; getData(): Promise; } /// This interface will contain all the component methods that can be called on the C# code. export interface IExampleBehaviors { refresh(): void; } export default class Example extends React.Component implements IExampleBehaviors { refresh(): void { alert("hey"); } render() { return } } ``` -------------------------------- ### Execute .NET-to-JS Method Calls Source: https://context7.com/outsystems/reactview/llms.txt Serialize .NET calls to JavaScript component methods, queuing them if the WebView is not ready and flushing them once the view signals it is loaded. This example demonstrates direct usage of the ExecutionEngine for fire-and-forget, synchronous, and asynchronous method evaluations. ```csharp // Internally, generated Behavior methods call ExecutionEngine: // view.Refresh() → executionEngine.ExecuteMethod(module, "refresh()", args) // view.GetData() → executionEngine.EvaluateMethodAsync(module, "getData()") // Direct usage (inside generated code or advanced scenarios): var engine = frame.ExecutionEngine; // Fire-and-forget call into JS engine.ExecuteMethod(viewModule, "refresh()"); // Synchronous evaluation (blocks until JS returns) string result = engine.EvaluateMethod(viewModule, "getTitle()"); // Async evaluation (preferred — does not block UI thread) string title = await engine.EvaluateMethodAsync(viewModule, "getTitle()"); // Pending calls made before the view is ready are automatically queued and // replayed once NotifyViewLoaded is received from JS. ``` -------------------------------- ### Subscribe to Plugin Event in C# Source: https://context7.com/outsystems/reactview/llms.txt Subscribe to a plugin event from the .NET host. The WithPlugin() extension method retrieves the .NET plugin proxy, allowing interaction with plugin events and methods. This example shows subscribing to a NotifyViewLoaded event. ```csharp // C#: subscribe to a plugin event from the .NET host mainView.WithPlugin().NotifyViewLoaded += viewName => { Console.WriteLine($"{viewName} loaded"); }; // Factory registration: public override IViewModule[] InitializePlugins() { return new IViewModule[] { new ViewPlugin() }; } ``` -------------------------------- ### C# Implementation of IViewModule Interface Source: https://context7.com/outsystems/reactview/llms.txt Demonstrates how a generated C# class implements the IViewModule interface, exposing properties, behaviors, and events for interaction with a JavaScript component. Usage in application code is also shown. ```csharp public partial class MainView : ReactView { // Property setter calls into the JS component via generated code public string TitleMessage { get => MainModule.GetProperty("titleMessage"); set => MainModule.SetProperty("titleMessage", value); } // Calling a Behavior invokes the matching TypeScript method on the component public void Refresh() => MainModule.ExecuteMethod("refresh"); // Event subscription — JS calls .NET when the event fires public event Func GetTasksCount { add => MainModule.GetTasksCount += value; remove => MainModule.GetTasksCount -= value; } } // Usage in application code: var mainView = new MainView(); mainView.TitleMessage = "Task Manager"; mainView.GetTasksCount += () => myTaskList.Count; // .NET provides data to JS mainView.Ready += () => mainView.Refresh(); // call JS method from .NET ``` -------------------------------- ### Handle Custom Resource Requests in .NET Source: https://context7.com/outsystems/reactview/llms.txt Use the CustomResourceRequested event to intercept resource requests from React components. This allows serving dynamically generated binary data without writing to disk. The resourceKey is the first query parameter, and options are additional parameters. ```csharp // .NET: handle custom resource requests for a child view taskListView.CustomResourceRequested += OnTaskListViewCustomResourceRequested; private Resource OnTaskListViewCustomResourceRequested(string resourceKey, params string[] options) { // resourceKey is the first query param; options are additional params // e.g., resourceKey="User1", options=["size=normal"] var imageStream = ResourcesManager.GetResource( GetType().Assembly, new[] { "Users", resourceKey + ".png" } ); return new Resource(imageStream); // Resource wraps a Stream } ``` -------------------------------- ### Configure ReactViewFactory Settings Source: https://context7.com/outsystems/reactview/llms.txt Override ReactViewFactory to customize initial settings for a ReactView, including default stylesheets, plugins, and debug mode. ```csharp public class AppReactViewFactory : ReactViewFactory { // Provide a default global stylesheet (switches based on theme) public override ResourceUrl DefaultStyleSheet => new ResourceUrl(typeof(AppReactViewFactory).Assembly, "Generated", Settings.IsLightTheme ? "LightTheme.css" : "DarkTheme.css"); // Register plugins — called once per frame initialization public override IViewModule[] InitializePlugins() { return new IViewModule[] { new ViewPlugin() }; } // Show developer tools on startup (useful during development) public override bool ShowDeveloperTools => false; // Enable F12 dev tools and resource load error banners public override bool EnableDebugMode => #if DEBUG true; #else false; #endif // Preload view in background for faster first render public override bool EnableViewPreload => true; // Automatically dispose inner (child) views on unmount public override bool EnsureInnerViewsAreDisposed => true; } // Switching the stylesheet at runtime (e.g., theme change handler): public class MyView : ReactView { protected override ReactViewFactory Factory => new AppReactViewFactory(); public MyView() : base(new MyViewModule()) { Settings.ThemeChanged += () => RefreshDefaultStyleSheet(); // reloads stylesheet } } ``` -------------------------------- ### C# Dynamic Child View Binding with GetOrAddChildView Source: https://context7.com/outsystems/reactview/llms.txt Shows how to dynamically bind child view modules to named frames using GetOrAddChildView in C#. This enables runtime view swapping and composition. The JS side renders the dynamic frame. ```csharp // .NET adapter — toggle between two different child view types at runtime public partial class MainView { private uint counter; private string currentEditorViewName; public IViewModule ToggleEditorView() { if (counter == 0) { // Tell JS which frame name to render in the GetInnerViewName += () => currentEditorViewName; } var childViewName = "canvas-" + counter++; currentEditorViewName = childViewName; // Alternate between TaskListView and UsersView on each call IViewModule view = counter % 2 == 0 ? MainModule.GetOrAddChildView(childViewName) : MainModule.GetOrAddChildView(childViewName); RefreshInnerView(); // calls JS refreshInnerView() behavior to re-render return view; } } // JS side renders the dynamic frame: // ``` -------------------------------- ### Configure View Preload Cache Size Source: https://context7.com/outsystems/reactview/llms.txt Control the cache size for pre-rendered component HTML to reduce time-to-first-render. This global setting increases cache slots for applications with many view variations. The cache key is derived from the component source path and a hash of serialized property values. ```csharp // Global setting — increase cache slots for apps with many view variations ReactView.PreloadedCacheEntriesSize = 10; // default is 6 // Enable per-view in factory: public override bool EnableViewPreload => true; // The pre-rendering happens automatically in Loader.ts: // 1. On first load: render React component → serialize innerHTML → store in localStorage // 2. On subsequent loads: read innerHTML from localStorage → inject into DOM → React hydrates // without a full re-render, making the view appear instantly ``` -------------------------------- ### Define and Use ReactView in Avalonia Source: https://context7.com/outsystems/reactview/llms.txt Subclass ReactView to define a view and use it in Avalonia XAML code-behind. Handles lifecycle events, property setting, and command execution. ```csharp public class MainView : ReactView { // MainViewModule is auto-generated by ViewGenerator from MainView.tsx declarations public MainView() : base(new MainViewModule()) { } // Override Factory to customize settings protected override ReactViewFactory Factory => new AppReactViewFactory(); } // 2. Use the view in Avalonia XAML code-behind var view = new MainView(); view.TitleMessage = "My App"; // set a generated property view.Ready += () => { Console.WriteLine("View is ready"); view.ZoomPercentage = 1.25; // zoom to 125% }; view.UnhandledAsyncException += (sender, args) => { Console.WriteLine($"JS Error: {args.Exception.Message}"); args.Handled = true; }; view.ResourceLoadFailed += (url) => Console.WriteLine($"Resource failed: {url}"); // Add to Avalonia window Content = view; // Later: access edit commands view.EditCommands.Copy(); view.EditCommands.Paste(); // Open/close developer tools view.ShowDeveloperTools(); view.CloseDeveloperTools(); // Retrieve a plugin instance registered in the factory var plugin = view.WithPlugin(); plugin.DoSomething(); ``` -------------------------------- ### Consume Custom Resources in TypeScript Source: https://context7.com/outsystems/reactview/llms.txt Consume custom resources served via the ResourceLoader context in React components. The url() function within the context builds the custom resource URL with optional parameters. ```typescript // TypeScript: consume custom resources via ResourceLoader context import { ResourceLoader } from "ResourceLoader"; class TaskListItem extends React.Component<{ task: ITask }> { render(): JSX.Element { return (
{/* url() builds the custom resource URL with optional params */} {url => ( )}
{this.props.task.text}
); } } ``` -------------------------------- ### Define and Consume a Plugin in TypeScript Source: https://context7.com/outsystems/reactview/llms.txt Define a plugin class and retrieve its instance within a React component using PluginsContext. The getPluginInstance method is used to access the plugin registered by the factory. Ensure the plugin is correctly registered in the factory. ```typescript // TypeScript: define and consume a plugin import { PluginsContext } from "PluginsProvider"; import ViewPlugin from "../ViewPlugin/ViewPlugin"; export default class MainView extends React.Component { private readonly viewPlugin: ViewPlugin; constructor(props: IMainViewProperties, context: any) { super(props, context); // Retrieve the plugin instance registered by the factory this.viewPlugin = context.getPluginInstance(ViewPlugin); } public componentDidMount(): void { // Call a plugin method from the component this.viewPlugin.notifyViewLoaded("Main View"); } } ``` -------------------------------- ### Redirect Embedded Resources to Webpack Dev Server Source: https://context7.com/outsystems/reactview/llms.txt Redirect embedded resources to a webpack dev server during development. This handler intercepts requests and forwards them to the dev server, except for internal ReactViewResources. Ensure the devServerUri is configured. ```csharp // Redirect embedded resources to a webpack dev server during development private static void OnEmbeddedResourceRequested(ResourceHandler resourceHandler) { var resourceUrl = resourceHandler.Url; // Let the internal ReactViewResources load normally if (resourceUrl.Contains("ReactViewResources")) { return; } // Forward everything else to the running webpack-dev-server resourceUrl = new Uri(resourceUrl).PathAndQuery; resourceHandler.Redirect(new Uri(devServerUri, resourceUrl).ToString()); } // Enable hot-reload in DEBUG builds: public ExtendedReactView(IViewModule mainModule) : base(mainModule) { #if DEBUG if (devServerUri != null) { EmbeddedResourceRequested += OnEmbeddedResourceRequested; } #endif } ``` -------------------------------- ### TypeScript ViewFrame Component for Embedding Child Views Source: https://context7.com/outsystems/reactview/llms.txt Illustrates the usage of the ViewFrame React component in TypeScript for embedding child IViewModule components within a parent React tree. The 'name' property must match the .NET side's GetOrAddChildView frame name. ```typescript import { ViewFrame } from "ViewFrame"; import TaskListView from "../TaskListView/TaskListView"; // Declare the child view type in an interface export interface IChildViews { ListView: TaskListView; } export default class MainView extends React.Component implements IMainViewBehaviors { render(): JSX.Element { return (

{this.props.titleMessage}

{/* "ListView" name must match the C# GetOrAddChildView call */} name="ListView" className="list-container" />
); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.