TemplateExample.vala 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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 & Typography */
  28. * { box-sizing: border-box; margin: 0; padding: 0; }
  29. body {
  30. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  31. line-height: 1.6;
  32. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  33. min-height: 100vh;
  34. }
  35. /* Header */
  36. header {
  37. background: rgba(44, 62, 80, 0.95);
  38. color: white;
  39. padding: 1rem 2rem;
  40. display: flex;
  41. justify-content: space-between;
  42. align-items: center;
  43. backdrop-filter: blur(10px);
  44. box-shadow: 0 2px 20px rgba(0,0,0,0.2);
  45. }
  46. header nav a {
  47. color: white;
  48. margin-right: 1.5rem;
  49. text-decoration: none;
  50. font-weight: 500;
  51. transition: opacity 0.2s;
  52. }
  53. header nav a:hover { opacity: 0.8; }
  54. header nav a:last-child { margin-right: 0; }
  55. header .visit-info {
  56. font-size: 0.85rem;
  57. opacity: 0.8;
  58. }
  59. /* Main Content */
  60. main.container {
  61. max-width: 1200px;
  62. margin: 2rem auto;
  63. padding: 0 1rem;
  64. }
  65. /* Cards */
  66. .card {
  67. background: white;
  68. border-radius: 12px;
  69. padding: 2rem;
  70. margin-bottom: 1.5rem;
  71. box-shadow: 0 10px 40px rgba(0,0,0,0.15);
  72. }
  73. /* Typography */
  74. h1 { color: #2c3e50; margin-bottom: 1rem; }
  75. h2 { color: #34495e; margin-bottom: 0.75rem; margin-top: 1.5rem; }
  76. h3 { color: #34495e; margin-bottom: 0.5rem; margin-top: 1rem; }
  77. p { color: #555; margin-bottom: 1rem; }
  78. ul, ol { margin-left: 1.5rem; margin-bottom: 1rem; }
  79. li { margin-bottom: 0.5rem; color: #555; }
  80. /* Links */
  81. a { color: #667eea; text-decoration: none; transition: color 0.2s; }
  82. a:hover { color: #764ba2; text-decoration: underline; }
  83. /* Code */
  84. code {
  85. background: #f0f0f0;
  86. padding: 0.2rem 0.5rem;
  87. border-radius: 4px;
  88. font-size: 0.9em;
  89. color: #e74c3c;
  90. }
  91. pre {
  92. background: #263238;
  93. color: #aed581;
  94. padding: 1rem;
  95. border-radius: 8px;
  96. overflow-x: auto;
  97. font-size: 0.9rem;
  98. margin: 1rem 0;
  99. }
  100. /* Footer */
  101. footer {
  102. background: rgba(44, 62, 80, 0.9);
  103. color: rgba(255,255,255,0.7);
  104. padding: 1.5rem;
  105. text-align: center;
  106. margin-top: 2rem;
  107. backdrop-filter: blur(10px);
  108. }
  109. /* Buttons & Forms */
  110. button {
  111. background: #667eea;
  112. color: white;
  113. border: none;
  114. padding: 0.75rem 1.5rem;
  115. border-radius: 6px;
  116. cursor: pointer;
  117. font-size: 1rem;
  118. font-weight: 500;
  119. transition: all 0.2s;
  120. }
  121. button:hover {
  122. background: #5a6fd6;
  123. transform: translateY(-1px);
  124. box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  125. }
  126. input[type="text"] {
  127. padding: 0.75rem;
  128. border: 2px solid #e0e0e0;
  129. border-radius: 6px;
  130. font-size: 1rem;
  131. transition: border-color 0.2s;
  132. }
  133. input[type="text"]:focus {
  134. outline: none;
  135. border-color: #667eea;
  136. }
  137. """;
  138. /**
  139. * Admin CSS - Additional styles for admin section
  140. */
  141. private const string ADMIN_CSS = """
  142. /* Admin Section Layout */
  143. .admin-section {
  144. display: flex;
  145. gap: 2rem;
  146. margin-top: 1rem;
  147. }
  148. /* Admin Sidebar */
  149. .admin-sidebar {
  150. width: 220px;
  151. background: rgba(52, 73, 94, 0.95);
  152. padding: 1.5rem;
  153. border-radius: 12px;
  154. box-shadow: 0 4px 20px rgba(0,0,0,0.15);
  155. backdrop-filter: blur(10px);
  156. }
  157. .admin-sidebar h3 {
  158. color: white;
  159. margin-bottom: 1rem;
  160. font-size: 1.1rem;
  161. border-bottom: 1px solid rgba(255,255,255,0.2);
  162. padding-bottom: 0.75rem;
  163. }
  164. .admin-sidebar ul {
  165. list-style: none;
  166. margin: 0;
  167. padding: 0;
  168. }
  169. .admin-sidebar li { margin-bottom: 0.5rem; }
  170. .admin-sidebar a {
  171. color: rgba(255,255,255,0.7);
  172. display: block;
  173. padding: 0.5rem 0.75rem;
  174. border-radius: 6px;
  175. transition: all 0.2s;
  176. }
  177. .admin-sidebar a:hover {
  178. color: white;
  179. background: rgba(255,255,255,0.1);
  180. text-decoration: none;
  181. }
  182. /* Admin Content Area */
  183. .admin-content {
  184. flex: 1;
  185. min-width: 0;
  186. }
  187. /* Dashboard Stats */
  188. .dashboard-stats {
  189. display: flex;
  190. gap: 1.5rem;
  191. flex-wrap: wrap;
  192. }
  193. .stat-card {
  194. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  195. color: white;
  196. padding: 1.5rem;
  197. border-radius: 12px;
  198. min-width: 180px;
  199. box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
  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: white;
  222. margin-bottom: 0.75rem;
  223. border-radius: 8px;
  224. box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  225. transition: transform 0.2s, box-shadow 0.2s;
  226. }
  227. .user-item:hover {
  228. transform: translateX(4px);
  229. box-shadow: 0 4px 12px rgba(0,0,0,0.12);
  230. }
  231. .user-item .user-name {
  232. flex: 1;
  233. font-weight: 500;
  234. color: #2c3e50;
  235. }
  236. .user-item .user-status {
  237. color: #27ae60;
  238. font-size: 0.9rem;
  239. font-weight: 500;
  240. }
  241. /* Add Form */
  242. .add-form {
  243. display: flex;
  244. gap: 0.75rem;
  245. margin-top: 1.5rem;
  246. }
  247. .add-form input[type="text"] {
  248. flex: 1;
  249. max-width: 300px;
  250. }
  251. /* Navigation Links */
  252. .nav-link {
  253. display: inline-block;
  254. margin-top: 1.5rem;
  255. color: #667eea;
  256. font-weight: 500;
  257. }
  258. .nav-link:hover { color: #764ba2; }
  259. """;
  260. // =============================================================================
  261. // STORES - Simple data stores for demonstration
  262. // =============================================================================
  263. class AppState : Object {
  264. public int visit_count { get; set; }
  265. public string last_visit { get; set; }
  266. }
  267. class UserStore : Object {
  268. private Series<string> users = new Series<string>();
  269. construct {
  270. users.add("Alice");
  271. users.add("Bob");
  272. users.add("Charlie");
  273. }
  274. public Enumerable<string> get_all() {
  275. return users;
  276. }
  277. public void add_user(string name) {
  278. users.add(name);
  279. }
  280. public int count() {
  281. return (int)users.length;
  282. }
  283. }
  284. // =============================================================================
  285. // TEMPLATES - Provide reusable page layouts
  286. // =============================================================================
  287. /**
  288. * MainLayoutTemplate - The base template for all pages
  289. *
  290. * Provides:
  291. * - HTML document structure
  292. * - Common <head> elements (scripts, styles)
  293. * - Site-wide header with navigation
  294. * - Site-wide footer
  295. *
  296. * Uses <spry-template-outlet> where child content/templates will be inserted
  297. */
  298. class MainLayoutTemplate : PageTemplate {
  299. private AppState app_state = inject<AppState>();
  300. public override string markup { get {
  301. return """
  302. <!DOCTYPE html>
  303. <html lang="en">
  304. <head>
  305. <meta charset="UTF-8">
  306. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  307. <title>Spry Template Example</title>
  308. <link rel="stylesheet" href="/styles/main.css">
  309. <script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.8/dist/htmx.min.js"></script>
  310. </head>
  311. <body>
  312. <header>
  313. <nav>
  314. <a href="/">Home</a>
  315. <a href="/about">About</a>
  316. <a href="/admin">Admin</a>
  317. </nav>
  318. <small class="visit-info" sid="visit-info"></small>
  319. </header>
  320. <main class="container">
  321. <spry-template-outlet />
  322. </main>
  323. <footer>
  324. <p>Built with Spry Framework - Template Example</p>
  325. </footer>
  326. </body>
  327. </html>
  328. """;
  329. }}
  330. public override async void prepare() throws Error {
  331. this["visit-info"].text_content = @"Visits: $(app_state.visit_count) | Last: $(app_state.last_visit)";
  332. }
  333. }
  334. /**
  335. * AdminSectionTemplate - A nested template for admin pages
  336. *
  337. * This template is applied to routes starting with /admin
  338. * It adds an admin sidebar navigation around the page content
  339. *
  340. * Templates are applied in order of rank (based on prefix length):
  341. * 1. MainLayoutTemplate (rank 0, prefix "") - outermost
  342. * 2. AdminSectionTemplate (rank 1, prefix "/admin") - nested inside main
  343. * 3. PageComponent - innermost content
  344. */
  345. class AdminSectionTemplate : PageTemplate {
  346. public override string markup { get {
  347. return """
  348. <head>
  349. <link rel="stylesheet" href="/styles/admin.css">
  350. </head>
  351. <div class="admin-section">
  352. <aside class="admin-sidebar">
  353. <h3>Admin Menu</h3>
  354. <ul>
  355. <li><a href="/admin">Dashboard</a></li>
  356. <li><a href="/admin/users">Users</a></li>
  357. </ul>
  358. </aside>
  359. <div class="admin-content">
  360. <spry-template-outlet />
  361. </div>
  362. </div>
  363. """;
  364. }}
  365. }
  366. // =============================================================================
  367. // PAGE COMPONENTS - Render content into templates
  368. // =============================================================================
  369. /**
  370. * HomePage - The main landing page
  371. *
  372. * Extends PageComponent (not Component) to automatically use template rendering
  373. * The handle_request method in PageComponent:
  374. * 1. Finds all matching templates (MainLayoutTemplate matches "")
  375. * 2. Renders each template in order
  376. * 3. Inserts each rendered content into the previous template's outlet
  377. */
  378. class HomePage : PageComponent {
  379. private AppState app_state = inject<AppState>();
  380. public const string ROUTE = "/";
  381. public override string markup { get {
  382. return """
  383. <div class="card" sid="home">
  384. <h1>Welcome to Spry!</h1>
  385. <p>This example demonstrates template-based pages using <code>PageComponent</code> and <code>PageTemplate</code>.</p>
  386. <h2>Features</h2>
  387. <ul>
  388. <li><strong>MainLayoutTemplate</strong> - Provides base HTML, header, footer</li>
  389. <li><strong>AdminSectionTemplate</strong> - Adds sidebar for /admin/* routes</li>
  390. <li><strong>PageComponent</strong> - Pages automatically inherit templates</li>
  391. </ul>
  392. <h2>Try These Pages</h2>
  393. <ul>
  394. <li><a href="/about">About Page</a> - Uses main layout only</li>
  395. <li><a href="/admin">Admin Dashboard</a> - Uses admin template + main layout</li>
  396. <li><a href="/admin/users">Admin Users</a> - Interactive user list</li>
  397. </ul>
  398. <p sid="visit-count"></p>
  399. </div>
  400. """;
  401. }}
  402. public override async void prepare() throws Error {
  403. app_state.visit_count++;
  404. app_state.last_visit = new DateTime.now_local().format("%H:%M:%S");
  405. this["visit-count"].text_content = @"You have visited $(app_state.visit_count) times.";
  406. }
  407. }
  408. /**
  409. * AboutPage - A simple about page
  410. */
  411. class AboutPage : PageComponent {
  412. public const string ROUTE = "/about";
  413. public override string markup { get {
  414. return """
  415. <div class="card">
  416. <h1>About Spry Templates</h1>
  417. <h2>How Templates Work</h2>
  418. <p>Templates use <code><spry-template-outlet /></code> to define where child content will be inserted.</p>
  419. <h3>Template Resolution</h3>
  420. <p>When a <code>PageComponent</code> handles a request:</p>
  421. <ol>
  422. <li>It finds all registered <code>PageTemplate</code>s matching the route</li>
  423. <li>Templates are ordered by their prefix length (rank)</li>
  424. <li>Each template is rendered, with content nested into outlets</li>
  425. </ol>
  426. <h3>Route Matching</h3>
  427. <pre>
  428. Prefix "" matches all routes
  429. Prefix "/admin" matches /admin and /admin/*
  430. Prefix "/admin/users" matches /admin/users only
  431. </pre>
  432. <a href="/" class="nav-link">Back to Home</a>
  433. </div>
  434. """;
  435. }}
  436. }
  437. /**
  438. * AdminDashboardPage - Admin dashboard with statistics
  439. */
  440. class AdminDashboardPage : PageComponent {
  441. private UserStore user_store = inject<UserStore>();
  442. public const string ROUTE = "/admin";
  443. public override string markup { get {
  444. return """
  445. <div class="card">
  446. <h1>Admin Dashboard</h1>
  447. <div class="dashboard-stats">
  448. <div class="stat-card">
  449. <h3>Total Users</h3>
  450. <div class="stat-value" sid="user-count"></div>
  451. </div>
  452. </div>
  453. <a href="/" class="nav-link">Back to Home</a>
  454. </div>
  455. """;
  456. }}
  457. public override async void prepare() throws Error {
  458. this["user-count"].text_content = user_store.count().to_string();
  459. }
  460. }
  461. /**
  462. * AdminUsersPage - Admin page with interactive user list
  463. *
  464. * Demonstrates HTMX interactions within a templated page
  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">
  474. <h1>User Management</h1>
  475. <div class="user-list" sid="user-list">
  476. <!-- Users rendered here -->
  477. </div>
  478. <form class="add-form" sid="add-form" spry-action=":AddUser" spry-target="user-list" hx-swap="innerHTML">
  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. application.add_transient<MainLayoutTemplate>()
  557. .as<PageTemplate>()
  558. .with_metadata(new TemplateRoutePrefix(""));
  559. // AdminSectionTemplate applies to /admin/* routes
  560. application.add_transient<AdminSectionTemplate>()
  561. .as<PageTemplate>()
  562. .with_metadata(new TemplateRoutePrefix("/admin"));
  563. // Register page components as endpoints
  564. application.add_transient<HomePage>();
  565. application.add_endpoint<HomePage>(new EndpointRoute(HomePage.ROUTE));
  566. application.add_transient<AboutPage>();
  567. application.add_endpoint<AboutPage>(new EndpointRoute(AboutPage.ROUTE));
  568. application.add_transient<AdminDashboardPage>();
  569. application.add_endpoint<AdminDashboardPage>(new EndpointRoute(AdminDashboardPage.ROUTE));
  570. application.add_transient<AdminUsersPage>();
  571. application.add_endpoint<AdminUsersPage>(new EndpointRoute(AdminUsersPage.ROUTE));
  572. // Register child components
  573. application.add_transient<UserItemComponent>();
  574. // Register CSS as FastResources
  575. application.add_startup_endpoint<FastResource>(new EndpointRoute("/styles/main.css"), () => {
  576. try {
  577. return new FastResource.from_string(MAIN_CSS)
  578. .with_content_type("text/css; charset=utf-8")
  579. .with_default_compressors();
  580. } catch (Error e) {
  581. error("Failed to create main CSS resource: %s", e.message);
  582. }
  583. });
  584. application.add_startup_endpoint<FastResource>(new EndpointRoute("/styles/admin.css"), () => {
  585. try {
  586. return new FastResource.from_string(ADMIN_CSS)
  587. .with_content_type("text/css; charset=utf-8")
  588. .with_default_compressors();
  589. } catch (Error e) {
  590. error("Failed to create admin CSS resource: %s", e.message);
  591. }
  592. });
  593. application.run();
  594. } catch (Error e) {
  595. printerr("Error: %s\n", e.message);
  596. Process.exit(1);
  597. }
  598. }