Simple example on deno-deploy
reggi opened this issue · comments
I think a simple example on deno-deploy would be really cool, right now there's just a lot of boiler-plate to think about. I also think that using JSX could would be cool as well just wrapping the render method so something else can create the HTML string like https://hdot.dev/ or preact (https://www.npmjs.com/package/preact-render-to-string).
import { createLiveView, html } from "liveviewjs";
/**
* A basic counter that increments and decrements a number.
*/
export const counterLiveView = createLiveView<
{ count: number }, // Define LiveView Context (a.k.a state)
{ type: "increment" } | { type: "decrement" } // Define LiveView Events
>({
mount: (socket) => {
// init state, set count to 0
socket.assign({ count: 0 });
},
handleEvent: (event, socket) => {
// handle increment and decrement events
const { count } = socket.context;
switch (event.type) {
case "increment":
socket.assign({ count: count + 1 });
break;
case "decrement":
socket.assign({ count: count - 1 });
break;
}
},
render: (context) => {
// render the view based on the state
const { count } = context;
return html`
<div>
<h1>Count is: ${count}</h1>
<button phx-click="decrement">-</button>
<button phx-click="increment">+</button>
</div>
`;
},
});
serve({
"/": counterLiveView,
})
Part of the reason we use the html
tagged template literal is because we need to know what parts of the template are "static" (don't ever change) and what parts are "dynamic" (might change based on state). This is so we can send down only the dynamic parts that have changed after the event lifecycle. The tagged template literal makes this very straightforward and easy - we don't need to parse the template at all. Additionally, there isn't a "transpilation" step like there is in JSX.
JSX is widely supported and prob one I would lean toward supporting "first". My main concerns are:
- I am not familiar with the internals of getting JSX and whether it is "easy" to get the statics/dynamics part of the template extracted
- I am concerned about adding a transpilation step
Do you know if it is easy to extract dynamic vs static parts from a JSX template? Any pointers?
Also, I like the idea of a minimal deno deploy example.
Yeah so I've been using deno fresh a bunch which ships with preact, none of the preact code ever sees the client (except in the case of an island), the preact-render-to-string module strips out all the preact things things like an onClick
attribute for instance here's an example (it serves text here not html) https://dash.deno.com/playground/sad-hedgehog-20, in this way it's just a jsx to html interpreter.