Skip to content

Commit

Permalink
Merge branch 'dev'
Browse files Browse the repository at this point in the history
  • Loading branch information
frostime committed Mar 30, 2024
2 parents af7dd45 + b600616 commit 16ef0f8
Show file tree
Hide file tree
Showing 14 changed files with 189 additions and 142 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
### [2024-03-29] v1.4.0: 优化预约功能

- 重构了预约插入功能,[#184](https://github.com/frostime/siyuan-dailynote-today/issues/184)
- 重构了获取今日日记的方法,依赖更新的 `custom-daily-note-` 属性
- 如果当天有预约,则图标加高亮 [#183](https://github.com/frostime/siyuan-dailynote-today/issues/183)


### [2023-12-09] v1.3.1: 允许用户在同步后创建日记

- 允许用户在同步后创建日记
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "siyuan-dailynote-today",
"version": "1.2.9",
"version": "1.4.0",
"description": "",
"main": ".src/index.js",
"keywords": [],
Expand Down
4 changes: 2 additions & 2 deletions plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
"en_US": "Daily Note Today"
},
"url": "https://github.com/frostime/siyuan-dailynote-today",
"version": "1.3.2",
"minAppVersion": "2.11.1",
"version": "1.4.0",
"minAppVersion": "3.0.0",
"description": {
"zh_CN": "自动创建日记 + 快速打开日记 + 日程 TODO 管理 + 移动块功能",
"en_US": "Automatically open today's notes + Quickly open today's notes + TODO mangagement for today + Move blocks"
Expand Down
89 changes: 14 additions & 75 deletions src/components/toolbar-menu.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
import { IMenuItemOption, Menu, Plugin, showMessage } from "siyuan";
import { currentDiaryStatus, openDiary, updateTodayReservation } from "../func";
import { IMenuItemOption, Menu, showMessage } from "siyuan";
import { currentDiaryStatus, openDiary } from "../func";
import notebooks from "../global-notebooks";
import { reservation, settings } from "../global-status";
import { i18n, isMobile, debug } from "../utils";
import { eventBus } from "../event-bus";
import { iconDiary } from "./svg";

import * as serverApi from '@/serverApi';
import type DailyNoteTodayPlugin from '@/index';
// import * as serverApi from '@/serverApi';


let ContextMenuListener: EventListener;
let UpdateDailyNoteStatusListener: EventListener;
export class ToolbarMenuItem {
plugin: Plugin;
plugin: DailyNoteTodayPlugin;
ele: HTMLElement;
iconStatus: Map<string, string>;

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

constructor(plugin: Plugin) {
constructor(plugin: DailyNoteTodayPlugin) {
this.plugin = plugin;
ContextMenuListener = (event: MouseEvent) => this.contextMenu(event);
UpdateDailyNoteStatusListener = () => this.updateDailyNoteStatus();
Expand All @@ -41,32 +40,11 @@ export class ToolbarMenuItem {

}

/**
* #TODO: 将这个函数重构放到 reservation.ts 下
* #TODO: 2.10.16 版本之后 SiYuan 的 createDailyNote 返回 doc id, 所以可以不需要再使用监听了
* 根据预约情况, 监听日记本的加载, 如果是今天的日记本, 则更新预约状态
* @returns
*/
startMonitorDailyNoteForReservation() {
if (!reservation.isTodayReserved) {
return
}
this.plugin.eventBus.on("loaded-protyle-static", this.onProtyleLoadedBindThis);
// 3分钟后, 取消监听, 防止不必要的性能损耗
setTimeout(
() => {
this.plugin.eventBus.off("loaded-protyle-static", 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-static", this.onProtyleLoadedBindThis);
debug('TopBarIcon released');
}

Expand Down Expand Up @@ -152,59 +130,20 @@ export class ToolbarMenuItem {
let item: IMenuItemOption = {
label: notebook.name,
icon: this.iconStatus.get(notebook.id),
click: async () => openDiary(notebook),
click: async () => {
if (notebook.id === notebooks.default.id) {
await openDiary(notebook);
this.plugin.routineHandler.tryAutoInsertResv();
} else {
openDiary(notebook);
}
}
}
menuItems.push(item);
}
return menuItems;
}

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


const CheckReservation = async (blockId: BlockId, cnt: number =1) => {
if (cnt > 3) {
return;
}
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) {
debug('Got Today\'s daily note');
this.plugin.eventBus.off("loaded-protyle-static", this.onProtyleLoadedBindThis);
await updateTodayReservation(notebooks.default, true);
}
}
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
16 changes: 15 additions & 1 deletion src/func/dailynote/basic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* @Author : Yp Z
* @Date : 2023-11-12 18:06:46
* @FilePath : /src/func/dailynote/basic.ts
* @LastEditTime : 2023-11-12 18:15:30
* @LastEditTime : 2024-03-30 21:57:20
* @Description :
*/
import * as serverApi from '@/serverApi';
Expand Down Expand Up @@ -31,6 +31,20 @@ export async function getDailynoteSprig(notebookId: string): Promise<string> {
return sprig;
}

/**
*
*/
export async function queryTodayDailyNoteDoc(notebookId: NotebookId): Promise<Block[]> {
let td = formatDate(new Date());
const sql = `
select distinct B.* from blocks as B join attributes as A
on B.id = A.block_id
where A.name = 'custom-dailynote-${td}' and B.box = '${notebookId}'
`;
const blocks: Block[] = await serverApi.sql(sql);
return blocks;
}

/**
* 要求思源解析模板
* @param sprig
Expand Down
8 changes: 7 additions & 1 deletion src/func/dailynote/open-dn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* @Author : frostime
* @Date : 2023-11-12 19:53:10
* @FilePath : /src/func/dailynote/open-dn.ts
* @LastEditTime : 2023-12-04 20:30:15
* @LastEditTime : 2024-03-29 21:27:13
* @Description :
*/
import { showMessage, confirm, openTab, openMobileFileById } from 'siyuan';
Expand All @@ -23,6 +23,9 @@ export async function createDiary(notebook: Notebook, todayDiaryHpath: string) {
let doc_id = await serverApi.createDocWithMd(notebook.id, todayDiaryHpath, "");
info(`创建日记: ${notebook.name} ${todayDiaryHpath}`);
setCustomDNAttr(doc_id);

notebook.dailyNoteDocId = doc_id;

return doc_id;
}

Expand All @@ -33,6 +36,9 @@ export async function createDiary(notebook: Notebook, todayDiaryHpath: string) {
export async function openDiary(notebook: Notebook) {
let appId = utils.app.appId;
let dailynote = await serverApi.createDailyNote(notebook.id, appId);
if (dailynote) {
notebook.dailyNoteDocId = dailynote?.id;
}
showMessage(`${i18n.Open}: ${notebook.name}`, 2000, 'info');
//打开文档
if (isMobile === true) {
Expand Down
64 changes: 56 additions & 8 deletions src/func/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
/**
* Copyright (c) 2023 frostime all rights reserved.
*/
import { settings } from '@/global-status';
import { reservation, settings } from '@/global-status';
import { autoOpenDailyNote, checkDuplicateDiary } from './dailynote';

import type DailyNoteTodayPlugin from '@/index';
import type { EventBus } from 'siyuan';
import { debouncer } from '@/utils';
import { updateTodayReservation } from './reserve';
import { updateStyleSheet } from './style';
import notebooks from '@/global-notebooks';

export * from './dailynote';
export * from './misc';
export * from './reserve';
export * from './style';


// const WAIT_TIME_FOR_SYNC_CHECK: Milisecond = 1000 * 60 * 5;
Expand All @@ -19,7 +23,7 @@ const MAX_CHECK_SYNC_TIMES: number = 10; //为了避免每次同步都检查,
/**
* 处理插件加载完成后一系列关于日记、同步、预约等复杂的逻辑
*/
export class StartupEventHandler {
export class RoutineEventHandler {
plugin: DailyNoteTodayPlugin;
eventBus: EventBus;

Expand All @@ -32,7 +36,9 @@ export class StartupEventHandler {
autoOpenAfterSync: false,

isSyncChecked: false,
hasCheckSyncFor: 0
hasCheckSyncFor: 0,

hasAutoInsertResv: false //今天是否已经自动插入了预约
}

constructor(plugin: DailyNoteTodayPlugin) {
Expand All @@ -57,14 +63,15 @@ export class StartupEventHandler {

async onPluginLoad() {

this.updateResvIconStyle();
const SYNC_ENABLED = window.siyuan.config.sync.enabled;
if (!SYNC_ENABLED) {
//Case 1: 如果思源没有开启同步, 就直接创建, 并无需绑定同步事件
await this.tryToOpen();
await this.tryAutoOpenDN();
} else if (this.flag.autoOpenAfterSync === false) {
//Case 2: 如果思源开启了同步, 但是用户没有设置在同步后打开, 就直接创建
this.bindSyncEvent();
this.tryToOpen();
await this.tryAutoOpenDN();
} else {
//Case 3: 如果思源开启了同步, 并且用户设置了在同步后打开, 就绑定同步事件
this.bindSyncEvent();
Expand All @@ -75,7 +82,7 @@ export class StartupEventHandler {
console.debug('sync-end', detail);

if (this.flag.hasOpened === false && this.flag.autoOpenAfterSync === true) {
this.tryToOpen();
this.tryAutoOpenDN();
}

if (!this.flag.isSyncChecked) {
Expand All @@ -84,10 +91,28 @@ export class StartupEventHandler {
}


public resetSyncCheckStatus() {
public resetStatusFlag() {
this.flag.isSyncChecked = false; //重置同步检查状态
this.flag.hasCheckSyncFor = 0; //重置同步检查次数

this.flag.hasOpened = false; //重置是否已经打开

this.flag.hasAutoInsertResv = false; //重置是否已经插入预约
}

/**
* 如果今天有预约,就在 head 中插入特殊的样式
*/
public updateResvIconStyle() {
if (reservation.isTodayReserved()) {
updateStyleSheet(`
span[data-type="siyuan-dailynote-todaydock_tab"][data-title="${this.plugin.i18n.DockReserve.arial}"] {
background-color: var(--b3-theme-primary-lightest);
}
`);
} else {
updateStyleSheet('');
}
}

/********** Duplicate **********/
Expand All @@ -107,13 +132,36 @@ export class StartupEventHandler {
}
private checkDuplicateDiary_Debounce: typeof this.checkDuplicateDiary = null;

private async tryToOpen() {
/**
* 尝试自动打开日记
*/
private async tryAutoOpenDN() {
if (this.flag.openOnStart === false) return;
await autoOpenDailyNote();
this.flag.hasOpened = true;
//在自动打开日记后一段时间后,进行相关的检查处理
setTimeout(() => {
this.tryAutoInsertResv();
this.checkDuplicateDiary();
}, 1500);
}

/**
* 尝试自动插入今天的预约
*/
public async tryAutoInsertResv() {
//如果已经插入过了,就不再插入
if (this.flag.hasAutoInsertResv === true) return;

//如果今天没有预约,就不插入
if (!reservation.isTodayReserved()) return;

let succeed = updateTodayReservation(notebooks.default);

if (succeed) {
this.flag.hasAutoInsertResv = true;
}

}

}
20 changes: 12 additions & 8 deletions src/func/misc.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { openTab } from 'siyuan';
import { openTab, showMessage } from 'siyuan';

import { warn, error, debug, app } from "@/utils";
import * as serverApi from '@/serverApi';
import { settings } from '@/global-status';
import { getDailynoteSprig, renderDailynotePath } from './dailynote';
import { getDailynoteSprig, queryTodayDailyNoteDoc } from './dailynote';

const default_sprig = `/daily note/{{now | date "2006/01"}}/{{now | date "2006-01-02"}}`
const hiddenNotebook: Set<string> = new Set(["思源笔记用户指南", "SiYuan User Guide"]);
Expand Down Expand Up @@ -35,13 +35,17 @@ export async function queryNotebooks(): Promise<Array<Notebook> | null> {
for (let notebook of all_notebooks) {
let sprig = await getDailynoteSprig(notebook.id);
notebook.dailynoteSprig = sprig != "" ? sprig : default_sprig;
notebook.dailynoteHpath = await renderDailynotePath(notebook.dailynoteSprig);
notebook.dailynoteHpath = "";

//防止出现不符合规范的 sprig, 不过根据 debug 情况看似乎不会出现这种情况
if (notebook.dailynoteHpath == "") {
warn(`Invalid daily note srpig of ${notebook.name}`);
notebook.dailynoteSprig = default_sprig;
notebook.dailynoteHpath = await renderDailynotePath(default_sprig);
const docs = await queryTodayDailyNoteDoc(notebook.id);
if (docs.length > 0) {
const doc = docs[0];
notebook.dailyNoteDocId = doc.id;
notebook.dailynoteHpath = doc.hpath;
}

if (docs.length > 1) {
showMessage(`Warning: More than one daily-notes are founded in ${notebook.name}`, 5, "error");
}

if (notebook.icon == "") {
Expand Down
Loading

0 comments on commit 16ef0f8

Please sign in to comment.