summaryrefslogtreecommitdiffstats
path: root/_writing/editor.html
blob: 07f53a5ad2baf8e5ce97a4ad9aac5b0806bc47dc (plain)
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>writing desk</title>
<link rel="icon" href="/favicon.ico">
<style>
@font-face{font-family:"Fira Code";font-weight:400;font-display:swap;src:url("/fira/woff2/FiraCode-Regular.woff2") format("woff2");}
@font-face{font-family:"Fira Code";font-weight:500;font-display:swap;src:url("/fira/woff2/FiraCode-Medium.woff2") format("woff2");}
@font-face{font-family:"Fira Code";font-weight:700;font-display:swap;src:url("/fira/woff2/FiraCode-Bold.woff2") format("woff2");}

:root{
  --bg:#1d2021; --bg1:#282828; --bg2:#32302f; --bg3:#3c3836;
  --fg:#ebdbb2; --fg-dim:#a89984; --fg-faint:#7c6f64;
  --red:#fb4934; --green:#b8bb26; --yellow:#fabd2f;
  --blue:#83a598; --purple:#d3869b; --aqua:#8ec07c; --orange:#fe8019;
}
*{box-sizing:border-box;}
html,body{height:100%;}
body{
  margin:0; background:var(--bg); color:var(--fg);
  font:13px/1.6 "Fira Code",ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
  display:grid; grid-template-rows:2.6rem 1fr 1.7rem; overflow:hidden;
}
button{font:inherit; cursor:pointer;}
::selection{background:var(--yellow); color:var(--bg);}

/* ---------- top bar ---------- */
.bar{
  display:flex; align-items:center; gap:.5rem; padding:0 .8rem;
  background:var(--bg1); border-bottom:1px solid var(--bg3); min-width:0;
}
.bar__brand{color:var(--fg-faint); font-size:.78rem; white-space:nowrap; margin-right:.4rem;}
.bar__spacer{flex:1 1 auto;}
.btn{
  appearance:none; background:var(--bg2); border:1px solid var(--bg3); color:var(--fg-dim);
  font-size:.75rem; padding:.28rem .8rem; white-space:nowrap;
}
.btn:hover{background:var(--bg3); color:var(--fg);}
.btn:focus-visible{outline:2px solid var(--aqua); outline-offset:1px;}
.btn--go{border-color:var(--green); color:var(--green);}
.btn--go:hover{background:var(--green); color:var(--bg);}
.btn--warn{border-color:var(--bg3); color:var(--fg-faint);}
.btn--warn:hover{background:var(--red); border-color:var(--red); color:var(--bg);}
.btn[disabled]{opacity:.35; pointer-events:none;}

.pill{font-size:.68rem; letter-spacing:.08em; text-transform:uppercase; padding:.15rem .5rem; border:1px solid;}
.pill--draft{color:var(--orange); border-color:var(--orange);}
.pill--published{color:var(--green); border-color:var(--green);}
.dot{color:var(--yellow); font-size:1.1rem; line-height:1; width:.7rem;}

/* ---------- panes ---------- */
.panes{display:grid; grid-template-columns:15rem 1fr 1fr; min-height:0;}
.pane{min-width:0; min-height:0; display:flex; flex-direction:column; border-right:1px solid var(--bg3);}
.pane:last-child{border-right:0;}
.pane__head{
  flex:0 0 auto; display:flex; align-items:center; gap:.5rem;
  background:var(--bg2); border-bottom:1px solid var(--bg3); padding:.3rem .7rem;
  font-size:.68rem; letter-spacing:.09em; text-transform:uppercase; color:var(--fg-faint);
}
.pane__head b{color:var(--yellow); font-weight:500; letter-spacing:.09em;}
.pane__head .right{margin-left:auto; text-transform:none; letter-spacing:0;}

/* ---------- sidebar ---------- */
.side{overflow-y:auto; padding-bottom:1rem;}
.side__group{color:var(--fg-faint); font-size:.65rem; letter-spacing:.1em; text-transform:uppercase; padding:.9rem .8rem .3rem;}
.item{
  display:block; width:100%; text-align:left; background:none; border:0;
  color:var(--fg-dim); padding:.4rem .8rem; border-left:2px solid transparent;
}
.item:hover{background:var(--bg1); color:var(--fg);}
.item.is-active{background:var(--bg2); color:var(--fg); border-left-color:var(--yellow);}
.item__title{display:block; font-size:.8rem; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;}
.item__meta{display:block; font-size:.65rem; color:var(--fg-faint);}
.side__empty{color:var(--fg-faint); font-size:.72rem; padding:.4rem .8rem;}

