Skip to content

Commit

Permalink
refactor: fix some todos
Browse files Browse the repository at this point in the history
  • Loading branch information
ivan-lednev committed Aug 20, 2023
1 parent cda361f commit 7d07d1c
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 63 deletions.
22 changes: 22 additions & 0 deletions src/parser/calculate-default-duration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { getDiffInMinutes } from "../util/moment";
import { DEFAULT_DURATION_MINUTES } from "../constants";
import type { createPlanItem } from "./parser";

export function calculateDefaultDuration(
item: ReturnType<typeof createPlanItem>,
next?: ReturnType<typeof createPlanItem>,
) {
if (item.endTime) {
return getDiffInMinutes(item.startTime, item.endTime);
}

if (next) {
const minutesUntilNext = getDiffInMinutes(next.startTime, item.startTime);

if (minutesUntilNext < DEFAULT_DURATION_MINUTES) {
return minutesUntilNext;
}
}

return DEFAULT_DURATION_MINUTES;
}
20 changes: 18 additions & 2 deletions src/parser/parser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,26 @@ const defaultPlannerHeading = "Day planner";
// todo: replace with toMatchObject
it.skip("parses tasks with timestamps from lines", () => {
expect(
parsePlanItems(basic.content, basic.metadata, defaultPlannerHeading, ""),
parsePlanItems(
basic.content,
basic.metadata,
defaultPlannerHeading,
"",
window.moment(),
),
).toMatchSnapshot();
});

// todo: replace with toMatchObject
it.skip("grabs subtasks", () => {
expect(
parsePlanItems(subtasks.content, subtasks.metadata, "Day planner", ""),
parsePlanItems(
subtasks.content,
subtasks.metadata,
"Day planner",
"",
window.moment(),
),
).toMatchSnapshot();
});

