Skip to content

Commit

Permalink
fix 优化启动时自动插入预约块的就方案; close #169
Browse files Browse the repository at this point in the history
  • Loading branch information
frostime committed Oct 22, 2023
1 parent 1ab08fa commit eb95b09
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 7 deletions.
72 changes: 70 additions & 2 deletions src/components/toolbar-menu.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { IMenuItemOption, Menu, Plugin, confirm, showMessage } from "siyuan";
import { currentDiaryStatus, openDiary, initTodayReservation } from "../func";
import { currentDiaryStatus, openDiary, initTodayReservation, updateTodayReservation } from "../func";
import notebooks from "../global-notebooks";
import { reservation, settings } from "../global-status";
import { info, i18n, isMobile } from "../utils";
import { eventBus } from "../event-bus";
import { iconDiary } from "./svg";

import * as serverApi from '@/serverApi';


let ContextMenuListener: EventListener;
let UpdateDailyNoteStatusListener: EventListener;
Expand All @@ -14,6 +16,8 @@ export class ToolbarMenuItem {
ele: HTMLElement;
iconStatus: Map<string, string>;

private onProtyleLoadedBindThis = this.onProtyleLoaded.bind(this);

constructor(plugin: Plugin) {
this.plugin = plugin;
ContextMenuListener = (event: MouseEvent) => this.contextMenu(event);
Expand All @@ -34,13 +38,33 @@ export class ToolbarMenuItem {

// setting 异步加载完成后, 发送 event bus
eventBus.subscribe(eventBus.EventSettingLoaded, () => { this.addTopBarIcon(); });

}

/**
* 根据预约情况, 监听日记本的加载, 如果是今天的日记本, 则更新预约状态
* @returns
*/
startMonitorDailyNoteForReservation() {
if (!reservation.isTodayReserved) {
return
}
this.plugin.eventBus.on("loaded-protyle", this.onProtyleLoadedBindThis);
// 3分钟后, 取消监听, 防止不必要的性能损耗
setTimeout(
() => {
this.plugin.eventBus.off("loaded-protyle", this.onProtyleLoadedBindThis);
},
1000 * 60 * 2
);
}

release() {
this.ele.removeEventListener('contextmenu', ContextMenuListener);
eventBus.unSubscribe('moveBlocks', UpdateDailyNoteStatusListener);
this.ele.remove();
this.ele = null;
this.plugin.eventBus.off("loaded-protyle", this.onProtyleLoadedBindThis);
info('TopBarIcon released');
}

Expand Down Expand Up @@ -156,7 +180,7 @@ export class ToolbarMenuItem {
let notebook: Notebook = notebooks.default;
if (notebook) {
await openDiary(notebook);
initTodayReservation(notebook);
// initTodayReservation(notebook);
} else {
confirm(i18n.Name, `${notebookId} ${i18n.InvalidDefaultNotebook}`)
return
Expand All @@ -165,6 +189,50 @@ export class ToolbarMenuItem {
}
}

/**
* 监听自动打开日记后,插入当天预约用
*/
private async onProtyleLoaded({ detail }) {
const block_ = detail.block;
if (block_.id != block_.rootID) {
return;
}
//是否为文档
const headElement: HTMLElement = detail?.model?.headElement;
if (!headElement) {
return;
}
//笔记本是否是默认笔记本
const notebookId = detail.notebookId;
if (notebookId !== notebooks.default.id) {
return;
}


const CheckReservation = async (blockId: BlockId, cnt: number =1) => {
if (cnt > 3) {
return;
}
console.debug("检查", blockId);
const block: Block = await serverApi.getBlockByID(blockId);
if (block === undefined) {
console.warn(`New opened docId ${blockId} undefined`);
//能调用这个函数,说明这个文档一定存在,查不到就继续等继续差
setTimeout(() => CheckReservation(blockId, cnt++), 1000 * cnt);
return
}
// console.log(block.hpath);
if (notebooks.default.dailynoteHpath === block.hpath) {
console.debug('Got Today\'s daily note');
this.plugin.eventBus.off("loaded-protyle", this.onProtyleLoadedBindThis);
await updateTodayReservation(notebooks.default, true);
}
}
console.debug("2s后检查", block_.id);
//如果是新创建的日记,那么在这一刻后端是拿不到对应的块的,所以需要先等一下
setTimeout(() => CheckReservation(block_.id), 1000 * 2);
}

async updateDailyNoteStatus() {
let diaryStatus: Map<string, boolean> = await currentDiaryStatus();
notebooks.notebooks.forEach((notebook) => {
Expand Down
4 changes: 2 additions & 2 deletions src/func/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*/
import { showMessage, confirm, Dialog, openTab } from 'siyuan';
import notebooks from '../global-notebooks';
import { info, warn, error, i18n, lute, app, isMobile, formatBlockTime } from "../utils";
import { info, warn, error, i18n, lute, app, isMobile, formatBlockTime, debug } from "../utils";
import * as serverApi from '../serverApi';
import { reservation, settings } from '../global-status';
import { Retrieve, RetvFactory } from './reserve';
Expand Down Expand Up @@ -324,7 +324,7 @@ export async function updateDocReservation(docId: string, refresh: boolean = fal
const hasInserted = retvBlocks.length > 0;

if (hasInserted && !refresh) {
info(`今日已经插入过预约了`);
debug(`今日已经插入过预约了`);
return;
} else {
resvBlockIds = resvBlockIds.map((id) => `"${id}"`);
Expand Down
4 changes: 4 additions & 0 deletions src/global-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,10 @@ class ReservationManger {
this.reserved.set(blockId, date_str);
}

isTodayReserved(): boolean {
return this.getTodayReservations().length > 0;
}

//获取今天的预约
getTodayReservations(): string[] {
let date = new Date();
Expand Down
8 changes: 5 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,16 +61,18 @@ export default class DailyNoteTodayPlugin extends Plugin {
this.initPluginUI();

//初始化数据
reservation.load();
await settings.load();
await notebooks.init(); //依赖 settings.load();
// await reservation.load();
// await settings.load();
// await notebooks.init(); //依赖 settings.load();
await Promise.all([reservation.load(), settings.load(), notebooks.init()]);

this.initBlockIconClickEvent(); //依赖 settings.load();

this.initUpToDate(); //依赖 settings.load();

eventBus.subscribe(eventBus.EventUpdateAll, () => { this.updateAll() });

this.toolbarItem.startMonitorDailyNoteForReservation();
// 如果有笔记本,且设置中允许启动时打开,则打开第一个笔记本
await this.toolbarItem.autoOpenDailyNote();

Expand Down
4 changes: 4 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ export function checkI18n(): boolean {
// showMessage('i18n check failed', 5000, 'error');
// }

export function debug(...msg: any[]): void {
console.debug(`[DailyNoteToday][DEBUG] ${msg}`);
}

export function info(...msg: any[]): void {
console.log(`[DailyNoteToday][INFO] ${msg}`);
}
Expand Down

0 comments on commit eb95b09

Please sign in to comment.