forked from kjk/notionapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
html.go
1917 lines (1747 loc) · 47.1 KB
/
html.go
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
package tohtml
import (
"bytes"
"fmt"
"html"
"os"
"os/exec"
"path"
"reflect"
"strconv"
"strings"
"github.com/hweeks/notionapi"
)
func maybePanic(format string, args ...interface{}) {
notionapi.MaybePanic(format, args...)
}
func logf(format string, args ...interface{}) {
notionapi.Logf(format, args...)
}
func isSafeChar(r rune) bool {
if r >= '0' && r <= '9' {
return true
}
if r >= 'a' && r <= 'z' {
return true
}
if r >= 'A' && r <= 'Z' {
return true
}
return false
}
// safeName returns a file-system safe name
func safeName(s string) string {
var res string
for _, r := range s {
if !isSafeChar(r) {
res += " "
} else {
res += string(r)
}
}
// replace multi-dash with single dash
for strings.Contains(res, " ") {
res = strings.Replace(res, " ", " ", -1)
}
res = strings.TrimLeft(res, " ")
res = strings.TrimRight(res, " ")
return res
}
func fileNameFromPageCoverURL(uri string) string {
parts := strings.Split(uri, "/")
lastIdx := len(parts) - 1
return parts[lastIdx]
}
func FilePathFromPageCoverURL(uri string, block *notionapi.Block) string {
// TODO: not sure about this heuristic. Maybe turn it into a whitelist:
// if starts with notion.so or aws, then download and convert to local
// otherwise leave alone
if strings.HasPrefix(uri, "https://cdn.dutchcowboys.nl/uploads") {
return uri
}
if strings.HasPrefix(uri, "https://images.unsplash.com") {
return uri
}
if strings.HasPrefix(uri, "https://www.notion.so/images/") {
return uri
}
if strings.HasPrefix(uri, "/images/page-cover/") {
return "https://www.notion.so" + uri
}
fileName := fileNameFromPageCoverURL(uri)
// TODO: probably need to build multiple dirs
dir := safeName(block.Title)
return path.Join(dir, fileName)
}
func filePathForPage(block *notionapi.Block) string {
name := safeName(block.Title) + ".html"
for block.Parent != nil && block != block.Parent {
block = block.Parent
if block.Type != notionapi.BlockPage {
continue
}
name = safeName(block.Title) + "/" + name
}
return name
}
func urlBaseName(uri string) string {
parts := strings.Split(uri, "/")
return parts[len(parts)-1]
}
func filePathForCollection(page *notionapi.Page, col *notionapi.Collection) string {
name := safeName(col.GetName()) + ".html"
name = safeName(page.Root().Title) + "/" + name
return name
}
// title columns are links to pages. this generates a link to a page
func (c *Converter) tableTitleCellURL(tv *notionapi.TableView, row, col int) string {
if c.TableTitleCellURLOverride != nil {
return c.TableTitleCellURLOverride(tv, row, col)
}
title := ""
titleSpans := tv.CellContent(row, col)
if len(titleSpans) == 0 {
logf("title is empty)")
} else {
title = titleSpans[0].Text
}
if title == "" {
title = "Untitled"
}
name := safeName(title) + ".html"
colName := tv.Collection.GetName()
if colName == "" {
colName = "Untitled Database"
}
name = safeName(colName) + "/" + name
block := tv.Page.Root()
for block.Parent != nil && block != block.Parent {
block = block.Parent
if block.Type != notionapi.BlockPage {
continue
}
name = safeName(block.Title) + "/" + name
}
return name
}
func getCollectionDownloadedFileName(page *notionapi.Page, col *notionapi.Collection, uri string) string {
name := urlBaseName(uri)
name = safeName(col.GetName()) + "/" + name
name = safeName(page.Root().Title) + "/" + name
return name
}
func getDownloadedFileName(uri string, block *notionapi.Block) string {
shouldDownload := false
if strings.HasPrefix(uri, "https://s3-us-west-2.amazonaws.com/secure.notion-static.com/") {
shouldDownload = true
}
if !shouldDownload {
return uri
}
name := urlBaseName(uri)
switch block.Type {
case notionapi.BlockFile:
// do nothing
default:
name = safeName(block.Title) + "/" + name
}
var parents []string
tmp := block
for tmp.Parent != nil {
tmp = tmp.Parent
if tmp.Type != notionapi.BlockPage {
continue
}
parents = append(parents, safeName(tmp.Title))
}
for _, s := range parents {
name = s + "/" + name
}
for strings.Contains(name, "//") {
name = strings.Replace(name, "//", "/", -1)
}
return name
}
func getFileOrSourceURL(block *notionapi.Block) string {
if len(block.FileIDs) > 0 {
return getDownloadedFileName(block.Source, block)
}
return block.Source
}
func htmlFileName(title string) string {
s := safeName(title)
return s + ".html"
}
// HTMLFileNameForPage returns file name for html file
func HTMLFileNameForPage(page *notionapi.Page) string {
return htmlFileName(page.Root().Title)
}
type PageByIDProvider interface {
PageByID(id string) *notionapi.Page
}
var _ PageByIDProvider = &PageByIDFromPages{}
type PageByIDFromPages struct {
pages []*notionapi.Page
idToPage map[string]*notionapi.Page
}
// NewPageByIDFromPages creates PageByIDProvider from array of pages
func NewPageByIDFromPages(pages []*notionapi.Page) *PageByIDFromPages {
res := &PageByIDFromPages{
pages: pages,
}
res.idToPage = map[string]*notionapi.Page{}
for _, page := range pages {
id := notionapi.ToDashID(page.ID)
res.idToPage[id] = page
}
return res
}
func (p *PageByIDFromPages) PageByID(pageID string) *notionapi.Page {
pageID = notionapi.ToDashID(pageID)
return p.idToPage[pageID]
}
// BlockRenderFunc is a function for rendering a particular block
type BlockRenderFunc func(block *notionapi.Block) bool
// Converter converts a Page to HTML
type Converter struct {
// Buf is where HTML is being written to
Buf *bytes.Buffer
Page *notionapi.Page
// tracks current number of numbered lists
ListNo int
// if true tries to render as closely to Notion's HTML
// export as possible
NotionCompat bool
// UseKatexToRenderEquation requires katex CLI to be installed
// https://katex.org/docs/cli.html
// npm install -g katex
// If true, converts BlockEquation to HTML using katex
// Tested with katex 0.10.2
UseKatexToRenderEquation bool
// If UseKatexToRenderEquation is true, you can provide path to katex binary
// here. Otherwise we'll try to locate it using exec.LookPath()
// If UseKatexToRenderEquation is true but we can't locate katex binary
// we'll return an error
KatexPath string
// if true, adds <a href="#{$NotionID}">svg(anchor-icon)</a>
// to h1/h2/h3
AddHeaderAnchor bool
// allows over-riding rendering of specific blocks
// return false for default rendering
RenderBlockOverride BlockRenderFunc
// RewriteURL allows re-writing URLs e.g. to convert inter-notion URLs
// to destination URLs
RewriteURL func(url string) string
// Returns URL for a title cell (that links to a page)
TableTitleCellURLOverride func(tv *notionapi.TableView, row, col int) string
// if true, generates stand-alone HTML with inline CSS
// otherwise it's just the inner part going inside the body
FullHTML bool
CustomCSS string
// we need this to properly render ordered and numbered lists
CurrBlocks []*notionapi.Block
CurrBlockIdx int
PageByIDProvider PageByIDProvider
// data provided by they caller, useful when providing
// RenderBlockOverride
Data interface{}
didImportKatexCSS bool
bufs []*bytes.Buffer
indent int
}
// NewConverter returns customizable HTML renderer
func NewConverter(page *notionapi.Page) *Converter {
return &Converter{
Page: page,
}
}
// PageByID returns Page given its ID
func (c *Converter) PageByID(pageID string) *notionapi.Page {
if c.PageByIDProvider != nil {
return c.PageByIDProvider.PageByID(pageID)
}
return nil
}
// PushNewBuffer creates a new buffer and sets Buf to it
func (c *Converter) PushNewBuffer() {
c.bufs = append(c.bufs, c.Buf)
c.Buf = &bytes.Buffer{}
}
// PopBuffer pops a buffer
func (c *Converter) PopBuffer() *bytes.Buffer {
res := c.Buf
n := len(c.bufs)
c.Buf = c.bufs[n-1]
c.bufs = c.bufs[:n-1]
return res
}
const spaces = "\n "
func (c *Converter) indentStr(n int) string {
n = n*2 + 1
if n > len(spaces) {
n = len(spaces)
}
return spaces[:n]
}
func (c *Converter) Printf(format string, args ...interface{}) {
c.Buf.WriteString(c.indentStr(c.indent))
c.NoIndentPrintf(format, args...)
}
func (c *Converter) NoIndentPrintf(format string, args ...interface{}) {
s := format
if len(args) > 0 {
s = fmt.Sprintf(format, args...)
}
c.Buf.WriteString(s)
}
func (c *Converter) decIndent() {
c.indent--
}
// A writes <a></a> element to output
func (c *Converter) A(uri, text, cls string) {
c.indent++
defer c.decIndent()
// TODO: Notion seems to encode url but it's probably not correct
// (it encodes "&" as "&")
// at best should only encoede as url
uri = EscapeHTML(uri)
text = EscapeHTML(text)
if cls != "" {
cls = fmt.Sprintf(` class="%s"`, cls)
}
if uri == "" {
c.Printf(`<a%s>%s</a>`, cls, text)
return
}
c.Printf(`<a%s href="%s">%s</a>`, cls, uri, text)
}
// PrevBlock is a block preceding current block
func (c *Converter) PrevBlock() *notionapi.Block {
if c.CurrBlockIdx == 0 {
return nil
}
return c.CurrBlocks[c.CurrBlockIdx-1]
}
// NextBlock is a block preceding current block
func (c *Converter) NextBlock() *notionapi.Block {
nextIdx := c.CurrBlockIdx + 1
lastIdx := len(c.CurrBlocks) - 1
if nextIdx > lastIdx {
return nil
}
return c.CurrBlocks[nextIdx]
}
// IsPrevBlockOfType returns true if previous block is of a given type
func (c *Converter) IsPrevBlockOfType(t string) bool {
b := c.PrevBlock()
if b == nil {
return false
}
return b.Type == t
}
// IsNextBlockOfType returns true if next block is of a given type
func (c *Converter) IsNextBlockOfType(t string) bool {
b := c.NextBlock()
if b == nil {
return false
}
return b.Type == t
}
// FormatDate formats the data
func (c *Converter) FormatDate(d *notionapi.Date) string {
// TODO: allow over-riding date formatting
s := notionapi.FormatDate(d)
return fmt.Sprintf(`<time>%s</time>`, s)
}
// RewrittenURL optionally transforms the url via the
// function provided by the user
func (c *Converter) RewrittenURL(uri string) string {
if c.RewriteURL != nil {
return c.RewriteURL(uri)
}
return uri
}
// RenderInline renders inline block
func (c *Converter) RenderInline(b *notionapi.TextSpan) {
var start, end string
text := b.Text
for i := range b.Attrs {
attr := b.Attrs[len(b.Attrs)-i-1]
switch notionapi.AttrGetType(attr) {
case notionapi.AttrHighlight:
// TODO: possibly needs to change b.Highlight
hl := notionapi.AttrGetHighlight(attr)
start += fmt.Sprintf(`<mark class="highlight-%s">`, hl)
end = `</mark>` + end
case notionapi.AttrBold:
start += `<strong>`
end = `</strong>` + end
case notionapi.AttrItalic:
start += `<em>`
end = `</em>` + end
case notionapi.AttrStrikeThrought:
start += `<del>`
end = `</del>` + end
case notionapi.AttrCode:
start += `<code>`
end = `</code>` + end
case notionapi.AttrPage:
pageID := notionapi.AttrGetPageID(attr)
pageTitle := ""
relURL := notionapi.ToNoDashID(pageID)
nid := notionapi.NewNotionID(pageID)
block := c.Page.BlockByID(nid)
if block != nil {
pageTitle = block.Title
}
if pageTitle != "" {
urlName := safeName(pageTitle)
urlName = strings.Replace(urlName, " ", "-", -1)
relURL = urlName + "-" + relURL
}
uri := c.RewrittenURL("https://www.notion.so/" + relURL)
start += fmt.Sprintf(`<a href="%s">%s</a>`, uri, EscapeHTML(pageTitle))
text = ""
case notionapi.AttrLink:
uri := c.RewrittenURL(notionapi.AttrGetLink(attr))
if uri == "" {
start += `<a>`
} else {
// TODO: notion escapes url but it seems to be wrong
uri = EscapeHTML(uri)
start += fmt.Sprintf(`<a href="%s">`, uri)
}
end = `</a>` + end
case notionapi.AttrUser:
userID := notionapi.AttrGetUserID(attr)
userName := notionapi.GetUserNameByID(c.Page, userID)
start += fmt.Sprintf(`<span class="user">@%s</span>`, userName)
text = ""
case notionapi.AttrDate:
date := notionapi.AttrGetDate(attr)
start += c.FormatDate(date)
text = ""
}
}
c.NoIndentPrintf(start + EscapeHTML(text) + end)
}
// RenderInlines renders inline blocks
func (c *Converter) RenderInlines(blocks []*notionapi.TextSpan) {
for _, block := range blocks {
c.RenderInline(block)
}
}
// GetInlineContent is like RenderInlines but instead of writing to
// output buffer, we return it as string
func (c *Converter) GetInlineContent(blocks []*notionapi.TextSpan) string {
if len(blocks) == 0 {
return ""
}
c.PushNewBuffer()
for _, block := range blocks {
c.RenderInline(block)
}
return c.PopBuffer().String()
}
// RenderCode renders BlockCode
func (c *Converter) RenderCode(block *notionapi.Block) {
cls := "code"
if !c.NotionCompat {
lang := strings.ToLower(strings.TrimSpace(block.CodeLanguage))
if lang != "" {
cls += " lang-" + lang
}
}
c.Printf(`<pre id="%s" class="%s">`, block.ID, cls)
{
code := EscapeHTML(block.Code)
c.NoIndentPrintf(`<code>%s</code>`, code)
}
c.Printf("</pre>")
}
// EscapeHTML escapes HTML in the same way as Notion.
func EscapeHTML(s string) string {
s = html.EscapeString(s)
// don't get why this is needed but it happens in
// https://www.notion.so/Blendle-s-Employee-Handbook-3b617da409454a52bc3a920ba8832bf7
s = strings.Replace(s, "'", "'", -1)
s = strings.Replace(s, """, """, -1)
return s
}
func isURL(uri string) bool {
if strings.HasPrefix(uri, "http://") {
return true
}
if strings.HasPrefix(uri, "https://") {
return true
}
return false
}
func (c *Converter) renderPageHeader(block *notionapi.Block) {
c.Printf(`<header>`)
{
c.indent++
defer c.decIndent()
formatPage := block.FormatPage()
// formatPage == nil happened in bf5d1c1f793a443ca4085cc99186d32f
pageCover, _ := block.PropAsString("format.page_cover")
if pageCover != "" {
position := (1 - formatPage.PageCoverPosition) * 100
coverURL := FilePathFromPageCoverURL(pageCover, block)
// TODO: Notion incorrectly escapes them
coverURL = EscapeHTML(coverURL)
c.Printf(`<img class="page-cover-image" src="%s" style="object-position:center %v%%"/>`, coverURL, position)
}
pageIcon, _ := block.PropAsString("format.page_icon")
if pageIcon != "" {
// TODO: "undefined" is a bug in Notion export
clsCover := "undefined"
if pageCover != "" {
clsCover = "page-header-icon-with-cover"
}
c.Printf(`<div class="page-header-icon %s">`, clsCover)
c.indent++
if isURL(pageIcon) {
fileName := getDownloadedFileName(pageIcon, block)
c.Printf(`<img class="icon" src="%s"/>`, fileName)
} else {
c.Printf(`<span class="icon">%s</span>`, pageIcon)
}
c.decIndent()
c.Printf(`</div>`)
}
c.Printf(`<h1 class="page-title">`)
{
c.indent++
c.RenderInlines(block.InlineContent)
c.decIndent()
}
c.Printf(`</h1>`)
}
c.Printf(`</header>`)
}
// RenderCollectionViewPage renders BlockCollectionViewPage
func (c *Converter) RenderCollectionViewPage(block *notionapi.Block) {
colID := block.FixCollectionID()
//when collection is empty, we don't have ID
if colID == "" {
return
}
nid := notionapi.NewNotionID(colID)
col := c.Page.CollectionByID(nid)
icon := col.Icon
name := col.GetName()
c.indent++
defer c.decIndent()
c.Printf(`<figure id="%s" class="link-to-page">`, block.ID)
{
c.indent++
filePath := filePathForCollection(c.Page, col)
c.Printf(`<a href="%s">`, filePath)
{
uri := getCollectionDownloadedFileName(c.Page, col, icon)
c.Printf(`<img class="icon" src="%s"/>`, uri)
}
// TODO: should name be inlines?
c.Printf(`%s</a>`, name)
c.decIndent()
}
c.Printf(`</figure>`)
}
func (c *Converter) renderLinkToPageNotion(block *notionapi.Block) {
uri := filePathForPage(block)
cls := GetBlockColorClass(block) + " link-to-page"
cls = CleanAttributeValue(cls)
c.indent++
defer c.decIndent()
c.Printf(`<figure id="%s" class="%s">`, block.ID, cls)
{
c.indent++
c.Printf(`<a href="%s">`, uri)
pageIcon, ok := block.PropAsString("format.page_icon")
if ok {
if isURL(pageIcon) {
fileName := getDownloadedFileName(pageIcon, block)
c.Printf(`<img class="icon" src="%s"/>`, fileName)
} else {
c.Printf(`<span class="icon">%s</span>`, pageIcon)
}
}
// TODO: possibly r.RenderInlines(block.InlineContent)
c.Printf(EscapeHTML(block.Title))
c.Printf(`</a>`)
defer c.decIndent()
}
c.Printf(`</figure>`)
}
func (c *Converter) renderLinkToPage(block *notionapi.Block) {
if c.NotionCompat {
c.renderLinkToPageNotion(block)
return
}
uri := filePathForPage(block)
cls := GetBlockColorClass(block) + " link-to-page"
cls = CleanAttributeValue(cls)
c.indent++
defer c.decIndent()
c.Printf(`<div id="%s" class="%s">`, block.ID, cls)
{
c.indent++
c.Printf(`<a href="%s">`, uri)
pageIcon, ok := block.PropAsString("format.page_icon")
if ok {
if isURL(pageIcon) {
fileName := getDownloadedFileName(pageIcon, block)
c.Printf(`<img class="icon" src="%s"/>`, fileName)
} else {
c.Printf(`<span class="icon">%s</span>`, pageIcon)
}
}
// TODO: possibly r.RenderInlines(block.InlineContent)
c.Printf(EscapeHTML(block.Title))
c.Printf(`</a>`)
defer c.decIndent()
}
c.Printf(`</div>`)
}
func (c *Converter) renderRootPage(block *notionapi.Block) {
if c.FullHTML {
c.Printf(`<html>`)
{
c.indent++
c.Printf(`<head>`)
{
c.indent++
c.Printf(`<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>`)
c.Printf(`<title>%s</title>`, EscapeHTML(block.Title))
styleValue := c.CustomCSS
if c.CustomCSS == "" {
styleValue = CSS
}
c.Printf("<style>%s\t\n</style>", styleValue)
c.decIndent()
}
c.Printf(`</head>`)
c.decIndent()
}
c.Printf(`<body>`)
c.indent++
}
clsFont := "sans"
fp := block.FormatPage()
if fp != nil {
if fp.PageFont != "" {
clsFont = fp.PageFont
}
}
c.Printf(`<article id="%s" class="page %s">`, block.ID, clsFont)
c.indent++
c.renderPageHeader(block)
{
c.indent++
c.Printf(`<div class="page-body">`)
c.RenderChildren(block)
c.Printf(`</div>`)
c.decIndent()
}
c.decIndent()
c.Printf(`</article>`)
if c.FullHTML {
c.decIndent()
c.Printf(`</body>`)
c.Printf(`</html>`)
}
}
func (c *Converter) renderSubPage(block *notionapi.Block) {
c.indent++
c.renderLinkToPage(block)
c.decIndent()
}
// RenderPage renders BlockPage
func (c *Converter) RenderPage(block *notionapi.Block) {
c.indent++
defer c.decIndent()
if c.Page.IsRoot(block) {
c.renderRootPage(block)
return
}
if c.Page.IsSubPage(block) {
c.renderSubPage(block)
} else {
c.renderLinkToPage(block)
}
}
// GetBlockColorClass returns "block-color-" + format.block_color
// which is name of css class for different colors
func GetBlockColorClass(block *notionapi.Block) string {
col, _ := block.PropAsString("format.block_color")
if col == "" {
return ""
}
return "block-color-" + col
}
// RenderText renders BlockText
func (c *Converter) RenderText(block *notionapi.Block) {
c.indent++
defer c.decIndent()
cls := GetBlockColorClass(block)
if c.NotionCompat {
c.Printf(`<p id="%s" class="%s">`, block.ID, cls)
c.RenderInlines(block.InlineContent)
c.RenderChildren(block)
c.Printf(`</p>`)
return
}
c.Printf(`<div id="%s" class="%s">`, block.ID, cls)
c.RenderInlines(block.InlineContent)
c.RenderChildren(block)
c.Printf(`</div>`)
}
func equationToHTML(katexPath string, equation string) (string, error) {
cmd := exec.Command(katexPath, "-d")
stdin, err := cmd.StdinPipe()
if err != nil {
return "", err
}
var out bytes.Buffer
cmd.Stdout = &out
err = cmd.Start()
if err != nil {
return "", err
}
_, err = stdin.Write([]byte(equation))
if err != nil {
_ = cmd.Process.Kill()
return "", err
}
err = stdin.Close()
if err != nil {
return "", err
}
if err = cmd.Wait(); err != nil {
return "", err
}
res := out.String()
return res, nil
}
// RenderEquation renders BlockEquation
func (c *Converter) RenderEquation(block *notionapi.Block) {
c.indent++
defer c.decIndent()
if !c.UseKatexToRenderEquation {
c.Printf(`<figure id="%s" class="equation">`, block.ID)
c.RenderInlines(block.InlineContent)
c.Printf(`</figure>`)
return
}
ts := block.InlineContent
s := notionapi.TextSpansToString(ts)
htmlStr, err := equationToHTML(c.KatexPath, s)
if err != nil {
c.Printf(`<figure id="%s" class="equation">`, block.ID)
c.RenderInlines(block.InlineContent)
c.Printf(`</figure>`)
return
}
c.Printf(`<figure id="%s" class="equation">`, block.ID)
{
if !c.didImportKatexCSS {
c.Printf(`<style>@import url('https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.10.0/katex.min.css')</style>`)
c.didImportKatexCSS = true
}
c.Printf(`<div class="equation-container">`)
{
c.Printf(htmlStr)
}
c.Printf(`</div>`)
}
c.Printf(`</figure>`)
}
// RenderNumberedList renders BlockNumberedList
func (c *Converter) RenderNumberedList(block *notionapi.Block) {
c.indent++
defer c.decIndent()
isPrevSame := c.IsPrevBlockOfType(notionapi.BlockNumberedList)
if isPrevSame {
c.ListNo++
} else {
c.ListNo = 1
}
cls := GetBlockColorClass(block) + " numbered-list"
cls = CleanAttributeValue(cls)
// Notion puts <ol> around every <li>
if c.NotionCompat || !isPrevSame {
c.Printf(`<ol id="%s" class="%s" start="%d">`, block.ID, cls, c.ListNo)
}
{
c.indent++
c.Printf(`<li>`)
{
c.indent++
c.RenderInlines(block.InlineContent)
c.RenderChildren(block)
c.indent--
}
c.Printf(`</li>`)
c.indent--
}
isNextSame := c.IsNextBlockOfType(notionapi.BlockNumberedList)
if c.NotionCompat || !isNextSame {
c.Printf(`</ol>`)
}
}
// RenderBulletedList renders BlockBulletedList
func (c *Converter) RenderBulletedList(block *notionapi.Block) {
c.indent++
defer c.decIndent()
isPrevSame := c.IsPrevBlockOfType(notionapi.BlockBulletedList)
cls := GetBlockColorClass(block) + " bulleted-list"
cls = CleanAttributeValue(cls)
// Notion puts <ul> around every <li>
if c.NotionCompat || !isPrevSame {
c.Printf(`<ul id="%s" class="%s">`, block.ID, cls)
}
{
c.indent++
c.Printf(`<li>`)
{
c.RenderInlines(block.InlineContent)
c.RenderChildren(block)
}
c.Printf(`</li>`)
c.indent--
}
isNextSame := c.IsNextBlockOfType(notionapi.BlockBulletedList)
if c.NotionCompat || !isNextSame {
c.Printf(`</ul>`)
}
}
// RenderHeaderLevel renders BlockHeader, SubHeader and SubSubHeader
func (c *Converter) RenderHeaderLevel(block *notionapi.Block, level int) {
c.indent++
defer c.decIndent()
cls := GetBlockColorClass(block)
c.Printf(`<h%d id="%s" class="%s">`, level, block.ID, cls)
c.RenderInlines(block.InlineContent)
if c.AddHeaderAnchor {
c.Printf(`<a class="header-anchor" href="#%s" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8"><path d="M5.88.03c-.18.01-.36.03-.53.09-.27.1-.53.25-.75.47a.5.5 0 1 0 .69.69c.11-.11.24-.17.38-.22.35-.12.78-.07 1.06.22.39.39.39 1.04 0 1.44l-1.5 1.5c-.44.44-.8.48-1.06.47-.26-.01-.41-.13-.41-.13a.5.5 0 1 0-.5.88s.34.22.84.25c.5.03 1.2-.16 1.81-.78l1.5-1.5c.78-.78.78-2.04 0-2.81-.28-.28-.61-.45-.97-.53-.18-.04-.38-.04-.56-.03zm-2 2.31c-.5-.02-1.19.15-1.78.75l-1.5 1.5c-.78.78-.78 2.04 0 2.81.56.56 1.36.72 2.06.47.27-.1.53-.25.75-.47a.5.5 0 1 0-.69-.69c-.11.11-.24.17-.38.22-.35.12-.78.07-1.06-.22-.39-.39-.39-1.04 0-1.44l1.5-1.5c.4-.4.75-.45 1.03-.44.28.01.47.09.47.09a.5.5 0 1 0 .44-.88s-.34-.2-.84-.22z"></path></svg></a>`, block.ID)
}
c.Printf(`</h%d>`, level)
}
// RenderHeader renders BlockHeader
func (c *Converter) RenderHeader(block *notionapi.Block) {
c.RenderHeaderLevel(block, 1)
}
// RenderSubHeader renders BlockSubHeader
func (c *Converter) RenderSubHeader(block *notionapi.Block) {
c.RenderHeaderLevel(block, 2)
}
// RenderSubSubHeader renders BlocSubSubkHeader
func (c *Converter) RenderSubSubHeader(block *notionapi.Block) {
c.RenderHeaderLevel(block, 3)
}
// RenderTodo renders BlockTodo
func (c *Converter) RenderTodo(block *notionapi.Block) {
c.Printf(`<ul id="%s" class="to-do-list">`, block.ID)
{
c.Printf(`<li>`)
{
cls := "checkbox-off"
if block.IsChecked {
cls = "checkbox-on"
}
c.Printf(`<div class="checkbox %s"></div>`, cls)
cls = "to-do-children-unchecked"
if block.IsChecked {
cls = "to-do-children-checked"
}
c.Printf(`<span class="%s">`, cls)
c.RenderInlines(block.InlineContent)
c.Printf(`</span>`)
c.RenderChildren(block)
}
c.Printf(`</li>`)
}
c.Printf(`</ul>`)
}
// RenderToggle renders BlockToggle
func (c *Converter) RenderToggle(block *notionapi.Block) {
cls := GetBlockColorClass(block) + " toggle"
cls = CleanAttributeValue(cls)
c.Printf(`<details id="%s" class="%s">`, block.ID, cls)
{
c.Printf(`<summary>`)
c.RenderInlines(block.InlineContent)
c.Printf(`</summary>`)
c.RenderChildren(block)
}
c.Printf(`</details>`)
}
// RenderQuote renders BlockQuote
func (c *Converter) RenderQuote(block *notionapi.Block) {
c.Printf(`<blockquote id="%s" class="">`, block.ID)
{
c.RenderInlines(block.InlineContent)
// TODO: do they have children?
c.RenderChildren(block)
}
c.Printf(`</blockquote>`)
}
// CleanAttributeValue cleans value of an attribute
func CleanAttributeValue(v string) string {
v = strings.TrimSpace(v)
for {
s := strings.Replace(v, " ", " ", -1)
if s == v {
return v
}