/* ---------- editor ---------- */
.meta{flex:0 0 auto; padding:.7rem .9rem .55rem; border-bottom:1px solid var(--bg3); background:var(--bg);}
.meta input{
  background:none; border:0; outline:none; color:var(--fg); font:inherit; width:100%; padding:0;
}
.meta input::placeholder{color:var(--fg-faint);}
.meta__title{font-size:1.05rem; font-weight:700; margin-bottom:.35rem;}
.meta__row{display:flex; gap:.9rem; flex-wrap:wrap; align-items:baseline; font-size:.72rem; color:var(--fg-faint);}
.meta__field{display:flex; align-items:baseline; gap:.35rem; min-width:0;}
.meta__field label{flex:0 0 auto;}
.meta__field input{font-size:.72rem; color:var(--fg-dim); width:auto; min-width:4rem;}
.meta__field--grow{flex:1 1 8rem;}
.meta__field--grow input{width:100%;}
.meta__field input:focus{color:var(--aqua);}
.linkbtn{appearance:none; background:none; border:0; padding:0; color:var(--fg-dim); font-size:.72rem;}
.linkbtn:hover,.linkbtn:focus-visible{color:var(--aqua); outline:none;}
.linkbtn--x:hover,.linkbtn--x:focus-visible{color:var(--red);}
.linkbtn[disabled]{opacity:.35; pointer-events:none;}

textarea{
  flex:1 1 auto; min-height:0; width:100%; resize:none;
  background:var(--bg); border:0; outline:none; color:var(--fg);
  font:inherit; font-size:.84rem; line-height:1.75; padding:1rem 1.1rem;
  tab-size:2;
}
textarea::placeholder{color:var(--fg-faint);}
textarea::-webkit-scrollbar,.side::-webkit-scrollbar{width:10px;}
textarea::-webkit-scrollbar-thumb,.side::-webkit-scrollbar-thumb{background:var(--bg3);}

/* ---------- preview ---------- */
.preview{flex:1 1 auto; min-height:0; border:0; width:100%; background:var(--bg);}

/* ---------- status ---------- */
.foot{
  display:flex; align-items:center; gap:1.1rem; padding:0 .8rem;
  background:var(--bg2); border-top:1px solid var(--bg3);
  font-size:.68rem; color:var(--fg-faint); white-space:nowrap; overflow:hidden;
}
.foot kbd{color:var(--yellow); font:inherit;}
.foot__msg{margin-left:auto; color:var(--aqua); overflow:hidden; text-overflow:ellipsis;}
.foot__msg.is-err{color:var(--red);}

/* ---------- history ---------- */
.sheet{
  position:fixed; inset:0; background:rgba(0,0,0,.55); z-index:20;
  display:none; align-items:flex-start; justify-content:center; padding:4rem 1rem;
}
.sheet.is-open{display:flex;}
.sheet__box{
  background:var(--bg1); border:1px solid var(--bg3); width:min(30rem,100%);
  max-height:70vh; display:flex; flex-direction:column;
}
.sheet__head{
  background:var(--bg2); border-bottom:1px solid var(--bg3); padding:.4rem .8rem;
  font-size:.7rem; letter-spacing:.09em; text-transform:uppercase; color:var(--fg-faint);
  display:flex; align-items:center; gap:.6rem;
}
.sheet__head b{color:var(--yellow); font-weight:500; letter-spacing:.09em;}
.sheet__head .right{margin-left:auto; text-transform:none; letter-spacing:0;}
.sheet__list{overflow-y:auto;}
.sheet__note{color:var(--fg-faint); font-size:.72rem; padding:.9rem .8rem;}
.snap{
  display:flex; width:100%; text-align:left; background:none; border:0;
  border-bottom:1px solid var(--bg3); color:var(--fg-dim);
  padding:.5rem .8rem; gap:.8rem; align-items:baseline;
}
.snap:last-child{border-bottom:0;}
.snap:hover{background:var(--bg2); color:var(--fg);}
.snap__when{font-size:.8rem;}
.snap__size{margin-left:auto; font-size:.68rem; color:var(--fg-faint);}
.snap--current .snap__when{color:var(--green);}

/* ---------- syntax reference ---------- */
#syntaxSheet{padding-top:2rem;}
#syntaxSheet .sheet__box{width:min(40rem,100%); max-height:calc(100vh - 4rem);}
.headbtn{
  appearance:none; background:none; border:0; padding:0;
  color:var(--fg-faint); font:inherit; font-size:.68rem;
  letter-spacing:.09em; text-transform:uppercase;
}
.headbtn:hover,.headbtn:focus-visible{color:var(--aqua); outline:none;}
.ref{overflow-y:auto;}
.ref__row{
  display:grid; grid-template-columns:minmax(11rem,4fr) 5fr; gap:1rem;
  padding:.42rem .8rem; border-bottom:1px solid var(--bg2); align-items:baseline;
}
.ref__row:last-child{border-bottom:0;}
.ref__md{color:var(--yellow); font-size:.78rem; white-space:pre-wrap;}
.ref__what{color:var(--fg-dim); font-size:.74rem;}
.ref__group{
  padding:.7rem .8rem .25rem; color:var(--fg-faint); font-size:.65rem;
  letter-spacing:.1em; text-transform:uppercase;
}