Expand All @@ -30,6 +42,7 @@ it.skip("parses bullet lists without checkboxes", () => {
withoutTasks.metadata,
defaultPlannerHeading,
"",
window.moment(),
),
).toMatchSnapshot();
});
Expand All @@ -42,6 +55,7 @@ it.skip("parses end time", () => {
endTime.metadata,
defaultPlannerHeading,
"",
window.moment(),
),
).toMatchSnapshot();
});
Expand All @@ -53,6 +67,7 @@ it("handles list items above daily plan", () => {
listItemsAbove.metadata,
defaultPlannerHeading,
"",
window.moment(),
),
).toMatchObject([{ text: "Wake up" }]);
});
Expand All @@ -64,6 +79,7 @@ it("handles tasks under subheadings", () => {
subheadings.metadata,
defaultPlannerHeading,
"",
window.moment(),
),
).toMatchObject([
{ text: "Wake up" },
Expand Down
68 changes: 12 additions & 56 deletions src/parser/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,45 +3,18 @@ import { parseTimestamp } from "../timestamp/timestamp";
import { timestampRegExp } from "../regexp";
import { isTopLevelListItem } from "../../obsidian-metadata-utils/src/list";
import { getTextAtPosition } from "../../obsidian-metadata-utils/src/position";
import {
getDiffInMinutes,
getMinutesSinceMidnightOfDayTo,
minutesToMomentOfDay,
} from "../util/moment";
import { DEFAULT_DURATION_MINUTES } from "../constants";
import {
getMomentOfActiveDay,
getTimeFromYOffset,
roundToSnapStep,
} from "../store/timeline-store";
import { getDailyNoteForToday } from "../util/daily-notes";
import { getMinutesSinceMidnightOfDayTo } from "../util/moment";
import { getMomentOfActiveDay } from "../store/timeline-store";
import type { PlanItem, PlanItemLocation } from "../types";

// todo: out of place
export function calculateDefaultDuration(
item: ReturnType<typeof createPlanItem>,
next?: ReturnType<typeof createPlanItem>,
) {
if (item.endTime) {
return getDiffInMinutes(item.startTime, item.endTime);
}

if (next) {
const minutesUntilNext = getDiffInMinutes(next.startTime, item.startTime);

if (minutesUntilNext < DEFAULT_DURATION_MINUTES) {
return minutesUntilNext;
}
}

return DEFAULT_DURATION_MINUTES;
}
import { calculateDefaultDuration } from "./calculate-default-duration";
import type { Moment } from "moment";

export function parsePlanItems(
content: string,
metadata: CachedMetadata,
planHeadingContent: string,
path: string,
day: Moment,
): PlanItem[] {
const listItemsUnderPlan = getListItemsUnderHeading(
metadata,
Expand All @@ -59,6 +32,7 @@ export function parsePlanItems(
createPlanItem({
line: li.listItemLineContent,
location: { path, line: li.line },
day,
}),
)
.filter((item) => item !== null)
Expand Down Expand Up @@ -87,6 +61,7 @@ export function parsePlanItems(
.sort((a, b) => a.startMinutes - b.startMinutes);
}

// todo: this belongs to metadata-utils
export function getListItemsUnderHeading(
metadata: CachedMetadata,
heading: string,
Expand Down Expand Up @@ -125,12 +100,14 @@ export function getHeadingByText(metadata: CachedMetadata, text: string) {
return headings?.find((h) => h.heading === text);
}

function createPlanItem({
export function createPlanItem({
line,
location,
day,
}: {
line: string;
location: PlanItemLocation;
day: Moment;
}) {
const match = timestampRegExp.exec(line.trim());
if (!match) {
Expand All @@ -142,13 +119,13 @@ function createPlanItem({
} = match;

// todo: parser should not depend on UI state
const startTime = parseTimestamp(start, getMomentOfActiveDay());
const startTime = parseTimestamp(start, day);

return {
listTokens,
startTime,
// todo: parser should not depend on UI state
endTime: parseTimestamp(end, getMomentOfActiveDay()),
endTime: parseTimestamp(end, day),
rawStartTime: start,
rawEndTime: end,
text,
Expand Down Expand Up @@ -191,24 +168,3 @@ function getListItemContent(content: string, listItems: ListItemCache[]) {
},
);
}

// todo: move
export function createPlanItemFromTimeline(pointerYOffset: number) {
const startMinutes = getTimeFromYOffset(roundToSnapStep(pointerYOffset));
const endMinutes = startMinutes + DEFAULT_DURATION_MINUTES;

return {
id: String(Math.random()),
startMinutes,
durationMinutes: DEFAULT_DURATION_MINUTES,
endMinutes,
text: "New item",
startTime: minutesToMomentOfDay(startMinutes, getMomentOfActiveDay()),
endTime: minutesToMomentOfDay(endMinutes, getMomentOfActiveDay()),
// todo: no hardcode
listTokens: "- ",
location: {
path: getDailyNoteForToday().path,
},
};
}
2 changes: 1 addition & 1 deletion src/store/update-timestamp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import type { PlanItem } from "../types";
export async function updateTimestamps(id: string, timestamp: Timestamp) {
tasks.update((previous) => {
return previous.map((task) => {
// todo: replace with ID
if (task.id !== id) {
return task;
}
Expand All @@ -30,6 +29,7 @@ async function updateDurationInDailyNote(
const file = get(appStore).vault.getAbstractFileByPath(task.location.path);

if (!(file instanceof TFile)) {
// todo: we can do better
throw new Error("Something is wrong");
}

Expand Down
1 change: 0 additions & 1 deletion src/ui/components/task.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@
? (100 / itemPlacing.columns) * itemPlacing.start
: 0;
// todo: clean up
$: relationToNow = isGhost
? "future"
: getRelationToNow($time, startTime, endTime);
Expand Down
32 changes: 30 additions & 2 deletions src/ui/hooks/use-create.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import { createPlanItemFromTimeline } from "../../parser/parser";
import { appendToPlan } from "../../plan";
import { getTimelineFile, tasks } from "../../store/timeline-store";
import {
getMomentOfActiveDay,
getTimeFromYOffset,
getTimelineFile,
roundToSnapStep,
tasks,
} from "../../store/timeline-store";
import { get, writable } from "svelte/store";
import { DEFAULT_DURATION_MINUTES } from "../../constants";
import { minutesToMomentOfDay } from "../../util/moment";
import { getDailyNoteForToday } from "../../util/daily-notes";

export function useCreate() {
const creating = writable(false);
Expand Down Expand Up @@ -38,3 +46,23 @@ export function useCreate() {
confirmCreation,
};
}

function createPlanItemFromTimeline(pointerYOffset: number) {
const startMinutes = getTimeFromYOffset(roundToSnapStep(pointerYOffset));
const endMinutes = startMinutes + DEFAULT_DURATION_MINUTES;

return {
id: String(Math.random()),
startMinutes,
durationMinutes: DEFAULT_DURATION_MINUTES,
endMinutes,
text: "New item",
startTime: minutesToMomentOfDay(startMinutes, getMomentOfActiveDay()),
endTime: minutesToMomentOfDay(endMinutes, getMomentOfActiveDay()),
// todo: no hardcode
listTokens: "- ",
location: {
path: getDailyNoteForToday().path,
},
};
}
17 changes: 16 additions & 1 deletion src/util/obsidian.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { appStore, getTimelineFile, tasks } from "../store/timeline-store";
import { get } from "svelte/store";
import { parsePlanItems } from "../parser/parser";
import { settings } from "../store/settings";
import { getDateFromFile } from "obsidian-daily-notes-interface";

export async function openFileInEditor(file: TFile) {
const app = get(appStore);
Expand Down Expand Up @@ -41,5 +42,19 @@ async function getPlanItemsFromFile(file: TFile) {
const fileContents = await app.vault.cachedRead(file);
const metadata = app.metadataCache.getFileCache(file);

return parsePlanItems(fileContents, metadata, plannerHeading, file.path);
const fileDay = getDateFromFile(file, "day");

if (!fileDay) {
throw new Error(
`Tried to parse plan in file that is not a daily note: ${file.path}`,
);
}

return parsePlanItems(
fileContents,
metadata,
plannerHeading,
file.path,
fileDay,
);
}

0 comments on commit 7d07d1c

Please sign in to comment.