Skip to content

Commit

Permalink
fix: can't log into specific log file (#28)
Browse files Browse the repository at this point in the history
* fix: Cant log sessions after the update #27
  • Loading branch information
eatgrass authored Jan 15, 2024
1 parent 9965209 commit 7e152c9
Show file tree
Hide file tree
Showing 6 changed files with 126 additions and 111 deletions.
25 changes: 1 addition & 24 deletions src/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { type TimerState, type Mode } from 'Timer'
import * as utils from 'utils'
import PomodoroTimerPlugin from 'main'
import { TFile, Notice, moment } from 'obsidian'
import { incrTaskActual, type TaskItem } from 'Tasks'
import { type TaskItem } from 'Tasks'

export type TimerLog = {
duration: number
Expand Down Expand Up @@ -56,29 +56,6 @@ export default class Logger {
}
}

// update task item
if (this.plugin.getSettings().enableTaskTracking) {
if (
state.mode === 'WORK' &&
log.finished &&
state.task?.path &&
state.task?.blockLink
) {
let file = this.plugin.app.vault.getAbstractFileByPath(
state.task.path,
)
if (file && file instanceof TFile) {
let f = file as TFile
incrTaskActual(
this.plugin.getSettings().taskFormat,
this.plugin.app,
state.task.blockLink,
f,
)
}
}
}

return logFile
}

Expand Down
103 changes: 99 additions & 4 deletions src/TaskTracker.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import type { TaskItem } from 'Tasks'
import { type TaskItem } from 'Tasks'
import type PomodoroTimerPlugin from 'main'
import { TFile, Keymap } from 'obsidian'
import { TFile, Keymap, MarkdownView } from 'obsidian'
import { DESERIALIZERS, POMODORO_REGEX } from 'serializer'
import {
writable,
type Readable,
type Writable,
type Unsubscriber,
} from 'svelte/store'
import { extractTaskComponents } from 'utils'

export type TaskTrackerState = {
task?: TaskItem
Expand Down Expand Up @@ -111,15 +113,15 @@ export default class TaskTracker implements TaskTrackerStore {
if (task.blockLink) {
if (!line.endsWith(task.blockLink)) {
// block id mismatch?
lines[task.line] += ` ${task.blockLink}`
lines[task.line] += `${task.blockLink}`
this.plugin.app.vault.modify(f, lines.join('\n'))
return
}
} else {
// generate block id
let blockId = this.createBlockId()
task.blockLink = blockId
lines[task.line] += ` ${blockId}`
lines[task.line] += `${blockId}`
this.plugin.app.vault.modify(f, lines.join('\n'))
}
}
Expand Down Expand Up @@ -183,4 +185,97 @@ export default class TaskTracker implements TaskTrackerStore {
})
}
}

public async updateActual() {
// update task item
if (
this.plugin.getSettings().enableTaskTracking &&
this.task &&
this.task.blockLink
) {
let file = this.plugin.app.vault.getAbstractFileByPath(
this.task.path,
)
if (file && file instanceof TFile) {
let f = file as TFile
if (this.task?.actual) {
this.task.actual += 1
} else {
this.task.actual = 1
}

await this.incrTaskActual(this.task.blockLink, f)
}
}
}

private async incrTaskActual(blockLink: string, file: TFile) {
const format = this.plugin.getSettings().taskFormat

if (file.extension !== 'md') {
return
}

let metadata = this.plugin.app.metadataCache.getFileCache(file)
let content = await this.plugin.app.vault.read(file)

if (!content || !metadata) {
return
}

const lines = content.split('\n')

for (let rawElement of metadata.listItems || []) {
if (rawElement.task) {
let lineNr = rawElement.position.start.line
let line = lines[lineNr]

const components = extractTaskComponents(line)

if (!components) {
continue
}

if (components.blockLink === blockLink) {
const match = components.body.match(POMODORO_REGEX)
if (match !== null) {
let pomodoros = match[1]
let [actual = '0', expected] = pomodoros.split('/')
let text = `🍅:: ${parseInt(actual) + 1}`
if (expected !== undefined) {
text += `/${expected.trim()}`
}
line = line
.replace(/🍅:: *(\d* *\/? *\d* *)/, text)
.trim()
lines[lineNr] = line
} else {
let detail = DESERIALIZERS[format].deserialize(
components.body,
)
line = line.replace(
detail.description,
`${detail.description} [🍅:: 1]`,
)

lines[lineNr] = line
}

this.plugin.app.vault.modify(file, lines.join('\n'))
this.plugin.app.metadataCache.trigger(
'changed',
file,
content,
metadata,
)

// refresh view
this.plugin.app.workspace
.getActiveViewOfType(MarkdownView)
?.load()
break
}
}
}
}
}
81 changes: 2 additions & 79 deletions src/Tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,10 @@ import { type CachedMetadata, type TFile, type App } from 'obsidian'
import { extractTaskComponents } from 'utils'
import { writable, derived, type Readable, type Writable } from 'svelte/store'

import {
DataviewTaskSerializer,
DefaultTaskSerializer,
type TaskDeserializer,
DEFAULT_SYMBOLS,
} from 'serializer'
import type { TaskFormat } from 'Settings'
import type { Unsubscriber } from 'svelte/motion'
import { MarkdownView } from 'obsidian'

