| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483 |
- using Astralis;
- using Astralis.Document;
- using Invercargill;
- using Invercargill.DataStructures;
- /**
- * DocumentBuilderTemplate Example
- *
- * Demonstrates loading an existing HTML template and modifying elements
- * using the DocumentModel classes. Shows how to:
- * - Load HTML from a string template
- * - Use XPath selectors to find specific elements
- * - Modify element content, attributes, and classes
- * - Add new elements dynamically
- * - Handle form POST to update the document state
- *
- * This example complements DocumentBuilder.vala by showing template-based
- * document manipulation rather than building from scratch.
- *
- * Usage: document-builder-template [port]
- */
- // Application state - a simple counter
- class AppState : Object {
- public int counter { get; set; }
- public string last_action { get; set; }
- public DateTime last_update { get; set; }
-
- public AppState() {
- counter = 0;
- last_action = "Initialized";
- last_update = new DateTime.now_local();
- }
-
- public void increment() {
- counter++;
- last_action = "Incremented";
- last_update = new DateTime.now_local();
- }
-
- public void decrement() {
- counter--;
- last_action = "Decremented";
- last_update = new DateTime.now_local();
- }
-
- public void reset() {
- counter = 0;
- last_action = "Reset";
- last_update = new DateTime.now_local();
- }
- }
- // Global app state
- AppState app_state;
- // HTML template loaded as a constant
- private const string HTML_TEMPLATE = """
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8"/>
- <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
- <title>Document Template Example</title>
- <style>
- 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;
- }
- </style>
- </head>
- <body>
- <div class="card" id="main-card">
- <h1 id="page-title">📄 Template Document Builder</h1>
- <p id="description">This page demonstrates loading an HTML template and modifying it dynamically.</p>
- </div>
-
- <div class="card" id="counter-card">
- <div class="counter-display">
- <div class="counter-label">Current Value</div>
- <div class="counter-value" id="counter-value">0</div>
- </div>
-
- <div class="button-group" id="button-group">
- <form method="POST" action="/decrement" style="display: inline;">
- <button type="submit" class="btn-danger">− Decrease</button>
- </form>
- <form method="POST" action="/reset" style="display: inline;">
- <button type="submit" class="btn-primary">↺ Reset</button>
- </form>
- <form method="POST" action="/increment" style="display: inline;">
- <button type="submit" class="btn-success">+ Increase</button>
- </form>
- </div>
-
- <div class="info-grid" id="info-grid">
- <div class="info-item" id="status-item">
- <div class="info-label">Status</div>
- <div class="info-value" id="status-value">Zero</div>
- </div>
- <div class="info-item" id="action-item">
- <div class="info-label">Last Action</div>
- <div class="info-value" id="action-value">Initialized</div>
- </div>
- <div class="info-item" id="time-item">
- <div class="info-label">Last Update</div>
- <div class="info-value" id="time-value">--:--:--</div>
- </div>
- <div class="info-item" id="count-item">
- <div class="info-label">Total Changes</div>
- <div class="info-value" id="changes-value">0</div>
- </div>
- </div>
- </div>
-
- <div class="card" id="code-card">
- <h2>How It Works</h2>
- <p>The server loads the HTML template and uses XPath selectors to find and modify elements:</p>
-
- <pre id="code-example">// Load the template
- var doc = new HtmlDocument.from_string(HTML_TEMPLATE);
- // Find and modify elements using XPath
- var counter_el = doc.select_one("//div[@id='counter-value']");
- counter_el.text_content = counter.to_string();
- // Add/remove classes based on state
- if (counter > 0) {
- counter_el.add_class("status-positive");
- }</pre>
-
- <h3>DocumentModel Features Used:</h3>
- <ul class="feature-list" id="feature-list">
- <li><code>HtmlDocument.from_string()</code> - Load HTML from template</li>
- <li><code>doc.select_one(xpath)</code> - Find single element by XPath</li>
- <li><code>doc.select(xpath)</code> - Find multiple elements</li>
- <li><code>element.text_content</code> - Get/set text content</li>
- <li><code>element.add_class()/remove_class()</code> - Modify CSS classes</li>
- <li><code>element.set_attribute()</code> - Set element attributes</li>
- <li><code>doc.to_result()</code> - Return as HttpResult</li>
- </ul>
- </div>
-
- <div class="card" id="footer-card">
- <p style="text-align: center; color: #666; margin: 0;">
- Built with <code>Astralis.Document</code> |
- <a href="/raw">View Raw HTML</a>
- </p>
- </div>
- </body>
- </html>
- """;
- // Main page endpoint - loads template and modifies it
- class HomePageEndpoint : Object, Endpoint {
- public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
- // Load the HTML template
- var doc = new HtmlDocument.from_string(HTML_TEMPLATE);
-
- // Update the counter value
- var counter_el = doc.select_one("//div[@id='counter-value']");
- if (counter_el != null) {
- counter_el.text_content = app_state.counter.to_string();
-
- // Update status class based on counter value
- counter_el.remove_class("status-positive");
- counter_el.remove_class("status-negative");
- counter_el.remove_class("status-zero");
-
- if (app_state.counter > 0) {
- counter_el.add_class("status-positive");
- } else if (app_state.counter < 0) {
- counter_el.add_class("status-negative");
- } else {
- counter_el.add_class("status-zero");
- }
- }
-
- // Update status text
- var status_el = doc.select_one("//div[@id='status-value']");
- if (status_el != null) {
- if (app_state.counter > 0) {
- status_el.text_content = "Positive";
- status_el.remove_class("status-negative");
- status_el.remove_class("status-zero");
- status_el.add_class("status-positive");
- } else if (app_state.counter < 0) {
- status_el.text_content = "Negative";
- status_el.remove_class("status-positive");
- status_el.remove_class("status-zero");
- status_el.add_class("status-negative");
- } else {
- status_el.text_content = "Zero";
- status_el.remove_class("status-positive");
- status_el.remove_class("status-negative");
- status_el.add_class("status-zero");
- }
- }
-
- // Update last action
- var action_el = doc.select_one("//div[@id='action-value']");
- if (action_el != null) {
- action_el.text_content = app_state.last_action;
- }
-
- // Update timestamp
- var time_el = doc.select_one("//div[@id='time-value']");
- if (time_el != null) {
- time_el.text_content = app_state.last_update.format("%H:%M:%S");
- }
-
- // Update changes count (use absolute value of counter as "total changes")
- var changes_el = doc.select_one("//div[@id='changes-value']");
- if (changes_el != null) {
- changes_el.text_content = app_state.counter.abs().to_string();
- }
-
- return doc.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 {
- // Load template without modifications
- var doc = new HtmlDocument.from_string(HTML_TEMPLATE);
-
- // Add a notice at the top
- var body = doc.body;
- if (body != null) {
- var notice = body.append_child_element("div");
- notice.set_attribute("style", "background: #fff3cd; color: #856404; padding: 15px; margin: 10px 0; border-radius: 8px; border: 1px solid #ffc107;");
- notice.append_text("⚠️ This is the raw template without dynamic modifications. ");
- var link = notice.append_child_element("a");
- link.set_attribute("href", "/");
- link.append_text("← Back to dynamic version");
- }
-
- return doc.to_result();
- }
- }
- // API endpoint that demonstrates modifying multiple elements at once
- class BulkUpdateEndpoint : Object, Endpoint {
- public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
- var doc = new HtmlDocument.from_string(HTML_TEMPLATE);
-
- // Demonstrate selecting multiple elements
- var all_info_values = doc.select("//div[contains(@class, 'info-value')]");
-
- // Update all info values to show they were bulk-modified
- all_info_values.set_text_all("BULK UPDATED");
- all_info_values.add_class_all("status-positive");
-
- // Also demonstrate setting attributes on multiple elements
- var all_cards = doc.select("//div[contains(@class, 'card')]");
- all_cards.set_attribute_all("data-bulk-update", "true");
-
- // Update title to indicate bulk operation
- var title = doc.select_one("//h1[@id='page-title']");
- if (title != null) {
- title.text_content = "📄 Bulk Update Demo";
- }
-
- // Add explanation
- var desc = doc.select_one("//p[@id='description']");
- if (desc != null) {
- desc.text_content = "This demonstrates HtmlNodeList operations: set_text_all(), add_class_all(), and set_attribute_all().";
- }
-
- return doc.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("║ Astralis DocumentBuilderTemplate Example ║\n");
- print("╠══════════════════════════════════════════════════════════════╣\n");
- print(@"║ Port: $port");
- for (int i = 0; i < 50 - port.to_string().length - 7; i++) print(" ");
- print(" ║\n");
- print("╠══════════════════════════════════════════════════════════════╣\n");
- print("║ Endpoints: ║\n");
- print("║ / - Counter page (template with modifications) ║\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("║ /bulk - Bulk update demo ║\n");
- print("╚══════════════════════════════════════════════════════════════╝\n");
- print("\nPress Ctrl+C to stop the server\n\n");
-
- try {
- var application = new WebApplication(port);
-
- // Register compression components
- application.container.register_singleton<GzipCompressor>(() => new GzipCompressor());
- application.container.register_singleton<ZstdCompressor>(() => new ZstdCompressor());
- application.container.register_singleton<BrotliCompressor>(() => new BrotliCompressor());
-
- // Register endpoints
- application.add_endpoint<HomePageEndpoint>(new EndpointRoute("/"));
- application.add_endpoint<IncrementEndpoint>(new EndpointRoute("/increment"));
- application.add_endpoint<DecrementEndpoint>(new EndpointRoute("/decrement"));
- application.add_endpoint<ResetEndpoint>(new EndpointRoute("/reset"));
- application.add_endpoint<RawHtmlEndpoint>(new EndpointRoute("/raw"));
- application.add_endpoint<BulkUpdateEndpoint>(new EndpointRoute("/bulk"));
-
- application.run();
-
- } catch (Error e) {
- printerr("Error: %s\n", e.message);
- Process.exit(1);
- }
- }
|