DocumentBuilderTemplate.vala 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. using Astralis;
  2. using Invercargill;
  3. using Invercargill.DataStructures;
  4. using Inversion;
  5. /**
  6. * DocumentBuilderTemplate Example
  7. *
  8. * Demonstrates loading an existing HTML template and modifying elements
  9. * using the DocumentModel classes. Shows how to:
  10. * - Define a MarkupTemplate subclass with embedded HTML
  11. * - Register the template as a singleton with WebApplication
  12. * - Inject and use the template in endpoints
  13. * - Use XPath selectors to find specific elements
  14. * - Modify element content, attributes, and classes
  15. * - Handle form POST to update the document state
  16. *
  17. * This example complements DocumentBuilder.vala by showing template-based
  18. * document manipulation rather than building from scratch.
  19. *
  20. * Usage: document-builder-template [port]
  21. */
  22. // Application state - a simple counter
  23. class AppState : Object {
  24. public int counter { get; set; }
  25. public int total_changes { get; set; }
  26. public string last_action { get; set; }
  27. public DateTime last_update { get; set; }
  28. public AppState() {
  29. counter = 0;
  30. total_changes = 0;
  31. last_action = "Initialized";
  32. last_update = new DateTime.now_local();
  33. }
  34. public void increment() {
  35. counter++;
  36. total_changes++;
  37. last_action = "Incremented";
  38. last_update = new DateTime.now_local();
  39. }
  40. public void decrement() {
  41. counter--;
  42. total_changes++;
  43. last_action = "Decremented";
  44. last_update = new DateTime.now_local();
  45. }
  46. public void reset() {
  47. counter = 0;
  48. total_changes++;
  49. last_action = "Reset";
  50. last_update = new DateTime.now_local();
  51. }
  52. }
  53. /**
  54. * CSS content for the counter page.
  55. * Served as a FastResource for optimal performance with pre-compression.
  56. */
  57. private const string COUNTER_CSS = """
  58. body {
  59. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  60. max-width: 700px;
  61. margin: 0 auto;
  62. padding: 20px;
  63. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  64. min-height: 100vh;
  65. }
  66. .card {
  67. background: white;
  68. border-radius: 12px;
  69. padding: 25px;
  70. margin: 15px 0;
  71. box-shadow: 0 10px 40px rgba(0,0,0,0.2);
  72. }
  73. h1 {
  74. color: #333;
  75. margin-top: 0;
  76. }
  77. .counter-display {
  78. text-align: center;
  79. padding: 30px;
  80. background: #f8f9fa;
  81. border-radius: 8px;
  82. margin: 20px 0;
  83. }
  84. .counter-value {
  85. font-size: 72px;
  86. font-weight: bold;
  87. color: #667eea;
  88. line-height: 1;
  89. }
  90. .counter-label {
  91. color: #666;
  92. font-size: 14px;
  93. text-transform: uppercase;
  94. letter-spacing: 2px;
  95. }
  96. .button-group {
  97. display: flex;
  98. gap: 10px;
  99. justify-content: center;
  100. margin: 20px 0;
  101. }
  102. button {
  103. padding: 12px 24px;
  104. border: none;
  105. border-radius: 6px;
  106. cursor: pointer;
  107. font-size: 16px;
  108. font-weight: 600;
  109. transition: all 0.2s;
  110. }
  111. button:hover {
  112. transform: translateY(-2px);
  113. box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  114. }
  115. .btn-primary {
  116. background: #667eea;
  117. color: white;
  118. }
  119. .btn-primary:hover {
  120. background: #5a6fd6;
  121. }
  122. .btn-danger {
  123. background: #e74c3c;
  124. color: white;
  125. }
  126. .btn-danger:hover {
  127. background: #c0392b;
  128. }
  129. .btn-success {
  130. background: #2ecc71;
  131. color: white;
  132. }
  133. .btn-success:hover {
  134. background: #27ae60;
  135. }
  136. .info-grid {
  137. display: grid;
  138. grid-template-columns: repeat(2, 1fr);
  139. gap: 15px;
  140. margin: 20px 0;
  141. }
  142. .info-item {
  143. background: #f8f9fa;
  144. padding: 15px;
  145. border-radius: 6px;
  146. text-align: center;
  147. }
  148. .info-label {
  149. font-size: 12px;
  150. color: #666;
  151. text-transform: uppercase;
  152. letter-spacing: 1px;
  153. }
  154. .info-value {
  155. font-size: 18px;
  156. font-weight: 600;
  157. color: #333;
  158. margin-top: 5px;
  159. }
  160. .status-positive {
  161. color: #2ecc71 !important;
  162. }
  163. .status-negative {
  164. color: #e74c3c !important;
  165. }
  166. .status-zero {
  167. color: #666 !important;
  168. }
  169. code {
  170. background: #e8e8e8;
  171. padding: 2px 6px;
  172. border-radius: 4px;
  173. font-size: 14px;
  174. }
  175. pre {
  176. background: #263238;
  177. color: #aed581;
  178. padding: 15px;
  179. border-radius: 6px;
  180. overflow-x: auto;
  181. font-size: 13px;
  182. }
  183. .feature-list {
  184. margin: 0;
  185. padding-left: 20px;
  186. }
  187. .feature-list li {
  188. margin: 8px 0;
  189. color: #555;
  190. }
  191. a {
  192. color: #667eea;
  193. text-decoration: none;
  194. }
  195. a:hover {
  196. text-decoration: underline;
  197. }
  198. """;
  199. /**
  200. * CounterTemplate - A cached HTML template for the counter page.
  201. *
  202. * This class extends MarkupTemplate to provide a reusable, cached template.
  203. * The HTML is parsed once and cached; new_instance() returns efficient copies.
  204. * CSS is served separately via CounterStyles FastResource for optimal caching.
  205. */
  206. class CounterTemplate : MarkupTemplate {
  207. /// <summary>
  208. /// Returns the HTML markup for this template.
  209. /// CSS is linked externally via /styles.css for better caching.
  210. /// </summary>
  211. protected override string markup { get {
  212. return """<!DOCTYPE html>
  213. <html lang="en">
  214. <head>
  215. <meta charset="UTF-8"/>
  216. <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  217. <title>Document Template Example</title>
  218. <link rel="stylesheet" href="/styles.css"/>
  219. </head>
  220. <body>
  221. <div class="card" id="main-card">
  222. <h1 id="page-title">๐Ÿ“„ Template Document Builder</h1>
  223. <p id="description">This page demonstrates loading an HTML template and modifying it dynamically.</p>
  224. </div>
  225. <div class="card" id="counter-card">
  226. <div class="counter-display">
  227. <div class="counter-label">Current Value</div>
  228. <div class="counter-value" id="counter-value">0</div>
  229. </div>
  230. <div class="button-group" id="button-group">
  231. <form method="POST" action="/decrement" style="display: inline;">
  232. <button type="submit" class="btn-danger">โˆ’ Decrease</button>
  233. </form>
  234. <form method="POST" action="/reset" style="display: inline;">
  235. <button type="submit" class="btn-primary">โ†บ Reset</button>
  236. </form>
  237. <form method="POST" action="/increment" style="display: inline;">
  238. <button type="submit" class="btn-success">+ Increase</button>
  239. </form>
  240. </div>
  241. <div class="info-grid" id="info-grid">
  242. <div class="info-item" id="status-item">
  243. <div class="info-label">Status</div>
  244. <div class="info-value" id="status-value">Zero</div>
  245. </div>
  246. <div class="info-item" id="action-item">
  247. <div class="info-label">Last Action</div>
  248. <div class="info-value" id="action-value">Initialized</div>
  249. </div>
  250. <div class="info-item" id="time-item">
  251. <div class="info-label">Last Update</div>
  252. <div class="info-value" id="time-value">--:--:--</div>
  253. </div>
  254. <div class="info-item" id="count-item">
  255. <div class="info-label">Total Changes</div>
  256. <div class="info-value" id="changes-value">0</div>
  257. </div>
  258. </div>
  259. </div>
  260. <div class="card" id="code-card">
  261. <h2>How It Works</h2>
  262. <p>The server loads the HTML template and uses XPath selectors to find and modify elements:</p>
  263. <pre id="code-example">// Load the template
  264. var doc = new MarkupDocument.from_string(HTML_TEMPLATE);
  265. // Find and modify elements using XPath
  266. var counter_el = doc.select_one("//div[@id='counter-value']");
  267. counter_el.text_content = counter.to_string();
  268. // Add/remove classes based on state
  269. if (counter > 0) {
  270. counter_el.add_class("status-positive");
  271. }</pre>
  272. <h3>DocumentModel Features Used:</h3>
  273. <ul class="feature-list" id="feature-list">
  274. <li><code>MarkupDocument.from_string()</code> - Load HTML from template</li>
  275. <li><code>doc.select_one(xpath)</code> - Find single element by XPath</li>
  276. <li><code>doc.select(xpath)</code> - Find multiple elements</li>
  277. <li><code>element.text_content</code> - Get/set text content</li>
  278. <li><code>element.add_class()/remove_class()</code> - Modify CSS classes</li>
  279. <li><code>element.set_attribute()</code> - Set element attributes</li>
  280. <li><code>doc.to_result()</code> - Return as HttpResult</li>
  281. </ul>
  282. </div>
  283. <div class="card" id="footer-card">
  284. <p style="text-align: center; color: #666; margin: 0;">
  285. Built with <code>Astralis.Document</code> |
  286. <a href="/raw">View Raw HTML</a>
  287. </p>
  288. </div>
  289. </body>
  290. </html>
  291. """;
  292. }}
  293. }
  294. // Main page endpoint - uses field initializer injection
  295. class HomePageEndpoint : Object, Endpoint {
  296. // Field initializer injection - template is injected by the DI container
  297. private CounterTemplate template = Inversion.inject<CounterTemplate>();
  298. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  299. // Get a copy of the cached template
  300. var doc = template.new_instance();
  301. // Update the counter value
  302. var counter_el = doc.select_one("//div[@id='counter-value']");
  303. if (counter_el != null) {
  304. counter_el.text_content = app_state.counter.to_string();
  305. // Update status class based on counter value
  306. counter_el.remove_class("status-positive");
  307. counter_el.remove_class("status-negative");
  308. counter_el.remove_class("status-zero");
  309. if (app_state.counter > 0) {
  310. counter_el.add_class("status-positive");
  311. } else if (app_state.counter < 0) {
  312. counter_el.add_class("status-negative");
  313. } else {
  314. counter_el.add_class("status-zero");
  315. }
  316. }
  317. // Update status text
  318. var status_el = doc.select_one("//div[@id='status-value']");
  319. if (status_el != null) {
  320. if (app_state.counter > 0) {
  321. status_el.text_content = "Positive";
  322. status_el.remove_class("status-negative");
  323. status_el.remove_class("status-zero");
  324. status_el.add_class("status-positive");
  325. } else if (app_state.counter < 0) {
  326. status_el.text_content = "Negative";
  327. status_el.remove_class("status-positive");
  328. status_el.remove_class("status-zero");
  329. status_el.add_class("status-negative");
  330. } else {
  331. status_el.text_content = "Zero";
  332. status_el.remove_class("status-positive");
  333. status_el.remove_class("status-negative");
  334. status_el.add_class("status-zero");
  335. }
  336. }
  337. // Update last action
  338. var action_el = doc.select_one("//div[@id='action-value']");
  339. if (action_el != null) {
  340. action_el.text_content = app_state.last_action;
  341. }
  342. // Update timestamp
  343. var time_el = doc.select_one("//div[@id='time-value']");
  344. if (time_el != null) {
  345. time_el.text_content = app_state.last_update.format("%H:%M:%S");
  346. }
  347. // Update total changes count
  348. var changes_el = doc.select_one("//div[@id='changes-value']");
  349. if (changes_el != null) {
  350. changes_el.text_content = app_state.total_changes.to_string();
  351. }
  352. return doc.to_result();
  353. }
  354. }
  355. // Increment endpoint
  356. class IncrementEndpoint : Object, Endpoint {
  357. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  358. app_state.increment();
  359. return new HttpStringResult("", (StatusCode)302)
  360. .set_header("Location", "/");
  361. }
  362. }
  363. // Decrement endpoint
  364. class DecrementEndpoint : Object, Endpoint {
  365. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  366. app_state.decrement();
  367. return new HttpStringResult("", (StatusCode)302)
  368. .set_header("Location", "/");
  369. }
  370. }
  371. // Reset endpoint
  372. class ResetEndpoint : Object, Endpoint {
  373. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  374. app_state.reset();
  375. return new HttpStringResult("", (StatusCode)302)
  376. .set_header("Location", "/");
  377. }
  378. }
  379. // Raw HTML endpoint - shows the unmodified template
  380. class RawHtmlEndpoint : Object, Endpoint {
  381. // Field initializer injection
  382. private CounterTemplate template = Inversion.inject<CounterTemplate>();
  383. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  384. // Get a fresh copy of the template
  385. var doc = template.new_instance();
  386. // Add a notice at the top
  387. var body = doc.body;
  388. if (body != null) {
  389. var notice = body.append_child_element("div");
  390. notice.set_attribute("style", "background: #fff3cd; color: #856404; padding: 15px; margin: 10px 0; border-radius: 8px; border: 1px solid #ffc107;");
  391. notice.append_text("โš ๏ธ This is the raw template without dynamic modifications. ");
  392. var link = notice.append_child_element("a");
  393. link.set_attribute("href", "/");
  394. link.append_text("โ† Back to dynamic version");
  395. }
  396. return doc.to_result();
  397. }
  398. }
  399. // API endpoint that demonstrates modifying multiple elements at once
  400. class BulkUpdateEndpoint : Object, Endpoint {
  401. // Field initializer injection
  402. private CounterTemplate template = Inversion.inject<CounterTemplate>();
  403. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  404. var doc = template.new_instance();
  405. // Demonstrate selecting multiple elements and iterating
  406. var all_info_values = doc.select("//div[contains(@class, 'info-value')]");
  407. // Update all info values to show they were bulk-modified
  408. foreach (var node in all_info_values) {
  409. node.text_content = "BULK UPDATED";
  410. node.add_class("status-positive");
  411. }
  412. // Also demonstrate setting attributes on multiple elements
  413. var all_cards = doc.select("//div[contains(@class, 'card')]");
  414. foreach (var card in all_cards) {
  415. card.set_attribute("data-bulk-update", "true");
  416. }
  417. // Update title to indicate bulk operation
  418. var title = doc.select_one("//h1[@id='page-title']");
  419. if (title != null) {
  420. title.text_content = "๐Ÿ“„ Bulk Update Demo";
  421. }
  422. // Add explanation
  423. var desc = doc.select_one("//p[@id='description']");
  424. if (desc != null) {
  425. desc.text_content = "This demonstrates Enumerable<MarkupNode> iteration for bulk operations.";
  426. }
  427. return doc.to_result();
  428. }
  429. }
  430. // Global app state
  431. AppState app_state;
  432. void main(string[] args) {
  433. int port = args.length > 1 ? int.parse(args[1]) : 8080;
  434. // Initialize app state
  435. app_state = new AppState();
  436. print("โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—\n");
  437. print("โ•‘ Astralis DocumentBuilderTemplate Example โ•‘\n");
  438. print("โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ\n");
  439. print(@"โ•‘ Port: $port");
  440. for (int i = 0; i < 50 - port.to_string().length - 7; i++) print(" ");
  441. print(" โ•‘\n");
  442. print("โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ\n");
  443. print("โ•‘ Endpoints: โ•‘\n");
  444. print("โ•‘ / - Counter page (template with modifications) โ•‘\n");
  445. print("โ•‘ /styles.css - CSS stylesheet (FastResource) โ•‘\n");
  446. print("โ•‘ /increment - Increase counter (POST) โ•‘\n");
  447. print("โ•‘ /decrement - Decrease counter (POST) โ•‘\n");
  448. print("โ•‘ /reset - Reset counter (POST) โ•‘\n");
  449. print("โ•‘ /raw - Raw template (no modifications) โ•‘\n");
  450. print("โ•‘ /bulk - Bulk update demo โ•‘\n");
  451. print("โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•\n");
  452. print("\nPress Ctrl+C to stop the server\n\n");
  453. try {
  454. var application = new WebApplication(port);
  455. // Register compression components
  456. application.use_compression();
  457. // Register the template as a singleton - it will be parsed once and cached
  458. // Each request gets a copy via new_instance()
  459. // Endpoints use field initializer injection with Inversion.inject<T>()
  460. application.add_startup<CounterTemplate>();
  461. // Register CSS as a FastResource - pre-compressed, cached in memory
  462. // This demonstrates serving static content efficiently with ETag caching
  463. application.add_startup_endpoint<FastResource>(new EndpointRoute("/styles.css"), () => {
  464. try {
  465. return new FastResource.from_string(COUNTER_CSS)
  466. .with_content_type("text/css; charset=utf-8")
  467. .with_default_compressors();
  468. } catch (Error e) {
  469. error("Failed to create CSS resource: %s", e.message);
  470. }
  471. });
  472. // Register endpoints
  473. application.add_endpoint<HomePageEndpoint>(new EndpointRoute("/"));
  474. application.add_endpoint<IncrementEndpoint>(new EndpointRoute("/increment"));
  475. application.add_endpoint<DecrementEndpoint>(new EndpointRoute("/decrement"));
  476. application.add_endpoint<ResetEndpoint>(new EndpointRoute("/reset"));
  477. application.add_endpoint<RawHtmlEndpoint>(new EndpointRoute("/raw"));
  478. application.add_endpoint<BulkUpdateEndpoint>(new EndpointRoute("/bulk"));
  479. application.run();
  480. } catch (Error e) {
  481. printerr("Error: %s\n", e.message);
  482. Process.exit(1);
  483. }
  484. }