Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[render] Fix children of callout are not rendered + Download internal images #8

Merged
merged 2 commits into from
May 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions examples/nextjs/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,6 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts

# Images downloaded from CMS
public/cms/*
Empty file.
40 changes: 39 additions & 1 deletion examples/nextjs/src/lib/fetchers.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,56 @@
import { unstable_cache } from "next/cache"
import { fetchBlocksChildren } from "@react-notion-cms/render"
import { Client } from "@notionhq/client"
import { statSync, writeFileSync } from "node:fs"
import nextConfig from "../../next.config.mjs"

const notionClient = new Client({
auth: process.env.NOTION_ACCESS_TOKEN,
})

export const getCachedPageContent = unstable_cache(
async (blockId: string) => {
return fetchBlocksChildren(notionClient, blockId)
return fetchBlocksChildren(
notionClient,
{
block_id: blockId,
page_size: 100,
},
{
resolveImageFn: downloadImageToPublicDir,
},
)
},
["cms-page"],
// {
// revalidate: false,
// tags: ["cms-page"],
// },
)

const downloadImageToPublicDir = async (url: string, meta: { blockId: string; lastEditedTime: Date }) => {
const fileUrl = new URL(url)
const originalFileName = fileUrl.pathname.substring(fileUrl.pathname.lastIndexOf("/") + 1)
const newFileName = `public/cms/${meta.blockId}-${originalFileName}`

let savedLastEditedTime: Date | null = null
try {
const stat = statSync(newFileName)
savedLastEditedTime = stat.mtime
} catch (error) {
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
console.debug(`${newFileName} not found`)
} else {
console.warn(`${newFileName}: ${error}`)
}
}
// Avoid download the file again and again
if (savedLastEditedTime === null || meta.lastEditedTime > savedLastEditedTime) {
const resp = await fetch(fileUrl)
const blob = await resp.blob()
writeFileSync(newFileName, new DataView(await blob.arrayBuffer()))
console.info(`downloaded image ${newFileName} of block ${meta.blockId}`)
}

return newFileName.replace("public", nextConfig.basePath ?? "")
}
3 changes: 2 additions & 1 deletion packages/render/src/block.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -148,13 +148,14 @@ const Block = ({ block, options }: { block: BlockObjectResponseWithChildren; opt
<div
style={{ marginTop: "6px", marginBottom: "6px", ...notionColor(block.callout.color, true) }}
className={
"box-border inline-flex w-full items-center rounded-[3px] border border-[--fg-color-0] py-4 pe-4 ps-3 dark:border-[--bg-color-2]"
"box-border inline-flex w-full items-start rounded-[3px] border border-[--fg-color-0] py-4 pe-4 ps-3 dark:border-[--bg-color-2]"
}
>
<Icon icon={block.callout.icon} width={28} />
{/* ref: .notion-callout-text */}
<div className="ms-4 whitespace-pre-wrap break-words">
<RichTexts value={block.callout.rich_text} options={options} />
{block._children && <RenderBlocks blocks={block._children} options={options} />}
</div>
</div>
)
Expand Down
32 changes: 25 additions & 7 deletions packages/render/src/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
import { type Client, isFullBlock, iteratePaginatedAPI } from "@notionhq/client"
import { BlockObjectResponseWithChildren } from "./types"
import { type ListBlockChildrenParameters } from "@notionhq/client/build/src/api-endpoints"

export const fetchBlocksChildren = async (client: Client, blockId: string) => {
type ResolveImageFn = (url: string, meta: { blockId: string; lastEditedTime: Date }) => Promise<string>

export const fetchBlocksChildren = async (
client: Client,
firstPageArgs: ListBlockChildrenParameters,
options: { resolveImageFn?: ResolveImageFn },
) => {
const result: Array<BlockObjectResponseWithChildren> = []
for await (const block of iteratePaginatedAPI(client.blocks.children.list, {
block_id: blockId,
page_size: 100,
})) {
for await (const block of iteratePaginatedAPI(client.blocks.children.list, firstPageArgs)) {
if (isFullBlock(block)) {
if (options.resolveImageFn && block.type === "image" && block.image.type === "file") {
block.image.file.url = await options.resolveImageFn(block.image.file.url, {
blockId: block.id,
lastEditedTime: new Date(block.last_edited_time),
})
}

if (!block.has_children) {
result.push(block)
continue
Expand All @@ -19,10 +30,17 @@ export const fetchBlocksChildren = async (client: Client, blockId: string) => {

result.push({
...block,
_children: await fetchBlocksChildren(client, childId),
_children: await fetchBlocksChildren(
client,
{
...firstPageArgs,
block_id: childId,
},
options,
),
})
}
}
console.info(`fetched children from notion block ${blockId}`)
console.info(`fetched children from notion block ${firstPageArgs.block_id}`)
return result
}