const DESERIALIZERS: Record<TaskFormat, TaskDeserializer> = {
TASKS: new DefaultTaskSerializer(DEFAULT_SYMBOLS),
DATAVIEW: new DataviewTaskSerializer(),
}
import { DESERIALIZERS, POMODORO_REGEX } from 'serializer'

export type TaskItem = {
path: string
Expand Down Expand Up @@ -159,73 +149,6 @@ export default class Tasks implements Readable<TaskStore> {
}
}

const POMODORO_REGEX = new RegExp(
'(?:(?=[^\\]]+\\])\\[|(?=[^)]+\\))\\() *🍅:: *(\\d* *\\/? *\\d*) *[)\\]](?: *,)?',
)

export async function incrTaskActual(
format: TaskFormat,
app: App,
blockLink: string,
file: TFile,
) {
if (file.extension !== 'md') {
return
}

let metadata = app.metadataCache.getFileCache(file)
let content = await app.vault.read(file)

if (!content || !metadata) {
return
}

const lines = content.split('\n')

for (let rawElement of metadata.listItems || []) {
if (rawElement.task) {
let lineNr = rawElement.position.start.line
let line = lines[lineNr]

const components = extractTaskComponents(line)
if (!components) {
continue
}

if (components.blockLink === blockLink) {
const match = components.body.match(POMODORO_REGEX)
if (match !== null) {
let pomodoros = match[1]
let [actual = '0', expected] = pomodoros.split('/')
let text = `🍅:: ${parseInt(actual) + 1}`
if (expected !== undefined) {
text += `/${expected.trim()}`
}
line = line.replace(/🍅:: *(\d* *\/? *\d* *)/, text).trim()
lines[lineNr] = line
} else {
let detail = DESERIALIZERS[format].deserialize(
components.body,
)
line = line.replace(
detail.description,
`${detail.description} [🍅:: 1]`,
)

lines[lineNr] = line
}

app.vault.modify(file, lines.join('\n'))
app.metadataCache.trigger('changed', file, content, metadata)

// refresh view
app.workspace.getActiveViewOfType(MarkdownView)?.load()
break
}
}
}
}

export function resolveTasks(
format: TaskFormat,
file: TFile,
Expand Down Expand Up @@ -258,7 +181,7 @@ export function resolveTasks(
fileName: file.name,
name: detail.description,
status: components.status,
blockLink: components.blockLink.trim(),
blockLink: components.blockLink,
checked: rawElement.task != '' && rawElement.task != ' ',
description: detail.description,
done: detail.doneDate?.format(dateformat),
Expand Down
11 changes: 10 additions & 1 deletion src/Timer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ export type TimerState = {
duration: number
}

export type TimerStore = TimerState & { remained: TimerRemained }
export type TimerStore = TimerState & {
remained: TimerRemained
finished: boolean
}

export default class Timer implements Readable<TimerStore> {
static DEFAULT_NOTIFICATION_AUDIO = new Audio(DEFAULT_NOTIFICATION)
Expand Down Expand Up @@ -75,6 +78,7 @@ export default class Timer implements Readable<TimerStore> {
this.store = derived(store, ($state) => ({
...$state,
remained: this.remain($state.count, $state.elapsed),
finished: $state.count == $state.elapsed,
}))

this.subscribe = this.store.subscribe
Expand Down Expand Up @@ -136,6 +140,11 @@ export default class Timer implements Readable<TimerStore> {
task.actual = task.actual ? task.actual + 1 : 1
}
const s = { ...state, task }

if (state.mode == 'WORK') {
this.plugin.tracker?.updateActual()
}

this.logger.log(s).then((logFile) => {
this.notify(s, logFile)
})
Expand Down
15 changes: 13 additions & 2 deletions src/serializer/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { Priority } from './TaskModels'
import type { TaskFormat } from 'Settings'
import { DataviewTaskSerializer } from './DataviewTaskSerializer'
import { DefaultTaskSerializer, DEFAULT_SYMBOLS } from './DefaultTaskSerializer'
import type { Moment } from 'moment'
/**
* A subset of fields of {@link Task} that can be parsed from the textual
Expand All @@ -16,7 +18,7 @@ export type TaskDetails = {
doneDate: Moment | null
cancelledDate: Moment | null
recurrenceRule: string
pomodoros: string
pomodoros: string
tags: string[]
}

Expand Down Expand Up @@ -49,3 +51,12 @@ export interface TaskDeserializer {

export { DefaultTaskSerializer, DEFAULT_SYMBOLS } from './DefaultTaskSerializer'
export { DataviewTaskSerializer } from './DataviewTaskSerializer'

export const POMODORO_REGEX = new RegExp(
'(?:(?=[^\\]]+\\])\\[|(?=[^)]+\\))\\() *🍅:: *(\\d* *\\/? *\\d*) *[)\\]](?: *,)?',
)

export const DESERIALIZERS: Record<TaskFormat, TaskDeserializer> = {
TASKS: new DefaultTaskSerializer(DEFAULT_SYMBOLS),
DATAVIEW: new DataviewTaskSerializer(),
}
2 changes: 1 addition & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export const ensureFileExists = async (

if (dirs.length) {
const dir = join(...dirs)
if (app.vault.getAbstractFileByPath(dir)) {
if (!app.vault.getAbstractFileByPath(dir)) {
await app.vault.createFolder(dir)
}
}
Expand Down

0 comments on commit 7e152c9

Please sign in to comment.