DocumentBuilderTemplate.vala 18 KB

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