-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Improve Insert Modified Notes to Daily Notes.md
Fix the bugs that the function may be called before it's completed. Improve the codes to be more modular.
- Loading branch information
Showing
1 changed file
with
78 additions
and
68 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,94 +1,104 @@ | ||
<%* | ||
// Based on Insert Static DV Table, dataview plugin and templater plugin. | ||
// Configuration Constants | ||
const RECORD_NOTE_FOLDER = "日志/Daily Notes"; | ||
const QUERY_STRING = `table WITHOUT ID file.link as "当日编辑", file.mtime as "编辑时间" from !"MyTestFolder" where file.mday = date(today) sort file.mtime asc limit 32`; | ||
const START_POSITION = "title: 当天编辑的文件\ncollapse: close"; | ||
const END_POSITION = "````"; | ||
const dv = app.plugins.plugins["dataview"].api; | ||
|
||
// Get today's date in ISO format | ||
let today = moment().format("YYYY-MM-DD"); | ||
|
||
// Specify the note where you want to record the data | ||
let DailyNote = moment(today).format("YYYY-MM-DD"); | ||
let recordNoteFolder = "日志/Daily Notes"; | ||
const recordNote = DailyNote; // Change this to your desired note name | ||
const note = app.vault.getAbstractFileByPath(`${recordNoteFolder}/${recordNote}.md`); | ||
|
||
// Define the start and end positions in the note to place the inserted data. | ||
// You can also use either "## Start Title" or "thing1\nthing2" if line break exist. | ||
let startPosition = "title: 当天编辑的文件\ncollapse: close"; | ||
let endPosition = "````"; // You can also use "## End Title" | ||
// Get the content that you want to add to recordNote | ||
let recordNote = DailyNote; | ||
let note = app.vault.getAbstractFileByPath(`${RECORD_NOTE_FOLDER}/${recordNote}.md`); | ||
|
||
const query = `table WITHOUT ID file.link as "当日编辑", file.mtime as "编辑时间" from !"MyTestFolder" where file.mday = date(today) sort file.mtime asc limit 32`; | ||
|
||
// Set Program Delay for templater to parse created files | ||
// Delay function | ||
function delay(ms) { | ||
return new Promise(resolve => setTimeout(resolve, ms)); | ||
return new Promise(resolve => setTimeout(resolve, ms)); | ||
} | ||
|
||
new Notice("Autoupdate scripts are running! ", 3000); | ||
console.log("Autoupdate scripts are running! "); | ||
|
||
// Function to create a new note | ||
async function createNewNote() { | ||
await tp.file.create_new("", recordNote, false, RECORD_NOTE_FOLDER); | ||
new Notice(`Created new note ${recordNote} in folder ${RECORD_NOTE_FOLDER}.`, 5000); | ||
console.log(`Created new note ${recordNote} in folder ${RECORD_NOTE_FOLDER}.`); | ||
await delay(500); | ||
} | ||
|
||
// Function to fetch query output | ||
async function fetchQueryOutput() { | ||
try { | ||
return await dv.queryMarkdown(QUERY_STRING); | ||
} catch (error) { | ||
new Notice("⚠️ ERROR querying data: " + error.message, 5000); | ||
console.log(`⚠️ ERROR: ${error}`); | ||
throw error; // Rethrow to handle in the calling function | ||
} | ||
} | ||
|
||
// Function to process query output | ||
function processQueryOutput(queryOutput) { | ||
const lines = queryOutput.split('\n'); | ||
return lines.length > 3 ? queryOutput.trimEnd() : "No note is modified today! "; | ||
} | ||
|
||
// Function to read note content | ||
async function readDailyNoteContent() { | ||
return await app.vault.read(note); | ||
} | ||
|
||
// Function to update the note | ||
async function updateNoteContent(content, recordData) { | ||
const regex = new RegExp(`${START_POSITION}[\\s\\S]*?(?=${END_POSITION})`); | ||
if (regex.test(content)) { | ||
const newContent = content.replace(regex, `${START_POSITION}\n${recordData}\n`); | ||
await app.vault.modify(note, newContent); | ||
new Notice("Daily note auto updated! ", 2000); | ||
console.log("Daily note auto updated! "); | ||
} else { | ||
new Notice("⚠️ ERROR updating note: " + recordNote + "! Check console log.", 5000); | ||
console.log(`⚠️ ERROR: The given pattern "${START_POSITION} ... ${END_POSITION}" is not found in ${recordNote}! `); | ||
} | ||
} | ||
|
||
// Main function to update daily notes | ||
async function updateDailyNotes() { | ||
// Specify if note exists | ||
if (!tp.file.find_tfile(recordNote)) { | ||
// If the note doesn't exist, create it in the specified folder using Templater | ||
await tp.file.create_new("", recordNote, false, recordNoteFolder) | ||
new Notice(`Created new note ${recordNote} in folder ${recordNoteFolder}.`, 5000); | ||
console.log(`Created new note ${recordNote} in folder ${recordNoteFolder}.`); | ||
await delay(500); | ||
} | ||
|
||
// Data Processing | ||
startPosition = startPosition.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); | ||
endPosition = endPosition.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); | ||
const regex = new RegExp(`${startPosition}[\\s\\S]*?(?=${endPosition})`); | ||
|
||
const dv = app.plugins.plugins["dataview"].api; | ||
const dvqueryOutput = await dv.queryMarkdown(query); | ||
const queryOutput = dvqueryOutput.value | ||
let recordData; | ||
const lines = queryOutput.split('\n'); | ||
if (lines.length > 3) { | ||
recordData = queryOutput.trimEnd(); | ||
} | ||
else { | ||
recordData = "No note is modified today! "; | ||
} | ||
|
||
// Append the data to the specified note | ||
const content = await app.vault.read(note); | ||
let newContent; | ||
if (regex.test(content)) { | ||
newContent = content.replace(regex, `${startPosition}\n${recordData}\n`); | ||
await app.vault.modify(note, newContent); | ||
new Notice("Daily note auto updated! ", 2000); | ||
console.log("Daily note auto updated! "); | ||
} | ||
else { | ||
new Notice("⚠️ ERROR updating note: " + recordNote +"! Check console log.", 5000); | ||
console.log(`⚠️ ERROR: The given pattern "${startPosition} ... ${endPosition}" is not found in ${recordNote}! `); | ||
} | ||
}; | ||
try { | ||
if (!tp.file.find_tfile(recordNote)) { | ||
await createNewNote(); | ||
} | ||
|
||
const dvqueryOutput = await fetchQueryOutput(); | ||
const recordData = processQueryOutput(dvqueryOutput.value); | ||
const content = await readDailyNoteContent(); | ||
await updateNoteContent(content, recordData); | ||
} catch (error) { | ||
new Notice("⚠️ An unexpected error occurred: " + error.message, 5000); | ||
console.log(`⚠️ ERROR: ${error}`); | ||
} | ||
} | ||
|
||
// Debounce function to limit the rate at which a function can fire | ||
function debounce(func, wait) { | ||
let timeout; | ||
return function(...args) { | ||
const later = () => { | ||
clearTimeout(timeout); | ||
func(...args); | ||
}; | ||
clearTimeout(timeout); | ||
timeout = setTimeout(later, wait); | ||
timeout = setTimeout(() => func.apply(this, args), wait); | ||
}; | ||
} | ||
|
||
// Set up event listener to run the update function on every file save with debounce | ||
app.vault.on('modify', debounce(async (file) => { | ||
console.log(`Detected File Change: ${file.name}`); | ||
if (file.name === `${recordNote}.md`) | ||
await delay(200); | ||
else | ||
await updateDailyNotes(); | ||
console.log(`Detected File Change: ${file.name}`); | ||
if (file.name === `${recordNote}.md`) { | ||
await delay(200); | ||
} else { | ||
await updateDailyNotes(); | ||
console.log(`Try updating ${recordNote}.md`); | ||
} | ||
}, 60000)); // 60 seconds debounce | ||
|
||
|
||
%> | ||
%> |