import "@johnlindquist/kit";
const { Client } = await npm("@notionhq/client");
const { format, parseISO, formatISO, isSameMinute } = await npm("date-fns");
const NOTION_URL = await env("NOTION_URL");
const DATABASE_ID = await env("NOTION_DATABASE_ID");
const TOKEN = await env("NOTION_TOKEN");
const notion = new Client({
auth: TOKEN,
});
const createHeadingBlock = (content: string) => {
return {
object: "block",
type: "heading_2",
heading_2: {
text: [
{
type: "text",
text: {
content,
},
},
],
},
};
};
const createBulletItemBlock = (content: string) => {
return {
object: "block",
type: "bulleted_list_item",
bulleted_list_item: {
text: [
{
type: "text",
text: {
content,
},
},
],
},
};
};
const queryDatabase = async () =>
await notion.databases.query({
database_id: DATABASE_ID,
filter: {
and: [
{
property: "Name",
text: {
contains: "Thoughts",
},
},
{
property: "Created",
created_time: {
equals: formatISO(new Date(), { representation: "date" }),
},
},
],
},
sorts: [
{
property: "Created",
direction: "ascending",
},
],
});
const createPage = async () =>
await notion.pages.create({
parent: {
database_id: DATABASE_ID,
},
icon: {
type: "emoji",
emoji: "📝",
},
properties: {
Name: {
title: [
{
text: {
content: `${format(new Date(), "yyyy-MM-dd")} - Thoughts`,
},
},
],
},
Tags: {
multi_select: [{ name: "Daily" }],
},
},
children: [createHeadingBlock(`${format(new Date(), "HH:mm")}`)],
});
const hasThoughtsForTheDay = (thoughts?: any[]) => thoughts && thoughts.length > 0;
const { results: database } = await queryDatabase();
const page = hasThoughtsForTheDay(database) ? database[0] : await createPage();
while (true) {
const thought = await arg({
placeholder: "Thought:",
hint: `Type "open" to open journal in browser`,
});
if (thought === "open") {
focusTab(`${NOTION_URL}/${DATABASE_ID}`);
break;
}
const { results: children } = await notion.blocks.children.list({
block_id: page.id,
page_size: 42,
});
const headingBlock = [...children].reverse().find((obj: any) => obj.type === "heading_2");
const isSameTime = isSameMinute(parseISO(headingBlock?.created_time), new Date());
if (!isSameTime) {
await notion.blocks.children.append({
block_id: page.id,
children: [createHeadingBlock(format(new Date(), "HH:mm"))],
});
}
await notion.blocks.children.append({
block_id: page.id,
children: [createBulletItemBlock(thought)],
});
}