.empty{
  flex:1 1 auto; display:flex; flex-direction:column; align-items:center; justify-content:center;
  gap:.6rem; color:var(--fg-faint); font-size:.8rem; text-align:center; padding:2rem;
}

@media (max-width:1100px){
  .panes{grid-template-columns:11rem 1fr 1fr;}
}
@media (max-width:820px){
  .panes{grid-template-columns:1fr;}
  .pane--side,.pane--preview{display:none;}
}
</style>
</head>
<body>

<header class="bar">
  <span class="bar__brand">~/writing</span>
  <span class="dot" id="dirty" title="unsaved changes"></span>
  <span class="pill pill--draft" id="statusPill">draft</span>
  <span class="bar__spacer"></span>
  <button class="btn" id="btnHistory" type="button">history</button>
  <button class="btn" id="btnPreview" type="button">open preview</button>
  <button class="btn" id="btnSave" type="button">save</button>
  <button class="btn btn--go" id="btnPublish" type="button">publish</button>
  <button class="btn btn--warn" id="btnDelete" type="button">delete</button>
</header>

<main class="panes">

  <section class="pane pane--side">
    <div class="pane__head"><b>posts</b><span class="right"><button class="btn" id="btnNew" type="button">new</button></span></div>
    <div class="side" id="side"></div>
  </section>

  <section class="pane pane--editor">
    <div class="pane__head"><b>source</b><button class="headbtn" id="btnSyntax" type="button" title="markdown reference (ctrl+/)">syntax?</button><span class="right" id="counts"></span></div>
    <div class="meta">
      <input class="meta__title" id="fTitle" type="text" placeholder="Title" spellcheck="false" autocomplete="off">
      <div class="meta__row">
        <span class="meta__field"><label for="fDate">date</label><input id="fDate" type="date"></span>
        <span class="meta__field meta__field--grow"><label for="fSlug">slug</label><input id="fSlug" type="text" placeholder="auto" spellcheck="false" autocomplete="off"></span>
        <span class="meta__field meta__field--grow"><label for="fTags">tags</label><input id="fTags" type="text" placeholder="agents, tooling" spellcheck="false" autocomplete="off"></span>
        <span class="meta__field"><label for="fCover">cover</label><button class="linkbtn" id="btnCover" type="button" title="5:2 banner — other shapes are centre-cropped to fit">add 5:2</button><button class="linkbtn linkbtn--x" id="btnCoverRemove" type="button" hidden>&times; remove</button><input id="fCover" type="file" accept="image/webp,image/png,image/jpeg,image/gif" hidden></span>
      </div>
    </div>
    <textarea id="body" spellcheck="true" placeholder="Write here. Markdown: # heading, **bold**, `code`, > quote, - list, ![alt](/assets/pic.webp &quot;caption&quot;)"></textarea>
  </section>

  <section class="pane pane--preview">
    <div class="pane__head"><b>preview</b><span class="right" id="previewNote">live</span></div>
    <iframe class="preview" id="preview" title="Live preview"></iframe>
  </section>

</main>

<div class="sheet" id="sheet">
  <div class="sheet__box" role="dialog" aria-modal="true" aria-label="Version history">
    <div class="sheet__head"><b>history</b><span class="right"><button class="btn" id="btnCloseHistory" type="button">close</button></span></div>
    <div class="sheet__list" id="snapList"></div>
    <p class="sheet__note">Every save that changed something is kept here, newest first. Opening one loads it into the editor without overwriting anything &mdash; save to keep it.</p>
  </div>
</div>

