TemplateExample.vala 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. using Astralis;
  2. using Invercargill;
  3. using Invercargill.DataStructures;
  4. using Inversion;
  5. using Spry;
  6. /**
  7. * TemplateExample.vala - Demonstrates PageComponent and PageTemplate usage
  8. *
  9. * This example shows how to create template-based pages where:
  10. * - MainLayoutTemplate provides the base HTML structure with header and footer
  11. * - AdminSectionTemplate adds an admin navigation sidebar (nested template)
  12. * - PageComponents render their content into template outlets
  13. *
  14. * Route structure:
  15. * / -> HomePage (uses MainLayoutTemplate)
  16. * /about -> AboutPage (uses MainLayoutTemplate)
  17. * /admin -> AdminDashboardPage (uses AdminSectionTemplate -> MainLayoutTemplate)
  18. * /admin/users -> AdminUsersPage (uses AdminSectionTemplate -> MainLayoutTemplate)
  19. */
  20. // =============================================================================
  21. // STYLESHEETS - CSS content served as FastResources
  22. // =============================================================================
  23. /**
  24. * Main CSS - Base styles for all pages
  25. */
  26. private const string MAIN_CSS = """
  27. /* Base Reset & Layout */
  28. * { box-sizing: border-box; margin: 0; padding: 0; }
  29. html, body {
  30. height: 100%;
  31. }
  32. body {
  33. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  34. line-height: 1.6;
  35. background: #f5f7fa;
  36. display: flex;
  37. flex-direction: column;
  38. min-height: 100vh;
  39. }
  40. /* Header */
  41. header {
  42. background: #2c3e50;
  43. color: white;
  44. padding: 1rem 2rem;
  45. display: flex;
  46. justify-content: space-between;
  47. align-items: center;
  48. flex-shrink: 0;
  49. }
  50. header nav a {
  51. color: white;
  52. margin-right: 1.5rem;
  53. text-decoration: none;
  54. font-weight: 500;
  55. transition: opacity 0.2s;
  56. }
  57. header nav a:hover { opacity: 0.8; }
  58. header nav a:last-child { margin-right: 0; }
  59. header .visit-info {
  60. font-size: 0.85rem;
  61. opacity: 0.8;
  62. }
  63. /* Main Content - grows to fill space */
  64. main.container {
  65. flex: 1;
  66. max-width: 1200px;
  67. width: 100%;
  68. margin: 0 auto;
  69. padding: 2rem 1rem;
  70. }
  71. /* Cards */
  72. .card {
  73. background: white;
  74. border-radius: 12px;
  75. padding: 2rem;
  76. margin-bottom: 1.5rem;
  77. box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  78. }
  79. /* Typography */
  80. h1 { color: #2c3e50; margin-bottom: 1rem; }
  81. h2 { color: #34495e; margin-bottom: 0.75rem; margin-top: 1.5rem; }
  82. h3 { color: #34495e; margin-bottom: 0.5rem; margin-top: 1rem; }
  83. p { color: #555; margin-bottom: 1rem; }
  84. ul, ol { margin-left: 1.5rem; margin-bottom: 1rem; }
  85. li { margin-bottom: 0.5rem; color: #555; }
  86. /* Links */
  87. a { color: #3498db; text-decoration: none; transition: color 0.2s; }
  88. a:hover { color: #2980b9; text-decoration: underline; }
  89. /* Code */
  90. code {
  91. background: #f0f0f0;
  92. padding: 0.2rem 0.5rem;
  93. border-radius: 4px;
  94. font-size: 0.9em;
  95. color: #e74c3c;
  96. }
  97. pre {
  98. background: #263238;
  99. color: #aed581;
  100. padding: 1rem;
  101. border-radius: 8px;
  102. overflow-x: auto;
  103. font-size: 0.9rem;
  104. margin: 1rem 0;
  105. }
  106. /* Footer - at bottom */
  107. footer {
  108. background: #2c3e50;
  109. color: rgba(255,255,255,0.7);
  110. padding: 1.5rem;
  111. text-align: center;
  112. flex-shrink: 0;
  113. }
  114. /* Buttons & Forms */
  115. button {
  116. background: #3498db;
  117. color: white;
  118. border: none;
  119. padding: 0.75rem 1.5rem;
  120. border-radius: 6px;
  121. cursor: pointer;
  122. font-size: 1rem;
  123. font-weight: 500;
  124. transition: all 0.2s;
  125. }
  126. button:hover {
  127. background: #2980b9;
  128. }
  129. input[type="text"] {
  130. padding: 0.75rem;
  131. border: 2px solid #e0e0e0;
  132. border-radius: 6px;
  133. font-size: 1rem;
  134. transition: border-color 0.2s;
  135. }
  136. input[type="text"]:focus {
  137. outline: none;
  138. border-color: #3498db;
  139. }
  140. """;
  141. /**
  142. * Admin CSS - Additional styles for admin section
  143. */
  144. private const string ADMIN_CSS = """
  145. /* Admin Section Layout */
  146. .admin-section {
  147. display: flex;
  148. gap: 2rem;
  149. }
  150. /* Admin Sidebar */
  151. .admin-sidebar {
  152. width: 220px;
  153. background: #34495e;
  154. padding: 1.5rem;
  155. border-radius: 12px;
  156. flex-shrink: 0;
  157. }
  158. .admin-sidebar h3 {
  159. color: white;
  160. margin-bottom: 1rem;
  161. font-size: 1.1rem;
  162. border-bottom: 1px solid rgba(255,255,255,0.2);
  163. padding-bottom: 0.75rem;
  164. }
  165. .admin-sidebar ul {
  166. list-style: none;
  167. margin: 0;
  168. padding: 0;
  169. }
  170. .admin-sidebar li { margin-bottom: 0.5rem; margin-left: 0; }
  171. .admin-sidebar a {
  172. color: rgba(255,255,255,0.7);
  173. display: block;
  174. padding: 0.5rem 0.75rem;
  175. border-radius: 6px;
  176. transition: all 0.2s;
  177. }
  178. .admin-sidebar a:hover {
  179. color: white;
  180. background: rgba(255,255,255,0.1);
  181. text-decoration: none;
  182. }
  183. /* Admin Content Area */
  184. .admin-content {
  185. flex: 1;
  186. min-width: 0;
  187. }
  188. /* Dashboard Stats */
  189. .dashboard-stats {
  190. display: flex;
  191. gap: 1.5rem;
  192. flex-wrap: wrap;
  193. }
  194. .stat-card {
  195. background: #3498db;
  196. color: white;
  197. padding: 1.5rem;
  198. border-radius: 12px;
  199. min-width: 180px;
  200. }
  201. .stat-card h3 {
  202. color: rgba(255,255,255,0.9);
  203. font-size: 0.85rem;
  204. text-transform: uppercase;
  205. letter-spacing: 1px;
  206. margin: 0 0 0.5rem 0;
  207. }
  208. .stat-card .stat-value {
  209. font-size: 2.5rem;
  210. font-weight: bold;
  211. }
  212. /* User List */
  213. .user-list {
  214. margin: 1.5rem 0;
  215. }
  216. .user-item {
  217. display: flex;
  218. align-items: center;
  219. gap: 1rem;
  220. padding: 1rem 1.25rem;
  221. background: #f8f9fa;
  222. margin-bottom: 0.75rem;
  223. border-radius: 8px;
  224. transition: background 0.2s;
  225. }
  226. .user-item:hover {
  227. background: #e9ecef;
  228. }
  229. .user-item .user-name {
  230. flex: 1;
  231. font-weight: 500;
  232. color: #2c3e50;
  233. }
  234. .user-item .user-status {
  235. color: #27ae60;
  236. font-size: 0.9rem;
  237. font-weight: 500;
  238. }
  239. /* Add Form */
  240. .add-form {
  241. display: flex;
  242. gap: 0.75rem;
  243. margin-top: 1.5rem;
  244. }
  245. .add-form input[type="text"] {
  246. flex: 1;
  247. max-width: 300px;
  248. }
  249. /* Navigation Links */
  250. .nav-link {
  251. display: inline-block;
  252. margin-top: 1.5rem;
  253. color: #3498db;
  254. font-weight: 500;
  255. }
  256. .nav-link:hover { color: #2980b9; }
  257. """;
  258. // =============================================================================
  259. // STORES - Simple data stores for demonstration
  260. // =============================================================================
  261. class AppState : Object {
  262. public int visit_count { get; set; }
  263. public string last_visit { get; set; }
  264. }
  265. class UserStore : Object {
  266. private Series<string> users = new Series<string>();
  267. construct {
  268. users.add("Alice");
  269. users.add("Bob");
  270. users.add("Charlie");
  271. }
  272. public Enumerable<string> get_all() {
  273. return users;
  274. }
  275. public void add_user(string name) {
  276. users.add(name);
  277. }
  278. public int count() {
  279. return (int)users.length;
  280. }
  281. }
  282. // =============================================================================
  283. // TEMPLATES - Provide reusable page layouts
  284. // =============================================================================
  285. /**
  286. * MainLayoutTemplate - The base template for all pages
  287. *
  288. * Provides:
  289. * - HTML document structure
  290. * - Common <head> elements (scripts, styles)
  291. * - Site-wide header with navigation
  292. * - Site-wide footer
  293. *
  294. * Uses <spry-template-outlet> where child content/templates will be inserted
  295. */
  296. class MainLayoutTemplate : PageTemplate {
  297. private AppState app_state = inject<AppState>();
  298. public override string markup { get {
  299. return """
  300. <!DOCTYPE html>
  301. <html lang="en">
  302. <head>
  303. <meta charset="UTF-8">
  304. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  305. <title>Spry Template Example</title>
  306. <link rel="stylesheet" href="/styles/main.css">
  307. <script spry-res="htmx.js"></script>
  308. </head>
  309. <body>
  310. <header>
  311. <nav>
  312. <a href="/">Home</a>
  313. <a href="/about">About</a>
  314. <a href="/admin">Admin</a>
  315. </nav>
  316. <small class="visit-info" sid="visit-info"></small>
  317. </header>
  318. <main class="container">
  319. <spry-template-outlet />
  320. </main>
  321. <footer>
  322. <p>Built with Spry Framework - Template Example</p>
  323. </footer>
  324. </body>
  325. </html>
  326. """;
  327. }}
  328. public override async void prepare() throws Error {
  329. this["visit-info"].text_content = @"Visits: $(app_state.visit_count) | Last: $(app_state.last_visit)";
  330. }
  331. }
  332. /**
  333. * AdminSectionTemplate - A nested template for admin pages
  334. *
  335. * This template is applied to routes starting with /admin
  336. * It adds an admin sidebar navigation around the page content
  337. *
  338. * Templates are applied in order of rank (based on prefix length):
  339. * 1. MainLayoutTemplate (rank 0, prefix "") - outermost
  340. * 2. AdminSectionTemplate (rank 1, prefix "/admin") - nested inside main
  341. * 3. PageComponent - innermost content
  342. */
  343. class AdminSectionTemplate : PageTemplate {
  344. public override string markup { get {
  345. return """
  346. <head>
  347. <link rel="stylesheet" href="/styles/admin.css">
  348. </head>
  349. <div class="admin-section">
  350. <aside class="admin-sidebar">
  351. <h3>Admin Menu</h3>
  352. <ul>
  353. <li><a href="/admin">Dashboard</a></li>
  354. <li><a href="/admin/users">Users</a></li>
  355. </ul>
  356. </aside>
  357. <div class="admin-content">
  358. <spry-template-outlet />
  359. </div>
  360. </div>
  361. """;
  362. }}
  363. }
  364. // =============================================================================
  365. // PAGE COMPONENTS - Render content into templates
  366. // =============================================================================
  367. /**
  368. * HomePage - The main landing page
  369. *
  370. * Extends PageComponent (not Component) to automatically use template rendering
  371. * The handle_request method in PageComponent:
  372. * 1. Finds all matching templates (MainLayoutTemplate matches "")
  373. * 2. Renders each template in order
  374. * 3. Inserts each rendered content into the previous template's outlet
  375. */
  376. class HomePage : PageComponent {
  377. private AppState app_state = inject<AppState>();
  378. public const string ROUTE = "/";
  379. public override string markup { get {
  380. return """
  381. <div class="card" sid="home">
  382. <h1>Welcome to Spry!</h1>
  383. <p>This example demonstrates template-based pages using <code>PageComponent</code> and <code>PageTemplate</code>.</p>
  384. <h2>Features</h2>
  385. <ul>
  386. <li><strong>MainLayoutTemplate</strong> - Provides base HTML, header, footer</li>
  387. <li><modulestrong>AdminSectionTemplate</strong> - Adds sidebar for /admin/* routes</li>
  388. <li><strong>PageComponent</strong> - Pages automatically inherit templates</li>
  389. </ul>
  390. <h2>Try These Pages</h2>
  391. <ul>
  392. <li><a href="/about">About Page</a> - Uses main layout only</li>
  393. <li><a href="/admin">Admin Dashboard</a> - Uses admin template + main layout</li>
  394. <li><a href="/admin/users">Admin Users</a> - Interactive user list</li>
  395. </ul>
  396. <p sid="visit-count"></p>
  397. </div>
  398. """;
  399. }}
  400. public override async void prepare() throws Error {
  401. app_state.visit_count++;
  402. app_state.last_visit = new DateTime.now_local().format("%H:%M:%S");
  403. this["visit-count"].text_content = @"You have visited $(app_state.visit_count) times.";
  404. }
  405. }
  406. /**
  407. * AboutPage - A simple about page
  408. */
  409. class AboutPage : PageComponent {
  410. public const string ROUTE = "/about";
  411. public override string markup { get {
  412. return """
  413. <div class="card">
  414. <h1>About Spry Templates</h1>
  415. <h2>How Templates Work</h2>
  416. <p>Templates use <code><spry-template-outlet /></code> to define where child content will be inserted.</p>
  417. <h3>Template Resolution</h3>
  418. <p>When a <code>PageComponent</code> handles a request:</p>
  419. <ol>
  420. <li>It finds all registered <code>PageTemplate</code>s matching the route</li>
  421. <li>Templates are ordered by their prefix length (rank)</li>
  422. <li>Each template is rendered, with content nested into outlets</li>
  423. </ol>
  424. <h3>Route Matching</h3>
  425. <pre>
  426. Prefix "" matches all routes
  427. Prefix "/admin" matches /admin and /admin/*
  428. Prefix "/admin/users" matches /admin/users only
  429. </pre>
  430. <a href="/" class="nav-link">Back to Home</a>
  431. </div>
  432. """;
  433. }}
  434. }
  435. /**
  436. * AdminDashboardPage - Admin dashboard with statistics
  437. */
  438. class AdminDashboardPage : PageComponent {
  439. private UserStore user_store = inject<UserStore>();
  440. public const string ROUTE = "/admin";
  441. public override string markup { get {
  442. return """
  443. <div class="card">
  444. <h1>Admin Dashboard</h1>
  445. <div class="dashboard-stats">
  446. <div class="stat-card">
  447. <h3>Total Users</h3>
  448. <div class="stat-value" sid="user-count"></div>
  449. </div>
  450. </div>
  451. <a href="/" class="nav-link">Back to Home</a>
  452. </div>
  453. """;
  454. }}
  455. public override async void prepare() throws Error {
  456. this["user-count"].text_content = user_store.count().to_string();
  457. }
  458. }
  459. /**
  460. * AdminUsersPage - Admin page with interactive user list
  461. *
  462. * Demonstrates HTMX interactions within a templated page.
  463. * The form targets the card with outerHTML swap so the entire card
  464. * is replaced with the updated content.
  465. */
  466. class AdminUsersPage : PageComponent {
  467. private UserStore user_store = inject<UserStore>();
  468. private ComponentFactory factory = inject<ComponentFactory>();
  469. private HttpContext http_context = inject<HttpContext>();
  470. public const string ROUTE = "/admin/users";
  471. public override string markup { get {
  472. return """
  473. <div class="card" sid="users-card">
  474. <h1>User Management</h1>
  475. <div class="user-list">
  476. <spry-outlet sid="user-list"/>
  477. </div>
  478. <form class="add-form" sid="add-form" spry-action=":AddUser" spry-target="users-card" hx-swap="outerHTML">
  479. <input type="text" name="username" placeholder="Enter username" required>
  480. <button type="submit">Add User</button>
  481. </form>
  482. <a href="/admin" class="nav-link">Back to Dashboard</a>
  483. </div>
  484. """;
  485. }}
  486. public override async void prepare() throws Error {
  487. refresh_user_list();
  488. }
  489. private void refresh_user_list() throws Error {
  490. var users = user_store.get_all();
  491. var items = new Series<Renderable>();
  492. users.iterate((name) => {
  493. var item = factory.create<UserItemComponent>();
  494. item.username = name;
  495. items.add(item);
  496. });
  497. set_outlet_children("user-list", items);
  498. }
  499. public async override void handle_action(string action) throws Error {
  500. if (action == "AddUser") {
  501. var username = http_context.request.query_params.get_any_or_default("username");
  502. if (username != null && username.length > 0) {
  503. user_store.add_user(username);
  504. }
  505. refresh_user_list();
  506. }
  507. }
  508. }
  509. /**
  510. * UserItemComponent - Individual user item in the list
  511. */
  512. class UserItemComponent : Component {
  513. public string username { set; get; }
  514. public override string markup { get {
  515. return """
  516. <div class="user-item" sid="user-item">
  517. <span class="user-name" sid="name"></span>
  518. <span class="user-status">Active</span>
  519. </div>
  520. """;
  521. }}
  522. public override async void prepare() throws Error {
  523. this["name"].text_content = username;
  524. }
  525. }
  526. // =============================================================================
  527. // APPLICATION SETUP
  528. // =============================================================================
  529. void main(string[] args) {
  530. int port = args.length > 1 ? int.parse(args[1]) : 8080;
  531. print("═══════════════════════════════════════════════════════════════\n");
  532. print(" Spry Template Example (PageComponent + PageTemplate)\n");
  533. print("═══════════════════════════════════════════════════════════════\n");
  534. print(" Port: %d\n", port);
  535. print("═══════════════════════════════════════════════════════════════\n");
  536. print(" Endpoints:\n");
  537. print(" / - Home page (MainLayoutTemplate)\n");
  538. print(" /about - About page (MainLayoutTemplate)\n");
  539. print(" /admin - Admin dashboard (AdminSectionTemplate)\n");
  540. print(" /admin/users - User management (AdminSectionTemplate)\n");
  541. print(" /styles/main.css - Main stylesheet (FastResource)\n");
  542. print(" /styles/admin.css - Admin stylesheet (FastResource)\n");
  543. print("═══════════════════════════════════════════════════════════════\n");
  544. print("\nPress Ctrl+C to stop the server\n\n");
  545. try {
  546. var application = new WebApplication(port);
  547. // Enable compression
  548. application.use_compression();
  549. // Add Spry module for component actions
  550. application.add_module<SpryModule>();
  551. // Register stores as singletons
  552. application.add_singleton<AppState>();
  553. application.add_singleton<UserStore>();
  554. // Register templates with route prefixes
  555. // MainLayoutTemplate applies to ALL routes (empty prefix)
  556. var spry_cfg = application.configure_with<SpryConfigurator>();
  557. spry_cfg.add_template<MainLayoutTemplate>("");
  558. // AdminSectionTemplate applies to /admin/* routes
  559. spry_cfg.add_template<AdminSectionTemplate>("/admin");
  560. // Register page components as endpoints
  561. application.add_transient<HomePage>();
  562. application.add_endpoint<HomePage>(new EndpointRoute(HomePage.ROUTE));
  563. application.add_transient<AboutPage>();
  564. application.add_endpoint<AboutPage>(new EndpointRoute(AboutPage.ROUTE));
  565. application.add_transient<AdminDashboardPage>();
  566. application.add_endpoint<AdminDashboardPage>(new EndpointRoute(AdminDashboardPage.ROUTE));
  567. application.add_transient<AdminUsersPage>();
  568. application.add_endpoint<AdminUsersPage>(new EndpointRoute(AdminUsersPage.ROUTE));
  569. // Register child components
  570. application.add_transient<UserItemComponent>();
  571. // Register CSS as FastResources
  572. application.add_startup_endpoint<FastResource>(new EndpointRoute("/styles/main.css"), () => {
  573. try {
  574. return new FastResource.from_string(MAIN_CSS)
  575. .with_content_type("text/css; charset=utf-8")
  576. .with_default_compressors();
  577. } catch (Error e) {
  578. error("Failed to create main CSS resource: %s", e.message);
  579. }
  580. });
  581. application.add_startup_endpoint<FastResource>(new EndpointRoute("/styles/admin.css"), () => {
  582. try {
  583. return new FastResource.from_string(ADMIN_CSS)
  584. .with_content_type("text/css; charset=utf-8")
  585. .with_default_compressors();
  586. } catch (Error e) {
  587. error("Failed to create admin CSS resource: %s", e.message);
  588. }
  589. });
  590. application.run();
  591. } catch (Error e) {
  592. printerr("Error: %s\n", e.message);
  593. Process.exit(1);
  594. }
  595. }