-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathblog-to-newsletter.html
More file actions
1280 lines (1149 loc) · 39.6 KB
/
blog-to-newsletter.html
File metadata and controls
1280 lines (1149 loc) · 39.6 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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blog to Newsletter</title>
<style>
* {
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
max-width: 900px;
margin: 0 auto;
padding: 20px;
line-height: 1.6;
color: #333;
}
h1 {
margin-top: 0;
color: #1a1a1a;
}
.info {
background: #f0f7ff;
border: 1px solid #b8d4ff;
border-radius: 6px;
padding: 15px;
margin-bottom: 20px;
}
.info a {
color: #0066cc;
}
.days-since {
font-size: 1.1em;
color: #666;
margin-bottom: 15px;
}
.controls {
background: #f9f9f9;
border: 1px solid #ddd;
border-radius: 6px;
padding: 20px;
margin-bottom: 20px;
}
.control-group {
margin-bottom: 15px;
}
.control-group:last-child {
margin-bottom: 0;
}
label {
display: flex;
align-items: center;
gap: 10px;
cursor: pointer;
}
input[type="range"] {
width: 200px;
}
input[type="checkbox"] {
width: 18px;
height: 18px;
}
textarea {
width: 100%;
height: 100px;
padding: 10px;
font-family: inherit;
font-size: 14px;
border: 1px solid #ccc;
border-radius: 4px;
resize: vertical;
}
.buttons {
display: flex;
gap: 10px;
flex-wrap: wrap;
margin-bottom: 20px;
}
button {
padding: 12px 20px;
font-size: 16px;
border: none;
border-radius: 6px;
cursor: pointer;
transition: background-color 0.2s;
}
.primary-btn {
background: #0066cc;
color: white;
font-weight: bold;
}
.primary-btn:hover {
background: #0055aa;
}
.secondary-btn {
background: #666;
color: white;
}
.secondary-btn:hover {
background: #555;
}
.html-length {
color: #666;
font-size: 0.9em;
margin-bottom: 10px;
}
.status {
padding: 12px;
border-radius: 6px;
margin-bottom: 15px;
}
.status.loading {
background: #fff3cd;
color: #856404;
}
.status.error {
background: #f8d7da;
color: #721c24;
}
.status.success {
background: #d4edda;
color: #155724;
}
h2 {
margin-top: 30px;
border-bottom: 2px solid #eee;
padding-bottom: 10px;
}
h3 {
margin-top: 20px;
}
.story-order {
margin-bottom: 20px;
}
.story-order ul {
list-style: none;
padding: 0;
margin: 10px 0;
background: #fff;
border: 1px solid #ddd;
border-radius: 6px;
user-select: none;
-webkit-user-select: none;
}
.story-order li {
padding: 12px 15px;
padding-left: 40px;
border-bottom: 1px solid #eee;
cursor: grab;
background: white;
transition: transform 0.15s ease, box-shadow 0.15s ease, background-color 0.15s ease;
position: relative;
touch-action: none;
}
.story-order li::before {
content: '⋮⋮';
position: absolute;
left: 12px;
top: 50%;
transform: translateY(-50%);
color: #aaa;
font-size: 14px;
letter-spacing: 2px;
}
.story-order li:last-child {
border-bottom: none;
}
.story-order li:hover {
background: #f8f8f8;
}
.story-order li:active {
cursor: grabbing;
}
.story-order li.dragging {
background: #e8f4ff;
box-shadow: 0 4px 12px rgba(0, 102, 204, 0.3);
transform: scale(1.02);
z-index: 100;
border-radius: 4px;
}
.story-order li.drag-over {
background: #f0f7ff;
}
.story-order .drop-indicator {
height: 3px;
background: #0066cc;
border-radius: 2px;
margin: -1.5px 0;
pointer-events: none;
}
.newsletter-preview {
background: white;
border: 1px solid #ddd;
border-radius: 6px;
padding: 20px;
margin-top: 20px;
}
.newsletter-preview img {
max-width: 100%;
height: auto;
}
.newsletter-preview hr {
border: none;
border-top: 1px solid #ddd;
margin: 20px 0;
}
.newsletter-preview h3 a {
color: #0066cc;
text-decoration: none;
}
.newsletter-preview h3 a:hover {
text-decoration: underline;
}
.newsletter-preview blockquote {
border-left: 4px solid #ddd;
margin: 10px 0;
padding: 10px 20px;
background: #f9f9f9;
}
.previous-links {
margin-top: 30px;
}
.previous-links input[type="text"] {
width: 100%;
padding: 10px;
font-size: 14px;
border: 1px solid #ccc;
border-radius: 4px;
margin-bottom: 10px;
}
.links-table {
max-height: 300px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
}
.links-table table {
width: 100%;
border-collapse: collapse;
}
.links-table td {
padding: 8px 12px;
border-bottom: 1px solid #eee;
font-size: 13px;
word-break: break-all;
}
.links-table tr:last-child td {
border-bottom: none;
}
.hidden {
display: none;
}
.long-urls-warning {
background: #fff3cd;
border: 1px solid #ffc107;
border-radius: 6px;
padding: 15px;
margin-bottom: 20px;
}
.long-urls-warning h4 {
margin: 0 0 10px 0;
color: #856404;
}
.long-urls-warning ul {
list-style: none;
padding: 0;
margin: 0;
}
.long-urls-warning li {
margin-bottom: 10px;
padding: 10px;
background: #fffef5;
border: 1px solid #ffe69c;
border-radius: 4px;
}
.long-urls-warning .url-text {
font-family: monospace;
font-size: 12px;
word-break: break-all;
color: #666;
margin-bottom: 8px;
}
.long-urls-warning .url-length {
font-size: 11px;
color: #856404;
margin-bottom: 8px;
}
.long-urls-warning .edit-url-btn {
padding: 6px 12px;
font-size: 13px;
background: #ffc107;
color: #000;
border: none;
border-radius: 4px;
cursor: pointer;
}
.long-urls-warning .edit-url-btn:hover {
background: #e0a800;
}
.newsletter-item {
position: relative;
}
.newsletter-item .delete-item-btn {
position: absolute;
top: 0;
right: 0;
background: #dc3545;
color: white;
border: none;
border-radius: 50%;
width: 24px;
height: 24px;
font-size: 16px;
line-height: 22px;
text-align: center;
cursor: pointer;
opacity: 0.5;
transition: opacity 0.15s;
}
.newsletter-item .delete-item-btn:hover {
opacity: 1;
}
</style>
</head>
<body>
<h1>Blog to Newsletter</h1>
<div class="info">
<p>This tool generates HTML from the <a href="https://datasette.simonwillison.net/simonwillisonblog" target="_blank">Datasette backup of simonwillison.net</a> (<a href="https://github.com/simonw/simonwillisonblog-backup/actions/workflows/backup.yml">action</a>) for copying into Substack.</p>
<p>See: <a href="https://simonwillison.net/2023/Apr/4/substack-observable/" target="_blank">Semi-automating a Substack newsletter with an Observable notebook</a></p>
</div>
<div class="days-since" id="daysSince">Loading...</div>
<div class="controls">
<div class="control-group">
<label>
Last <span id="numDaysValue">7</span> days:
<input type="range" id="numDays" min="1" max="60" value="7">
</label>
</div>
<div class="control-group">
<label>
<input type="checkbox" id="skipExisting" checked>
Skip content sent in prior newsletters
</label>
</div>
<div class="control-group">
<label>
<input type="checkbox" id="onlyPreCutoff" checked>
Only include post content prior to the cutoff comment
</label>
</div>
<div class="control-group">
<label for="rssInput">Paste RSS here if Substack feed is unavailable:</label>
<textarea id="rssInput" placeholder="Paste RSS XML content here (optional)"></textarea>
</div>
</div>
<div id="status" class="status hidden"></div>
<div class="buttons">
<button class="primary-btn" id="copyRichText">Copy rich text newsletter to clipboard</button>
<button class="primary-btn" id="copyHtml">Copy HTML newsletter to clipboard</button>
<button class="secondary-btn" id="copyLinksOnly">Copy just the links/quotes/TILs</button>
</div>
<div class="html-length" id="htmlLength"></div>
<div class="long-urls-warning hidden" id="longUrlsWarning">
<h4>Warning: Long URLs detected (>200 characters)</h4>
<ul id="longUrlsList"></ul>
</div>
<div class="story-order" id="storyOrderSection">
<h3>Set order of the stories:</h3>
<ul id="storyOrderList"></ul>
</div>
<h2>Newsletter preview</h2>
<div class="newsletter-preview" id="preview"></div>
<div class="previous-links">
<h2>Links sent in previous newsletters</h2>
<input type="text" id="linksSearch" placeholder="Search previous links...">
<div class="links-table" id="linksTable"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
(async function() {
// State
let rawContent = [];
let content = [];
let entries = [];
let blogmarks = [];
let quotations = [];
let tils = [];
let notes = [];
let chapters = [];
let previousLinks = [];
let storyOrder = [];
let newsletterHTML = '';
let daysSinceLastNewsletter = 0;
// DOM elements
const numDaysInput = document.getElementById('numDays');
const numDaysValue = document.getElementById('numDaysValue');
const skipExistingInput = document.getElementById('skipExisting');
const onlyPreCutoffInput = document.getElementById('onlyPreCutoff');
const rssInput = document.getElementById('rssInput');
const statusEl = document.getElementById('status');
const previewEl = document.getElementById('preview');
const htmlLengthEl = document.getElementById('htmlLength');
const storyOrderList = document.getElementById('storyOrderList');
const storyOrderSection = document.getElementById('storyOrderSection');
const linksSearch = document.getElementById('linksSearch');
const linksTable = document.getElementById('linksTable');
const daysSinceEl = document.getElementById('daysSince');
const longUrlsWarning = document.getElementById('longUrlsWarning');
const longUrlsList = document.getElementById('longUrlsList');
// URL replacements map (old URL -> new URL)
let urlReplacements = new Map();
// Persist story order in URL hash fragment
function updateUrlHash() {
const ids = storyOrder.map(s => parseInt(s.split(':')[0], 10));
history.replaceState(null, '', '#order=' + ids.join(','));
}
// Read story order from URL hash and reorder storyOrder accordingly
function applyOrderFromHash() {
const hash = location.hash;
if (!hash.startsWith('#order=')) return;
const hashIds = hash.slice('#order='.length).split(',')
.map(s => parseInt(s, 10))
.filter(id => !isNaN(id));
if (hashIds.length === 0) return;
const storyMap = new Map(
storyOrder.map(s => [parseInt(s.split(':')[0], 10), s])
);
const currentIds = Array.from(storyMap.keys());
// Keep only IDs that exist in current entries
const validHashIds = hashIds.filter(id => storyMap.has(id));
// Remaining IDs not mentioned in the hash, in their default order
const remainingIds = currentIds.filter(id => !validHashIds.includes(id));
const newIdOrder = [...validHashIds, ...remainingIds];
storyOrder = newIdOrder.map(id => storyMap.get(id));
}
// SQL query
const sql = `
with content as (
select
id,
'entry' as type,
title,
created,
slug,
'<h3><a href="' || 'https://simonwillison.net/' || strftime('%Y/', created)
|| substr('JanFebMarAprMayJunJulAugSepOctNovDec', (strftime('%m', created) - 1) * 3 + 1, 3)
|| '/' || cast(strftime('%d', created) as integer) || '/' || slug || '/' || '">'
|| title || '</a> - ' || date(created) || '</h3>' || body
as html,
'null' as json,
'' as external_url
from blog_entry
union all
select
id,
'blogmark' as type,
link_title,
created,
slug,
'<p><strong>Link</strong> ' || date(created) || ' <a href="'|| link_url || '">'
|| link_title || '</a>:</p><p>' || ' ' || replace(commentary, '
', '<br>') || '</p>'
as html,
json_object(
'created', date(created),
'link_url', link_url,
'link_title', link_title,
'commentary', commentary,
'use_markdown', use_markdown
) as json,
link_url as external_url
from blog_blogmark
union all
select
id,
'quotation' as type,
source,
created,
slug,
'<strong>Quote</strong> ' || date(created) ||
'<blockquote><p><em>' ||
replace(quotation, '
', '<br>') ||
'</em></p></blockquote><p><a href="' ||
coalesce(source_url, '#') || '">' || source || '</a>' ||
case
when nullif(trim(context), '') is not null
then ', ' || context
else ''
end ||
'</p>' as html,
json_object(
'created', date(created),
'quotation', quotation,
'source', source,
'source_url', source_url,
'context', context
) as json,
source_url as external_url
from blog_quotation
union all
select
id,
'note' as type,
case
when title is not null and title <> '' then title
else 'Note on ' || date(created)
end,
created,
slug,
'No HTML',
json_object(
'created', date(created),
'link_url', 'https://simonwillison.net/' || strftime('%Y/', created)
|| substr('JanFebMarAprMayJunJulAugSepOctNovDec', (strftime('%m', created) - 1) * 3 + 1, 3)
|| '/' || cast(strftime('%d', created) as integer) || '/' || slug || '/',
'link_title', '',
'commentary', body,
'use_markdown', 1
),
'' as external_url
from blog_note
union all
select
c.id,
'chapter' as type,
c.title,
c.created,
c.slug,
'No HTML' as html,
json_object(
'created', date(c.created),
'title', c.title,
'body', c.body,
'chapter_slug', c.slug,
'guide_title', g.title,
'guide_slug', g.slug
) as json,
'https://simonwillison.net/guides/' || g.slug || '/' || c.slug || '/' as external_url
from guides_chapter c
join guides_guide g on c.guide_id = g.id
where c.is_draft = 0
union all
select
rowid,
'til' as type,
title,
created,
'null' as slug,
'<p><strong>TIL</strong> ' || date(created) || ' <a href="'|| 'https://til.simonwillison.net/' || topic || '/' || slug || '">' || title || '</a>:' || ' ' || substr(html, 1, instr(html, '</p>') - 1) || ' …</p>' as html,
'null' as json,
'https://til.simonwillison.net/' || topic || '/' || slug as external_url
from til
),
collected as (
select
id,
type,
title,
case
when type in ('til', 'chapter')
then external_url
else 'https://simonwillison.net/' || strftime('%Y/', created)
|| substr('JanFebMarAprMayJunJulAugSepOctNovDec', (strftime('%m', created) - 1) * 3 + 1, 3) ||
'/' || cast(strftime('%d', created) as integer) || '/' || slug || '/'
end as url,
created,
html,
json,
external_url,
case
when type = 'entry' then (
select json_group_array(tag)
from blog_tag
join blog_entry_tags on blog_tag.id = blog_entry_tags.tag_id
where blog_entry_tags.entry_id = content.id
)
when type = 'blogmark' then (
select json_group_array(tag)
from blog_tag
join blog_blogmark_tags on blog_tag.id = blog_blogmark_tags.tag_id
where blog_blogmark_tags.blogmark_id = content.id
)
when type = 'quotation' then (
select json_group_array(tag)
from blog_tag
join blog_quotation_tags on blog_tag.id = blog_quotation_tags.tag_id
where blog_quotation_tags.quotation_id = content.id
)
else '[]'
end as tags
from content
where created >= date('now', '-' || :numdays || ' days')
order by created desc
)
select id, type, title, url, created, html, json, external_url, tags
from collected
order by
case type
when 'entry' then 0
else 1
end,
case type
when 'entry' then created
else -strftime('%s', created)
end desc;
`;
function showStatus(message, type = 'loading') {
statusEl.textContent = message;
statusEl.className = 'status ' + type;
}
function hideStatus() {
statusEl.className = 'status hidden';
}
// Fetch RSS from GitHub backup or Cloudflare worker
async function fetchRSS() {
if (rssInput.value.trim()) {
return rssInput.value.trim();
}
try {
// Try Cloudflare worker first (more up to date)
const response = await fetch('https://restless-cherry-7938.simonw.workers.dev/');
if (response.ok) {
return await response.text();
}
} catch (e) {
console.log('Cloudflare worker failed, trying GitHub backup');
}
// Fallback to GitHub backup
const response = await fetch('https://raw.githubusercontent.com/simonw/simonwillisonblog-backup/main/simonw-substack-com.xml');
return await response.text();
}
// Parse RSS and extract previous newsletter links
function parseRSS(rssText) {
const parser = new DOMParser();
const doc = parser.parseFromString(rssText, 'application/xml');
// Get previous newsletter date
const pubDateEl = doc.querySelector('channel > item > pubDate');
if (pubDateEl) {
const date = new Date(pubDateEl.textContent);
daysSinceLastNewsletter = (new Date() - date) / (1000 * 60 * 60 * 24);
daysSinceEl.textContent = `${daysSinceLastNewsletter.toFixed(2)} days since the last newsletter.`;
// Set default numDays to days since last newsletter + 1
const defaultDays = Math.min(60, Math.ceil(daysSinceLastNewsletter) + 1);
numDaysInput.value = defaultDays;
numDaysValue.textContent = defaultDays;
}
// Extract HTML content from all items
const namespaceResolver = (prefix) => {
const ns = { content: 'http://purl.org/rss/1.0/modules/content/' };
return ns[prefix] || null;
};
const result = doc.evaluate(
'//content:encoded',
doc,
namespaceResolver,
XPathResult.ANY_TYPE,
null
);
let node;
let html = [];
while ((node = result.iterateNext())) {
html.push(node.textContent);
}
const allHtml = html.join('\n');
// Extract URLs using regex
const regex = /(?:"|")(https?:\/\/[^\s"<>]+)(?:"|")/g;
previousLinks = Array.from(allHtml.matchAll(regex), match => match[1]);
renderLinksTable();
}
// Fetch content from Datasette
async function fetchContent(numDays) {
const url = `https://datasette.simonwillison.net/simonwillisonblog.json?sql=${encodeURIComponent(sql)}&_shape=array&numdays=${numDays}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch content: ${response.status}`);
}
return await response.json();
}
// Render first three paragraphs of a chapter with word count suffix
function renderChapterExcerpt(body, chapterUrl) {
const fullHtml = marked.parse(body);
const tempDiv = document.createElement('div');
tempDiv.innerHTML = fullHtml;
const paragraphs = tempDiv.querySelectorAll(':scope > p');
if (paragraphs.length <= 3) return fullHtml;
const excerptDiv = document.createElement('div');
for (let i = 0; i < 3; i++) {
excerptDiv.appendChild(paragraphs[i].cloneNode(true));
}
let excerptHtml = excerptDiv.innerHTML;
const wordCount = body.split(/\s+/).filter(w => w.length > 0).length;
const formattedCount = wordCount.toLocaleString();
const suffix = ` <span style="font-size: 0.9em">[... <a href="${chapterUrl}">${formattedCount} word${wordCount !== 1 ? 's' : ''}</a>]</span>`;
const lastP = excerptHtml.lastIndexOf('</p>');
if (lastP !== -1) {
excerptHtml = excerptHtml.substring(0, lastP) + suffix + excerptHtml.substring(lastP);
} else {
excerptHtml += suffix;
}
return excerptHtml;
}
// Filter content based on settings
function filterContent() {
const skipExisting = skipExistingInput.checked;
const onlyPreCutoff = onlyPreCutoffInput.checked;
// Filter by existing links
let filtered = skipExisting
? rawContent.filter(e => !previousLinks.includes(e.url) && !previousLinks.includes(e.external_url))
: rawContent;
// Parse tags
filtered = filtered.map(({ tags, ...rest }) => ({
...rest,
tags: typeof tags === 'string' ? JSON.parse(tags) : tags
}));
// Apply cutoff and markdown rendering
if (onlyPreCutoff) {
filtered = filtered.map(e => {
if (e.json !== 'null' && (e.type === 'blogmark' || e.type === 'note')) {
const info = typeof e.json === 'string' ? JSON.parse(e.json) : e.json;
if (info.use_markdown) {
const entry = { ...e };
if (e.type === 'blogmark') {
const commentary = marked.parse(info.commentary || '');
entry.html = `<p><strong>Link</strong> ${info.created} <a href="${info.link_url}">${info.link_title}</a>:</p>${commentary}`;
} else if (e.type === 'note') {
const commentary = marked.parse(info.commentary || '');
entry.html = `<p><strong>Note</strong> <a href="${e.url}">${info.created}</a></p>${commentary}`;
}
return entry;
}
}
if (e.type === 'quotation' && e.json !== 'null') {
const info = typeof e.json === 'string' ? JSON.parse(e.json) : e.json;
const entry = { ...e };
const quotationHtml = marked.parse(info.quotation || '');
const contextHtml = info.context ? ', ' + marked.parseInline(info.context) : '';
entry.html = `<p><strong>Quote</strong> ${info.created}</p><blockquote>${quotationHtml}</blockquote><p><a href="${info.source_url || '#'}">${info.source}</a>${contextHtml}</p>`;
return entry;
}
if (e.html) {
const entry = { ...e };
entry.html = entry.html.split('<!-- cutoff -->')[0];
return entry;
}
return e;
});
}
// Always render chapter HTML from markdown
filtered = filtered.map(e => {
if (e.type === 'chapter' && e.json !== 'null') {
const info = typeof e.json === 'string' ? JSON.parse(e.json) : e.json;
const entry = { ...e };
const chapterUrl = `https://simonwillison.net/guides/${info.guide_slug}/${info.chapter_slug}/`;
const guideUrl = `https://simonwillison.net/guides/${info.guide_slug}/`;
const excerptHtml = renderChapterExcerpt(info.body, chapterUrl);
entry.html = `<p style="font-size: 0.85em; color: #999; margin: 0 0 -0.2em 0; line-height: 1.2;"><a href="${guideUrl}" style="color: #999; text-decoration: none;">${info.guide_title}</a> ></p><h3 style="margin-top: 0.2em; margin-bottom: 0.5em;"><a href="${chapterUrl}">${info.title}</a> - ${info.created}</h3>${excerptHtml}`;
return entry;
}
return e;
});
content = filtered;
entries = content.filter(e => e.type === 'entry');
blogmarks = content.filter(e => e.type === 'blogmark');
quotations = content.filter(e => e.type === 'quotation');
tils = content.filter(e => e.type === 'til');
notes = content.filter(e => e.type === 'note');
chapters = content.filter(e => e.type === 'chapter');
// Initialize story order
storyOrder = entries.map(e => `${e.id}: ${e.title}`).reverse();
applyOrderFromHash();
renderStoryOrder();
generateNewsletter();
}
// Render story order drag-and-drop list with touch support
function renderStoryOrder() {
if (entries.length <= 1) {
storyOrderSection.classList.add('hidden');
return;
}
storyOrderSection.classList.remove('hidden');
storyOrderList.innerHTML = '';
let draggedItem = null;
let dropIndicator = null;
let touchStartY = 0;
let initialIndex = 0;
// Create drop indicator element
function createDropIndicator() {
const indicator = document.createElement('div');
indicator.className = 'drop-indicator';
return indicator;
}
// Remove any existing drop indicator
function removeDropIndicator() {
if (dropIndicator && dropIndicator.parentNode) {
dropIndicator.parentNode.removeChild(dropIndicator);
}
dropIndicator = null;
}
// Get insertion point based on Y position
function getInsertionPoint(y) {
const items = Array.from(storyOrderList.querySelectorAll('li:not(.dragging)'));
for (const item of items) {
const rect = item.getBoundingClientRect();
const midY = rect.top + rect.height / 2;
if (y < midY) {
return { element: item, position: 'before' };
}
}
// If we're past all items, insert after the last one
if (items.length > 0) {
return { element: items[items.length - 1], position: 'after' };
}
return null;
}
// Update drop indicator position
function updateDropIndicator(y) {
const insertion = getInsertionPoint(y);
if (!insertion) {
removeDropIndicator();
return;
}
if (!dropIndicator) {
dropIndicator = createDropIndicator();
}
if (insertion.position === 'before') {
insertion.element.parentNode.insertBefore(dropIndicator, insertion.element);
} else {
insertion.element.parentNode.insertBefore(dropIndicator, insertion.element.nextSibling);
}
}
// Finalize the drop
function finalizeDrop(y) {
if (!draggedItem) return;
const insertion = getInsertionPoint(y);
if (insertion) {
if (insertion.position === 'before') {
storyOrderList.insertBefore(draggedItem, insertion.element);
} else {
storyOrderList.insertBefore(draggedItem, insertion.element.nextSibling);
}
}
draggedItem.classList.remove('dragging');
removeDropIndicator();
// Update storyOrder array
storyOrder = Array.from(storyOrderList.querySelectorAll('li')).map(el => el.textContent);
updateUrlHash();
generateNewsletter();
draggedItem = null;
}
// Create list items
storyOrder.forEach((item, index) => {
const li = document.createElement('li');
li.textContent = item;
li.draggable = true;
// Mouse drag events
li.addEventListener('dragstart', (e) => {
draggedItem = li;
initialIndex = index;
li.classList.add('dragging');
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', '');
// Delay to allow the drag image to be captured
requestAnimationFrame(() => {
li.style.opacity = '0.5';
});
});
li.addEventListener('dragend', (e) => {
li.style.opacity = '';
finalizeDrop(e.clientY);
});
li.addEventListener('dragover', (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
updateDropIndicator(e.clientY);
});
li.addEventListener('drop', (e) => {
e.preventDefault();
});
// Touch events for mobile support
li.addEventListener('touchstart', (e) => {
if (e.touches.length !== 1) return;
draggedItem = li;
initialIndex = index;
touchStartY = e.touches[0].clientY;
// Small delay to distinguish from scroll
setTimeout(() => {
if (draggedItem === li) {
li.classList.add('dragging');
}
}, 100);
}, { passive: true });
li.addEventListener('touchmove', (e) => {
if (!draggedItem || draggedItem !== li) return;
e.preventDefault();
const touch = e.touches[0];
const y = touch.clientY;
if (!li.classList.contains('dragging')) {
li.classList.add('dragging');
}
updateDropIndicator(y);
}, { passive: false });
li.addEventListener('touchend', (e) => {
if (!draggedItem || draggedItem !== li) return;
const touch = e.changedTouches[0];
finalizeDrop(touch.clientY);
});
li.addEventListener('touchcancel', () => {
if (draggedItem) {
draggedItem.classList.remove('dragging');
removeDropIndicator();
draggedItem = null;
}