Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions examples/webui-todo-app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"name": "@microsoft/fast-webui-todo-app-example",
"version": "1.0.0",
"description": "",
"main": "dist/exports.js",
"type": "module",
"private": true,
"scripts": {
"build": "vite build",
"start": "npm run build && node server.js",
"test": "npm run build"
},
"author": {
"name": "Microsoft",
"url": "https://discord.gg/FcSNfg4"
},
"homepage": "https://www.fast.design/",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/Microsoft/fast.git",
"directory": "examples/webui-todo-app"
},
"dependencies": {
"@microsoft/fast-element": "^2.10.2",
"@microsoft/fast-html": "*",
"@microsoft/webui": "^0.0.2",
"express": "4.22.1",
"tslib": "^2.6.3"
}
}
127 changes: 127 additions & 0 deletions examples/webui-todo-app/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import fs from "node:fs";
import { build, render } from "@microsoft/webui";
import express from "express";

const app = express();
const port = 8081;

// Build templates into a binary protocol at startup (build-time compilation)
const result = build({ appDir: "./src", plugin: "fast" });

// The f-template elements define the declarative FAST component templates for
// client-side hydration. They use single-brace {} bindings so the SSR step
// does not attempt to fill them in — FAST-html resolves them in the browser.
const COMPONENT_TEMPLATES = `
<f-template name="todo-app">
<template>
<style>
:host {
display: block;
padding: 16px;
max-width: 320px;
}
.todo-list {
list-style-type: none;
padding: 0;
}
.todo {
margin: 8px 0px;
display: flex;
}
.description {
display: inline-block;
align-self: center;
margin: 0px 8px;
flex: 1;
}
.description.done {
text-decoration: line-through;
}
</style>
<h1>FAST Todos</h1>
<todo-form></todo-form>
<section>
<label for="filter">Filter:</label>
<select name="filter" title="filter" :value="{todos.activeFilter}">
<option value="all">All</option>
<option value="active">Active</option>
<option value="completed">Completed</option>
</select>
</section>
<ul class="todo-list">
<f-repeat value="{item in todos.filtered}">
<li class="todo">
<input type="checkbox" :checked="{item.done}" />
<span class="description">{item.description}</span>
<button @click="{$c.parent.todos.remove(item)}" aria-label="Remove item">&times;</button>
</li>
</f-repeat>
</ul>
</template>
</f-template>
<f-template name="todo-form">
<template>
<style>
form {
display: flex;
align-items: center;
}
button {
margin: 4px;
}
</style>
<form @submit="{submitTodo()}">
<input type="text" :value="{description}" />
<button type="submit" ?disabled="{!description}">Add Todo</button>
</form>
</template>
</f-template>
`;

function escapeHtml(str) {
return str
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}

function renderTodoItems(todos) {
if (todos.length === 0) return "";
return todos
.map(
todo => `
<li class="todo">
<input type="checkbox"${todo.done ? " checked" : ""} />
<span class="description${todo.done ? " done" : ""}">${escapeHtml(todo.description)}</span>
<button aria-label="Remove item">&times;</button>
</li>`,
)
.join("");
}

app.use(express.static("./www"));

app.get("/", (req, res) => {
const todoData = JSON.parse(fs.readFileSync("./todo-data.json").toString());

// Render the page template using webui, injecting prerendered todo items and
// the declarative component template definitions as raw HTML
const html = render(result.protocol, {
prerenderedItems: renderTodoItems(todoData),
componentTemplates: COMPONENT_TEMPLATES,
});

// Inject initial state so the client-side FAST components can hydrate with
// the same data that was used for prerendering
const withState = html.replace(
"</body>",
`<script>window.__INITIAL_STATE__ = ${JSON.stringify(todoData)};</script></body>`,
);

res.send(withState);
});

app.listen(port, () => {
console.log(`WebUI Todo app listening on port ${port}`);
});
68 changes: 68 additions & 0 deletions examples/webui-todo-app/src/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>FAST Todos</title>
</head>
<body>
<todo-app defer-hydration>
<template shadowrootmode="open">
<style>
:host {
display: block;
padding: 16px;
max-width: 320px;
}
.todo-list {
list-style-type: none;
padding: 0;
}
.todo {
margin: 8px 0px;
display: flex;
}
.description {
display: inline-block;
align-self: center;
margin: 0px 8px;
flex: 1;
}
.description.done {
text-decoration: line-through;
}
</style>
<h1>FAST Todos</h1>
<todo-form defer-hydration>
<template shadowrootmode="open">
<style>
form {
display: flex;
align-items: center;
}
button {
margin: 4px;
}
</style>
<form>
<input type="text" />
<button type="submit" disabled>Add Todo</button>
</form>
</template>
</todo-form>
<section>
<label for="filter">Filter:</label>
<select name="filter" title="filter">
<option value="all">All</option>
<option value="active">Active</option>
<option value="completed">Completed</option>
</select>
</section>
<ul class="todo-list">
{{{prerenderedItems}}}
</ul>
</template>
</todo-app>
{{{componentTemplates}}}
<script type="module" src="/bundle.js"></script>
</body>
</html>
24 changes: 24 additions & 0 deletions examples/webui-todo-app/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { RenderableFASTElement, TemplateElement } from "@microsoft/fast-html";
import { TodoApp } from "./todo-app.js";
import { TodoForm } from "./todo-form.js";
import { DefaultTodoList, TodoList } from "./todo-list.js";

