Skip to content

Commit

Permalink
fix: adapt for user defined date formats
Browse files Browse the repository at this point in the history
  • Loading branch information
pengx17 committed Nov 7, 2021
1 parent 7596ac2 commit 14b467e
Show file tree
Hide file tree
Showing 6 changed files with 95 additions and 58 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"dependencies": {
"@logseq/libs": "0.0.1-alpha.30",
"@types/uuid": "^8.3.1",
"dayjs": "^1.10.7",
"date-fns": "^2.25.0",
"react": "^17.0.2",
"react-calendar-heatmap": "^1.8.1",
"react-dom": "^17.0.2",
Expand Down
13 changes: 7 additions & 6 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 15 additions & 13 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import React, { useRef } from "react";
import { Heatmap } from "./Heatmap";
import { useAppVisible, useThemeMode } from "./utils";

console.log(await logseq.App.getUserInfo())
const Heatmap = React.lazy(() =>
import("./Heatmap").then((d) => ({ default: d.Heatmap }))
);

function App() {
const innerRef = useRef<HTMLDivElement>(null);
Expand All @@ -23,16 +23,18 @@ function App() {
}, [visible]);
if (started) {
return (
<main
className={`absolute inset-0 ${themeMode}`}
onClick={(e) => {
if (!innerRef.current?.contains(e.target as any)) {
window.logseq.hideMainUI();
}
}}
>
<Heatmap ref={innerRef} />
</main>
<React.Suspense fallback="loading...">
<main
className={`absolute inset-0 ${themeMode}`}
onClick={(e) => {
if (!innerRef.current?.contains(e.target as any)) {
window.logseq.hideMainUI();
}
}}
>
<Heatmap ref={innerRef} />
</main>
</React.Suspense>
);
}
return null;
Expand Down
70 changes: 36 additions & 34 deletions src/Heatmap.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";
import advancedFormat from "dayjs/plugin/advancedFormat";

import {
addDays,
addWeeks,
differenceInDays,
endOfWeek,
parse,
startOfWeek,
} from "date-fns";
import * as React from "react";
import CalendarHeatmap from "react-calendar-heatmap";
import ReactTooltip from "react-tooltip";
import { useMountedState } from "react-use";
import "./Heatmap.css";
import { getIconPosition as getTriggerIconPosition } from "./utils";

dayjs.extend(customParseFormat);
dayjs.extend(advancedFormat);

const defaultFormat = "YYYY-MM-DD";
import {
formatAsDashed,
formatAsLocale,
formatAsParam,
getIconPosition as getTriggerIconPosition,
} from "./utils";

const useActivities = (startDate: string, endDate: string) => {
const [values, setValues] = React.useState<
Expand All @@ -22,43 +26,42 @@ const useActivities = (startDate: string, endDate: string) => {

React.useLayoutEffect(() => {
(async () => {
const d0 = dayjs(startDate).format("YYYYMMDD");
const d1 = dayjs(endDate).format("YYYYMMDD");
const date0 = new Date(startDate);
const date1 = new Date(endDate);

const res: any[] = await logseq.DB.datascriptQuery(`
[:find (pull ?p [*]) (count ?b)
:where
[?b :block/page ?p]
[?p :block/journal? true]
[?p :block/journal-day ?d]
[(>= ?d ${d0})] [(<= ?d ${d1})]]
[(>= ?d ${formatAsParam(date0)})] [(<= ?d ${formatAsParam(date1)})]]
`);

const mapping = Object.fromEntries(
res.map(([page, count]: any[]) => {
const datum = {
count: count ?? 0,
date: dayjs("" + page["journal-day"], "YYYYMMDD").format(
defaultFormat
date: formatAsDashed(
parse(`${page["journal-day"]}`, "yyyyMMdd", new Date())
),
originalName: page["original-name"] as string,
};
return [datum.date, datum];
})
);

const totalDays = dayjs(endDate).diff(dayjs(startDate), "d") + 1;
const totalDays = differenceInDays(date1, date0) + 1;
const newValues: Datum[] = [];
for (let i = 0; i < totalDays; i++) {
const date = dayjs(startDate).add(i, "d").format(defaultFormat);
const date = formatAsDashed(addDays(date0, i));
if (mapping[date]) {
newValues.push(mapping[date]);
} else {
newValues.push({
date,
count: 0,
// FIXME: only support default date format for now
originalName: dayjs(date).format("MMM Do, YYYY"),
originalName: formatAsLocale(date),
});
}
}
Expand Down Expand Up @@ -167,24 +170,23 @@ const DateRange = ({
}) => {
React.useLayoutEffect(() => {
if (!range) {
const endDate = dayjs(today).endOf("week").format(defaultFormat);
const startDate = dayjs(endDate)
.add(-NUM_WEEKS, "week")
.startOf("week")
.format(defaultFormat);
const endDate = formatAsDashed(endOfWeek(new Date(today)));
const startDate = formatAsDashed(
startOfWeek(addWeeks(endOfWeek(new Date(today)), -NUM_WEEKS))
);
onRangeChange([startDate, endDate]);
}
}, [range]);

const onRangeClick = (isPrev: boolean) => {
const [, endDate] = range!;
const newEndDate = dayjs(endDate)
.add(isPrev ? -12 : 12, "weeks")
.format(defaultFormat);
const newStartDate = dayjs(newEndDate)
.add(-NUM_WEEKS, "week")
.startOf("week")
.format(defaultFormat);
const newEndDate = formatAsDashed(
addWeeks(new Date(endDate), isPrev ? -12 : 12)
);

const newStartDate = formatAsDashed(
startOfWeek(addWeeks(new Date(newEndDate), -NUM_WEEKS))
);

onRangeChange([newStartDate, newEndDate]);
};
Expand All @@ -195,11 +197,11 @@ const DateRange = ({
<div className="text-xs mb-2">
From
<span className="date-range-tag" onClick={() => onRangeClick(true)}>
{dayjs(startDate).format("MMM Do, YYYY")}
{formatAsLocale(startDate)}
</span>
to
<span className="date-range-tag" onClick={() => onRangeClick(false)}>
{dayjs(endDate).format("MMM Do, YYYY")}
{formatAsLocale(endDate)}
</span>
</div>
);
Expand All @@ -208,7 +210,7 @@ const DateRange = ({
};

export const Heatmap = React.forwardRef<HTMLDivElement>(({}, ref) => {
const today = dayjs().format(defaultFormat);
const today = formatAsDashed(new Date());
const [range, setRange] = React.useState<[string, string] | null>(null);
const { bottom, right } = getTriggerIconPosition();
return (
Expand Down
7 changes: 4 additions & 3 deletions src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import "virtual:windi-devtools";
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { openIconName } from "./utils";
import { getDisplayDateFormat, openIconName } from "./utils";

// @ts-expect-error
const css = (t, ...args) => String.raw(t, ...args);
Expand All @@ -24,7 +24,8 @@ function main() {

function createModel() {
return {
show() {
async show() {
await getDisplayDateFormat();
logseq.showMainUI();
},
};
Expand Down Expand Up @@ -53,7 +54,7 @@ function main() {
logseq.App.registerUIItem("toolbar", {
key: openIconName,
template: `
<a data-on-click="show">
<a data-on-click="show" style="inline-block">
<div class="logseq-heatmap-trigger-icon"></div>
</a>
`,
Expand Down
33 changes: 32 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { format } from "date-fns";
import React, { useState } from "react";
import { useMountedState } from "react-use";

Expand Down Expand Up @@ -50,7 +51,7 @@ export const useThemeMode = () => {
(top?.document
.querySelector("html")
?.getAttribute("data-theme") as typeof mode) ??
(matchMedia("prefers-color-scheme: dark").matches ? "dark" : "light")
(matchMedia("prefers-color-scheme: dark").matches ? "dark" : "light")
);
logseq.App.onThemeModeChanged((s) => {
console.log(s);
Expand All @@ -62,3 +63,33 @@ export const useThemeMode = () => {

return mode;
};


export let displayDateFormat = "MMM do, yyyy";

export async function getDisplayDateFormat() {
let format =
(await logseq.App.getUserConfigs())?.preferredDateFormat ?? "MMM do, yyyy";

displayDateFormat = format;
return format;
}

export const toDate = (d: Date | string) => {
if (typeof d !== "string") {
return d;
}
return new Date(d);
};

export const formatAsDashed = (d: Date | string) => {
return format(toDate(d), "yyyy-MM-dd");
};

export const formatAsParam = (d: Date | string) => {
return format(toDate(d), "yyyyMMdd");
};

export const formatAsLocale = (d: Date | string) => {
return format(toDate(d), displayDateFormat);
};

0 comments on commit 14b467e

Please sign in to comment.