This commit is contained in:
Michael Zhang 2023-08-23 15:21:01 -05:00
commit 6c6ea36148
17 changed files with 2324 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
node_modules
/dist

23
README.md Normal file
View file

@ -0,0 +1,23 @@
## Hello World Sample
This is a Hello World sample that just get you started :)
### Demo
![demo](./demo.gif)
### API
[![npm version](https://badge.fury.io/js/%40logseq%2Flibs.svg)](https://badge.fury.io/js/%40logseq%2Flibs)
##### Logseq
- `ready (callback?: (e: any) => void | {}): Promise<any>`
##### Logseq.App
- `showMsg: (content: string, status?: 'success' | 'warning' | string) => void`
### Running the Sample
- `Load unpacked plugin` in Logseq Desktop client.

12
index.html Normal file
View file

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="src/main.ts"></script>
</body>
</html>

24
lib/month.ts Normal file
View file

@ -0,0 +1,24 @@
import {
addDays,
endOfMonth,
getWeek,
isSameWeek,
startOfMonth,
} from "date-fns";
/**
* Return week bounds in a [closed, open) fashion
* The last week is not returned if it contains the next month's start date
* @param date
*/
export function weekBoundsOfMonth(date: Date): [number, number] {
const firstDayOfMonth = startOfMonth(date);
const startWeek = getWeek(firstDayOfMonth);
const lastDayOfMonth = endOfMonth(date);
const firstDayOfNextMonth = addDays(lastDayOfMonth, 1);
let endWeek = getWeek(lastDayOfMonth);
if (isSameWeek(lastDayOfMonth, firstDayOfNextMonth)) endWeek -= 1;
return [startWeek, endWeek];
}

BIN
logseq.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

1750
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

35
package.json Normal file
View file

@ -0,0 +1,35 @@
{
"name": "logseq-calendar",
"version": "0.1.0",
"author": "Michael Zhang <mail@mzhang.io>",
"main": "dist/index.html",
"description": "Calendar app for Logseq",
"license": "MIT",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"devDependencies": {
"@logseq/libs": "^0.0.1-alpha.29",
"@types/react": "^18.2.21",
"@types/react-dom": "^18.2.7",
"@vitejs/plugin-react": "^4.0.4",
"sass": "^1.66.1",
"typescript": "^5.1.6",
"vite": "^4.4.9",
"vite-tsconfig-paths": "^4.2.0"
},
"browserslist": [
"chrome 80"
],
"logseq": {
"id": "_edodonfur",
"icon": "logseq.png"
},
"dependencies": {
"classnames": "^2.3.2",
"date-fns": "^2.30.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}

12
src/App.module.scss Normal file
View file

@ -0,0 +1,12 @@
main.app {
width: 100%;
height: 100%;
backdrop-filter: blur(30px);
display: flex;
flex-direction: column;
}
.header {
padding-top: 40px;
}

54
src/App.tsx Normal file
View file

@ -0,0 +1,54 @@
import { endOfMonth, format, startOfMonth } from "date-fns";
import styles from "./App.module.scss";
import Calendar from "./calendar/Calendar";
import { useEffect } from "react";
export default function App() {
const onDateClick = async (date: Date) => {
const start = startOfMonth(date);
const end = endOfMonth(date);
const fmt = (date: Date) => format(date, "YMMdd");
const fmtDate = fmt(date);
const fmtStart = fmt(start);
const fmtEnd = fmt(end);
console.log(fmtStart, fmtDate, fmtEnd);
const journals: any[] = await logseq.DB.datascriptQuery(`
[:find (pull ?p [*])
:where
[?b :block/page ?p]
[?p :block/journal? true]
[?p :block/journal-day ?d]
[(>= ?d ${fmtStart})] [(<= ?d ${fmtEnd})]]
`);
const journalsMap = new Map(
journals.flatMap((x) => x).map((x) => [x["journal-day"].toString(), x])
);
console.log("JOURNALS", journalsMap);
const targetEntry = journalsMap.get(fmtDate);
console.log("Target", targetEntry);
let name;
if (targetEntry) name = targetEntry["original-name"];
else {
// TODO: Try to create a new journal page?
return;
}
logseq.App.pushState("page", { name });
logseq.hideMainUI();
};
return (
<main className={styles.app}>
<div className="header">
Header
<button onClick={() => logseq.hideMainUI()}>Close</button>
</div>
<Calendar onDateClick={onDateClick} />
</main>
);
}

View file

@ -0,0 +1,34 @@
.calendar {
flex-grow: 1;
height: 100%;
display: flex;
flex-direction: column;
position: relative;
overflow: auto;
}
.header {
position: sticky;
.title {
font-size: 22px;
}
}
.daysOfWeek {
display: grid;
grid-template-columns: repeat(7, 1fr);
div {
flex-grow: 1;
text-align: right;
font-weight: 100;
border-bottom: 1px solid gray;
}
}
.scrollyPart {
flex-grow: 1;
overflow: auto;
}

107
src/calendar/Calendar.tsx Normal file
View file

@ -0,0 +1,107 @@
import { forwardRef, useCallback, useEffect, useRef, useState } from "react";
import styles from "./Calendar.module.scss";
import { addMonths, subMonths } from "date-fns";
import Month from "./Month";
import { weekBoundsOfMonth } from "lib/month";
const daysOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
interface CalendarProps {
onDateClick?: (_: Date) => void;
}
export default function Calendar({ onDateClick }: CalendarProps) {
const [viewportHeight, setViewportHeight] = useState(0);
const [scrollyEl, setScrollyEl] = useState<HTMLDivElement>(null);
const scrollyRef = useCallback((node: HTMLDivElement) => {
if (node) {
setScrollyEl(node);
setViewportHeight(node.clientHeight);
}
}, []);
useEffect(() => {
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
setViewportHeight(scrollyEl.clientHeight);
}
});
if (scrollyEl) observer.observe(scrollyEl);
return () => {
if (scrollyEl) observer.unobserve(scrollyEl);
};
}, [scrollyEl]);
console.log("SCROLLY REF IS", scrollyRef);
const [middleMonthEl, setMiddleMonthEl] = useState<HTMLDivElement>(null);
const middleMonthRef = useCallback((node: HTMLDivElement) => {
if (node) setMiddleMonthEl(node);
}, []);
// The calendar should always show 6 rows
const dateCellHeight = viewportHeight / 6;
const now = new Date();
const [currentlyShownMonth, setCurrentlyShownMonth] = useState(now);
const monthName = currentlyShownMonth.toLocaleDateString("default", {
month: "long",
});
const prevMonth = subMonths(currentlyShownMonth, 1);
const nextMonth = addMonths(currentlyShownMonth, 1);
const [monthsShown, setMonthsShown] = useState([
prevMonth,
currentlyShownMonth,
nextMonth,
]);
useEffect(() => {
middleMonthEl?.scrollIntoView();
}, [middleMonthRef]);
return (
<div className={styles.calendar}>
<div className={styles.header}>
<div className={styles.title}>
<b>{monthName}</b>
{currentlyShownMonth.getFullYear()}
</div>
<div className={styles.daysOfWeek}>
{daysOfWeek.map((day) => (
<div key={day} className={styles.dayOfWeek}>
{day}
</div>
))}
</div>
</div>
<div className={styles.scrollyPart} ref={scrollyRef}>
{monthsShown.map((month) => {
// How many rows will this month take up?
const [startWeek, endWeek] = weekBoundsOfMonth(month);
const numWeeks = endWeek - startWeek + 1;
const dateGridHeight = dateCellHeight * numWeeks;
const props = {
month,
dateGridHeight,
};
const ref =
(month === currentlyShownMonth && middleMonthRef) || undefined;
return (
<Month
key={month.toString()}
{...props}
ref={ref}
onDateClick={onDateClick}
/>
);
})}
</div>
</div>
);
}

View file

@ -0,0 +1,38 @@
.monthTitle {
}
.dateGrid {
display: grid;
grid-template-columns: repeat(7, 1fr);
}
.dateCell {
display: flex;
flex-direction: column;
border-width: 1px 0 0 1px;
border-color: lightgray;
border-style: solid;
}
.dateNumber {
cursor: default;
text-align: right;
display: flex;
justify-content: flex-end;
padding: 4px;
span {
padding: 8px;
border-radius: 24px;
display: flex;
justify-content: center;
align-items: center;
&.today {
background-color: red;
color: white;
}
}
}

65
src/calendar/Month.tsx Normal file
View file

@ -0,0 +1,65 @@
import { forwardRef } from "react";
import styles from "./Month.module.scss";
import {
addDays,
endOfMonth,
getWeek,
isSameDay,
startOfMonth,
startOfWeek,
} from "date-fns";
import classNames from "classnames";
import { weekBoundsOfMonth } from "lib/month";
interface MonthProps {
month: Date;
dateGridHeight: number;
onDateClick?: (_: Date) => void;
}
function Month({ month, dateGridHeight, onDateClick }: MonthProps, ref) {
const now = new Date();
const monthName = month.toLocaleString("default", { month: "long" });
const [startWeek, endWeek] = weekBoundsOfMonth(month);
const numWeeks = endWeek - startWeek + 1;
const weeksArr = Array(numWeeks)
.fill(0)
.map((_, i) => addDays(startOfMonth(month), 7 * i));
const datesArr = weeksArr.flatMap((week) => {
const start = startOfWeek(week);
return Array(7)
.fill(0)
.map((_, i) => addDays(start, i));
});
return (
<>
<div
className={styles.dateGrid}
style={{ height: `${dateGridHeight}px` }}
ref={ref}
>
{datesArr.map((date) => {
const isFirst = isSameDay(date, startOfMonth(date));
const isToday = isSameDay(date, now);
return (
<div key={date.toString()} className={styles.dateCell}>
<div
className={styles.dateNumber}
onClick={() => onDateClick?.(date)}
>
<span className={classNames(isToday && styles.today)}>
{isFirst && monthName}
{date.getDate()}
</span>
</div>
</div>
);
})}
</div>
</>
);
}
export default forwardRef(Month);

11
src/global.scss Normal file
View file

@ -0,0 +1,11 @@
html,
body,
#app {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
font-family: sans-serif;
}