const SSRState = (window as any).__INITIAL_STATE__ || [];
TodoList.provide(document, new DefaultTodoList(SSRState));

RenderableFASTElement(TodoApp).defineAsync({
name: "todo-app",
templateOptions: "defer-and-hydrate",
});

RenderableFASTElement(TodoForm).defineAsync({
name: "todo-form",
templateOptions: "defer-and-hydrate",
});

TemplateElement.options({
"todo-app": { observerMap: "all" },
"todo-form": { observerMap: "all" },
}).define({
name: "f-template",
});
6 changes: 6 additions & 0 deletions examples/webui-todo-app/src/todo-app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { FASTElement } from "@microsoft/fast-element";
import { TodoList } from "./todo-list.js";

export class TodoApp extends FASTElement {
@TodoList todos!: TodoList;
}
12 changes: 12 additions & 0 deletions examples/webui-todo-app/src/todo-form.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { FASTElement, observable } from "@microsoft/fast-element";
import { TodoList } from "./todo-list.js";

export class TodoForm extends FASTElement {
@observable public description: string = "";
@TodoList todos!: TodoList;

public submitTodo() {
this.description && this.todos.add(this.description);
this.description = "";
}
}
69 changes: 69 additions & 0 deletions examples/webui-todo-app/src/todo-list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { Observable, observable, volatile } from "@microsoft/fast-element";
import { Context } from "@microsoft/fast-element/context.js";
import { reactive } from "@microsoft/fast-element/state.js";

export type Todo = { description: string; done: boolean };
export type TodoListFilter = "all" | "active" | "completed";
export const TodoList = Context.create<TodoList>("TodoList");
export interface TodoList {
activeFilter: TodoListFilter;
readonly filtered: readonly Todo[];
add(description: string): void;
remove(todo: Todo): void;
}

export class DefaultTodoList {
@observable private _todos: Todo[] = [];
@observable public activeFilter: TodoListFilter = "all";

public get all() {
return this._todos;
}

@volatile
public get filtered(): readonly Todo[] {
// This property is decorated with @volatile because the exact
// observable dependencies of the property can change between
// invocations. Normally, FAST assumes that the dependencies of
// a binding are the same across invocations, for optimization
// purposes. So, in this case, we need to tell the system not to
// make that assumption.

switch (this.activeFilter) {
case "active":
return this._todos.filter(x => !x.done);
case "completed":
return this._todos.filter(x => x.done);
default:
return this._todos;
}
}

constructor(todos?: Todo[]) {
if (todos) {
this._todos = todos.map(x => reactive(x));
}
}

public add(description: string) {
this.splice(this._todos.length, 0, reactive({ description, done: false }));
}

public remove(todo: Todo) {
const index = this._todos.indexOf(todo);
index !== -1 && this.splice(index, 1);
}

/**
* This method centralizes all updates to the internal array so that we
* can guarantee that observers are notified in the appropriate cases.
*/
private splice(index: number, removeCount: number, ...newItem: Todo[]) {
this._todos.splice(index, removeCount, ...newItem);

// Because the filtered property returns different arrays depending
// on the filter, we need to notify FAST that the dependent _todos
// observable has changed whenever we splice the internal data structure.
this.activeFilter !== "all" && Observable.notify(this, "_todos");
}
}
5 changes: 5 additions & 0 deletions examples/webui-todo-app/todo-data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[
{ "description": "Buy groceries", "done": false },
{ "description": "Walk the dog", "done": true },
{ "description": "Read a book", "done": false }
]
19 changes: 19 additions & 0 deletions examples/webui-todo-app/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"pretty": true,
"target": "ES2015",
"module": "ES2015",
"moduleResolution": "bundler",
"importHelpers": true,
"experimentalDecorators": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"noEmitOnError": true,
"strict": true,
"outDir": "dist",
"rootDir": "src",
"lib": ["dom", "esnext"]
},
"include": ["src"]
}
19 changes: 19 additions & 0 deletions examples/webui-todo-app/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { defineConfig } from "vite";

export default defineConfig({
build: {
outDir: "www",
emptyOutDir: true,
sourcemap: true,
rollupOptions: {
input: "src/main.ts",
output: {
entryFileNames: "bundle.js",
},
},
},
server: {
port: 9001,
open: !process.env.CI,
},
});
Loading
Loading