HtmxExample.vala 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. using Astralis;
  2. using Invercargill;
  3. using Invercargill.DataStructures;
  4. using Inversion;
  5. /**
  6. * HTMX Example
  7. *
  8. * Demonstrates using htmx (from CDN) with Astralis for dynamic content updates
  9. * without full page reloads. Shows various htmx attributes and swap strategies:
  10. * - hx-get: Make GET requests to swap content
  11. * - hx-post: Make POST requests for actions
  12. * - hx-swap: Control how content is inserted (innerHTML, outerHTML, beforeend, etc.)
  13. * - hx-trigger: Control when requests are triggered (click, load, every, etc.)
  14. * - hx-target: Specify where to swap the response
  15. * - hx-indicator: Show loading states
  16. *
  17. * htmx CDN: https://cdn.jsdelivr.net/npm/htmx.org@2.0.8/dist/htmx.min.js
  18. *
  19. * Usage: htmx-example [port]
  20. */
  21. // Application state for the click counter
  22. class ClickState : Object {
  23. public int click_count { get; set; }
  24. public DateTime last_click { get; set; }
  25. public string click_history { get; set; }
  26. public ClickState() {
  27. click_count = 0;
  28. last_click = new DateTime.now_local();
  29. click_history = "";
  30. }
  31. public void record_click(string button_name) {
  32. click_count++;
  33. last_click = new DateTime.now_local();
  34. var timestamp = last_click.format("%H:%M:%S");
  35. click_history = @"[$timestamp] $button_name\n" + click_history;
  36. // Keep only last 10 entries
  37. var lines = click_history.split("\n");
  38. if (lines.length > 10) {
  39. click_history = string.joinv("\n", lines[0:10]);
  40. }
  41. }
  42. }
  43. // Task list item
  44. class TaskItem : Object {
  45. public int id { get; set; }
  46. public string text { get; set; }
  47. public bool completed { get; set; }
  48. public TaskItem(int id, string text) {
  49. this.id = id;
  50. this.text = text;
  51. this.completed = false;
  52. }
  53. }
  54. // Task manager state
  55. class TaskManager : Object {
  56. private int next_id = 1;
  57. public List<TaskItem> tasks;
  58. public TaskManager() {
  59. tasks = new List<TaskItem>();
  60. // Add some initial tasks
  61. add_task("Learn htmx basics");
  62. add_task("Build dynamic web apps");
  63. add_task("Enjoy simple hypermedia");
  64. }
  65. public TaskItem add_task(string text) {
  66. var task = new TaskItem(next_id++, text);
  67. tasks.append(task);
  68. return task;
  69. }
  70. public bool toggle_task(int id) {
  71. foreach (var task in tasks) {
  72. if (task.id == id) {
  73. task.completed = !task.completed;
  74. return true;
  75. }
  76. }
  77. return false;
  78. }
  79. public bool delete_task(int id) {
  80. unowned List<TaskItem>? found_link = null;
  81. unowned List<TaskItem>? link = tasks.first();
  82. while (link != null) {
  83. if (link.data.id == id) {
  84. found_link = link;
  85. break;
  86. }
  87. link = link.next;
  88. }
  89. if (found_link != null) {
  90. tasks.delete_link(found_link);
  91. return true;
  92. }
  93. return false;
  94. }
  95. public TaskItem? get_task(int id) {
  96. foreach (var task in tasks) {
  97. if (task.id == id) {
  98. return task;
  99. }
  100. }
  101. return null;
  102. }
  103. }
  104. /**
  105. * CSS content for the htmx example page.
  106. */
  107. private const string HTMX_CSS = """
  108. body {
  109. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  110. max-width: 900px;
  111. margin: 0 auto;
  112. padding: 20px;
  113. background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
  114. min-height: 100vh;
  115. color: #eee;
  116. }
  117. .card {
  118. background: rgba(255, 255, 255, 0.1);
  119. backdrop-filter: blur(10px);
  120. border-radius: 12px;
  121. padding: 25px;
  122. margin: 15px 0;
  123. border: 1px solid rgba(255, 255, 255, 0.1);
  124. }
  125. h1, h2, h3 {
  126. color: #fff;
  127. margin-top: 0;
  128. }
  129. .htmx-logo {
  130. font-size: 48px;
  131. text-align: center;
  132. margin-bottom: 10px;
  133. }
  134. .subtitle {
  135. text-align: center;
  136. color: #aaa;
  137. margin-bottom: 30px;
  138. }
  139. .button-group {
  140. display: flex;
  141. gap: 10px;
  142. flex-wrap: wrap;
  143. justify-content: center;
  144. margin: 20px 0;
  145. }
  146. button, .btn {
  147. padding: 12px 24px;
  148. border: none;
  149. border-radius: 6px;
  150. cursor: pointer;
  151. font-size: 16px;
  152. font-weight: 600;
  153. transition: all 0.2s;
  154. text-decoration: none;
  155. display: inline-block;
  156. }
  157. button:hover, .btn:hover {
  158. transform: translateY(-2px);
  159. box-shadow: 0 4px 12px rgba(0,0,0,0.3);
  160. }
  161. .btn-primary {
  162. background: #3b82f6;
  163. color: white;
  164. }
  165. .btn-primary:hover {
  166. background: #2563eb;
  167. }
  168. .btn-success {
  169. background: #10b981;
  170. color: white;
  171. }
  172. .btn-success:hover {
  173. background: #059669;
  174. }
  175. .btn-danger {
  176. background: #ef4444;
  177. color: white;
  178. }
  179. .btn-danger:hover {
  180. background: #dc2626;
  181. }
  182. .btn-warning {
  183. background: #f59e0b;
  184. color: white;
  185. }
  186. .btn-warning:hover {
  187. background: #d97706;
  188. }
  189. .btn-small {
  190. padding: 6px 12px;
  191. font-size: 14px;
  192. }
  193. .counter-display {
  194. text-align: center;
  195. padding: 30px;
  196. background: rgba(0, 0, 0, 0.2);
  197. border-radius: 8px;
  198. margin: 20px 0;
  199. }
  200. .counter-value {
  201. font-size: 72px;
  202. font-weight: bold;
  203. color: #3b82f6;
  204. line-height: 1;
  205. }
  206. .info-grid {
  207. display: grid;
  208. grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  209. gap: 15px;
  210. margin: 20px 0;
  211. }
  212. .info-item {
  213. background: rgba(0, 0, 0, 0.2);
  214. padding: 15px;
  215. border-radius: 6px;
  216. text-align: center;
  217. }
  218. .info-label {
  219. font-size: 12px;
  220. color: #aaa;
  221. text-transform: uppercase;
  222. letter-spacing: 1px;
  223. }
  224. .info-value {
  225. font-size: 18px;
  226. font-weight: 600;
  227. color: #fff;
  228. margin-top: 5px;
  229. }
  230. .task-list {
  231. list-style: none;
  232. padding: 0;
  233. margin: 0;
  234. }
  235. .task-item {
  236. display: flex;
  237. align-items: center;
  238. gap: 10px;
  239. padding: 12px;
  240. background: rgba(0, 0, 0, 0.2);
  241. border-radius: 6px;
  242. margin-bottom: 8px;
  243. transition: all 0.2s;
  244. }
  245. .task-item:hover {
  246. background: rgba(0, 0, 0, 0.3);
  247. }
  248. .task-item.completed .task-text {
  249. text-decoration: line-through;
  250. color: #666;
  251. }
  252. .task-text {
  253. flex: 1;
  254. }
  255. .task-actions {
  256. display: flex;
  257. gap: 5px;
  258. }
  259. .add-task-form {
  260. display: flex;
  261. gap: 10px;
  262. margin-bottom: 20px;
  263. }
  264. .add-task-form input[type="text"] {
  265. flex: 1;
  266. padding: 12px;
  267. border: 1px solid rgba(255, 255, 255, 0.2);
  268. border-radius: 6px;
  269. background: rgba(0, 0, 0, 0.2);
  270. color: #fff;
  271. font-size: 16px;
  272. }
  273. .add-task-form input[type="text"]::placeholder {
  274. color: #666;
  275. }
  276. .add-task-form input[type="text"]:focus {
  277. outline: none;
  278. border-color: #3b82f6;
  279. }
  280. .history-log {
  281. background: rgba(0, 0, 0, 0.3);
  282. border-radius: 6px;
  283. padding: 15px;
  284. font-family: monospace;
  285. font-size: 13px;
  286. max-height: 200px;
  287. overflow-y: auto;
  288. white-space: pre-wrap;
  289. color: #10b981;
  290. }
  291. .loading-indicator {
  292. display: none;
  293. text-align: center;
  294. padding: 10px;
  295. }
  296. .htmx-request .loading-indicator {
  297. display: block;
  298. }
  299. .htmx-request .loading-indicator + .content {
  300. opacity: 0.5;
  301. }
  302. .spinner {
  303. border: 3px solid rgba(255, 255, 255, 0.1);
  304. border-top: 3px solid #3b82f6;
  305. border-radius: 50%;
  306. width: 24px;
  307. height: 24px;
  308. animation: spin 1s linear infinite;
  309. display: inline-block;
  310. }
  311. @keyframes spin {
  312. 0% { transform: rotate(0deg); }
  313. 100% { transform: rotate(360deg); }
  314. }
  315. code {
  316. background: rgba(0, 0, 0, 0.3);
  317. padding: 2px 6px;
  318. border-radius: 4px;
  319. font-size: 14px;
  320. color: #f59e0b;
  321. }
  322. pre {
  323. background: rgba(0, 0, 0, 0.3);
  324. color: #aed581;
  325. padding: 15px;
  326. border-radius: 6px;
  327. overflow-x: auto;
  328. font-size: 13px;
  329. }
  330. .feature-list {
  331. margin: 0;
  332. padding-left: 20px;
  333. }
  334. .feature-list li {
  335. margin: 8px 0;
  336. color: #ccc;
  337. }
  338. .live-clock {
  339. font-size: 24px;
  340. font-family: monospace;
  341. text-align: center;
  342. padding: 15px;
  343. background: rgba(0, 0, 0, 0.2);
  344. border-radius: 6px;
  345. }
  346. .clicker-area {
  347. text-align: center;
  348. padding: 30px;
  349. background: rgba(0, 0, 0, 0.1);
  350. border-radius: 8px;
  351. margin: 20px 0;
  352. border: 2px dashed rgba(255, 255, 255, 0.2);
  353. }
  354. .clicker-area:hover {
  355. border-color: #3b82f6;
  356. background: rgba(59, 130, 246, 0.1);
  357. }
  358. """;
  359. /**
  360. * HtmxTemplate - Main page template with htmx CDN script.
  361. */
  362. class HtmxTemplate : MarkupTemplate {
  363. protected override string markup { get {
  364. return """<!DOCTYPE html>
  365. <html lang="en">
  366. <head>
  367. <meta charset="UTF-8"/>
  368. <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  369. <title>htmx Example - Astralis</title>
  370. <link rel="stylesheet" href="/styles.css"/>
  371. <script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.8/dist/htmx.min.js"></script>
  372. </head>
  373. <body>
  374. <div class="htmx-logo">⚡</div>
  375. <p class="subtitle">htmx + Astralis: High Power Tools for HTML</p>
  376. <div class="card" id="main-card">
  377. <h1>htmx Examples</h1>
  378. <p>This page demonstrates <code>htmx</code> integration with Astralis.
  379. Content updates happen via AJAX without full page reloads.</p>
  380. </div>
  381. <!-- Live Clock Example: Auto-updating content with hx-trigger="every 1s" -->
  382. <div class="card">
  383. <h2>🕐 Live Clock</h2>
  384. <p>Auto-updates every second using <code>hx-trigger="every 1s"</code>:</p>
  385. <div id="clock-container" class="live-clock"
  386. hx-get="/clock"
  387. hx-trigger="load, every 1s">
  388. Loading...
  389. </div>
  390. </div>
  391. <!-- Click Counter Example: Button clicks via hx-post -->
  392. <div class="card">
  393. <h2>👆 Click Counter</h2>
  394. <p>Click buttons to update the counter. Uses <code>hx-post</code> and <code>hx-swap="innerHTML"</code>:</p>
  395. <div class="counter-display">
  396. <div class="counter-value" id="counter-value">0</div>
  397. <div class="button-group">
  398. <button hx-post="/click/decrement"
  399. hx-target="#counter-value"
  400. hx-swap="innerHTML"
  401. class="btn-danger">− Decrement</button>
  402. <button hx-post="/click/reset"
  403. hx-target="#counter-value"
  404. hx-swap="innerHTML"
  405. class="btn-warning">↺ Reset</button>
  406. <button hx-post="/click/increment"
  407. hx-target="#counter-value"
  408. hx-swap="innerHTML"
  409. class="btn-success">+ Increment</button>
  410. </div>
  411. </div>
  412. <div class="info-grid">
  413. <div class="info-item">
  414. <div class="info-label">Last Click</div>
  415. <div class="info-value" id="last-click">--:--:--</div>
  416. </div>
  417. <div class="info-item">
  418. <div class="info-label">History</div>
  419. <div class="info-value" id="click-history" style="font-size: 12px; font-family: monospace;">No clicks yet</div>
  420. </div>
  421. </div>
  422. <!-- Update history via hx-get on click -->
  423. <div hx-get="/click/history"
  424. hx-trigger="click from:.button-group button"
  425. hx-target="#click-history"
  426. hx-swap="innerHTML"></div>
  427. <div hx-get="/click/time"
  428. hx-trigger="click from:.button-group button"
  429. hx-target="#last-click"
  430. hx-swap="innerHTML"></div>
  431. </div>
  432. <!-- Task List Example: CRUD operations with htmx -->
  433. <div class="card">
  434. <h2>✅ Task List</h2>
  435. <p>A simple task manager with add, toggle, and delete operations:</p>
  436. <form class="add-task-form" hx-post="/tasks/add" hx-target="#task-list" hx-swap="innerHTML">
  437. <input type="text" name="task" placeholder="Enter a new task..." required=""/>
  438. <button type="submit" class="btn-primary">Add Task</button>
  439. </form>
  440. <ul class="task-list" id="task-list">
  441. <!-- Tasks loaded dynamically -->
  442. </ul>
  443. <div hx-get="/tasks" hx-trigger="load" hx-target="#task-list" hx-swap="innerHTML"></div>
  444. </div>
  445. <!-- Click Anywhere Example -->
  446. <div class="card">
  447. <h2>🎯 Click Area</h2>
  448. <p>Click anywhere in the area below to record a click. Uses <code>hx-trigger="click"</code>:</p>
  449. <div class="clicker-area"
  450. hx-post="/area/click"
  451. hx-trigger="click"
  452. hx-target="#area-result"
  453. hx-swap="innerHTML">
  454. <p>Click anywhere in this area!</p>
  455. <div id="area-result" style="margin-top: 10px; font-size: 14px; color: #aaa;">
  456. Clicks: 0
  457. </div>
  458. </div>
  459. </div>
  460. <!-- How It Works -->
  461. <div class="card">
  462. <h2>How It Works</h2>
  463. <p>htmx extends HTML with attributes that enable AJAX directly in your markup:</p>
  464. <pre><!-- Make a GET request and swap the response -->
  465. <div hx-get="/api/data" hx-swap="innerHTML">
  466. Click to load
  467. </div>
  468. <!-- POST on click, target another element -->
  469. <button hx-post="/api/action"
  470. hx-target="#result"
  471. hx-swap="outerHTML">
  472. Submit
  473. </button>
  474. <!-- Poll every second -->
  475. <div hx-get="/clock" hx-trigger="every 1s">
  476. Loading clock...
  477. </div></pre>
  478. <h3>Key htmx Attributes Used:</h3>
  479. <ul class="feature-list">
  480. <li><code>hx-get</code> - Make a GET request to the specified URL</li>
  481. <li><code>hx-post</code> - Make a POST request to the specified URL</li>
  482. <li><code>hx-trigger</code> - When to trigger the request (click, load, every Ns)</li>
  483. <li><code>hx-target</code> - CSS selector for where to place the response</li>
  484. <li><code>hx-swap</code> - How to swap content (innerHTML, outerHTML, beforeend)</li>
  485. </ul>
  486. </div>
  487. <div class="card">
  488. <p style="text-align: center; color: #aaa; margin: 0;">
  489. Built with <code>Astralis</code> + <code>htmx</code> |
  490. <a href="https://htmx.org/" target="_blank" style="color: #3b82f6;">htmx docs</a>
  491. </p>
  492. </div>
  493. </body>
  494. </html>
  495. """;
  496. }}
  497. }
  498. // Helper function to render tasks HTML
  499. string render_tasks_html() {
  500. var sb = new StringBuilder();
  501. foreach (var task in task_manager.tasks) {
  502. string completed_class = task.completed ? "completed" : "";
  503. string check_text = task.completed ? "✓" : "○";
  504. string check_btn_class = task.completed ? "btn-success" : "btn-warning";
  505. sb.append(@"<li class=\"task-item $completed_class\">");
  506. sb.append(@"<span class=\"task-text\">$(escape_html(task.text))</span>");
  507. sb.append(@"<div class=\"task-actions\">");
  508. sb.append(@"<button class=\"btn $check_btn_class btn-small\" ");
  509. sb.append(@"hx-post=\"/tasks/$(task.id)/toggle\" ");
  510. sb.append(@"hx-target=\"#task-list\" ");
  511. sb.append(@"hx-swap=\"innerHTML\">$check_text</button> ");
  512. sb.append(@"<button class=\"btn btn-danger btn-small\" ");
  513. sb.append(@"hx-post=\"/tasks/$(task.id)/delete\" ");
  514. sb.append(@"hx-target=\"#task-list\" ");
  515. sb.append(@"hx-swap=\"innerHTML\">✕</button>");
  516. sb.append(@"</div>");
  517. sb.append(@"</li>");
  518. }
  519. return sb.str;
  520. }
  521. string escape_html(string text) {
  522. var result = text.replace("&", "&amp;");
  523. result = result.replace("<", "&lt;");
  524. result = result.replace(">", "&gt;");
  525. result = result.replace("\"", "&quot;");
  526. return result;
  527. }
  528. // Main page endpoint
  529. class HomePageEndpoint : Object, Endpoint {
  530. private HtmxTemplate template = Inversion.inject<HtmxTemplate>();
  531. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  532. var doc = template.new_instance();
  533. return doc.to_result();
  534. }
  535. }
  536. // Clock endpoint - returns just the time string
  537. class ClockEndpoint : Object, Endpoint {
  538. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  539. var now = new DateTime.now_local();
  540. return new HttpStringResult(now.format("%H:%M:%S"), StatusCode.OK)
  541. .set_header("Content-Type", "text/html; charset=utf-8");
  542. }
  543. }
  544. // Click counter increment endpoint
  545. class ClickIncrementEndpoint : Object, Endpoint {
  546. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  547. click_state.record_click("Increment");
  548. return new HttpStringResult(click_state.click_count.to_string(), StatusCode.OK)
  549. .set_header("Content-Type", "text/html; charset=utf-8");
  550. }
  551. }
  552. // Click counter decrement endpoint
  553. class ClickDecrementEndpoint : Object, Endpoint {
  554. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  555. click_state.record_click("Decrement");
  556. return new HttpStringResult(click_state.click_count.to_string(), StatusCode.OK)
  557. .set_header("Content-Type", "text/html; charset=utf-8");
  558. }
  559. }
  560. // Click counter reset endpoint
  561. class ClickResetEndpoint : Object, Endpoint {
  562. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  563. click_state.record_click("Reset");
  564. click_state.click_count = 0;
  565. return new HttpStringResult("0", StatusCode.OK)
  566. .set_header("Content-Type", "text/html; charset=utf-8");
  567. }
  568. }
  569. // Click history endpoint
  570. class ClickHistoryEndpoint : Object, Endpoint {
  571. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  572. if (click_state.click_history == "") {
  573. return new HttpStringResult("No clicks yet", StatusCode.OK)
  574. .set_header("Content-Type", "text/html; charset=utf-8");
  575. }
  576. // Return first line only for the small display
  577. var lines = click_state.click_history.split("\n");
  578. string first_line = lines.length > 0 ? lines[0] : "No clicks yet";
  579. return new HttpStringResult(first_line, StatusCode.OK)
  580. .set_header("Content-Type", "text/html; charset=utf-8");
  581. }
  582. }
  583. // Click time endpoint
  584. class ClickTimeEndpoint : Object, Endpoint {
  585. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  586. return new HttpStringResult(click_state.last_click.format("%H:%M:%S"), StatusCode.OK)
  587. .set_header("Content-Type", "text/html; charset=utf-8");
  588. }
  589. }
  590. // Area click counter
  591. int area_clicks = 0;
  592. class AreaClickEndpoint : Object, Endpoint {
  593. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  594. area_clicks++;
  595. return new HttpStringResult(@"Clicks: $area_clicks", StatusCode.OK)
  596. .set_header("Content-Type", "text/html; charset=utf-8");
  597. }
  598. }
  599. // Task list endpoint - returns HTML for all tasks
  600. class TaskListEndpoint : Object, Endpoint {
  601. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  602. return new HttpStringResult(render_tasks_html(), StatusCode.OK)
  603. .set_header("Content-Type", "text/html; charset=utf-8");
  604. }
  605. }
  606. // Add task endpoint
  607. class AddTaskEndpoint : Object, Endpoint {
  608. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  609. var form_data = yield FormDataParser.parse(
  610. context.request.request_body,
  611. context.request.content_type
  612. );
  613. string? task_text = form_data.get_field("task");
  614. if (task_text != null && task_text.strip().length > 0) {
  615. task_manager.add_task(task_text.strip());
  616. }
  617. return new HttpStringResult(render_tasks_html(), StatusCode.OK)
  618. .set_header("Content-Type", "text/html; charset=utf-8");
  619. }
  620. }
  621. // Toggle task endpoint
  622. class ToggleTaskEndpoint : Object, Endpoint {
  623. public async HttpResult handle_request(HttpContext context, RouteContext route_info) throws Error {
  624. string? id_str = null;
  625. route_info.mapped_parameters.try_get("id", out id_str);
  626. int task_id = int.parse(id_str ?? "0");
  627. task_manager.toggle_task(task_id);
  628. return new HttpStringResult(render_tasks_html(), StatusCode.OK)
  629. .set_header("Content-Type", "text/html; charset=utf-8");
  630. }
  631. }
  632. // Delete task endpoint
  633. class DeleteTaskEndpoint : Object, Endpoint {
  634. public async HttpResult handle_request(HttpContext context, RouteContext route_info) throws Error {
  635. string? id_str = null;
  636. route_info.mapped_parameters.try_get("id", out id_str);
  637. int task_id = int.parse(id_str ?? "0");
  638. task_manager.delete_task(task_id);
  639. return new HttpStringResult(render_tasks_html(), StatusCode.OK)
  640. .set_header("Content-Type", "text/html; charset=utf-8");
  641. }
  642. }
  643. // Global state
  644. ClickState click_state;
  645. TaskManager task_manager;
  646. void main(string[] args) {
  647. int port = args.length > 1 ? int.parse(args[1]) : 8080;
  648. // Initialize state
  649. click_state = new ClickState();
  650. task_manager = new TaskManager();
  651. print("╔══════════════════════════════════════════════════════════════╗\n");
  652. print("║ Astralis htmx Example ║\n");
  653. print("╠══════════════════════════════════════════════════════════════╣\n");
  654. print(@"║ Port: $port");
  655. for (int i = 0; i < 50 - port.to_string().length - 7; i++) print(" ");
  656. print(" ║\n");
  657. print("╠══════════════════════════════════════════════════════════════╣\n");
  658. print("║ Endpoints: ║\n");
  659. print("║ / - Main page with htmx examples ║\n");
  660. print("║ /styles.css - CSS stylesheet (FastResource) ║\n");
  661. print("║ /clock - Live clock (polled every second) ║\n");
  662. print("║ /click/* - Click counter endpoints ║\n");
  663. print("║ /tasks - Task list (GET all) ║\n");
  664. print("║ /tasks/add - Add task (POST) ║\n");
  665. print("║ /tasks/{id}/* - Task operations (toggle, delete) ║\n");
  666. print("║ /area/click - Click area counter ║\n");
  667. print("╠══════════════════════════════════════════════════════════════╣\n");
  668. print("║ htmx CDN: ║\n");
  669. print("║ https://cdn.jsdelivr.net/npm/htmx.org@2.0.8 ║\n");
  670. print("╚══════════════════════════════════════════════════════════════╝\n");
  671. print("\nPress Ctrl+C to stop the server\n\n");
  672. try {
  673. var application = new WebApplication(port);
  674. // Register compression
  675. application.use_compression();
  676. // Register template as singleton
  677. application.add_singleton<HtmxTemplate>();
  678. // Register CSS as FastResource
  679. application.add_singleton_endpoint<FastResource>(new EndpointRoute("/styles.css"), () => {
  680. try {
  681. return new FastResource.from_string(HTMX_CSS)
  682. .with_content_type("text/css; charset=utf-8")
  683. .with_default_compressors();
  684. } catch (Error e) {
  685. error("Failed to create CSS resource: %s", e.message);
  686. }
  687. });
  688. // Main page
  689. application.add_endpoint<HomePageEndpoint>(new EndpointRoute("/"));
  690. // Clock endpoint
  691. application.add_endpoint<ClockEndpoint>(new EndpointRoute("/clock"));
  692. // Click counter endpoints
  693. application.add_endpoint<ClickIncrementEndpoint>(new EndpointRoute("/click/increment"));
  694. application.add_endpoint<ClickDecrementEndpoint>(new EndpointRoute("/click/decrement"));
  695. application.add_endpoint<ClickResetEndpoint>(new EndpointRoute("/click/reset"));
  696. application.add_endpoint<ClickHistoryEndpoint>(new EndpointRoute("/click/history"));
  697. application.add_endpoint<ClickTimeEndpoint>(new EndpointRoute("/click/time"));
  698. // Area click endpoint
  699. application.add_endpoint<AreaClickEndpoint>(new EndpointRoute("/area/click"));
  700. // Task endpoints
  701. application.add_endpoint<TaskListEndpoint>(new EndpointRoute("/tasks"));
  702. application.add_endpoint<AddTaskEndpoint>(new EndpointRoute("/tasks/add"));
  703. application.add_endpoint<ToggleTaskEndpoint>(new EndpointRoute("/tasks/{id}/toggle"));
  704. application.add_endpoint<DeleteTaskEndpoint>(new EndpointRoute("/tasks/{id}/delete"));
  705. application.run();
  706. } catch (Error e) {
  707. printerr("Error: %s\n", e.message);
  708. Process.exit(1);
  709. }
  710. }