-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathsemi-isomorphic.html
587 lines (541 loc) · 23.5 KB
/
semi-isomorphic.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
<html>
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<head>
<title>
leontrolski - semi-isomorphic apps
</title>
<style>
body {margin: 5% auto; background: #fff7f7; color: #444444; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.8; max-width: 63%;}
@media screen and (max-width: 800px) {body {font-size: 14px; line-height: 1.4; max-width: 90%;}}
pre {width: 100%; border-top: 3px solid gray; border-bottom: 3px solid gray;}
a {border-bottom: 1px solid #444444; color: #444444; text-decoration: none; text-shadow: 0 1px 0 #ffffff; }
a:hover {border-bottom: 0;}
.inline {background: #b3b2b226; padding-left: 0.3em; padding-right: 0.3em; white-space: nowrap;}
blockquote {font-style: italic;color:black;background-color:#f2f2f2;padding:2em;}
details {border-bottom:solid 5px gray;}
</style>
<link href="https://unpkg.com/[email protected]/themes/prism-vs.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.20.0/components/prism-core.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.20.0/plugins/autoloader/prism-autoloader.min.js">
</script>
</head>
<body>
<a href="index.html">
<img src="pic.png" style="height:2em">
⇦
</a>
<p><i>2020-08-29</i></p>
<h1>
Evolving backend → frontend rendered <code class="inline">Python</code>
/ <code class="inline">JS</code>
apps with <code class="inline">dnjs</code>
</h1>
<p>
With very little ceremony or surprise, <a href="https://github.com/leontrolski/dnjs#dnjs">
dnjs
</a>
lets you <b>
specify configuration
</b>
, generate <b>
static html/css
</b>
, and <b>
render html on the backend/frontend
</b>
across languages. <a href="https://github.com/leontrolski/leontrolski.github.io/tree/master/src/semi-isomorphic.dn.js">
This page
</a>
is even written with it. <em>
A word of warning: the project is still in its development stages.
</em>
</p>
<h2>
What's the problem?
</h2>
<p>
In most worlds, when you're building a web app, there is a very clear divide between:
</p>
<ol>
<li>
"Let's build a backend-rendered page in <code class="inline">Python</code>
/ <code class="inline">JS</code>
/... rendering the html with some funky templating language. We can sprinkle in some ad-hoc <code class="inline">JS</code>
as we get there."
</li>
<li>
"Let's build a fully frontend-rendered app with <code class="inline">React</code>
/ <code class="inline">Vue</code>
/..."
</li>
</ol>
<p>
A lot of the time, teams plump for option 2, even when the user experience might be worse (slow loading times, lack of hyperlinking, etc), and the developer experience might be worse (lots of client state, hard to test, etc).
</p>
<p>
<code class="inline">dnjs</code>
takes the following positions:
</p>
<ul>
<li>
Most backend templating languages are clunky, often difficult to compose and missing tooling (eg. linters) available for fully-fledged languages.
</li>
<li>
There is a UI-complexity threshold at which one might choose to make part of the app frontend-rendered, this is OK.
</li>
<li>
The default ways of constructing DOM nodes in the browser are <a href="dom-syntax.html">
inelegant
</a>
.
</li>
<li>
Build chains and compile steps may eventually become necessary, but we'll start with browser-compatible code.
</li>
</ul>
<p>
It attempts to resolve these with a <a href="https://github.com/leontrolski/dnjs#how-exactly-does-dnjs-extend-json">
pure subset of <code class="inline">JS</code>
</a>
that is <b>
reasonable to implement in host languages
</b>
and <b>
has a standardised way of describing DOM nodes
</b>
. Being able to share things across the backend and the frontend means we can evolve our app over time. We can start with simple html forms, then progress to frontend-rendering as the complexity requires - <em>
while reusing previously written components
</em>
.
</p>
<p>
Let's walk through an example where we span this transition.
</p>
<h2>
An example app
</h2>
<p>
In this post, we will build the following simple web app, where we can add todos and check them if they're done. The data will be persisted on the backend:
</p>
<video controls src="videos/basic.webm" style="
margin: auto;
display: block;
max-width: calc(min(20em, 100%));
box-shadow: 0px 0px 6px 2px #0000002b;
margin-top: 2em;
margin-bottom: 2em;
">
</video>
<h2>
The 3 ways we will build it are:
</h2>
<ul>
<li>
Using just backend rendering and <code class="inline"><form></code>
elements à la 1995. This we'll refer to as <code class="inline">backend</code>
.
</li>
<li>
Using a sprinkling of imperative <code class="inline">JS</code>
to dynamically add the new comment without reloading the page. This we'll refer to as <code class="inline">classic</code>
.
</li>
<li>
Rendering the entire comment list with a <code class="inline">JS</code>
library (in this case <a href="https://mithril.js.org/">
mithril
</a>
). This we'll refer to as <code class="inline">declarative</code>
because we specify the DOM as a pure function of state.
</li>
</ul>
<h2>
Aside: running the examples
</h2>
<p>
The source for the above can be found in the <a href="https://github.com/leontrolski/dnjs/tree/master/examples/todo">
<code class="inline">examples/todo</code>
</a>
directory of the <code class="inline">dnjs</code>
repo. It has the following structure:
</p>
<pre class="language-bash"><code>├── app.py
├── shared
│ ├── components.dn.js
│ └── style.dn.js
├── static
│ ├── backend.js
│ ├── classic.js
│ ├── declarative.js
│ └── style.css
└── templates
└── page.dn.js</code>
</pre>
<p>
You should be able to run the server with:
</p>
<pre class="language-bash"><code>git clone [email protected]:leontrolski/dnjs.git
cd dnjs; python3 -m venv .env; source .env/bin/activate
pip install dnjs fastapi uvicorn aiofiles python-multipart
examples/todo/bin/serve
open 'http://localhost:8000/backend'</code>
</pre>
<h2>
Building the app with <code class="inline">backend</code>
</h2>
<p>
We're going to use the <code class="inline">Python</code>
library <a href="https://fastapi.tiangolo.com/">
FastAPI
</a>
for our backend. Let's start by looking at the body of the html we want to end up with:
</p>
<pre class="language-html"><code><h1 class="todo-bold todo-red">Hello Ms Backend</h1>
<div id="todo-list">
<form id="todoListForm" method="POST">
<ul>
<li class="todo-todo">
hullo
<input class="doneCheckbox" name="doneCheckbox" value="0" type="checkbox" />
</li>
<li class="todo-todo">
goodbye
<input class="doneCheckbox" name="doneCheckbox" value="1" type="checkbox" checked />
</li>
</ul>
<input name="newMessage" value="" placeholder="message" autocomplete="off" />
<button>add todo</button>
</form>
</div></code>
</pre>
<p>
As you can see, we're going to render just a normal html <code class="inline"><form></code>
. When we submit the form, it will POST one <code class="inline">newMessage</code>
with <code class="inline">value="some message"</code>
and many <code class="inline">doneCheckbox</code>
s, each with <code class="inline">value="index"</code>
- the indexes of todos that are checked.
</p>
<h3>
An aside on html forms
</h3>
<p>
Html forms are really not a thing of beauty, they map poorly to json structures, you can't nest them, they can only convey strings, etc. Lots of frontend devs in particular seem to have forgotten the weirdo ins and outs of how they work, for example: that <code class="inline"><button></code>
s and <code class="inline"><input type="checkbox"></code>
s have <code class="inline">(name, value)</code>
s <em>
that are only are POSTed when they are clicked/checked.
</em>
</p>
<p>
<em>
Despite
</em>
these shortcomings, they are well worth using for simple forms (that is to say - most forms). Not using any <code class="inline">JS</code>
means having basically zero state in the browser, and that makes reasoning about/testing the app way easier. Like way way easier.
</p>
<h3>
Back to the app
</h3>
<p>
Let's have a look at the <code class="inline">dnjs</code>
templating code we use to render the page from <code class="inline">Python</code>
, the base page is in <a href="https://github.com/leontrolski/dnjs/tree/master/examples/todo/templates/page.dn.js">
<code class="inline">examples/todo/templates/page.dn.js</code>
</a>
and looks like:
</p>
<pre class="language-javascript"><code>import { TodoList } from "../shared/components.dn.js"
const title = [classes.bold, classes.red]
export default (data) => (
...
m("h1", {class: title}, "Hello ", data.username),
m("#todo-list", TodoList(data.state)),
...
)</code>
</pre>
<p>
The components for the form itself can be found in <a href="https://github.com/leontrolski/dnjs/tree/master/examples/todo/shared/components.dn.js">
<code class="inline">examples/todo/shared/components.dn.js</code>
</a>
and look a bit like:
</p>
<pre class="language-javascript"><code>export const Todo = (todo) => m("li",
todo.message,
m("input.doneCheckbox", {name: "doneCheckbox", value: todo.i, checked: todo.done, type: "checkbox"}),
)
export const TodoList = (state) => m("form#todoListForm",
{method: "POST"},
m("ul", state.todos.map((todo, i) =>Todo({...todo, i: i}))),
m("input", {name: "newMessage", value: state.new}),
m("button", "add todo"),
)</code>
</pre>
<details>
<summary>
The equivalent handlebars code would look something like this.
</summary>
<pre class="language-html"><code><h1 class="{{classes.bold}} {{classes.red}}">Hello {{data.username}}</h1>
<div id="todo-list">
<form id="todoListForm" method="POST">
<ul>
{{#each state.todos}}
<li>
{{message}}
<input class="doneCheckbox" name="doneCheckbox" value="{{@index}}" {{#if done}}checked{{/if}} type="checkbox" />
</li>
{{/each}}
</ul>
<input name="newMessage" value="{{state.new}}" />
<button>add todo</button>
</form>
</div></code>
</pre>
</details>
<p>
We will render the page in <a href="https://github.com/leontrolski/dnjs/tree/master/examples/todo/app.py">
<code class="inline">examples/todo/app.py</code>
</a>
with:
</p>
<pre class="language-python"><code>@app.get("/backend", response_class=HTMLResponse)
def get_backend() -> str:
return dnjs.render(
templates / "page.dn.js",
PageData(
username="Ms Backend",
state=State(todos=_todos.todos, new=""),
)
)</code>
</pre>
<p>
We're rendering the <code class="inline">dnjs</code>
(a subset of <code class="inline">JS</code>
) with <code class="inline">Python</code>
... 🤯
</p>
<p>
In the same file, we handle <code class="inline">POST</code>
s with:
</p>
<pre class="language-python"><code>@app.post("/backend", response_class=HTMLResponse)
def post_backend(newMessage: str, doneCheckbox: List[int]) -> str:
if newMessage:
_todos.todos.append(Todo(message=newMessage, done=False))
for i, todo in enumerate(_todos.todos):
todo.done = i in doneCheckbox
return render(...)</code>
</pre>
<em>
Note, for demo purposes, we are storing the todos serverside with an in-memory structure <code class="inline">_todos</code>
.
</em>
<p>
In case you can't be bothered to run the example application, here's a video of me clicking around the <code class="inline">backend</code>
app with the console on.
</p>
<video controls src="videos/backend.webm" style="
margin: auto;
display: block;
max-width: calc(min(20em, 100%));
box-shadow: 0px 0px 6px 2px #0000002b;
margin-top: 2em;
margin-bottom: 2em;
">
</video>
<h2>
Adding some frontend rendering with <code class="inline">classic</code>
</h2>
<p>
The users of our app were posting lots of frequent comments, we decided it wasn't acceptable to have a page reload every time it happened. This means we had to add a sprinkling (23 lines) of <code class="inline">JS</code>
to:
</p>
<ul>
<li>
POST the data to the backed using <code class="inline">XHR</code>
.
</li>
<li>
Construct a new <code class="inline"><li></code>
element from the data.
</li>
<li>
Append that element to the existing <code class="inline"><ul></code>
in the DOM.
</li>
</ul>
<p>
The bulk of this - <a href="https://github.com/leontrolski/dnjs/tree/master/examples/todo/static/classic.js">
<code class="inline">examples/todo/static/classic.js</code>
</a>
- is as follows:
</p>
<pre class="language-javascript"><code>import { Todo } from "../shared/components.dn.js"
...
todoListFormEl.onsubmit = async e => {
// prevent the <form> from actually submitting
e.preventDefault()
...
// construct the todo data and send to the backend
const data = {
message: newMessageEl.value,
done: false
}
await fetch(
"/classic/todos",
{method: 'POST', body: JSON.stringify(data)}
)
// make the Todo DOM node and append it to the DOM
const newTodo = Todo(data, null)
todoListUlEl.appendChild(m.makeEl(newTodo))
...
}</code>
</pre>
<p>
The important thing here is that <b>
we were able to reuse the same <code class="inline">Todo</code>
component that we used on the backend on the frontend
</b>
. Cool huh!
</p>
<h3>
dnjs2dom
</h3>
<p>
In the <code class="inline">classic</code>
app, we use the teeny <a href="https://github.com/leontrolski/dnjs2dom#dnjs-client-helper">
dnjs2dom
</a>
library to turn the <code class="inline">m(...)</code>
components into actual DOM nodes. This library enables the line <code class="inline">todoListUlEl.appendChild(m.makeEl(newTodo))</code>
.
</p>
<p>
Let's show a video of this in action:
</p>
<video controls src="videos/classic.webm" style="
margin: auto;
display: block;
max-width: calc(min(20em, 100%));
box-shadow: 0px 0px 6px 2px #0000002b;
margin-top: 2em;
margin-bottom: 2em;
">
</video>
<h2>
Going whole-hog frontend rendering with <code class="inline">declarative</code>
</h2>
<p>
It's a bit contrived with this simple app, but let's imagine our UI's complexity has tipped over to the point where we want everything super dynamic. To achieve this, we will use the (excellent) <a href="https://mithril.js.org/">
mithril
</a>
- which <code class="inline">dnjs</code>
is handily compatible with.
</p>
<p>
Here's the line from <a href="https://github.com/leontrolski/dnjs/tree/master/examples/todo/static/declarative.js">
<code class="inline">examples/todo/static/declarative.js</code>
</a>
where we mount our components to the DOM with mithirl:
</p>
<pre class="language-javascript"><code>m.mount(todoListEl, {view: () => TodoList(state, actions)})</code>
</pre>
<p>
Note again - <b>
we were able to reuse the same <code class="inline">TodoList</code>
component that we used on the backend on the frontend.
</b>
</p>
<p>
<a href="https://mithril.js.org/">
mithril
</a>
wraps any <code class="inline">{onclick: f, onsubmit: g, ...}</code>
functions and rerenders the DOM as necessary in similar way to <code class="inline">React</code>
. Below is an example of one of the functions we pass via <code class="inline">m("form", {onsubmit: add}, ...)</code>
.
</p>
<pre class="language-javascript"><code>const add = (e) => {
e.preventDefault()
if (!state.new) return
state.todos.push({message: state.new, done: false})
state.new = ""
m.request({
url: "/declarative/todos",
method: "PUT",
body: {todos: state.todos}
})
}</code>
</pre>
<em>
Note that if we want to render the same component from the backend, we just pass in <code class="inline">{onsubmit: None}</code>
and it is ignored by <code class="inline">dnjs</code>
.
</em>
<p>
Let's show a video of our declaratively rendered app in action:
</p>
<video controls src="videos/declarative.webm" style="
margin: auto;
display: block;
max-width: calc(min(20em, 100%));
box-shadow: 0px 0px 6px 2px #0000002b;
margin-top: 2em;
margin-bottom: 2em;
">
</video>
<h1>
Bonus css <code class="inline">section</code>
</h1>
<p>
Our app has many pages, so we'd like to share/compose/namespace our css. Handily <code class="inline">dnjs</code>
can convert from <a href="https://github.com/leontrolski/dnjs/tree/master/examples/todo/shared/style.dn.js">
<code class="inline">examples/todo/shared/style.dn.js</code>
</a>
:
</p>
<pre class="language-javascript"><code>const _classes = {
bold: {
"font-weight": "bold",
},
red: {
"color": "red",
},
...
}
// namespace
export default Object.fromEntries(
Object.entries(_classes)
.map(([k, v], _) => [".{namespace}-{k}", v])
)</code>
</pre>
<p>
Via:
</p>
<pre class="language-bash"><code>dnjs shared/style.dn.js --css > static/style.css</code>
</pre>
<p>
To:
</p>
<pre class="language-css"><code>.todo-bold {
font-weight: bold;
}
.todo-red {
color: red;
}</code>
</pre>
<p>
In <a href="https://github.com/leontrolski/dnjs/tree/master/examples/todo/shared/style.dn.js">
<code class="inline">examples/todo/shared/style.dn.js</code>
</a>
we also export the names themselves of the css classes, so in the rendering code, we can refer to eg: <code class="inline">style.classes.bold</code>
and it will resolve to the name: <code class="inline">"todo-bold"</code>
.
</p>
<p>
Similar to the advantages in html-rendering land, having your css as "just data" means you can easily compose/transform it, again without resorting to a whole new DSL like <code class="inline">Sass</code>
.
</p>
</body>
</html>