DocumentBuilderTemplate.vala 17 KB

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