using Astralis; using Invercargill; using Invercargill.DataStructures; using Inversion; using Spry; /** * CounterComponent Example * * Demonstrates using the Spry.Component class to build dynamic HTML pages * with outlets for component composition. Shows how to: * - Define a Component subclass with embedded HTML markup * - Use spry-outlet elements for dynamic content injection * - Use add_outlet_child/set_outlet_child methods to populate outlets * - Handle form POST to update state * * This example mirrors the Astralis DocumentBuilderTemplate example but * uses the Component class abstraction for better code organization. * * Usage: counter-component [port] */ // Application state - a simple counter class AppState : Object { public int counter { get; set; } public int total_changes { get; set; } public string last_action { get; set; } public DateTime last_update { get; set; } public AppState() { counter = 0; total_changes = 0; last_action = "Initialized"; last_update = new DateTime.now_local(); } public void increment() { counter++; total_changes++; last_action = "Incremented"; last_update = new DateTime.now_local(); } public void decrement() { counter--; total_changes++; last_action = "Decremented"; last_update = new DateTime.now_local(); } public void reset() { counter = 0; total_changes++; last_action = "Reset"; last_update = new DateTime.now_local(); } } /** * CSS content for the counter page. * Served as a FastResource for optimal performance with pre-compression. */ private const string COUNTER_CSS = """ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 700px; margin: 0 auto; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; } .card { background: white; border-radius: 12px; padding: 25px; margin: 15px 0; box-shadow: 0 10px 40px rgba(0,0,0,0.2); } h1 { color: #333; margin-top: 0; } .counter-display { text-align: center; padding: 30px; background: #f8f9fa; border-radius: 8px; margin: 20px 0; } .counter-value { font-size: 72px; font-weight: bold; color: #667eea; line-height: 1; } .counter-label { color: #666; font-size: 14px; text-transform: uppercase; letter-spacing: 2px; } .button-group { display: flex; gap: 10px; justify-content: center; margin: 20px 0; } button { padding: 12px 24px; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; font-weight: 600; transition: all 0.2s; } button:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.15); } .btn-primary { background: #667eea; color: white; } .btn-primary:hover { background: #5a6fd6; } .btn-danger { background: #e74c3c; color: white; } .btn-danger:hover { background: #c0392b; } .btn-success { background: #2ecc71; color: white; } .btn-success:hover { background: #27ae60; } .info-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; margin: 20px 0; } .info-item { background: #f8f9fa; padding: 15px; border-radius: 6px; text-align: center; } .info-label { font-size: 12px; color: #666; text-transform: uppercase; letter-spacing: 1px; } .info-value { font-size: 18px; font-weight: 600; color: #333; margin-top: 5px; } .status-positive { color: #2ecc71 !important; } .status-negative { color: #e74c3c !important; } .status-zero { color: #666 !important; } code { background: #e8e8e8; padding: 2px 6px; border-radius: 4px; font-size: 14px; } pre { background: #263238; color: #aed581; padding: 15px; border-radius: 6px; overflow-x: auto; font-size: 13px; } .feature-list { margin: 0; padding-left: 20px; } .feature-list li { margin: 8px 0; color: #555; } a { color: #667eea; text-decoration: none; } a:hover { text-decoration: underline; } """; /** * InfoItemComponent - A single info grid item. */ class InfoItemComponent : Component { public override string markup { get { return """
"""; }} public string label { set { this["label"].text_content = value; }} public string info_value { set { this["value"].text_content = value; }} public string? status_class { set { var el = this["value"]; if (value != null) { el.add_class(value); } }} } /** * InfoGridComponent - Container for info items. */ class InfoGridComponent : Component { public void set_items(Enumerable items) { set_outlet_children("items", items); } public override string markup { get { return """
"""; }} } /** * CounterDisplayComponent - Shows the counter value with buttons. */ class CounterDisplayComponent : Component { private InfoGridComponent _info_grid; public CounterDisplayComponent() { _info_grid = new InfoGridComponent(); } public void set_info_items(Enumerable items) { _info_grid.set_items(items); set_outlet_child("info-grid", _info_grid); } public override string markup { get { return """
Current Value
0
"""; }} public int counter { set { var counter_el = this["counter-value"]; counter_el.text_content = value.to_string(); // Update status class counter_el.remove_class("status-positive"); counter_el.remove_class("status-negative"); counter_el.remove_class("status-zero"); if (value > 0) { counter_el.add_class("status-positive"); } else if (value < 0) { counter_el.add_class("status-negative"); } else { counter_el.add_class("status-zero"); } }} } /** * CounterPageComponent - The main page component. */ class CounterPageComponent : Component { public void set_counter_section(Component component) { set_outlet_child("counter-section", component); } public override string markup { get { return """ Component Counter Example

