Skip to content

Commit

Permalink
Render view based on daily note (#123)
Browse files Browse the repository at this point in the history
* feat: when opening a daily note

new setting to enable this feature
refactor reduceTimeSpans function to allow other dates than today

debounce rendering for some Obsidian events

* chore: update core-plugins.json and adjust npm script generateNotes

* chore: extract more logic from reduceTimeSpans to simplify

* chore: simplify Main.tsx

* chore: bumb version
  • Loading branch information
Kageetai authored Aug 12, 2024
1 parent 33a6994 commit 5939586
Show file tree
Hide file tree
Showing 9 changed files with 132 additions and 68 deletions.
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "journal-review",
"name": "Journal Review",
"version": "2.3.2",
"version": "2.4.0",
"minAppVersion": "0.15.0",
"description": "Review your daily notes on their anniversaries, like \"what happened today last year\".",
"author": "Kageetai",
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
{
"name": "obsidian-plugin-journal-review",
"version": "2.3.2",
"version": "2.4.0",
"description": "Review your daily notes on their anniversaries, like \"what happened today last year\"\n\n",
"main": "main.js",
"scripts": {
"dev": "node esbuild.config.mjs",
"build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production",
"version": "node version-bump.mjs && git add manifest.json versions.json",
"lint": "eslint .",
"generateNotes": "ts-node-esm ./scripts/generateNotes.ts vault 5"
"generateNotes": "ts-node ./scripts/generateNotes.ts vault 5"
},
"keywords": [],
"author": "Kageetai",
Expand Down
31 changes: 21 additions & 10 deletions src/components/Main.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,31 @@
import TimeSpan from "./TimeSpan";
import { RenderedTimeSpan } from "../constants";
import useContext from "../hooks/useContext";
import { Moment } from "moment";

interface Props {
timeSpans: RenderedTimeSpan[];
startDate?: Moment;
}

const Main = ({ timeSpans }: Props) => (
<div id="journal-review">
<h2>On this day...</h2>
const Main = ({ timeSpans, startDate }: Props) => {
const { settings } = useContext();

<ul className="list">
{timeSpans.map(({ title, notes }) => (
<TimeSpan key={title} title={title} notes={notes} wrapper={<li />} />
))}
</ul>
</div>
);
return (
<div id="journal-review">
{settings.renderOnFileSwitch && startDate ? (
<h2>On {startDate.format("ll")}...</h2>
) : (
<h2>On today...</h2>
)}

<ul className="list">
{timeSpans.map(({ title, notes }) => (
<TimeSpan key={title} title={title} notes={notes} wrapper={<li />} />
))}
</ul>
</div>
);
};

export default Main;
66 changes: 41 additions & 25 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
getDailyNote,
getDateFromFile,
} from "obsidian-daily-notes-interface";
import { Moment } from "moment";

export const DEBOUNCE_DELAY = 1000;
export const VIEW_TYPE = "on-this-day-view";
Expand Down Expand Up @@ -50,6 +51,7 @@ export interface Settings {
openInNewPane: boolean;
showNoteTitle: boolean;
useNotifications: boolean;
renderOnFileSwitch: boolean;
date: string;
}

Expand All @@ -63,57 +65,71 @@ export const DEFAULT_SETTINGS: Settings = {
openInNewPane: false,
showNoteTitle: true,
useNotifications: true,
renderOnFileSwitch: false,
date: "",
};

export const getTimeSpanTitle = ({ number, unit, recurring }: TimeSpan) =>
`${recurring ? "every" : ""} ${number} ${unit}${number > 1 ? "s" : ""}`;

const reduceToOldestNote = (oldestDate: Moment, currentNote: TFile) => {
const currentDate = getDateFromFile(currentNote, "day");
return currentDate?.isBefore(oldestDate) ? currentDate : oldestDate;
};

const getTitle = (
useHumanize: boolean,
now: Moment,
startDate: Moment,
unit: Unit,
) =>
useHumanize
? now.from(startDate)
: `${getTimeSpanTitle({ number: startDate.diff(now, unit), unit })} ago`;

const getNotesOverMargins = (
dayMargin: number,
mom: moment.Moment,
allDailyNotes: AllDailyNotes,
) =>
Array(dayMargin * 2 + 1)
.fill(0)
.map(
(_, i) =>
getDailyNote(
moment(mom).add(i - dayMargin, "days"),
allDailyNotes,
) as TFile,
)
.filter(Boolean);
Array.from(
{ length: dayMargin * 2 + 1 },
(_, i) =>
getDailyNote(
moment(mom).add(i - dayMargin, "days"),
allDailyNotes,
) as TFile,
).filter(Boolean);
const sortRenderedTimeSpanByDateDesc = (
a: RenderedTimeSpan,
b: RenderedTimeSpan,
) => (a.moment.isAfter(b.moment) ? -1 : 1);

export const reduceTimeSpans = (
timeSpans: Array<TimeSpan>,
timeSpans: TimeSpan[],
allDailyNotes: AllDailyNotes,
dayMargin: number,
useHumanize: boolean,
dayMargin: number,
startDate: Moment = moment(),
): RenderedTimeSpan[] => {
const oldestNoteDate = Object.values(allDailyNotes).reduce(
(oldestDate, currentNote) => {
const currentDate = getDateFromFile(currentNote, "day");
return currentDate?.isBefore(oldestDate) ? currentDate : oldestDate;
},
moment(),
reduceToOldestNote,
startDate,
);

return Object.values(
timeSpans.reduce<Record<string, RenderedTimeSpan>>(
(acc, { number, unit, recurring }) => {
const mom = moment();
const mom = moment(startDate);

// if we have a recurring time span, we want to go back until we reach the oldest note
do {
// go back one unit of the timespan
mom.subtract(number, unit);
const title = useHumanize
? mom.fromNow()
: `${getTimeSpanTitle({
number: moment().diff(mom, unit),
unit,
})} ago`;

const title = getTitle(useHumanize, mom, startDate, unit);
const notes = getNotesOverMargins(dayMargin, mom, allDailyNotes);

if (notes.length) {
// used mapped object type to group notes together under same titles,
// even if they come from different time span settings
Expand All @@ -129,5 +145,5 @@ export const reduceTimeSpans = (
},
{},
),
).sort((a, b) => (a.moment.isAfter(b.moment) ? -1 : 1));
).sort(sortRenderedTimeSpanByDateDesc);
};
2 changes: 1 addition & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ export default class JournalReviewPlugin extends Plugin {
const noteCount = reduceTimeSpans(
this.settings.timeSpans,
getAllDailyNotes(),
this.settings.dayMargin,
this.settings.useHumanize,
this.settings.dayMargin,
).reduce((count, timeSpan) => count + timeSpan.notes.length, 0);

if (noteCount) {
Expand Down
12 changes: 12 additions & 0 deletions src/settingsTab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,5 +233,17 @@ export class SettingsTab extends PluginSettingTab {
void this.plugin.saveSettings();
});
});

new Setting(containerEl)
.setName("Date based on selected note")
.setDesc("Use the date of the currently open daily note.")
.addToggle((toggle) => {
toggle
.setValue(this.plugin.settings.renderOnFileSwitch)
.onChange((value) => {
this.plugin.settings.renderOnFileSwitch = value;
void this.plugin.saveSettings();
});
});
}
}
30 changes: 22 additions & 8 deletions src/view.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ItemView, TFile, WorkspaceLeaf } from "obsidian";
import { debounce, ItemView, TFile, WorkspaceLeaf } from "obsidian";
import {
appHasDailyNotesPluginLoaded,
getAllDailyNotes,
Expand All @@ -9,6 +9,7 @@ import Main from "./components/Main";
import AppContext from "./components/context";
import { icon } from "./main";
import { reduceTimeSpans, Settings, VIEW_TYPE } from "./constants";
import { Moment } from "moment";

export default class OnThisDayView extends ItemView {
private readonly settings: Settings;
Expand All @@ -23,21 +24,31 @@ export default class OnThisDayView extends ItemView {
this.registerEvent(
this.app.vault.on("create", (file: TFile) => {
if (getDateFromFile(file, "day")) {
this.renderView();
this.debouncedRenderView();
}
}),
);
this.registerEvent(
this.app.vault.on("delete", (file: TFile) => {
if (getDateFromFile(file, "day")) {
this.renderView();
this.debouncedRenderView();
}
}),
);
this.registerEvent(
this.app.vault.on("rename", (file: TFile) => {
if (getDateFromFile(file, "day")) {
this.renderView();
this.debouncedRenderView();
}
}),
);

this.registerEvent(
this.app.workspace.on("file-open", (file) => {
const dateFromFile = file && getDateFromFile(file, "day");

if (this.settings.renderOnFileSwitch && dateFromFile) {
this.debouncedRenderView(dateFromFile);
}
}),
);
Expand All @@ -63,7 +74,7 @@ export default class OnThisDayView extends ItemView {
return "On this day";
}

renderView() {
renderView(startDate?: Moment) {
const container = this.containerEl.children[1];
const hasDailyNotesPluginLoaded = appHasDailyNotesPluginLoaded();

Expand All @@ -78,8 +89,9 @@ export default class OnThisDayView extends ItemView {
const timeSpans = reduceTimeSpans(
this.settings.timeSpans,
getAllDailyNotes(),
this.settings.dayMargin,
this.settings.useHumanize,
this.settings.dayMargin,
startDate,
);

render(
Expand All @@ -90,14 +102,16 @@ export default class OnThisDayView extends ItemView {
settings: this.settings,
}}
>
<Main timeSpans={timeSpans} />
<Main timeSpans={timeSpans} startDate={startDate} />
</AppContext.Provider>,
container,
);
}

debouncedRenderView = debounce(this.renderView.bind(this), 500);

async onOpen() {
this.renderView();
this.debouncedRenderView();
}

async onClose() {}
Expand Down
50 changes: 30 additions & 20 deletions vault/.obsidian/core-plugins.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
[
"file-explorer",
"global-search",
"switcher",
"graph",
"backlink",
"canvas",
"outgoing-link",
"tag-pane",
"page-preview",
"daily-notes",
"templates",
"note-composer",
"command-palette",
"editor-status",
"bookmarks",
"outline",
"word-count",
"file-recovery"
]
{
"file-explorer": true,
"global-search": true,
"switcher": true,
"graph": true,
"backlink": true,
"canvas": true,
"outgoing-link": true,
"tag-pane": true,
"properties": false,
"page-preview": true,
"daily-notes": true,
"templates": true,
"note-composer": true,
"command-palette": true,
"slash-command": false,
"editor-status": true,
"bookmarks": true,
"markdown-importer": false,
"zk-prefixer": false,
"random-note": false,
"outline": true,
"word-count": true,
"slides": false,
"audio-recorder": false,
"workspaces": false,
"file-recovery": true,
"publish": false,
"sync": false
}
3 changes: 2 additions & 1 deletion versions.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@
"2.2.0": "0.15.0",
"2.3.0": "0.15.0",
"2.3.1": "0.15.0",
"2.3.2": "0.15.0"
"2.3.2": "0.15.0",
"2.4.0": "0.15.0"
}

0 comments on commit 5939586

Please sign in to comment.