73
src/main.ts Normal file
View file

@ -0,0 +1,73 @@
import "@logseq/libs";
import App from "./App";
import { createRoot } from "react-dom/client";
import "./global.scss";
/**
* user model
*/
function createModel() {
return {
openCalendar() {
console.log("SHiET, clicked");
logseq.showMainUI();
},
};
}
/**
* app entry
*/
function main() {
logseq.setMainUIInlineStyle({
position: "fixed",
zIndex: 11,
});
const key = logseq.baseInfo.id;
logseq.provideStyle(`
@import url("https://at.alicdn.com/t/font_2409735_haugsknp36e.css");
div[data-injected-ui=open-calendar-${key}] {
display: flex;
align-items: center;
font-weight: 500;
position: relative;
top: 0px;
}
div[data-injected-ui=open-calendar-${key}] a {
opacity: 1;
padding: 6px;
}
div[data-injected-ui=open-calendar-${key}] iconfont {
font-size: 18px;
}
`);
// external btns
logseq.App.registerUIItem("toolbar", {
key: "open-calendar",
template: `
<a class="button" data-on-click="openCalendar" style="font-size: 14px;">
<i class="iconfont icon-calendar"></i>
&nbsp;
Calendar
</a>
`,
});
// main UI
// createApp(App).use(VCalendar, {}).mount("#app");
const el = document.getElementById("app")!;
createRoot(el).render(App());
}
// bootstrap
logseq.ready(createModel()).then(main).catch(console.error);
const el = document.getElementById("app")!;
createRoot(el).render(App());

79
tsconfig.json Normal file
View file

@ -0,0 +1,79 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "ESNext",
/* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "ESNext",
/* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
"noEmit": true,
/* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true,
/* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
"baseUrl": "./" /* Base directory to resolve non-absolute module names. */,
"paths": {} /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */,
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
"allowSyntheticDefaultImports": true,
/* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true,
/* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
"jsx": "react-jsx",
/* Advanced Options */
"skipLibCheck": true,
/* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true
/* Disallow inconsistently-cased references to the same file. */
}
}

5
vite.config.ts Normal file
View file

@ -0,0 +1,5 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";
export default defineConfig({ base: "", plugins: [react(), tsconfigPaths()] });