Repository navigation
Expand file tree
/
Copy pathedit.html
More file actions
793 lines (692 loc) · 25.9 KB
/
Copy pathedit.html
File metadata and controls
793 lines (692 loc) · 25.9 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>Write · Telepatch</title>
<style>
/* ---------------------------------------------------------------
The editor. Deliberately paler than the published site: a white
sheet under the same bar, so writing feels like a different room
from reading. Only the tags Telegraph accepts are reachable.
----------------------------------------------------------------*/
:root{
--paper:#FFFFFF;
--ink:#14181A;
--graphite:#5C6562;
--hair:#DCDFDA;
--patch:#1C5A4E;
--lamp:#C4342A;
--serif:Georgia,"Iowan Old Style","Palatino Linotype",Palatino,serif;
--sans:system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
--mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,monospace;
--col:52rem;
--pad:1.5rem;
}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%;overflow-y:scroll;scrollbar-gutter:stable}
body{
margin:0;background:var(--paper);color:var(--ink);
font-family:var(--serif);font-size:17px;line-height:1.6;
display:flex;flex-direction:column;min-height:100vh;min-height:100dvh;
}
a{color:var(--patch)}
:focus-visible{outline:2px solid var(--lamp);outline-offset:3px}
.col{width:min(100%,var(--col));margin-inline:auto;padding-inline:var(--pad)}
/* ---- the same bar as the site ---- */
.bar{
position:sticky;top:0;z-index:20;background:var(--paper);
border-bottom:1px solid var(--hair);
}
.bar .col{
display:flex;align-items:baseline;gap:1rem;padding-block:.6rem;
}
.brand{
font-family:var(--serif);font-size:1rem;font-weight:700;
letter-spacing:-.01em;color:var(--ink);text-decoration:none;white-space:nowrap;
}
.who{
font-family:var(--mono);font-size:.7rem;text-transform:uppercase;
letter-spacing:.08em;color:var(--graphite);
flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;
}
.go{
font-family:var(--mono);font-size:.7rem;text-transform:uppercase;
letter-spacing:.08em;background:none;border:0;padding:0;cursor:pointer;
color:var(--patch);white-space:nowrap;
}
.go:hover{color:var(--lamp)}
.go[disabled]{color:var(--graphite);cursor:default}
/* ---- toolbar: exactly what Telegraph accepts, nothing more ---- */
.tools{
position:sticky;top:2.6rem;z-index:19;background:var(--paper);
border-bottom:1px solid var(--hair);
}
.tools .col{display:flex;flex-wrap:wrap;gap:.15rem;padding-block:.4rem}
.tools button{
font-family:var(--mono);font-size:.7rem;
background:none;border:0;border-radius:3px;padding:.3rem .45rem;
color:var(--graphite);cursor:pointer;line-height:1;
}
.tools button:hover{background:#F1F3EF;color:var(--ink)}
.tools .sep{width:1px;background:var(--hair);margin:.2rem .35rem}
.tools b{font-weight:700}.tools i{font-style:italic}
.tools s{text-decoration:line-through}.tools u{text-decoration:underline}
main{flex:1 0 auto;padding-block:2.2rem 6rem}
/* ---- fields ---- */
[contenteditable]{outline:none}
[contenteditable]:empty:before{
content:attr(data-ph);color:#AFB5AF;pointer-events:none;
}
#title{
font-size:2.3rem;line-height:1.12;font-weight:700;letter-spacing:-.015em;
margin:0 0 .5rem;
}
#cats{
font-family:var(--mono);font-size:.7rem;text-transform:uppercase;
letter-spacing:.08em;color:var(--graphite);margin:0 0 1.4rem;
}
/* The overview is the article's intro: a blockquote at the top of the
page, which the site lifts out and sets as a standfirst. */
.ov{
border-left:2px solid var(--hair);padding-left:1.1rem;margin:0 0 1.6rem;
}
.ovlabel{
font-family:var(--mono);font-size:.62rem;text-transform:uppercase;
letter-spacing:.11em;color:var(--graphite);margin:0 0 .3rem;
}
#overview{font-size:1.18rem;line-height:1.55;color:var(--graphite);min-height:1.6em}
/* Contents is a preview. It is never stored — the site rebuilds it from
the headings, so what is shown here is what a reader will get. */
.toc{
border-top:1px solid var(--hair);border-bottom:1px solid var(--hair);
padding:.8rem 0 .9rem;margin:0 0 1.6rem;
}
.toc.off{display:none}
.toclabel{
font-family:var(--mono);font-size:.62rem;text-transform:uppercase;
letter-spacing:.11em;color:var(--graphite);margin:0 0 .45rem;
}
.toc ul{list-style:none;margin:0;padding:0}
.toc li{font-size:.96rem;line-height:1.35;margin:.18rem 0}
.toc li.sub{padding-left:1.2rem}
/* The permanent rule. Everything below it is the article. */
.divider{border:0;border-top:2px solid var(--ink);margin:0 0 1.6rem;opacity:.14}
#body{font-size:1.06rem;line-height:1.72;min-height:40vh}
#body p{margin:0 0 1.25rem}
#body h3{font-size:1.45rem;line-height:1.25;margin:2.2rem 0 .7rem}
#body h4{font-size:1.12rem;margin:1.8rem 0 .5rem}
#body blockquote{
margin:1.4rem 0;padding-left:1.1rem;
border-left:2px solid var(--hair);color:var(--graphite);
}
#body pre{
background:#F4F6F3;padding:.9rem;overflow-x:auto;
font-family:var(--mono);font-size:.85rem;
}
#body code{font-family:var(--mono);font-size:.9em;background:#F4F6F3;padding:.1em .3em}
#body ul,#body ol{margin:0 0 1.25rem;padding-left:1.4rem}
#body hr{border:0;border-top:1px solid var(--hair);margin:2.2rem 0}
#body img{max-width:100%;height:auto}
.byline{
font-family:var(--mono);font-size:.7rem;text-transform:uppercase;
letter-spacing:.08em;color:var(--graphite);
margin:0 0 1rem;display:flex;flex-wrap:wrap;gap:.4rem;align-items:baseline;
}
.byline .sep2{opacity:.5}
.byline [contenteditable]{
color:var(--ink);border-bottom:1px dotted var(--hair);min-width:6ch;
}
.byline [contenteditable]:focus{border-bottom-color:var(--patch)}
.mini{
font-family:var(--mono);font-size:.62rem;text-transform:uppercase;
letter-spacing:.08em;background:none;border:0;padding:0;cursor:pointer;
color:var(--graphite);
}
.mini:hover{color:var(--lamp)}
#who{cursor:text;border-bottom:1px dotted transparent}
#who:hover{border-bottom-color:var(--hair)}
#who:focus{outline:none;border-bottom-color:var(--patch);color:var(--ink)}
.drawer{
border-bottom:1px solid var(--hair);background:#FAFBF9;
padding:.9rem var(--pad);margin:0 calc(-1 * var(--pad)) 1.6rem;
}
.drawer h2{
font-family:var(--mono);font-size:.62rem;font-weight:400;
text-transform:uppercase;letter-spacing:.11em;color:var(--graphite);
margin:0 0 .5rem;
}
.drawer ul{list-style:none;margin:0;padding:0}
.drawer li{display:flex;gap:.75rem;align-items:baseline;padding:.25rem 0}
.drawer .t{flex:1;min-width:0;font-size:.98rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.drawer .when{font-family:var(--mono);font-size:.65rem;color:var(--graphite);white-space:nowrap}
.drawer .warn{
font-family:var(--sans);font-size:.75rem;color:var(--graphite);
margin:.7rem 0 0;padding-top:.6rem;border-top:1px solid var(--hair);
}
.note{
font-family:var(--sans);font-size:.8rem;color:var(--graphite);
margin:2.5rem 0 0;padding-top:1rem;border-top:1px solid var(--hair);
}
.note b{color:var(--ink)}
.err{color:var(--lamp)}
.gate{font-family:var(--sans);font-size:.95rem;color:var(--graphite);margin:3rem 0}
@media (max-width:34rem){
:root{--pad:1.1rem}
#title{font-size:1.75rem}
.tools .col{gap:.1rem}
}
</style>
</head>
<body>
<nav class="bar">
<div class="col">
<span class="brand">Telepatch</span>
<span class="who" id="who">…</span>
<button class="go" id="drafts">Drafts</button>
<button class="go" id="save" disabled>Save draft</button>
<button class="go" id="go" disabled>Publish</button>
</div>
</nav>
<div class="tools" id="tools" hidden>
<div class="col">
<button data-cmd="bold" title="Bold"><b>B</b></button>
<button data-cmd="italic" title="Italic"><i>I</i></button>
<button data-cmd="underline" title="Underline"><u>U</u></button>
<button data-cmd="strikeThrough" title="Strikethrough"><s>S</s></button>
<button data-link title="Link">link</button>
<span class="sep"></span>
<button data-block="h3" title="Heading">H3</button>
<button data-block="h4" title="Subheading">H4</button>
<button data-block="blockquote" title="Quote">quote</button>
<button data-block="pre" title="Code block">code</button>
<span class="sep"></span>
<button data-cmd="insertUnorderedList" title="Bulleted list">• list</button>
<button data-cmd="insertOrderedList" title="Numbered list">1. list</button>
<button data-cmd="insertHorizontalRule" title="Divider">rule</button>
<span class="sep"></span>
<button data-block="p" title="Plain paragraph">plain</button>
</div>
</div>
<main class="col" id="main">
<p class="gate" id="gate">Checking your identity…</p>
<div class="drawer" id="drawer" hidden></div>
<div id="sheet" hidden>
<div id="title" contenteditable data-ph="Title"></div>
<p class="byline">
by <span id="by" contenteditable data-ph="author name"></span>
<span class="sep2">·</span>
<span id="byurl" contenteditable data-ph="author link (optional)"></span>
<button class="mini" id="reset" title="Use the account default">reset</button>
</p>
<div id="cats" contenteditable data-ph="categories, comma separated"></div>
<div class="ov">
<p class="ovlabel">Post overview</p>
<div id="overview" contenteditable data-ph="A sentence readers see under the title. Optional."></div>
</div>
<div class="toc off" id="toc">
<p class="toclabel">Contents</p>
<ul id="toclist"></ul>
</div>
<hr class="divider">
<div id="body" contenteditable
data-ph="Write here. Type ## for a heading, ### for a subheading."></div>
<p class="note" id="note"></p>
</div>
</main>
<script>
(() => {
"use strict";
const API = "https://api.telegra.ph";
const SITE = location.href.replace(/edit\.html.*$/, "");
const $ = id => document.getElementById(id);
const el = (t, c, x) => {
const n = document.createElement(t);
if (c) n.className = c;
if (x != null) n.textContent = x;
return n;
};
/* The token rides in the fragment, which browsers never send to a server
and which is stripped from the Referer header. It is still in this
machine's history, which the note at the foot of the page says plainly. */
const parts = decodeURIComponent(location.hash.replace(/^#/, ""))
.split("/").filter(Boolean);
const token = parts[0] || "";
let path = parts[1] || "";
let account = null;
/* Only schemes that cannot execute. Telegraph strips a javascript: href on
its own side, but this editor's address bar holds the access token, so a
link pasted into the Link prompt must never become live script here.
Anything unrecognised is refused rather than guessed at. */
const SAFE_SCHEME = /^(?:https?:|mailto:)/i;
function safeUrl(raw) {
const value = String(raw == null ? "" : raw).trim();
if (!value) return null;
if (SAFE_SCHEME.test(value)) return value;
if (value.startsWith("/")) return "https://telegra.ph" + value;
if (/^[a-z][a-z0-9+.\-]*:/i.test(value)) return null; // some other scheme
return "https://telegra.ph/" + value;
}
async function call(method, params) {
const body = new URLSearchParams(params);
const res = await fetch(API + "/" + method, { method: "POST", body });
const data = await res.json();
if (!data.ok) throw new Error(data.error || "Telegraph refused that");
return data.result;
}
/* ---------- Telegraph's tag list, and nothing else ---------- */
const KEEP = {
B: "b", STRONG: "b", I: "i", EM: "i", U: "u",
S: "s", STRIKE: "s", DEL: "s",
CODE: "code", PRE: "pre", BLOCKQUOTE: "blockquote", ASIDE: "aside",
H1: "h3", H2: "h3", H3: "h3", H4: "h4", H5: "h4", H6: "h4",
UL: "ul", OL: "ol", LI: "li", HR: "hr", BR: "br", A: "a",
P: "p", DIV: "p", FIGURE: "figure", FIGCAPTION: "figcaption", IMG: "img"
};
const BLOCK = new Set(["p","h3","h4","blockquote","pre","ul","ol","hr","figure","aside"]);
function toNodes(root) {
const out = [];
for (const n of root.childNodes) {
if (n.nodeType === 3) { if (n.data) out.push(n.data); continue; }
if (n.nodeType !== 1) continue;
const tag = KEEP[n.tagName];
if (!tag) { out.push(...toNodes(n)); continue; } // span, font, anything else
if (tag === "br" || tag === "hr") { out.push({ tag }); continue; }
const node = { tag };
if (tag === "a") {
const href = safeUrl(n.getAttribute("href"));
if (href) node.attrs = { href };
}
if (tag === "img") {
const src = safeUrl(n.getAttribute("src"));
if (src) node.attrs = { src };
}
const kids = toNodes(n);
if (kids.length) node.children = kids;
out.push(node);
}
return out;
}
/* Loose inline content at the top level becomes a paragraph. */
function asBlocks(nodes) {
const out = [];
let buf = [];
const flush = () => {
if (buf.some(x => typeof x !== "string" || x.trim())) {
out.push({ tag: "p", children: buf });
}
buf = [];
};
for (const n of nodes) {
if (typeof n !== "string" && BLOCK.has(n.tag)) { flush(); out.push(n); }
else buf.push(n);
}
flush();
return out;
}
const textOf = n =>
typeof n === "string" ? n : (n.children || []).map(textOf).join("");
/* ---------- contents, rebuilt as headings appear ---------- */
function syncToc() {
const heads = [...$("body").querySelectorAll("h3, h4")];
const list = $("toclist");
list.replaceChildren();
for (const h of heads) {
const text = h.textContent.trim();
if (!text) continue;
list.appendChild(el("li", h.tagName === "H4" ? "sub" : null, text));
}
$("toc").classList.toggle("off", list.children.length < 2);
}
/* ---------- editing ---------- */
const cmd = (name, value) => {
document.execCommand(name, false, value || null);
$("body").focus();
syncToc();
};
function currentBlock() {
let n = document.getSelection().anchorNode;
while (n && n !== $("body")) {
if (n.nodeType === 1 && /^(P|DIV|H3|H4|BLOCKQUOTE|PRE|LI)$/.test(n.tagName)) return n;
n = n.parentNode;
}
return null;
}
/* "## " at the start of a line becomes a heading, the same markers the bot
understands, so the two ways of writing agree. */
function autoformat() {
const block = currentBlock();
if (!block) return;
const m = /^(#{1,3})\s/.exec(block.textContent);
if (!m) return;
const tag = m[1].length === 3 ? "h4" : "h3";
block.textContent = block.textContent.slice(m[0].length);
document.execCommand("formatBlock", false, tag);
const range = document.createRange();
range.selectNodeContents(currentBlock() || block);
range.collapse(false);
const sel = document.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
/* ---------- drafts ----------
localStorage, keyed by a hash of the token so one browser can hold
drafts for several identities without the token itself being written
down. Durability is genuinely uneven:
- Safari, desktop and iOS, evicts script-written storage after seven
days without a visit. A draft left for a fortnight is gone.
- Private windows clear everything on close.
- Storage is per-origin and per-browser: a draft started on a phone
is not on a laptop.
So drafts are a convenience for the next hour, not a filing cabinet,
and the drawer says so rather than implying otherwise. */
function keyspace(t) {
let h = 5381;
for (let i = 0; i < t.length; i++) h = ((h << 5) + h + t.charCodeAt(i)) | 0;
return "telepatch:" + (h >>> 0).toString(36) + ":";
}
const NS = keyspace(token);
let draftId = null;
function storageOk() {
try {
localStorage.setItem(NS + "probe", "1");
localStorage.removeItem(NS + "probe");
return true;
} catch (err) {
return false; // private mode, quota, or storage disabled outright
}
}
const HAS_STORE = storageOk();
function draftList() {
const out = [];
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i);
if (!k || !k.startsWith(NS) || k === NS + "probe") continue;
try { out.push(JSON.parse(localStorage.getItem(k))); } catch (err) { /* skip */ }
}
return out.sort((a, b) => (b.updated || 0) - (a.updated || 0));
}
function snapshot() {
return {
id: draftId || (draftId = String(Date.now())),
path,
title: $("title").textContent.trim(),
cats: $("cats").textContent.trim(),
by: $("by").textContent.trim(),
byurl: $("byurl").textContent.trim(),
overview: $("overview").innerHTML,
body: $("body").innerHTML,
updated: Date.now()
};
}
function saveDraft(quiet) {
if (!HAS_STORE) { if (!quiet) say("This browser will not store drafts.", true); return; }
const d = snapshot();
if (!d.title && !d.body.trim()) return;
try {
localStorage.setItem(NS + d.id, JSON.stringify(d));
if (!quiet) say("Draft saved in this browser.");
} catch (err) {
say("Could not save the draft — this browser's storage is full.", true);
}
}
function loadDraft(d) {
draftId = d.id;
path = d.path || "";
$("title").textContent = d.title || "";
$("cats").textContent = d.cats || "";
$("by").textContent = d.by || "";
$("byurl").textContent = d.byurl || "";
$("overview").innerHTML = d.overview || "";
$("body").innerHTML = d.body || "";
location.hash = token + (path ? "/" + path : "");
syncToc();
$("drawer").hidden = true;
say("Draft opened.");
}
function when(ms) {
const mins = Math.round((Date.now() - ms) / 60000);
if (mins < 1) return "just now";
if (mins < 60) return mins + "m ago";
const hrs = Math.round(mins / 60);
if (hrs < 24) return hrs + "h ago";
return Math.round(hrs / 24) + "d ago";
}
function toggleDrawer() {
const box = $("drawer");
if (!box.hidden) { box.hidden = true; return; }
box.replaceChildren(el("h2", null, "Drafts in this browser"));
const items = HAS_STORE ? draftList() : [];
if (!items.length) {
box.appendChild(el("p", "warn", HAS_STORE
? "Nothing saved yet."
: "This browser is refusing to store anything — a private window, or storage turned off."));
} else {
const list = el("ul");
for (const d of items) {
const li = el("li");
const open = el("button", "mini", "open");
open.addEventListener("click", () => loadDraft(d));
const drop = el("button", "mini", "delete");
drop.addEventListener("click", () => {
localStorage.removeItem(NS + d.id);
toggleDrawer(); toggleDrawer();
});
li.append(
el("span", "t", d.title || "Untitled"),
el("span", "when", when(d.updated)),
open, drop
);
list.appendChild(li);
}
box.appendChild(list);
}
box.appendChild(el("p", "warn",
"Drafts live only in this browser, on this device. Safari clears " +
"script storage after about a week without a visit, and private " +
"windows clear it on close. Publish anything you mean to keep."));
box.hidden = false;
}
/* ---------- publish ---------- */
async function publish() {
const title = $("title").textContent.trim();
if (!title) { say("Give it a title first.", true); $("title").focus(); return; }
const content = [];
const cats = $("cats").textContent.trim().replace(/^[,\s]+|[,\s]+$/g, "");
if (cats) content.push({ tag: "aside", children: [cats] });
const overview = asBlocks(toNodes($("overview")));
if (overview.length && textOf({ children: overview }).trim()) {
content.push({ tag: "blockquote", children: overview.flatMap(b => b.children || []) });
}
const body = asBlocks(toNodes($("body")));
if (!body.length) { say("Nothing written yet.", true); $("body").focus(); return; }
content.push(...body);
$("go").disabled = true;
say("Publishing…");
try {
const params = {
access_token: token,
title,
content: JSON.stringify(content),
author_name: $("by").textContent.trim(),
author_url: safeUrl($("byurl").textContent.trim()) || ""
};
if (path) params.path = path;
const page = await call(path ? "editPage" : "createPage", params);
path = page.path;
if (HAS_STORE && draftId) {
localStorage.removeItem(NS + draftId);
draftId = null;
}
location.hash = token + "/" + path;
const link = el("a", null, page.url);
link.href = page.url; link.target = "_blank"; link.rel = "noopener";
$("note").replaceChildren(
el("b", null, path ? "Published. " : "Published. "), link,
document.createTextNode(" — publishing again updates this page. "),
Object.assign(el("a", null, "Refresh your index"),
{ href: SITE, target: "_blank", rel: "noopener" }),
document.createTextNode(" with /site in Telegram to list it.")
);
} catch (err) {
say(err.message, true);
} finally {
$("go").disabled = false;
}
}
function say(text, bad) {
$("note").replaceChildren(el("span", bad ? "err" : null, text));
}
/* ---------- start ---------- */
async function start() {
if (!/^[A-Za-z0-9_-]{60}$/.test(token)) {
$("gate").textContent =
"This link is missing its access token. Open the editor from Telepatch in Telegram.";
return;
}
try {
account = await call("getAccountInfo", {
access_token: token,
fields: '["short_name","author_name","author_url"]'
});
} catch (err) {
$("gate").innerHTML = "";
$("gate").append(el("span", "err", "That token did not work — " + err.message));
return;
}
$("who").textContent = account.author_name || account.short_name || "";
$("by").textContent = account.author_name || account.short_name || "";
$("byurl").textContent = account.author_url || "";
$("who").setAttribute("contenteditable", "true");
$("who").title = "Click to change the account byline";
$("save").disabled = false;
$("gate").hidden = true;
$("sheet").hidden = false;
$("tools").hidden = false;
$("go").disabled = false;
if (path) {
try {
const page = await call("getPage", { path, return_content: "true" });
$("title").textContent = page.title || "";
if (page.author_name) $("by").textContent = page.author_name;
if (page.author_url) $("byurl").textContent = page.author_url;
const nodes = (page.content || []).slice();
if (nodes[0] && nodes[0].tag === "aside") {
$("cats").textContent = textOf(nodes.shift());
}
if (nodes[0] && nodes[0].tag === "blockquote") {
$("overview").textContent = textOf(nodes.shift());
}
$("body").innerHTML = "";
renderInto(nodes, $("body"));
syncToc();
say("Editing an existing page. Publishing updates it.");
} catch (err) {
say("Could not load that page — " + err.message, true);
path = "";
}
} else {
say("");
}
const note = el("span", null,
"Only Telegraph's formatting is available here, because it is all a " +
"Telegraph page can hold. Your access token is in this page's address — " +
"it is never sent to a server, but it is in this browser's history.");
$("note").appendChild(note);
}
/* Minimal renderer for loading an existing page back into the editor. */
function renderInto(nodes, parent) {
for (const n of nodes || []) {
if (typeof n === "string") { parent.appendChild(document.createTextNode(n)); continue; }
if (!n || !n.tag) continue;
const tag = BLOCK.has(n.tag) || KEEP[n.tag.toUpperCase()] ? n.tag : "p";
const node = document.createElement(tag);
if (n.tag === "a" && n.attrs) {
const href = safeUrl(n.attrs.href);
if (href) node.href = href;
}
if (n.attrs && n.attrs.src) {
const src = safeUrl(n.attrs.src);
if (src) node.src = src;
}
renderInto(n.children, node);
parent.appendChild(node);
}
}
/* ---------- wiring ---------- */
for (const b of document.querySelectorAll(".tools button")) {
b.addEventListener("mousedown", e => e.preventDefault());
b.addEventListener("click", () => {
if (b.dataset.cmd) return cmd(b.dataset.cmd);
if (b.dataset.block) return cmd("formatBlock", b.dataset.block);
if (b.hasAttribute("data-link")) {
const typed = prompt("Link to");
if (typed === null) return;
const url = safeUrl(typed);
if (!url) { say("That link uses a scheme this editor will not make.", true); return; }
cmd("createLink", url);
}
});
}
$("body").addEventListener("input", () => { autoformat(); syncToc(); });
$("go").addEventListener("click", publish);
$("save").addEventListener("click", () => saveDraft(false));
$("drafts").addEventListener("click", toggleDrawer);
$("reset").addEventListener("click", () => {
$("by").textContent = account.author_name || account.short_name || "";
$("byurl").textContent = account.author_url || "";
say("Byline reset to the account default.");
});
/* Clicking the name in the bar edits the account's own byline — the
default every future post starts from. It does not touch this post, and
it does not change anything already published: each page stores the
byline it was given. */
$("who").addEventListener("focus", () => {
$("who").dataset.was = $("who").textContent.trim();
});
$("who").addEventListener("blur", async () => {
const name = $("who").textContent.trim();
if (!name || name === $("who").dataset.was) {
$("who").textContent = $("who").dataset.was || "";
return;
}
try {
await call("editAccountInfo", { access_token: token, author_name: name });
account.author_name = name;
say("Account byline is now " + name + ". Posts already published keep theirs.");
} catch (err) {
$("who").textContent = $("who").dataset.was || "";
say(err.message, true);
}
});
$("who").addEventListener("keydown", e => {
if (e.key === "Enter") { e.preventDefault(); $("who").blur(); }
});
// Autosave, debounced. Cheap insurance against a closed tab.
let autosave;
for (const id of ["title", "cats", "by", "byurl", "overview", "body"]) {
$(id).addEventListener("input", () => {
clearTimeout(autosave);
autosave = setTimeout(() => saveDraft(true), 1200);
});
}
// Paste as plain text: pasted markup is the fastest way to smuggle tags
// Telegraph will only strip.
for (const id of ["title", "cats", "overview", "body"]) {
$(id).addEventListener("paste", e => {
e.preventDefault();
document.execCommand("insertText", false,
(e.clipboardData || window.clipboardData).getData("text/plain"));
});
}
for (const id of ["title", "cats"]) {
$(id).addEventListener("keydown", e => {
if (e.key === "Enter") { e.preventDefault(); $("body").focus(); }
});
}
start();
})();
</script>
</body>
</html>