Skip to content

Commit

Permalink
feat: 1.db utils refactor 2.pomodoro refactor 3.timeline follows cale…
Browse files Browse the repository at this point in the history
…ndar
  • Loading branch information
JuckZ committed Mar 7, 2023
1 parent a0d15c2 commit 70f66a5
Show file tree
Hide file tree
Showing 19 changed files with 478 additions and 557 deletions.
6 changes: 3 additions & 3 deletions src/locale/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,11 @@ export default {
todayTime: 'Today time',
totalTime: 'Total time',
noTimeLine: 'No timeline content',
startTask: '▶️ Start',
startTask: '🚀 Start',
stopTask: '⏸️ Stop',
finishTask: '✅ Finish',
cancelTask: '🔴 Cancel',
deleteTask: ' Delete',
cancelTask: ' Cancel',
deleteTask: '🗑️ Delete',
handleThisFirst: 'Please handle this unfinished task: ',
},
};
154 changes: 31 additions & 123 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,51 +19,39 @@ import Replacer from './Replacer';
import Process from './process/Process';
import { ref } from 'vue';
import type { Database } from 'sql.js';
import { checkInDefaultPath, checkInList, customSnippetPath, pomodoroDB } from './utils/constants';
import { checkInDefaultPath, checkInList, customSnippetPath } from './utils/constants';
import { monkeyPatchConsole } from './obsidian-hack/obsidian-debug-mobile';
import { EmojiPickerModal, ImageOriginModal, PomodoroReminderModal } from './ui/modal';
import { POMODORO_HISTORY_VIEW, PomodoroHistoryView } from './ui/view/PomodoroHistoryView';
import { BROWSER_VIEW, BrowserView } from './ui/view/BrowserView';
import { codeEmoji } from './render/Emoji';
import { toggleCursorEffects, toggleMouseClickEffects } from './render/CursorEffects';
import LoggerUtil, { initLogger } from './utils/logger';
import LoggerUtil from './utils/logger';
import { getAllFiles, getCleanTitle, getNotePath } from './utils/file';
import { getWeather } from './utils/weather';
import { getTagsFromTask, getTaskContentFromTask } from './utils/common';
import {
dbResultsToDBTables,
deleteFromDB,
getDB,
initialDBCtx,
insertIntoDB,
saveDBAndKeepAlive,
selectDB,
updateDBConditionally,
} from './utils/db/db';
import { DBUtil } from './utils/db/db';
import { insertAfterHandler } from './utils/content';
import { getLocalRandomImg, searchPicture } from './utils/genBanner';
import { loadSQL } from './utils/db/sqljs';
import { PomodoroStatus, initiateDB } from './utils/pomotodo';
import { PomodoroStatus } from './utils/pomotodo';
import { AwesomeBrainSettingTab, SETTINGS } from './settings';
import { PluginDataIO } from './data';
import { eventTypes } from './types/types';
import type { ExtApp } from './types/types';
import { onCodeMirrorChange, toggleBlast, toggleShake } from './render/Blast';
import { pomodoroSchema } from './schemas/spaces';
import type { Pomodoro } from './schemas/spaces';
import { notifyNtfy } from './api';
import t from './i18n';
import './main.scss';
import { NotifyUtil } from './utils/notify';
import { EditorUtil } from './utils/editor';
import { useSystemStore } from '@/stores';
import { EditorUtil, EditorUtils } from './utils/editor';
import { usePomodoroStore, useSystemStore } from '@/stores';