<div class="sheet" id="syntaxSheet">
  <div class="sheet__box" role="dialog" aria-modal="true" aria-label="Markdown reference">
    <div class="sheet__head"><b>markdown</b><span class="right"><button class="btn" id="btnCloseSyntax" type="button">close</button></span></div>
    <div class="ref">
      <div class="ref__group">structure</div>
      <div class="ref__row"><span class="ref__md"># Big heading</span><span class="ref__what">section heading &mdash; more #, smaller heading (up to ####)</span></div>
      <div class="ref__row"><span class="ref__md">---</span><span class="ref__what">divider line between sections</span></div>
      <div class="ref__row"><span class="ref__md">&gt; a quote</span><span class="ref__what">pulled-out quote block</span></div>
      <div class="ref__row"><span class="ref__md">- first thing</span><span class="ref__what">bullet list, one per line</span></div>
      <div class="ref__row"><span class="ref__md">1. first step</span><span class="ref__what">numbered list, one per line</span></div>
      <div class="ref__group">inside a sentence</div>
      <div class="ref__row"><span class="ref__md">**bold**</span><span class="ref__what">bold &mdash; ctrl+b</span></div>
      <div class="ref__row"><span class="ref__md">*italic*</span><span class="ref__what">italic, shown underlined (the font has no italics) &mdash; ctrl+i</span></div>
      <div class="ref__row"><span class="ref__md">~~crossed out~~</span><span class="ref__what">struck through &mdash; ctrl+shift+x</span></div>
      <div class="ref__row"><span class="ref__md">`code`</span><span class="ref__what">short code or a literal term &mdash; ctrl+e</span></div>
      <div class="ref__row"><span class="ref__md">[read this](https://&hellip;)</span><span class="ref__what">link &mdash; ctrl+k; pasting a bare URL also works</span></div>
      <div class="ref__group">media &amp; code</div>
      <div class="ref__row"><span class="ref__md">![what it shows](/assets/pic.webp "caption")</span><span class="ref__what">image on its own line, with the caption shown under it</span></div>
      <div class="ref__row"><span class="ref__md">```python
print("hi")
```</span><span class="ref__what">code block &mdash; the word after ``` labels the language, optional</span></div>
    </div>
    <p class="sheet__note"><kbd style="color:var(--yellow)">ctrl</kbd>+<kbd style="color:var(--yellow)">/</kbd> opens and closes this. The formatting keys wrap whatever is selected, and pressing one again takes it back off. The preview pane always shows the truth &mdash; when in doubt, just type it and look right.</p>
  </div>
</div>

<footer class="foot">
  <span><kbd>ctrl</kbd>+<kbd>s</kbd> save</span>
  <span><kbd>ctrl</kbd>+<kbd>b</kbd> <kbd>i</kbd> <kbd>k</kbd> format</span>
  <span><kbd>ctrl</kbd>+<kbd>/</kbd> syntax</span>
  <span>drafts autosave</span>
  <span id="fileHint"></span>
  <span class="foot__msg" id="msg"></span>
</footer>

<script type="module">
import { renderMarkdown, readingTime, excerpt, plainText } from "/lib/markdown.mjs";

const $ = (id) => document.getElementById(id);
const els = {
  side: $("side"), title: $("fTitle"), date: $("fDate"), slug: $("fSlug"), tags: $("fTags"),
  body: $("body"), preview: $("preview"), msg: $("msg"), counts: $("counts"), dirty: $("dirty"),
  pill: $("statusPill"), fileHint: $("fileHint"), previewNote: $("previewNote"),
};

const MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"];
const longDate = (iso) => {
  const m = String(iso || "").match(/^(\d{4})-(\d{2})-(\d{2})/);
  return m ? `${MONTHS[+m[2] - 1]} ${+m[3]}, ${m[1]}` : "";
};
const slugify = (s) =>
  String(s).toLowerCase().normalize("NFKD").replace(new RegExp("[\\u0300-\\u036f]", "g"), "")
    .replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);

// A slug nobody typed: the title's own, or the "untitled" a body-first draft
// starts with, either one possibly suffixed -2, -3 to dodge a clash. A draft
// leaves these out of the slug field so the slug keeps following the title.
const isAutoSlug = (slug, title) =>
  new RegExp(`^(${slugify(title) || "untitled"}|untitled)(-\\d+)?$`).test(slug);

let state = { slug: "", status: "draft", savedSlug: "", savedStatus: "", dirty: false, today: "", cover: null };
let posts = [];
let msgTimer, previewTimer, autosaveTimer;

function flash(text, isError = false) {
  els.msg.textContent = text;
  els.msg.classList.toggle("is-err", isError);
  clearTimeout(msgTimer);
  msgTimer = setTimeout(() => { els.msg.textContent = ""; els.msg.classList.remove("is-err"); }, 3200);
}

const api = async (url, options) => {
  const res = await fetch(url, options);
  if (!res.ok) throw new Error(await res.text());
  return res.json();
};
const post = (url, data) =>
  api(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) });

/* ---------- preview ---------- */

// The iframe loads the real post stylesheet, so what shows here is the same
// CSS the published page uses rather than an approximation of it.
const PREVIEW_SHELL = `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8">
<link rel="stylesheet" href="/style.css">
<link rel="stylesheet" href="/blog.css">
<style>body{overflow:auto;display:block;height:auto;}.main{overflow:visible;}.post{padding-top:1.6rem;}</style>
</head><body><div class="main"><article class="post">
<img class="post__cover" id="pCover" alt="" width="1000" height="400" hidden>
<h1 class="post__title" id="pTitle"></h1>
<p class="post__meta" id="pMeta"></p>
<hr class="post__rule">
<div class="prose" id="pBody"></div>
</article></div></body></html>`;

let previewReady = false;
els.preview.addEventListener("load", () => { previewReady = true; renderPreview(); });
els.preview.srcdoc = PREVIEW_SHELL;

function renderPreview() {
  if (!previewReady) return;
  const doc = els.preview.contentDocument;
  if (!doc || !doc.getElementById("pBody")) return;

  const body = els.body.value;
  const cover = doc.getElementById("pCover");
  cover.hidden = !state.cover;
  // Only touch src on a real change, or every keystroke refetches the image.
  if (state.cover && cover.getAttribute("src") !== state.cover) cover.src = state.cover;
  doc.getElementById("pTitle").textContent = els.title.value || "Untitled";
  const tags = els.tags.value.split(",").map((t) => t.trim()).filter(Boolean);
  doc.getElementById("pMeta").innerHTML =
    `<span>${longDate(els.date.value) || "no date"}</span><span class="sep">&middot;</span>` +
    `<span>${readingTime(body)} min read</span>` +
    (tags.length ? `<span class="sep">&middot;</span><span class="post__tags">` +
      tags.map((t) => `<span class="post__tag">#${t}</span>`).join("") + `</span>` : "");
  doc.getElementById("pBody").innerHTML = renderMarkdown(body);
}