Component Counter Example

This page demonstrates using Spry.Component with outlets for dynamic content.

How It Works

The page uses Component with spry-outlet elements for dynamic content:

component.set_outlet_child("content", child);

Component Features Used:

  • spry-outlet - Placeholder for child components
  • set_outlet_child() - Insert single component
  • to_result() - Render as HttpResult

Built with Spry.Component | View Raw HTML

"""; }} } /** * NoticeComponent - A simple notice for the raw view. */ class NoticeComponent : Component { public override string markup { get { return """

This is the raw template without dynamic modifications.

Back to dynamic version

"""; }} } // Global app state AppState app_state; // Home page endpoint - builds the component tree class HomePageEndpoint : Object, Endpoint { public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error { // Determine status string status_text; string status_class; if (app_state.counter > 0) { status_text = "Positive"; status_class = "status-positive"; } else if (app_state.counter < 0) { status_text = "Negative"; status_class = "status-negative"; } else { status_text = "Zero"; status_class = "status-zero"; } // Create info items var items = new Series(); var status_item = new InfoItemComponent(); status_item.label = "Status"; status_item.info_value = status_text; status_item.status_class = status_class; items.add(status_item); var action_item = new InfoItemComponent(); action_item.label = "Last Action"; action_item.info_value = app_state.last_action; items.add(action_item); var time_item = new InfoItemComponent(); time_item.label = "Last Update"; time_item.info_value = app_state.last_update.format("%H:%M:%S"); items.add(time_item); var changes_item = new InfoItemComponent(); changes_item.label = "Total Changes"; changes_item.info_value = app_state.total_changes.to_string(); items.add(changes_item); // Create the counter display component and set its info items var counter_display = new CounterDisplayComponent(); counter_display.counter = app_state.counter; counter_display.set_info_items(items); // Create the main page component and set the counter section var page = new CounterPageComponent(); page.set_counter_section(counter_display); // to_result() handles all outlet replacement return page.to_result(); } } // Increment endpoint class IncrementEndpoint : Object, Endpoint { public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error { app_state.increment(); return new HttpStringResult("", (StatusCode)302) .set_header("Location", "/"); } } // Decrement endpoint class DecrementEndpoint : Object, Endpoint { public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error { app_state.decrement(); return new HttpStringResult("", (StatusCode)302) .set_header("Location", "/"); } } // Reset endpoint class ResetEndpoint : Object, Endpoint { public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error { app_state.reset(); return new HttpStringResult("", (StatusCode)302) .set_header("Location", "/"); } } // Raw HTML endpoint - shows the unmodified template class RawHtmlEndpoint : Object, Endpoint { public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error { // Create a raw page without modifications var page = new CounterPageComponent(); // Add a notice component page.set_counter_section(new NoticeComponent()); return page.to_result(); } } void main(string[] args) { int port = args.length > 1 ? int.parse(args[1]) : 8080; // Initialize app state app_state = new AppState(); print("═══════════════════════════════════════════════════════════════\n"); print(" Spry CounterComponent Example\n"); print("═══════════════════════════════════════════════════════════════\n"); print(" Port: %d\n", port); print("═══════════════════════════════════════════════════════════════\n"); print(" Endpoints:\n"); print(" / - Counter page (Component-based)\n"); print(" /styles.css - CSS stylesheet (FastResource)\n"); print(" /increment - Increase counter (POST)\n"); print(" /decrement - Decrease counter (POST)\n"); print(" /reset - Reset counter (POST)\n"); print(" /raw - Raw template (no modifications)\n"); print("═══════════════════════════════════════════════════════════════\n"); print("\nPress Ctrl+C to stop the server\n\n"); try { var application = new WebApplication(port); // Register compression components application.use_compression(); // Register CSS as a FastResource application.add_startup_endpoint(new EndpointRoute("/styles.css"), () => { try { return new FastResource.from_string(COUNTER_CSS) .with_content_type("text/css; charset=utf-8") .with_default_compressors(); } catch (Error e) { error("Failed to create CSS resource: %s", e.message); } }); // Register endpoints application.add_endpoint(new EndpointRoute("/")); application.add_endpoint(new EndpointRoute("/increment")); application.add_endpoint(new EndpointRoute("/decrement")); application.add_endpoint(new EndpointRoute("/reset")); application.add_endpoint(new EndpointRoute("/raw")); application.run(); } catch (Error e) { printerr("Error: %s\n", e.message); Process.exit(1); } }