-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblog.tsx
More file actions
202 lines (179 loc) · 7.63 KB
/
blog.tsx
File metadata and controls
202 lines (179 loc) · 7.63 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
import { cache } from 'react'
import Syntax from 'react-syntax-highlighter/dist/esm/prism'
import theme from 'react-syntax-highlighter/dist/esm/styles/prism/dracula'
import Link from 'next/link'
import { splitArrayBy } from '@giraugh/tools'
import { Client, isFullBlock, isFullPage } from '@notionhq/client'
import { BlockObjectResponse, RichTextItemResponse } from '@notionhq/client/build/src/api-endpoints'
const notion = new Client({ auth: process.env.NOTION_API_KEY, fetch })
/** Format a date like `May 23, 2021` */
const formatDate = (from: string | undefined) => {
if (!from) return
return new Date(from).toLocaleDateString('en-US', {
year: 'numeric', month: 'long', day: 'numeric',
})
}
/** Extract the YouTube video ID from a URL */
const ytid = (url: string) => {
const match = url.match(/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/)
return (match && match[7].length == 11) ? match[7] : false
}
export const fetchPosts = cache(async (count = 100) => {
if (!process.env.BLOG_DATABASE_ID) return
const res = await notion.databases.query({
database_id: process.env.BLOG_DATABASE_ID,
filter: {
property: 'Published',
date: {
on_or_before: new Date().toISOString(),
},
},
sorts: [
{
property: 'Published',
direction: 'descending',
},
],
page_size: count,
})
return {
posts: res.results.flatMap(page => {
if (!isFullPage(page)) return []
if (page.properties.Number.type !== 'number'
|| page.properties.Title.type !== 'title'
) return []
return [{
id: page.id,
number: page.properties.Number.number,
title: page.properties.Title.title[0].plain_text,
}]
}),
has_more: res.has_more,
}
})
const renderBlockText = (text: RichTextItemResponse[]) =>
text.map((node, i) => {
if (node.type === 'text') {
const Tag = node.annotations.code ? 'code' : 'span'
// Add styles
const el = <Tag key={i} style={{
...node.annotations.bold && { fontWeight: 600 },
...node.annotations.italic && { fontStyle: 'italic' },
...node.annotations.strikethrough && { textDecoration: 'line-through' },
...node.annotations.underline && { textDecoration: 'underline' },
...node.annotations.strikethrough && node.annotations.underline && { textDecoration: 'line-through underline' },
}}>{node.text.content}</Tag>
// Wrap in a link
if (node.text.link) {
return <Link key={`${i}_link`} href={node.text.link.url} target="_blank" rel="nofollow noreferrer">{el}</Link>
}
return el
}
})
const renderBlock = (block: BlockObjectResponse) => {
if (block.type === 'paragraph') return <p key={block.id}>{renderBlockText(block.paragraph.rich_text)}</p>
if (block.type === 'heading_1') return <h2 key={block.id}>{renderBlockText(block.heading_1.rich_text)}</h2>
if (block.type === 'heading_2') return <h3 key={block.id}>{renderBlockText(block.heading_2.rich_text)}</h3>
if (block.type === 'heading_3') return <h4 key={block.id}>{renderBlockText(block.heading_3.rich_text)}</h4>
if (block.type === 'bulleted_list_item') return <li key={block.id}>{renderBlockText(block.bulleted_list_item.rich_text)}</li>
if (block.type === 'numbered_list_item') return <li key={block.id}>{renderBlockText(block.numbered_list_item.rich_text)}</li>
if (block.type === 'quote') return <blockquote key={block.id}>{renderBlockText(block.quote.rich_text)}</blockquote>
if (block.type === 'code' && block.code.rich_text[0].type === 'text') return <Syntax
key={block.id}
style={theme}
language={block.code.language}
customStyle={{
background: 'none',
textShadow: 'none',
margin: 'initial',
padding: 0,
fontFamily: 'initial',
borderRadius: 0,
}}
codeTagProps={{ style: {} }}
showLineNumbers
lineNumberStyle={{
minWidth: `${block.code.rich_text[0].text.content.split('\n').length.toString().length}ch`,
position: 'sticky',
left: 0,
background: 'inherit',
paddingInlineStart: '1.5em',
}}
>
{block.code.rich_text[0].text.content}
</Syntax>
if (block.type === 'image') return <figure key={block.id}>
<img
src={block.image.type === 'external' ? block.image.external.url : block.image.file.url}
alt={(block.image.caption.length > 0 && block.image.caption[0].type === 'text' && block.image.caption[0].text.content) || ''}
/>
{block.image.caption.length > 0 ? <figcaption>
{(block.image.caption[0].type === 'text' && block.image.caption[0].text.content) || ''}
</figcaption> : null}
</figure>
if (block.type === 'divider') return <hr key={block.id} />
if (block.type === 'video' && block.video.type === 'external' && block.video.external.url.includes('you')) return <figure key={block.id}>
<iframe
width="560"
height="315"
title="YouTube video player"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
src={`https://www.youtube.com/embed/${ytid(block.video.external?.url)}`}
/>
{block.video.caption.length > 0 ? <figcaption>
{(block.video.caption[0].type === 'text' && block.video.caption[0].text.content) || ''}
</figcaption> : null}
</figure>
if (block.type === 'embed') return <figure key={block.id}>
{block.embed.url.includes('codepen') && <iframe
height="300"
style={{ width: '100%' }}
scrolling="no"
title="CodePen embed"
allowFullScreen
allowTransparency
loading="lazy"
src={block.embed.url.replace('/pen/', '/embed/')}
/>}
{block.embed.caption.length > 0 ? <figcaption>
{(block.embed.caption[0].type === 'text' && block.embed.caption[0].text.content) || ''}
</figcaption> : null}
</figure>
}
export const fetchPost = cache(async (id: string) => {
if (!process.env.BLOG_DATABASE_ID) return
// Get page details
const pageRes = await notion.pages.retrieve({ page_id: id })
if (!pageRes || !isFullPage(pageRes)) return
if (pageRes.properties.Number.type !== 'number'
|| pageRes.properties.Title.type !== 'title'
|| pageRes.properties.Published.type !== 'date'
|| pageRes.properties['Last edited'].type !== 'last_edited_time'
|| pageRes.properties.Tags.type !== 'multi_select'
) return
const meta = {
id: pageRes.id,
number: pageRes.properties.Number.number,
title: pageRes.properties.Title.title[0].plain_text,
cover: pageRes.cover?.type === 'external' ? pageRes.cover.external.url : pageRes.cover?.file.url,
published: formatDate(pageRes.properties.Published.date?.start),
edited: formatDate(pageRes.properties['Last edited'].last_edited_time),
tags: pageRes.properties.Tags.multi_select,
}
// Get page content
const content = await notion.blocks.children.list({ block_id: id })
const blocks = content.results.filter(isFullBlock)
// Get page description
const firstParagraph = blocks.find(b => b.type === 'paragraph')
const description = firstParagraph?.type === 'paragraph' ? firstParagraph.paragraph.rich_text.map(t => t.plain_text).join('') : undefined
// Group list items together
const groupedBlocks = splitArrayBy(blocks, (a, b) => a.type !== b.type || !['bulleted_list_item', 'numbered_list_item'].includes(a.type))
const elements = groupedBlocks.flatMap((blockGroup, i) => {
const renderedBlocks = blockGroup.map(renderBlock)
if (blockGroup[0].type === 'bulleted_list_item') return [<ul key={i}>{renderedBlocks}</ul>]
if (blockGroup[0].type === 'numbered_list_item') return [<ol key={i}>{renderedBlocks}</ol>]
return renderedBlocks
})
return { meta, elements, description }
})