function queuePreview() {
  clearTimeout(previewTimer);
  previewTimer = setTimeout(renderPreview, 90);
}

/* ---------- sidebar ---------- */

function renderSidebar() {
  const groups = [
    ["drafts", posts.filter((p) => p.status === "draft")],
    ["published", posts.filter((p) => p.status === "published")],
  ];
  els.side.innerHTML = groups
    .map(([label, list]) => {
      const rows = list.length
        ? list
            .map((p) => {
              const active = p.slug === state.savedSlug && p.status === state.savedStatus ? " is-active" : "";
              return `<button class="item${active}" data-slug="${p.slug}" type="button">
                <span class="item__title">${p.title.replace(/</g, "&lt;")}</span>
                <span class="item__meta">${p.date || "no date"} &middot; ${p.minutes} min</span>
              </button>`;
            })
            .join("")
        : `<p class="side__empty">nothing yet</p>`;
      return `<div class="side__group">${label} (${list.length})</div>${rows}`;
    })
    .join("");

  els.side.querySelectorAll(".item").forEach((btn) => {
    btn.addEventListener("click", () => openPost(btn.dataset.slug));
  });
}

/* ---------- document state ---------- */

function currentDoc() {
  const slug = slugify(els.slug.value || els.title.value) || "untitled";
  return {
    slug,
    status: state.status,
    title: els.title.value.trim() || "Untitled",
    date: els.date.value || state.today,
    description: excerpt(els.body.value),
    tags: els.tags.value.split(",").map((t) => t.trim()).filter(Boolean),
    body: els.body.value,
    previousSlug: state.savedSlug,
    previousStatus: state.savedStatus,
  };
}

function setDirty(on) {
  state.dirty = on;
  els.dirty.textContent = on ? "●" : "";
}

function syncChrome() {
  const slug = slugify(els.slug.value || els.title.value) || "untitled";
  els.pill.textContent = state.status;
  els.pill.className = "pill pill--" + state.status;
  els.fileHint.textContent = `_writing/${state.status === "draft" ? "drafts" : "posts"}/${slug}.md`;
  els.slug.placeholder = slugify(els.title.value) || "auto";
  const words = plainText(els.body.value).split(" ").filter(Boolean).length;
  els.counts.textContent = `${words} words · ${readingTime(els.body.value)} min`;
  els.previewNote.textContent = state.status === "draft" ? "live · draft" : "live";
  $("btnPublish").textContent = state.status === "draft" ? "publish" : "rebuild";
  $("btnDelete").disabled = !state.savedSlug;
  $("btnHistory").disabled = !state.savedSlug;
  $("btnPreview").disabled = !state.savedSlug;
}

function onEdit() {
  setDirty(true);
  syncChrome();
  queuePreview();
  clearTimeout(autosaveTimer);
  // Drafts save themselves so nothing is ever lost mid-thought. A published
  // post only changes when you say so.
  if (state.status === "draft") autosaveTimer = setTimeout(() => save({ quiet: true }), 1600);
}

[els.title, els.date, els.slug, els.tags, els.body].forEach((el) => {
  el.addEventListener("input", onEdit);
});

