DocumentBuilderTemplate.vala 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. using Astralis;
  2. using Astralis.Document;
  3. using Invercargill;
  4. using Invercargill.DataStructures;
  5. /**
  6. * DocumentBuilderTemplate Example
  7. *
  8. * Demonstrates loading an existing HTML template and modifying elements
  9. * using the DocumentModel classes. Shows how to:
  10. * - Load HTML from a string template
  11. * - Use XPath selectors to find specific elements
  12. * - Modify element content, attributes, and classes
  13. * - Add new elements dynamically
  14. * - Handle form POST to update the document state
  15. *
  16. * This example complements DocumentBuilder.vala by showing template-based
  17. * document manipulation rather than building from scratch.
  18. *
  19. * Usage: document-builder-template [port]
  20. */
  21. // Application state - a simple counter
  22. class AppState : Object {
  23. public int counter { get; set; }
  24. public string last_action { get; set; }
  25. public DateTime last_update { get; set; }
  26. public AppState() {
  27. counter = 0;
  28. last_action = "Initialized";
  29. last_update = new DateTime.now_local();
  30. }
  31. public void increment() {
  32. counter++;
  33. last_action = "Incremented";
  34. last_update = new DateTime.now_local();
  35. }
  36. public void decrement() {
  37. counter--;
  38. last_action = "Decremented";
  39. last_update = new DateTime.now_local();
  40. }
  41. public void reset() {
  42. counter = 0;
  43. last_action = "Reset";
  44. last_update = new DateTime.now_local();
  45. }
  46. }
  47. // Global app state
  48. AppState app_state;
  49. // HTML template loaded as a constant
  50. private const string HTML_TEMPLATE = """
  51. <!DOCTYPE html>
  52. <html lang="en">
  53. <head>
  54. <meta charset="UTF-8"/>
  55. <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  56. <title>Document Template Example</title>
  57. <style>
  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. </style>
  199. </head>
  200. <body>
  201. <div class="card" id="main-card">
  202. <h1 id="page-title">๐Ÿ“„ Template Document Builder</h1>
  203. <p id="description">This page demonstrates loading an HTML template and modifying it dynamically.</p>
  204. </div>
  205. <div class="card" id="counter-card">
  206. <div class="counter-display">
  207. <div class="counter-label">Current Value</div>
  208. <div class="counter-value" id="counter-value">0</div>
  209. </div>
  210. <div class="button-group" id="button-group">
  211. <form method="POST" action="/decrement" style="display: inline;">
  212. <button type="submit" class="btn-danger">โˆ’ Decrease</button>
  213. </form>
  214. <form method="POST" action="/reset" style="display: inline;">
  215. <button type="submit" class="btn-primary">โ†บ Reset</button>
  216. </form>
  217. <form method="POST" action="/increment" style="display: inline;">
  218. <button type="submit" class="btn-success">+ Increase</button>
  219. </form>
  220. </div>
  221. <div class="info-grid" id="info-grid">
  222. <div class="info-item" id="status-item">
  223. <div class="info-label">Status</div>
  224. <div class="info-value" id="status-value">Zero</div>
  225. </div>
  226. <div class="info-item" id="action-item">
  227. <div class="info-label">Last Action</div>
  228. <div class="info-value" id="action-value">Initialized</div>
  229. </div>
  230. <div class="info-item" id="time-item">
  231. <div class="info-label">Last Update</div>
  232. <div class="info-value" id="time-value">--:--:--</div>
  233. </div>
  234. <div class="info-item" id="count-item">
  235. <div class="info-label">Total Changes</div>
  236. <div class="info-value" id="changes-value">0</div>
  237. </div>
  238. </div>
  239. </div>
  240. <div class="card" id="code-card">
  241. <h2>How It Works</h2>
  242. <p>The server loads the HTML template and uses XPath selectors to find and modify elements:</p>
  243. <pre id="code-example">// Load the template
  244. var doc = new HtmlDocument.from_string(HTML_TEMPLATE);
  245. // Find and modify elements using XPath
  246. var counter_el = doc.select_one("//div[@id='counter-value']");
  247. counter_el.text_content = counter.to_string();
  248. // Add/remove classes based on state
  249. if (counter > 0) {
  250. counter_el.add_class("status-positive");
  251. }</pre>
  252. <h3>DocumentModel Features Used:</h3>
  253. <ul class="feature-list" id="feature-list">
  254. <li><code>HtmlDocument.from_string()</code> - Load HTML from template</li>
  255. <li><code>doc.select_one(xpath)</code> - Find single element by XPath</li>
  256. <li><code>doc.select(xpath)</code> - Find multiple elements</li>
  257. <li><code>element.text_content</code> - Get/set text content</li>
  258. <li><code>element.add_class()/remove_class()</code> - Modify CSS classes</li>
  259. <li><code>element.set_attribute()</code> - Set element attributes</li>
  260. <li><code>doc.to_result()</code> - Return as HttpResult</li>
  261. </ul>
  262. </div>
  263. <div class="card" id="footer-card">
  264. <p style="text-align: center; color: #666; margin: 0;">
  265. Built with <code>Astralis.Document</code> |
  266. <a href="/raw">View Raw HTML</a>
  267. </p>
  268. </div>
  269. </body>
  270. </html>
  271. """;
  272. // Main page endpoint - loads template and modifies it
  273. class HomePageEndpoint : Object, Endpoint {
  274. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  275. // Load the HTML template
  276. var doc = new HtmlDocument.from_string(HTML_TEMPLATE);
  277. // Update the counter value
  278. var counter_el = doc.select_one("//div[@id='counter-value']");
  279. if (counter_el != null) {
  280. counter_el.text_content = app_state.counter.to_string();
  281. // Update status class based on counter value
  282. counter_el.remove_class("status-positive");
  283. counter_el.remove_class("status-negative");
  284. counter_el.remove_class("status-zero");
  285. if (app_state.counter > 0) {
  286. counter_el.add_class("status-positive");
  287. } else if (app_state.counter < 0) {
  288. counter_el.add_class("status-negative");
  289. } else {
  290. counter_el.add_class("status-zero");
  291. }
  292. }
  293. // Update status text
  294. var status_el = doc.select_one("//div[@id='status-value']");
  295. if (status_el != null) {
  296. if (app_state.counter > 0) {
  297. status_el.text_content = "Positive";
  298. status_el.remove_class("status-negative");
  299. status_el.remove_class("status-zero");
  300. status_el.add_class("status-positive");
  301. } else if (app_state.counter < 0) {
  302. status_el.text_content = "Negative";
  303. status_el.remove_class("status-positive");
  304. status_el.remove_class("status-zero");
  305. status_el.add_class("status-negative");
  306. } else {
  307. status_el.text_content = "Zero";
  308. status_el.remove_class("status-positive");
  309. status_el.remove_class("status-negative");
  310. status_el.add_class("status-zero");
  311. }
  312. }
  313. // Update last action
  314. var action_el = doc.select_one("//div[@id='action-value']");
  315. if (action_el != null) {
  316. action_el.text_content = app_state.last_action;
  317. }
  318. // Update timestamp
  319. var time_el = doc.select_one("//div[@id='time-value']");
  320. if (time_el != null) {
  321. time_el.text_content = app_state.last_update.format("%H:%M:%S");
  322. }
  323. // Update changes count (use absolute value of counter as "total changes")
  324. var changes_el = doc.select_one("//div[@id='changes-value']");
  325. if (changes_el != null) {
  326. changes_el.text_content = app_state.counter.abs().to_string();
  327. }
  328. return doc.to_result();
  329. }
  330. }
  331. // Increment endpoint
  332. class IncrementEndpoint : Object, Endpoint {
  333. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  334. app_state.increment();
  335. return new HttpStringResult("", (StatusCode)302)
  336. .set_header("Location", "/");
  337. }
  338. }
  339. // Decrement endpoint
  340. class DecrementEndpoint : Object, Endpoint {
  341. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  342. app_state.decrement();
  343. return new HttpStringResult("", (StatusCode)302)
  344. .set_header("Location", "/");
  345. }
  346. }
  347. // Reset endpoint
  348. class ResetEndpoint : Object, Endpoint {
  349. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  350. app_state.reset();
  351. return new HttpStringResult("", (StatusCode)302)
  352. .set_header("Location", "/");
  353. }
  354. }
  355. // Raw HTML endpoint - shows the unmodified template
  356. class RawHtmlEndpoint : Object, Endpoint {
  357. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  358. // Load template without modifications
  359. var doc = new HtmlDocument.from_string(HTML_TEMPLATE);
  360. // Add a notice at the top
  361. var body = doc.body;
  362. if (body != null) {
  363. var notice = body.append_child_element("div");
  364. notice.set_attribute("style", "background: #fff3cd; color: #856404; padding: 15px; margin: 10px 0; border-radius: 8px; border: 1px solid #ffc107;");
  365. notice.append_text("โš ๏ธ This is the raw template without dynamic modifications. ");
  366. var link = notice.append_child_element("a");
  367. link.set_attribute("href", "/");
  368. link.append_text("โ† Back to dynamic version");
  369. }
  370. return doc.to_result();
  371. }
  372. }
  373. // API endpoint that demonstrates modifying multiple elements at once
  374. class BulkUpdateEndpoint : Object, Endpoint {
  375. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  376. var doc = new HtmlDocument.from_string(HTML_TEMPLATE);
  377. // Demonstrate selecting multiple elements
  378. var all_info_values = doc.select("//div[contains(@class, 'info-value')]");
  379. // Update all info values to show they were bulk-modified
  380. all_info_values.set_text_all("BULK UPDATED");
  381. all_info_values.add_class_all("status-positive");
  382. // Also demonstrate setting attributes on multiple elements
  383. var all_cards = doc.select("//div[contains(@class, 'card')]");
  384. all_cards.set_attribute_all("data-bulk-update", "true");
  385. // Update title to indicate bulk operation
  386. var title = doc.select_one("//h1[@id='page-title']");
  387. if (title != null) {
  388. title.text_content = "๐Ÿ“„ Bulk Update Demo";
  389. }
  390. // Add explanation
  391. var desc = doc.select_one("//p[@id='description']");
  392. if (desc != null) {
  393. desc.text_content = "This demonstrates HtmlNodeList operations: set_text_all(), add_class_all(), and set_attribute_all().";
  394. }
  395. return doc.to_result();
  396. }
  397. }
  398. void main(string[] args) {
  399. int port = args.length > 1 ? int.parse(args[1]) : 8080;
  400. // Initialize app state
  401. app_state = new AppState();
  402. print("โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—\n");
  403. print("โ•‘ Astralis DocumentBuilderTemplate Example โ•‘\n");
  404. print("โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ\n");
  405. print(@"โ•‘ Port: $port");
  406. for (int i = 0; i < 50 - port.to_string().length - 7; i++) print(" ");
  407. print(" โ•‘\n");
  408. print("โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ\n");
  409. print("โ•‘ Endpoints: โ•‘\n");
  410. print("โ•‘ / - Counter page (template with modifications) โ•‘\n");
  411. print("โ•‘ /increment - Increase counter (POST) โ•‘\n");
  412. print("โ•‘ /decrement - Decrease counter (POST) โ•‘\n");
  413. print("โ•‘ /reset - Reset counter (POST) โ•‘\n");
  414. print("โ•‘ /raw - Raw template (no modifications) โ•‘\n");
  415. print("โ•‘ /bulk - Bulk update demo โ•‘\n");
  416. print("โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•\n");
  417. print("\nPress Ctrl+C to stop the server\n\n");
  418. try {
  419. var application = new WebApplication(port);
  420. // Register compression components
  421. application.container.register_singleton<GzipCompressor>(() => new GzipCompressor());
  422. application.container.register_singleton<ZstdCompressor>(() => new ZstdCompressor());
  423. application.container.register_singleton<BrotliCompressor>(() => new BrotliCompressor());
  424. // Register endpoints
  425. application.add_endpoint<HomePageEndpoint>(new EndpointRoute("/"));
  426. application.add_endpoint<IncrementEndpoint>(new EndpointRoute("/increment"));
  427. application.add_endpoint<DecrementEndpoint>(new EndpointRoute("/decrement"));
  428. application.add_endpoint<ResetEndpoint>(new EndpointRoute("/reset"));
  429. application.add_endpoint<RawHtmlEndpoint>(new EndpointRoute("/raw"));
  430. application.add_endpoint<BulkUpdateEndpoint>(new EndpointRoute("/bulk"));
  431. application.run();
  432. } catch (Error e) {
  433. printerr("Error: %s\n", e.message);
  434. Process.exit(1);
  435. }
  436. }