Skip to content

Commit

Permalink
fix: adding new notes more reliable
Browse files Browse the repository at this point in the history
  • Loading branch information
mablin7 committed Feb 26, 2022
1 parent 98d3dac commit 1ae3982
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 30 deletions.
35 changes: 22 additions & 13 deletions src/board.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,18 +98,23 @@ export function getMdList(boardState: BoardState): string {
const numCols = boardState.columns.length;
const cols: string[] = [];
for (let i = 0; i < numCols; i++) {
cols[i] = ("## " + boardState.columns[i].name + "\n" +
boardState.columns[i].notes.map((note) => "- " + getMdLink(note)).join("\n"));
cols[i] =
"## " +
boardState.columns[i].name +
"\n" +
boardState.columns[i].notes
.map((note) => "- " + getMdLink(note))
.join("\n");
}

const body = cols.join("\n\n")
const body = cols.join("\n\n");
const timestamp = `\n\n_Last updated at ${new Date().toLocaleString()} by Kanban plugin_`;

return body + timestamp;
}

export function getMdLink(note: NoteData): string {
if ((note?.title !== undefined) && (note?.id !== undefined)) {
if (note?.title !== undefined && note?.id !== undefined) {
return "[" + note.title + "](:/" + note.id + ")";
} else return "";
}
Expand Down Expand Up @@ -259,15 +264,12 @@ export default async function ({
configObj.filters || {};
const rootNotebookName = rootNotebookPath.split("/").pop() as string;

const baseFilters: Rule["filterNote"][] = [
(await rules.excludeNoteId(configNoteId, rootNotebookPath, configObj))
.filterNote,
const baseFilters: Rule[] = [
await rules.excludeNoteId(configNoteId, rootNotebookPath, configObj),
];

if (rootNotebookPath !== "/") {
baseFilters.push(
(await rules.notebookPath(rootNotebookPath, "", configObj)).filterNote
);
baseFilters.push(await rules.notebookPath(rootNotebookPath, "", configObj));
}

let hiddenTags: string[] = [];
Expand All @@ -276,7 +278,7 @@ export default async function ({
if (typeof val === "boolean") val = `${val}`;
if (val && key in rules) {
const rule = await rules[key](val, rootNotebookPath, configObj);
baseFilters.push(rule.filterNote);
baseFilters.push(rule);
if (key === "tag") hiddenTags.push(val as string);
else if (key === "tags")
hiddenTags = [...hiddenTags, ...(val as string[])];
Expand Down Expand Up @@ -320,7 +322,7 @@ export default async function ({
columnNames: configObj.columns.map(({ name }) => name),

sortNoteIntoColumn(note: NoteData) {
const matchesBaseFilters = baseFilters.every((f) => f(note));
const matchesBaseFilters = baseFilters.every((r) => r.filterNote(note));
if (matchesBaseFilters) {
const foundCol = regularColumns.find(({ rules }) =>
rules.some(({ filterNote }) => filterNote(note))
Expand All @@ -338,7 +340,14 @@ export default async function ({
const col = allColumns.find(
({ name }) => name === action.payload.colName
) as Column;
return col.rules.flatMap((r) => r.set(action.payload.noteId || ""));
const hasNotebookPathRule =
col.rules.find((r) => r.name === "notebookPath") !== undefined;
return [
...baseFilters
.filter((r) => !hasNotebookPathRule || r.name !== "notebookPath")
.flatMap((r) => r.set(action.payload.noteId || "")),
...col.rules.flatMap((r) => r.set(action.payload.noteId || "")),
];

case "moveNote":
const { noteId, newColumnName, oldColumnName, newIndex } =
Expand Down
44 changes: 27 additions & 17 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import createBoard, {
getBoardState,
parseConfigNote,
getMdTable,
getMdList
getMdList,
} from "./board";
import {
getConfigNote,
Expand Down Expand Up @@ -170,8 +170,8 @@ async function showBoard() {
} else if (msg.type === "newNote") {
await joplin.commands.execute("newNote");
newNoteChangedCb = async (noteId: string) => {
if (!openBoard || !("actionToQuery" in openBoard)) return
msg.payload.noteId = noteId
if (!openBoard || !("actionToQuery" in openBoard)) return;
msg.payload.noteId = noteId;
for (const query of openBoard.actionToQuery(msg, oldState)) {
log(`Executing update: \n${JSON.stringify(query, null, 4)}\n`);
await executeUpdateQuery(query);
Expand Down Expand Up @@ -202,17 +202,20 @@ async function showBoard() {
);
}


if (msg.type !== "poll"){
if ((openBoard.isValid) && (openBoard.parsedConfig.display?.markdown == "list"))
if (msg.type !== "poll") {
if (
openBoard.isValid &&
openBoard.parsedConfig.display?.markdown == "list"
)
setAfterConfig(openBoard.configNoteId, getMdList(newState));
else if ((openBoard.isValid) &&
(openBoard.parsedConfig.display?.markdown == "table" ||
openBoard.parsedConfig.display?.markdown == undefined))
else if (
openBoard.isValid &&
(openBoard.parsedConfig.display?.markdown == "table" ||
openBoard.parsedConfig.display?.markdown == undefined)
)
setAfterConfig(openBoard.configNoteId, getMdTable(newState));
}


log(
`Sending back update to webview: \n${JSON.stringify(
newState,
Expand Down Expand Up @@ -258,11 +261,13 @@ joplin.plugins.register({
// Have to call this on start otherwise layout from prevoius session is lost
showBoard().then(hideBoard);

let startedHandlingNewNote = false;
joplin.workspace.onNoteSelectionChange(
async ({ value }: { value: [string?] }) => {
log(`Note selection changed`);
const newNoteId = value?.[0] as string;
if (newNoteChangedCb && (await getNoteById(newNoteId))) newNoteChangedCb = undefined;
if (newNoteChangedCb && (await getNoteById(newNoteId)))
newNoteChangedCb = undefined;
if (newNoteId) handleNewlyOpenedNote(newNoteId);
}
);
Expand All @@ -273,14 +278,19 @@ joplin.plugins.register({
if (openBoard.configNoteId === id) {
if (!openBoard.isValid) await reloadConfig(id);
if (pollCb) pollCb();
} else if (await isNoteIdOnBoard(id, openBoard)) {
} else if ((await isNoteIdOnBoard(id, openBoard)) || newNoteChangedCb) {
log("Changed note was on the board, updating");
if (newNoteChangedCb) {
if (newNoteChangedCb && !startedHandlingNewNote) {
startedHandlingNewNote = true;
const note = await getNoteById(id);
if (note && note.title !== "") {
newNoteChangedCb(id);
newNoteChangedCb = undefined;
}
if (note) {
setTimeout(() => {
(newNoteChangedCb as (id: string) => void)(id);
newNoteChangedCb = undefined;
startedHandlingNewNote = false;
if (pollCb) pollCb();
}, 100); // For some reason this delay is required to make adding new notes reliable
} else startedHandlingNewNote = false;
}
if (pollCb) pollCb();
}
Expand Down
6 changes: 6 additions & 0 deletions src/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
import { log } from "./index";

export interface Rule {
name: string;
filterNote: (note: NoteData) => boolean;
set(noteId: string): UpdateQuery[];
unset(noteId: string): UpdateQuery[];
Expand All @@ -33,6 +34,7 @@ const rules: Rules = {
const tagID = (await getTagId(tagName)) || (await createTag(tagName));
log(`Tag ID: ${tagID}`);
return {
name: 'tag',
filterNote: (note: NoteData) => note.tags.includes(tagName),
set: (noteId: string) => [
{
Expand All @@ -57,6 +59,7 @@ const rules: Rules = {
tagNames.map((t) => rules.tag(t, rootNbPath, config))
);
return {
name: 'tags',
filterNote: (note: NoteData) =>
tagRules.some(({ filterNote }) => filterNote(note)),
set: (noteId: string) => tagRules.flatMap(({ set }) => set(noteId)),
Expand All @@ -83,6 +86,7 @@ const rules: Rules = {
const notebookIdsToSearch = [notebookId, ...childrenNotebookIds];

return {
name: 'notebookPath',
filterNote: (note: NoteData) =>
notebookIdsToSearch.includes(note.notebookId),
set: (noteId: string) => [
Expand Down Expand Up @@ -111,6 +115,7 @@ const rules: Rules = {
if (Array.isArray(val)) val = val[0];
const shouldBeCompeted = val.toLowerCase() === "true";
return {
name: 'completed',
filterNote: (note: NoteData) =>
note.isTodo && note.isCompleted === shouldBeCompeted,
set: (noteId: string) => [
Expand All @@ -137,6 +142,7 @@ const rules: Rules = {

async excludeNoteId(id: string | string[]) {
return {
name: 'excludeNoteId',
filterNote: (note: NoteData) => note.id !== id,
set: () => [],
unset: () => [],
Expand Down

0 comments on commit 1ae3982

Please sign in to comment.