// Tab indents rather than escaping the writing area.
els.body.addEventListener("keydown", (e) => {
  if (e.key !== "Tab") return;
  e.preventDefault();
  const { selectionStart: a, selectionEnd: b, value } = els.body;
  els.body.value = value.slice(0, a) + "  " + value.slice(b);
  els.body.selectionStart = els.body.selectionEnd = a + 2;
  onEdit();
});

/* ---------- formatting shortcuts ---------- */

// Every edit goes through execCommand so ctrl+z still undoes it. Assigning
// .value would wipe the textarea's undo history.
function replaceRange(a, b, text, selA, selB) {
  const ta = els.body;
  ta.setSelectionRange(a, b);
  if (!document.execCommand(text ? "insertText" : "delete", false, text)) {
    ta.setRangeText(text, a, b);
    onEdit();
  }
  ta.setSelectionRange(selA, selB);
}

// How many ch sit in a row from i, walking left (dir < 0) or right.
function runAt(s, i, dir, ch) {
  let n = 0;
  while (s[dir < 0 ? i - 1 - n : i + n] === ch) n++;
  return n;
}

/* Wraps the selection in mark, or unwraps it when the marks are already there
   (selected along with the text, or sitting just outside it), so a second
   press undoes the first like in any editor. */
function toggleMark(mark) {
  const v = els.body.value, L = mark.length, ch = mark[0];
  let a = els.body.selectionStart, b = els.body.selectionEnd;
  // A double-click often grabs a trailing space, and "**word **" is not bold.
  while (a < b && /\s/.test(v[a])) a++;
  while (b > a && /\s/.test(v[b - 1])) b--;
  // One star is italic, two bold, three both — so for stars the run length
  // decides which mark is present, not just whether a star is there.
  const has = (run) => (ch === "*" ? run === L || run === 3 : run >= L);

  if (b - a >= 2 * L && has(Math.min(runAt(v, a, 1, ch), runAt(v, b, -1, ch)))) {
    return replaceRange(a, b, v.slice(a + L, b - L), a, b - 2 * L);
  }
  if (has(Math.min(runAt(v, a, -1, ch), runAt(v, b, 1, ch)))) {
    return replaceRange(a - L, b + L, v.slice(a, b), a - L, b - L);
  }
  replaceRange(a, b, mark + v.slice(a, b) + mark, a + L, b + L);
}

function insertLink() {
  const a = els.body.selectionStart, b = els.body.selectionEnd;
  const sel = els.body.value.slice(a, b);
  // A selected URL becomes the target and the caret waits for the link text.
  if (/^https?:\/\/\S+$/.test(sel)) return replaceRange(a, b, `[](${sel})`, a + 1, a + 1);
  const caret = sel ? a + sel.length + 3 : a + 1;
  replaceRange(a, b, `[${sel}]()`, caret, caret);
}

const SHORTCUTS = {
  b: () => toggleMark("**"),
  i: () => toggleMark("*"),
  e: () => toggleMark("`"),
  k: insertLink,
  "shift+x": () => toggleMark("~~"),
};

els.body.addEventListener("keydown", (e) => {
  if (!(e.ctrlKey || e.metaKey) || e.altKey) return;
  const action = SHORTCUTS[(e.shiftKey ? "shift+" : "") + e.key.toLowerCase()];
  if (!action) return;
  e.preventDefault();
  action();
});

/* ---------- actions ---------- */

async function refresh(data) {
  posts = data.posts || posts;
  if (data.today) state.today = data.today;
  // The cover URL follows the slug, so a rename or publish hands back a new one.
  const cur = posts.find((p) => p.slug === state.savedSlug && p.status === state.savedStatus);
  setCover(cur ? cur.cover : null);
  renderSidebar();
  syncChrome();
}

async function save({ quiet = false } = {}) {
  const doc = currentDoc();
  if (!doc.title.trim() && !doc.body.trim()) return;
  try {
    const data = await post("/api/save", doc);
    state.slug = state.savedSlug = data.slug;
    state.savedStatus = doc.status;
    // Only an explicit slug gets pinned. Pinning the auto one here would freeze
    // a body-first draft at "untitled" before it ever had a title.
    if (els.slug.value || doc.status === "published") els.slug.value = data.slug;
    setDirty(false);
    await refresh(data);
    if (!quiet) flash("saved");
    else els.msg.textContent = "autosaved";
  } catch (err) {
    flash(String(err.message || err), true);
  }
}

