Skip to content

Commit

Permalink
refactor: Reformat code to match the format used by tasks-x plugin (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
claremacrae authored Sep 6, 2022
1 parent a429144 commit 11a3712
Show file tree
Hide file tree
Showing 68 changed files with 542 additions and 1,572 deletions.
7 changes: 5 additions & 2 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,12 @@ module.exports = {
'prettier/prettier': [
'error',
{
singleQuote: true,
tabWidth: 4,
trailingComma: 'all',
printWidth: 120,
tabWidth: 4,
useTabs: false,
singleQuote: true,
bracketSpacing: true,
},
],
semi: ['error', 'always'],
Expand Down
5 changes: 4 additions & 1 deletion .prettierrc.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
module.exports = {
trailingComma: 'all',
singleQuote: true,
printWidth: 120,
tabWidth: 4,
useTabs: false,
singleQuote: true,
bracketSpacing: true
};
157 changes: 55 additions & 102 deletions src/Cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,7 @@ export class Cache {
*/
private loadedAfterFirstResolve: boolean;

constructor({
metadataCache,
vault,
events,
}: {
metadataCache: MetadataCache;
vault: Vault;
events: TasksEvents;
}) {
constructor({ metadataCache, vault, events }: { metadataCache: MetadataCache; vault: Vault; events: TasksEvents }) {
this.metadataCache = metadataCache;
this.metadataCacheEventReferences = [];
this.vault = vault;
Expand Down Expand Up @@ -93,84 +85,69 @@ export class Cache {
}

private subscribeToCache(): void {
const resolvedEventeReference = this.metadataCache.on(
'resolved',
async () => {
// Resolved fires on every change.
// We only want to initialize if we haven't already.
if (!this.loadedAfterFirstResolve) {
this.loadedAfterFirstResolve = true;
this.loadVault();
}
},
);
const resolvedEventeReference = this.metadataCache.on('resolved', async () => {
// Resolved fires on every change.
// We only want to initialize if we haven't already.
if (!this.loadedAfterFirstResolve) {
this.loadedAfterFirstResolve = true;
this.loadVault();
}
});
this.metadataCacheEventReferences.push(resolvedEventeReference);

// Does not fire when starting up obsidian and only works for changes.
const changedEventReference = this.metadataCache.on(
'changed',
(file: TFile) => {
this.tasksMutex.runExclusive(() => {
this.indexFile(file);
});
},
);
const changedEventReference = this.metadataCache.on('changed', (file: TFile) => {
this.tasksMutex.runExclusive(() => {
this.indexFile(file);
});
});
this.metadataCacheEventReferences.push(changedEventReference);
}

private subscribeToVault(): void {
const createdEventReference = this.vault.on(
'create',
(file: TAbstractFile) => {
if (!(file instanceof TFile)) {
return;
}
const createdEventReference = this.vault.on('create', (file: TAbstractFile) => {
if (!(file instanceof TFile)) {
return;
}

this.tasksMutex.runExclusive(() => {
this.indexFile(file);
});
},
);
this.tasksMutex.runExclusive(() => {
this.indexFile(file);
});
});
this.vaultEventReferences.push(createdEventReference);

const deletedEventReference = this.vault.on(
'delete',
(file: TAbstractFile) => {
if (!(file instanceof TFile)) {
return;
}

this.tasksMutex.runExclusive(() => {
this.tasks = this.tasks.filter((task: Task) => {
return task.path !== file.path;
});
const deletedEventReference = this.vault.on('delete', (file: TAbstractFile) => {
if (!(file instanceof TFile)) {
return;
}

this.notifySubscribers();
this.tasksMutex.runExclusive(() => {
this.tasks = this.tasks.filter((task: Task) => {
return task.path !== file.path;
});
},
);
this.vaultEventReferences.push(deletedEventReference);

const renamedEventReference = this.vault.on(
'rename',
(file: TAbstractFile, oldPath: string) => {
if (!(file instanceof TFile)) {
return;
}
this.notifySubscribers();
});
});
this.vaultEventReferences.push(deletedEventReference);

this.tasksMutex.runExclusive(() => {
this.tasks = this.tasks.map((task: Task): Task => {
if (task.path === oldPath) {
return new Task({ ...task, path: file.path });
} else {
return task;
}
});
const renamedEventReference = this.vault.on('rename', (file: TAbstractFile, oldPath: string) => {
if (!(file instanceof TFile)) {
return;
}

this.notifySubscribers();
this.tasksMutex.runExclusive(() => {
this.tasks = this.tasks.map((task: Task): Task => {
if (task.path === oldPath) {
return new Task({ ...task, path: file.path });
} else {
return task;
}
});
},
);

this.notifySubscribers();
});
});
this.vaultEventReferences.push(renamedEventReference);
}

Expand Down Expand Up @@ -213,12 +190,7 @@ export class Cache {
if (listItems !== undefined) {
// Only read the file and process for tasks if there are list items.
const fileContent = await this.vault.cachedRead(file);
newTasks = Cache.getTasksFromFileContent(
fileContent,
listItems,
fileCache,
file,
);
newTasks = Cache.getTasksFromFileContent(fileContent, listItems, fileCache, file);
}

// If there are no changes in any of the tasks, there's
Expand Down Expand Up @@ -266,17 +238,10 @@ export class Cache {
let sectionIndex = 0;
for (const listItem of listItems) {
if (listItem.task !== undefined) {
if (
currentSection === null ||
currentSection.position.end.line <
listItem.position.start.line
) {
if (currentSection === null || currentSection.position.end.line < listItem.position.start.line) {
// We went past the current section (or this is the first task).
// Find the section that is relevant for this task and the following of the same section.
currentSection = Cache.getSection(
listItem.position.start.line,
fileCache.sections,
);
currentSection = Cache.getSection(listItem.position.start.line, fileCache.sections);
sectionIndex = 0;
}

Expand All @@ -291,10 +256,7 @@ export class Cache {
path: file.path,
sectionStart: currentSection.position.start.line,
sectionIndex,
precedingHeader: Cache.getPrecedingHeader(
listItem.position.start.line,
fileCache.headings,
),
precedingHeader: Cache.getPrecedingHeader(listItem.position.start.line, fileCache.headings),
});

if (task !== null) {
Expand All @@ -307,30 +269,21 @@ export class Cache {
return tasks;
}

private static getSection(
lineNumberTask: number,
sections: SectionCache[] | undefined,
): SectionCache | null {
private static getSection(lineNumberTask: number, sections: SectionCache[] | undefined): SectionCache | null {
if (sections === undefined) {
return null;
}

for (const section of sections) {
if (
section.position.start.line <= lineNumberTask &&
section.position.end.line >= lineNumberTask
) {
if (section.position.start.line <= lineNumberTask && section.position.end.line >= lineNumberTask) {
return section;
}
}

return null;
}

private static getPrecedingHeader(
lineNumberTask: number,
headings: HeadingCache[] | undefined,
): string | null {
private static getPrecedingHeader(lineNumberTask: number, headings: HeadingCache[] | undefined): string | null {
if (headings === undefined) {
return null;
}
Expand Down
11 changes: 2 additions & 9 deletions src/Commands/CreateOrEdit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,7 @@ import { App, Editor, MarkdownView, View } from 'obsidian';
import { TaskModal } from '../TaskModal';
import { Priority, Status, Task } from '../Task';

export const createOrEdit = (
checking: boolean,
editor: Editor,
view: View,
app: App,
) => {
export const createOrEdit = (checking: boolean, editor: Editor, view: View, app: App) => {
if (checking) {
return view instanceof MarkdownView;
}
Expand All @@ -28,9 +23,7 @@ export const createOrEdit = (
const task = taskFromLine({ line, path });

const onSubmit = (updatedTasks: Task[]): void => {
const serialized = updatedTasks
.map((task: Task) => task.toFileLineString())
.join('\n');
const serialized = updatedTasks.map((task: Task) => task.toFileLineString()).join('\n');
editor.setLine(lineNumber, serialized);
};

Expand Down
20 changes: 4 additions & 16 deletions src/Commands/ToggleDone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,7 @@ export const toggleLine = (line: string, path: string) => {
// Toggle the status of the checklist item.
const statusString = regexMatch[2].toLowerCase(); // Note for future: I do not think this toLowerCase is necessary and there is an issue about how it breaks some theme or snippet.
const newStatusString = statusString === ' ' ? 'x' : ' ';
toggledLine = line.replace(
Task.taskRegex,
`$1- [${newStatusString}] $3`,
);
toggledLine = line.replace(Task.taskRegex, `$1- [${newStatusString}] $3`);
} else if (Task.listItemRegex.test(line)) {
// Convert the list item to a checklist item.
toggledLine = line.replace(Task.listItemRegex, '$1$2 [ ]');
Expand All @@ -95,9 +92,7 @@ export const toggleLine = (line: string, path: string) => {
const toggleTask = (task: Task): string => {
// Toggling a recurring task will produce two Tasks
const toggledTasks = task.toggle();
const serialized = toggledTasks
.map((task: Task) => task.toFileLineString())
.join('\n');
const serialized = toggledTasks.map((task: Task) => task.toFileLineString()).join('\n');

return serialized;
};
Expand All @@ -113,11 +108,7 @@ const toggleTask = (task: Task): string => {
So cursor should be reset if 0, which includes being moved to new end if got shorter. Then might need to move right 2 or 3.
*/
export const calculateCursorOffset = (
origCursorCh: number,
line: string,
toggledLine: string,
) => {
export const calculateCursorOffset = (origCursorCh: number, line: string, toggledLine: string) => {
let newLineLen = toggledLine.length;
if (newLineLen <= line.length) {
// Line got shorter or stayed same length. Reset cursor to original position, capped at end of line.
Expand All @@ -126,10 +117,7 @@ export const calculateCursorOffset = (

// Special-case for done-date append, fixes #449
const doneDateLength = ' ✅ YYYY-MM-DD'.length;
if (
toggledLine.match(Task.doneDateRegex) &&
newLineLen - line.length >= doneDateLength
) {
if (toggledLine.match(Task.doneDateRegex) && newLineLen - line.length >= doneDateLength) {
newLineLen -= doneDateLength;
}

Expand Down
6 changes: 1 addition & 5 deletions src/Commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,7 @@ export class Commands {
id: 'edit-task',
name: 'Create or edit task',
icon: 'pencil',
editorCheckCallback: (
checking: boolean,
editor: Editor,
view: View,
) => {
editorCheckCallback: (checking: boolean, editor: Editor, view: View) => {
return createOrEdit(checking, editor, view, this.app);
},
});
Expand Down
5 changes: 1 addition & 4 deletions src/Config/Settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,7 @@ export const isFeatureEnabled = (internalName: string): boolean => {
* @param enabled the expected state of the feature.
* @returns the features with the specified feature toggled.
*/
export const toggleFeature = (
internalName: string,
enabled: boolean,
): FeatureFlag => {
export const toggleFeature = (internalName: string, enabled: boolean): FeatureFlag => {
settings.features[internalName] = enabled;
return settings.features;
};
Loading

0 comments on commit 11a3712

Please sign in to comment.