export const OpenUrl = ref('https://baidu.com');
const media = window.matchMedia('(prefers-color-scheme: dark)');
export default class AwesomeBrainManagerPlugin extends Plugin {
override app: ExtApp;
pluginDataIO: PluginDataIO;
private pomodoroTarget: Pomodoro | null;
private pomodoroHistoryView: PomodoroHistoryView | null;
quickPreviewFunction: (file: TFile, data: string) => any;
resizeFunction: () => any;
Expand Down Expand Up @@ -103,11 +91,8 @@ export default class AwesomeBrainManagerPlugin extends Plugin {
this.process = new Process(this);
this.pluginDataIO = new PluginDataIO(this);
this.bindFunction();
initLogger(SETTINGS.debugEnable);
}

saveSpacesDB = debounce(() => saveDBAndKeepAlive(this.spaceDBInstance(), this.spacesDBPath), 1000, true);

bindFunction() {
this.resizeFunction = this.customizeResize.bind(this);
this.clickFunction = this.customizeClick.bind(this);
Expand All @@ -121,51 +106,27 @@ export default class AwesomeBrainManagerPlugin extends Plugin {
this.vaultRenameFunction = this.customizeVaultRename.bind(this);
}

async sqlJS() {
// LoggerUtil.time("Loading SQlite");
const sqljs = await loadSQL();
// LoggerUtil.timeEnd("Loading SQlite");
return sqljs;
}

pomodoroChange(e: any) {
this.refreshPomodoroTarget();
}
openBrowserHandle(e: CustomEvent) {
this.openBrowser(e.detail.url);
}

spaceDBInstance() {
return this.spaceDB;
}

async startPomodoro(task: string) {
async addPomodoro(task: string) {
const createTime = moment().format('YYYY-MM-DD HH:mm:ss');
const tags: string[] = getTagsFromTask(task);
const content: string = getTaskContentFromTask(task);
const tagsStr = tags.join(',');
insertIntoDB(this.spaceDB, {
pomodoro: {
uniques: pomodoroSchema.uniques,
cols: pomodoroSchema.cols,
rows: [
{
timestamp: new Date().getTime() + '',
task: content,
createTime,
spend: '0',
breaknum: '0',
expectedTime: (SETTINGS.expectedTime.value * 60 * 1000).toString(),
status: 'todo',
tags: tagsStr,
},
],
},
});
saveDBAndKeepAlive(this.spaceDB, this.spacesDBPath);
const evt = new CustomEvent(eventTypes.pomodoroChange);
window.dispatchEvent(evt);
LoggerUtil.log(selectDB(this.spaceDBInstance(), pomodoroDB));
const currentPomodoro = {
timestamp: new Date().getTime() + '',
task: content,
start: '',
createTime,
spend: '0',
breaknum: '0',
expectedTime: (SETTINGS.expectedTime.value * 60 * 1000).toString(),
status: 'todo',
tags: tagsStr,
};
usePomodoroStore().addPomodoro(currentPomodoro as Pomodoro);
}

get snippetPath() {
Expand Down Expand Up @@ -224,7 +185,7 @@ export default class AwesomeBrainManagerPlugin extends Plugin {
title: 'Notify this to ntfy',
icon: 'megaphone',
clickFn: (menu: Menu, editor: Editor, info: MarkdownView | MarkdownFileInfo) => {
notifyNtfy(this.getCurrentSelection(editor));
notifyNtfy(EditorUtils.getCurrentSelection(editor));
},
},
{
Expand All @@ -234,7 +195,7 @@ export default class AwesomeBrainManagerPlugin extends Plugin {
const evt = new CustomEvent(eventTypes.calledFunction, {
detail: {
type: 'OpenAI',
keyword: this.getCurrentSelection(editor),
keyword: EditorUtils.getCurrentSelection(editor),
},
});
window.dispatchEvent(evt);
Expand All @@ -244,13 +205,13 @@ export default class AwesomeBrainManagerPlugin extends Plugin {
title: t.menu.planPomodoro,
icon: 'send',
clickFn: async (menu: Menu, editor: Editor, info: MarkdownView | MarkdownFileInfo) => {
let task = this.getCurrentSelection(editor);
let task = EditorUtils.getCurrentSelection(editor);
task = task.replace('- [x] ', '');
task = task.replace('- [ ] ', '').trim();
if (!task) {
task = t.menu.defaultTask + Date.now();
}
this.startPomodoro(task);
this.addPomodoro(task);
},
},
{
Expand All @@ -277,17 +238,6 @@ export default class AwesomeBrainManagerPlugin extends Plugin {
];
}

getCurrentSelection(editor: Editor) {
const cursorPos = editor.getCursor();
let content = editor.getSelection();
if (!content) {
if (cursorPos) {
content = editor.getLine(cursorPos.line);
}
}
return content;
}

async customizeEditorMenu(menu: Menu, editor: Editor, info: MarkdownView | MarkdownFileInfo): Promise<void> {
this.getMenus().forEach(menuMeta => {
menu.addItem(item => {
Expand Down Expand Up @@ -325,6 +275,11 @@ export default class AwesomeBrainManagerPlugin extends Plugin {

override async onload(): Promise<void> {
await this.pluginDataIO.load();
LoggerUtil.init(SETTINGS.debugEnable);
DBUtil.init(this, () => {
usePomodoroStore().loadPomodoroData();
this.startPomodoroTask();
});
EditorUtil.init(this);
NotifyUtil.init(this);
this.setupUI();
Expand All @@ -334,41 +289,20 @@ export default class AwesomeBrainManagerPlugin extends Plugin {
this.registerMarkdownCodeBlockProcessor('plantuml', this.process.UMLProcess);
this.registerMarkdownCodeBlockProcessor('vue', this.process.VueProcess);

this.spacesDBPath = normalizePath(
this.app.vault.configDir + '/plugins/awesome-brain-manager/ObsidianManager.mdb',
);
initialDBCtx(this.app);
this.spaceDB = await getDB(await loadSQL(), this.spacesDBPath);
const tables = dbResultsToDBTables(
this.spaceDBInstance().exec(
"SELECT name FROM sqlite_schema WHERE type ='table' AND name NOT LIKE 'sqlite_%';",
),
);
if (tables.length == 0) {
initiateDB(this.spaceDBInstance());
}
this.refreshPomodoroTarget();
this.app.workspace.onLayoutReady(async () => {
if (SETTINGS.debugEnable.value) {
monkeyPatchConsole(this);
}
this.watchVault();
this.startPomodoroTask();
});
}

private async refreshPomodoroTarget() {
const pomodoroList = (await selectDB(this.spaceDBInstance(), pomodoroDB)?.rows) || [];
this.pomodoroTarget = (pomodoroList.filter(pomodoro => pomodoro.status === 'ing')[0] as Pomodoro) || null;
}

private startPomodoroTask() {
// 进来就找到ing任务,如果有,则开始interval任务,倒计时准备弹窗提醒
// 监听数据库变化事件,若变化,则刷新监听的任务
// this.register
this.registerInterval(
window.setInterval(() => {
const pomodoro = this.pomodoroTarget;
const pomodoro = usePomodoroStore().currentPomodoro;
if (!pomodoro) {
return;
}
Expand All @@ -385,8 +319,7 @@ export default class AwesomeBrainManagerPlugin extends Plugin {
}
const changed = pomodoroStatus.changeState('done');
if (changed) {
this.updatePomodoro(pomodoro);
this.pomodoroTarget = null;
usePomodoroStore().updatePomodoro(pomodoro);
} else {
LoggerUtil.error('Update failed', pomodoro);
}
Expand All @@ -395,30 +328,6 @@ export default class AwesomeBrainManagerPlugin extends Plugin {
);
}

deletePomodoro(pomodoro: Pomodoro) {
deleteFromDB(this.spaceDBInstance(), pomodoroDB, `timestamp = ${pomodoro.timestamp}`);
saveDBAndKeepAlive(this.spaceDBInstance(), this.spacesDBPath);
const evt = new CustomEvent(eventTypes.pomodoroChange);
window.dispatchEvent(evt);
}

updatePomodoro(pomodoro: Pomodoro) {
updateDBConditionally(
this.spaceDBInstance(),
{
pomodoro: {
uniques: pomodoroSchema.uniques,
cols: pomodoroSchema.cols,
rows: [pomodoro],
},
},
`timestamp = ${pomodoro.timestamp}`,
);
saveDBAndKeepAlive(this.spaceDBInstance(), this.spacesDBPath);
const evt = new CustomEvent(eventTypes.pomodoroChange);
window.dispatchEvent(evt);
}

private async addACheck(path, filename, time, content) {
const normalizedPath = await getNotePath(path, filename);
const todayMoment = moment();
Expand Down Expand Up @@ -557,7 +466,7 @@ export default class AwesomeBrainManagerPlugin extends Plugin {
}

private setupUI() {
useSystemStore().updateLanguage(window.localStorage.getItem('language') || 'en')
useSystemStore().updateLanguage(window.localStorage.getItem('language') || 'en');
useSystemStore().updateTheme(document.body.classList.contains('theme-dark') ? 'dark' : 'light');
this.style = document.head.createEl('style', {
attr: { id: 'OBSIDIAN_MANAGER_CUSTOM_STYLE_SHEET' },
Expand Down Expand Up @@ -651,7 +560,6 @@ export default class AwesomeBrainManagerPlugin extends Plugin {
this.registerDomEvent(activeDocument, 'click', async (e: MouseEvent) => {
toggleMouseClickEffects(e, SETTINGS.clickString);
});
window.addEventListener(eventTypes.pomodoroChange, this.pomodoroChange.bind(this));
window.addEventListener(eventTypes.openBrowser, this.openBrowserHandle.bind(this));
[
this.app.workspace.on('click', this.clickFunction),
Expand Down
3 changes: 2 additions & 1 deletion src/stores/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createPinia } from 'pinia';
import { useEditorStore } from './editor';
import { useSystemStore } from './system';
import { usePomodoroStore } from './pomodoro';
const pinia = createPinia();
export default pinia;
export { useEditorStore, useSystemStore };
export { useEditorStore, useSystemStore, usePomodoroStore };
48 changes: 43 additions & 5 deletions src/stores/pomodoro.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,52 @@
import type { Pomodoro } from '@/schemas/spaces';
import { DBUtil } from '@/utils/db/db';
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { ref, type Ref } from 'vue';

// TODO 将数据持久化,优化性能 注意不同设备之间的持久化策略
export const usePomodoroStore = defineStore('pomodoro', () => {
const totalTask = ref(0);
function increment() {
totalTask.value++;
const currentPomodoro: Ref<Pomodoro | null> = ref(null);
const pomodoroHistory: Ref<Pomodoro[]> = ref([]);

function updatePomodoro(pomodoro: Pomodoro) {
DBUtil.updatePomodoro(pomodoro);
const updateIndex = pomodoroHistory.value.findIndex(item => item.timestamp === pomodoro.timestamp);
pomodoroHistory.value[updateIndex] = pomodoro;
if (pomodoro.timestamp === currentPomodoro.value?.timestamp && pomodoro.status === 'done') {
currentPomodoro.value = null;
} else if (pomodoro.status === 'ing') {
currentPomodoro.value = pomodoro;
}
}

async function loadPomodoroData() {
const data = await DBUtil.loadPomodoroData();
pomodoroHistory.value = data;
currentPomodoro.value = data.filter(pomodoro => pomodoro.status === 'ing')[0] as Pomodoro;
}

function addPomodoro(pomodoro: Pomodoro) {
DBUtil.addPomodoro(pomodoro);
pomodoroHistory.value.push(pomodoro);
}

function deletePomodoro(pomodoro: Pomodoro) {
DBUtil.deletePomodoro(pomodoro);
pomodoroHistory.value = pomodoroHistory.value.filter(item => item.timestamp !== pomodoro.timestamp);
if (currentPomodoro.value && currentPomodoro.value.timestamp === pomodoro.timestamp) {
currentPomodoro.value = null;
}
}

return {
totalTime: 0,
currentPomodoro,
totalTime: 0,
totalTask,
increment,
pomodoroHistory,
loadPomodoroData,
addPomodoro,
updatePomodoro,
deletePomodoro,
};
});
2 changes: 1 addition & 1 deletion src/types/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { App, type Command } from 'obsidian';

// TODO namespace?
export const eventTypes = {
dbInited: 'db-inited',
openBrowser: 'open-browser',
pomodoroChange: 'pomodoro-change',
calledFunction: 'called-function',
};

Expand Down
Loading

0 comments on commit 70f66a5

Please sign in to comment.