async function openPost(slug) {
  if (state.dirty) await save({ quiet: true });
  try {
    const data = await api(`/api/post?slug=${encodeURIComponent(slug)}`);
    els.title.value = data.title;
    els.date.value = data.date;
    // A published slug is a live URL and stays put. A draft's auto slug is
    // left unpinned, so retitling it still renames the file.
    els.slug.value = data.status === "draft" && isAutoSlug(data.slug, data.title) ? "" : data.slug;
    els.tags.value = (data.tags || []).join(", ");
    els.body.value = data.body;
    state.status = data.status;
    state.slug = state.savedSlug = data.slug;
    state.savedStatus = data.status;
    setCover(data.cover);
    setDirty(false);
    renderSidebar();
    syncChrome();
    renderPreview();
    els.body.scrollTop = 0;
  } catch (err) {
    flash(String(err.message || err), true);
  }
}

function newPost() {
  els.title.value = "";
  els.date.value = state.today;
  els.slug.value = "";
  els.tags.value = "";
  els.body.value = "";
  state.status = "draft";
  state.slug = state.savedSlug = "";
  state.savedStatus = "";
  setCover(null);
  setDirty(false);
  renderSidebar();
  syncChrome();
  renderPreview();
  els.title.focus();
}

/* ---------- cover ---------- */

const COVER_RATIO = 5 / 2;
const COVER_MAX_W = 2000;

function setCover(url) {
  state.cover = url || null;
  $("btnCover").textContent = state.cover ? "replace" : "add 5:2";
  $("btnCoverRemove").hidden = !state.cover;
  renderPreview();
}

/* A 5:2 image of sane size goes up untouched. Anything else is centre-cropped
   to 5:2 and scaled down here, so the file on the site is exactly the banner
   that shows. GIFs pass through as-is — redrawing one would freeze it — and the
   page's CSS crops them instead. */
async function prepareCover(file) {
  const ext = { "image/webp": "webp", "image/png": "png", "image/jpeg": "jpg", "image/gif": "gif" }[file.type];
  if (!ext) throw new Error("cover must be webp, png, jpg or gif");
  const img = await createImageBitmap(file);
  const { width: w, height: h } = img;
  const isFiveTwo = Math.abs(w / h - COVER_RATIO) < 0.01;
  const fits = isFiveTwo && w <= COVER_MAX_W;
  if (fits || ext === "gif") {
    img.close();
    return { blob: file, ext, note: fits ? `${w}×${h}` : `${w}×${h}, not 5:2 — the page crops it` };
  }

  const cw = Math.min(w, Math.round(h * COVER_RATIO));
  const ch = Math.round(cw / COVER_RATIO);
  const outW = Math.min(cw, COVER_MAX_W);
  const outH = Math.round(outW / COVER_RATIO);
  const canvas = document.createElement("canvas");
  canvas.width = outW;
  canvas.height = outH;
  const ctx = canvas.getContext("2d");
  ctx.imageSmoothingQuality = "high";
  ctx.drawImage(img, (w - cw) / 2, (h - ch) / 2, cw, ch, 0, 0, outW, outH);
  img.close();
  const blob = await new Promise((r) => canvas.toBlob(r, "image/webp", 0.9));
  // Browsers that cannot encode webp quietly hand back a png instead.
  const outExt = blob.type === "image/webp" ? "webp" : "png";
  return { blob, ext: outExt, note: `${w}×${h}${isFiveTwo ? "resized" : "cropped"} to ${outW}×${outH}` };
}

async function uploadCover(file) {
  if (!state.savedSlug) await save({ quiet: true });
  if (!state.savedSlug) return flash("write a title first", true);
  try {
    flash("processing cover…");
    const { blob, ext, note } = await prepareCover(file);
    const q = new URLSearchParams({ slug: state.savedSlug, status: state.savedStatus, ext });
    const data = await api(`/api/cover?${q}`, { method: "POST", body: blob });
    await refresh(data);
    flash(`cover set · ${note}${state.savedStatus === "published" ? " · rebuild to ship it" : ""}`);
  } catch (err) {
    flash(String(err.message || err), true);
  }
}

$("btnCover").addEventListener("click", () => $("fCover").click());
$("fCover").addEventListener("change", (e) => {
  const file = e.target.files[0];
  e.target.value = "";
  if (file) uploadCover(file);
});
$("btnCoverRemove").addEventListener("click", async () => {
  if (!state.savedSlug || !confirm("Remove the cover image?")) return;
  try {
    const data = await post("/api/cover/remove", { slug: state.savedSlug, status: state.savedStatus });
    await refresh(data);
    flash(state.savedStatus === "published" ? "cover removed · rebuild to ship it" : "cover removed");
  } catch (err) {
    flash(String(err.message || err), true);
  }
});

$("btnNew").addEventListener("click", newPost);
$("btnSave").addEventListener("click", () => save());

$("btnPublish").addEventListener("click", async () => {
  const doc = currentDoc();
  if (!doc.title.trim()) return flash("give it a title first", true);
  if (state.status === "draft" && !confirm(`Publish "${doc.title}"? It goes live on the site right away.`)) return;
  try {
    const data = await post("/api/publish", doc);
    state.status = "published";
    state.slug = state.savedSlug = data.slug;
    state.savedStatus = "published";
    els.slug.value = data.slug;
    setDirty(false);
    await refresh(data);
    flash(data.log || "published");
  } catch (err) {
    flash(String(err.message || err), true);
  }
});

$("btnDelete").addEventListener("click", async () => {
  if (!state.savedSlug) return;
  const name = els.title.value || state.savedSlug;
  const warning = state.savedStatus === "published"
    ? `Delete "${name}" permanently? It comes off the live site too.`
    : `Delete "${name}" permanently?`;
  if (!confirm(warning)) return;
  try {
    const data = await post("/api/delete", { slug: state.savedSlug, status: state.savedStatus, title: name });
    await refresh(data);
    newPost();
    flash(data.log || "deleted");
  } catch (err) {
    flash(String(err.message || err), true);
  }
});

$("btnPreview").addEventListener("click", async () => {
  if (state.dirty) await save({ quiet: true });
  window.open(`/preview/${state.savedSlug}/`, "_blank", "noopener");
});

/* ---------- history ---------- */

const sheet = $("sheet");
const closeHistory = () => sheet.classList.remove("is-open");

async function openHistory() {
  if (!state.savedSlug) return flash("save it once first", true);
  if (state.dirty) await save({ quiet: true });
  try {
    const { entries } = await api(`/api/history?slug=${encodeURIComponent(state.savedSlug)}`);
    const list = $("snapList");
    list.innerHTML = entries.length
      ? entries
          .map(
            (e, i) => `<button class="snap${i === 0 ? " snap--current" : ""}" data-stamp="${e.stamp}" type="button">
              <span class="snap__when">${e.label}${i === 0 ? " · current" : ""}</span>
              <span class="snap__size">${(e.bytes / 1024).toFixed(1)} kB</span>
            </button>`
          )
          .join("")
      : `<p class="sheet__note">Nothing yet. The first save starts the history.</p>`;
    list.querySelectorAll(".snap").forEach((btn) => {
      btn.addEventListener("click", () => restore(btn.dataset.stamp));
    });
    sheet.classList.add("is-open");
  } catch (err) {
    flash(String(err.message || err), true);
  }
}

async function restore(stamp) {
  try {
    const data = await api(
      `/api/history/entry?slug=${encodeURIComponent(state.savedSlug)}&stamp=${encodeURIComponent(stamp)}`
    );
    els.title.value = data.title;
    els.date.value = data.date;
    els.tags.value = (data.tags || []).join(", ");
    els.body.value = data.body;
    // Left dirty on purpose: nothing is committed to disk until you save, so a
    // wrong pick costs nothing.
    setDirty(true);
    syncChrome();
    renderPreview();
    closeHistory();
    flash("loaded — save to keep it");
  } catch (err) {
    flash(String(err.message || err), true);
  }
}

$("btnHistory").addEventListener("click", openHistory);
$("btnCloseHistory").addEventListener("click", closeHistory);
sheet.addEventListener("click", (e) => {
  if (e.target === sheet) closeHistory();
});

/* ---------- syntax reference ---------- */

const syntaxSheet = $("syntaxSheet");
const toggleSyntax = () => syntaxSheet.classList.toggle("is-open");
$("btnSyntax").addEventListener("click", toggleSyntax);
$("btnCloseSyntax").addEventListener("click", toggleSyntax);
syntaxSheet.addEventListener("click", (e) => {
  if (e.target === syntaxSheet) toggleSyntax();
});

document.addEventListener("keydown", (e) => {
  if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "s") {
    e.preventDefault();
    save();
    return;
  }
  if ((e.ctrlKey || e.metaKey) && e.key === "/") {
    e.preventDefault();
    toggleSyntax();
    return;
  }
  if (e.key === "Escape") {
    if (sheet.classList.contains("is-open")) closeHistory();
    if (syntaxSheet.classList.contains("is-open")) syntaxSheet.classList.remove("is-open");
  }
});

window.addEventListener("beforeunload", (e) => {
  if (!state.dirty) return;
  e.preventDefault();
  e.returnValue = "";
});

/* ---------- boot ---------- */

(async () => {
  const data = await api("/api/list");
  state.today = data.today;
  posts = data.posts;
  renderSidebar();
  if (posts.length) await openPost(posts.find((p) => p.status === "draft")?.slug || posts[0].slug);
  else newPost();
})();
</script>
</body>
</html>