Skip to content

Commit

Permalink
Enable strict mode type checking
Browse files Browse the repository at this point in the history
  • Loading branch information
tgrosinger committed Jan 5, 2022
1 parent 3426b56 commit bf88103
Show file tree
Hide file tree
Showing 10 changed files with 103 additions and 40 deletions.
42 changes: 22 additions & 20 deletions src/ledgerview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,16 @@ export const LedgerViewType = 'ledger';
export class LedgerView extends TextFileView {
private readonly plugin: LedgerPlugin;
private txCache: TransactionCache;
private currentFilePath: string;
private readonly updateInterface: LedgerModifier;
private currentFilePath: string | null;
private updateInterface: LedgerModifier | null;

constructor(leaf: WorkspaceLeaf, plugin: LedgerPlugin) {
super(leaf);
this.plugin = plugin;
this.txCache = plugin.txCache;

const file = plugin.app.metadataCache.getFirstLinkpathDest(
plugin.settings.ledgerFile,
'',
);
this.updateInterface = new LedgerModifier(plugin, file);
this.currentFilePath = null;
this.updateInterface = null;

this.addAction('pencil', 'Switch to Markdown View', () => {
const state = leaf.view.getState();
Expand Down Expand Up @@ -102,9 +99,7 @@ export class LedgerView extends TextFileView {

if (this.currentFilePath !== file.path) {
this.currentFilePath = file.path;
this.updateInterface.setLedgerFile(
this.plugin.app.metadataCache.getFirstLinkpathDest(file.path, ''),
);
this.updateInterface = new LedgerModifier(this.plugin, file);
this.redraw();
}
}
Expand All @@ -119,16 +114,23 @@ export class LedgerView extends TextFileView {
console.debug('Ledger: Creating dashboard view');

const contentEl = this.containerEl.children[1];
ReactDOM.render(
React.createElement(LedgerDashboard, {
tutorialIndex: this.plugin.settings.tutorialIndex,
setTutorialIndex: this.setTutorialIndex,
settings: this.plugin.settings,
txCache: this.txCache,
updater: this.updateInterface,
}),
this.contentEl,
);

if (this.currentFilePath && this.updateInterface) {
ReactDOM.render(
React.createElement(LedgerDashboard, {
tutorialIndex: this.plugin.settings.tutorialIndex,
setTutorialIndex: this.setTutorialIndex,
settings: this.plugin.settings,
txCache: this.txCache,
updater: this.updateInterface,
}),
this.contentEl,
);
} else {
contentEl.empty();
const span = contentEl.createSpan();
span.setText('Loading...');
}
};

private readonly setTutorialIndex = (index: number): void => {
Expand Down
15 changes: 14 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
addIcon,
MarkdownView,
Menu,
Notice,
ObsidianProtocolData,
Plugin,
TAbstractFile,
Expand All @@ -24,9 +25,16 @@ declare global {
}

export default class LedgerPlugin extends Plugin {
// @ts-ignore - Not initialized in the constructor due to how Obsidian
// plugins are initialized.
public settings: ISettings;

// @ts-ignore - Not initialized in the constructor due to how Obsidian
// plugins are initialized.
public txCache: TransactionCache;

// @ts-ignore - Not initialized in the constructor due to how Obsidian
// plugins are initialized.
private txCacheSubscriptions: ((txCache: TransactionCache) => void)[];

public async onload(): Promise<void> {
Expand Down Expand Up @@ -81,7 +89,7 @@ export default class LedgerPlugin extends Plugin {
this.register(
around(MarkdownView.prototype, {
onMoreOptionsMenu(next) {
return function (menu: Menu) {
return function (this: MarkdownView, menu: Menu) {
if (this.file.path === self.settings.ledgerFile) {
menu
.addItem((item) => {
Expand Down Expand Up @@ -179,6 +187,11 @@ export default class LedgerPlugin extends Plugin {

private readonly openLedgerDashboard = async (): Promise<void> => {
let leaf = this.app.workspace.activeLeaf;
if (!leaf) {
new Notice('Unable to find active leaf');
return;
}

if (leaf.getViewState().pinned) {
leaf = this.app.workspace.splitActiveLeaf('horizontal');
}
Expand Down
2 changes: 1 addition & 1 deletion src/transaction-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export const valueForAccount = (
}
if (line.account === account || line.dealiasedAccount === account) {
return i + 1 === tx.value.expenselines.length
? -1 * getTotalAsNum(tx) // On the last line
? -1 * line.amount // On the last line
: line.amount;
}
}
Expand Down
13 changes: 4 additions & 9 deletions src/ui/AccountsList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ const Tree: React.FC<{
{props.data.account}
</AccountName>
</TreeRow>
{hasChildren && expanded
{hasChildren && expanded && subRows
? subRows.map((child) => (
<Tree
txCache={props.txCache}
Expand Down Expand Up @@ -161,11 +161,6 @@ const deselectRowsWithoutPrefix = (
selectedAccounts: string[],
prefixes: string[],
): string[] =>
selectedAccounts.filter((account) => {
for (let i = 0; i < prefixes.length; i++) {
if (account.startsWith(prefixes[i])) {
return true;
}
}
return false;
});
selectedAccounts.filter((account) =>
prefixes.some((prefix) => account.startsWith(prefix)),
);
3 changes: 2 additions & 1 deletion src/ui/CreateLedgerEntry.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -181,12 +181,13 @@ export const CreateLedgerEntry: React.FC<{

// TODO: This is not a ISO8601. Once reconciliation is added, remove this and reformat file.
const formattedDate = date.replace(/-/g, '/');
const formattedTotal = currencySymbol + parseFloat(total).toFixed(2);
const lastI = accounts.length - 1;
const expenseLines = accounts
.map((account, i) =>
i === lastI
? ` ${account.value}`
: ` ${account.value} ${currencySymbol}${parseFloat(total)}`,
: ` ${account.value} ${formattedTotal}`,
)
.join('\n');
const txStr = `\n${formattedDate} ${localPayee}\n${expenseLines}`;
Expand Down
7 changes: 5 additions & 2 deletions src/ui/TextSuggest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,11 @@ export const TextSuggest: React.FC<{
const [selectedIndex, setSelectedIndex] = React.useState(0);

const [visible, setVisibility] = React.useState(false);
const [referenceElement, setReferenceElement] = React.useState(null);
const [popperElement, setPopperElement] = React.useState(null);
const [referenceElement, setReferenceElement] =
React.useState<HTMLElement | null>(null);
const [popperElement, setPopperElement] = React.useState<HTMLElement | null>(
null,
);
const { styles, attributes } = usePopper(referenceElement, popperElement, {
placement: 'bottom-start',
});
Expand Down
4 changes: 2 additions & 2 deletions src/ui/TransactionList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export const MobileTransactionEntry: React.FC<{
return (
<div>
<h3>{props.tx.value.payee}</h3>
<div>From: {nonCommentLines[-1].account}</div>
<div>From: {(nonCommentLines.last() as EnhancedExpenseLine).account}</div>
<div>Amount: {getTotal(props.tx, props.currencySymbol)}</div>
</div>
);
Expand Down Expand Up @@ -189,7 +189,7 @@ const buildTableRows = (
date: tx.value.date,
payee: tx.value.payee,
total: getTotal(tx, currencySymbol),
from: nonCommentLines.last().account,
from: nonCommentLines[nonCommentLines.length - 1].account,
to: <i>Multiple</i>,
actions: makeClone(tx),
};
Expand Down
45 changes: 42 additions & 3 deletions tests/parser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
TransactionWithBlock,
} from '../src/parser';
import { settingsWithDefaults } from '../src/settings';
import { assert } from 'console';
import * as moment from 'moment';

window.moment = moment;
Expand All @@ -26,6 +27,10 @@ describe('splitIntoBlocks()', () => {
const input = ['line1', 'line2', 'line3'].join('\n');
const result = splitIntoBlocks(input);
expect(result).toHaveLength(1);
if (!result[0]) {
assert(false);
return; // Appease the type checker
}
expect(result[0].firstLine).toEqual(0);
expect(result[0].lastLine).toEqual(2);
expect(result[0].block).toEqual('line1\nline2\nline3');
Expand All @@ -34,6 +39,10 @@ describe('splitIntoBlocks()', () => {
const input = ['line1', 'line2', 'line3', ''].join('\n');
const result = splitIntoBlocks(input);
expect(result).toHaveLength(1);
if (!result[0]) {
assert(false);
return; // Appease the type checker
}
expect(result[0].firstLine).toEqual(0);
expect(result[0].lastLine).toEqual(2);
expect(result[0].block).toEqual('line1\nline2\nline3');
Expand All @@ -42,6 +51,10 @@ describe('splitIntoBlocks()', () => {
const input = ['line1', 'line2', 'line3', '', 'line4', 'line5'].join('\n');
const result = splitIntoBlocks(input);
expect(result).toHaveLength(2);
if (!result[0] || !result[1]) {
assert(false);
return; // Appease the type checker
}
expect(result[0].firstLine).toEqual(0);
expect(result[0].lastLine).toEqual(2);
expect(result[0].block).toEqual('line1\nline2\nline3');
Expand All @@ -55,6 +68,10 @@ describe('splitIntoBlocks()', () => {
);
const result = splitIntoBlocks(input);
expect(result).toHaveLength(2);
if (!result[0] || !result[1]) {
assert(false);
return; // Appease the type checker
}
expect(result[0].firstLine).toEqual(0);
expect(result[0].lastLine).toEqual(2);
expect(result[0].block).toEqual('line1\nline2\nline3');
Expand All @@ -68,6 +85,10 @@ describe('splitIntoBlocks()', () => {
);
const result = splitIntoBlocks(input);
expect(result).toHaveLength(2);
if (!result[0] || !result[1]) {
assert(false);
return; // Appease the type checker
}
expect(result[0].firstLine).toEqual(0);
expect(result[0].lastLine).toEqual(2);
expect(result[0].block).toEqual('line1\nline2\nline3');
Expand All @@ -81,6 +102,10 @@ describe('splitIntoBlocks()', () => {
);
const result = splitIntoBlocks(input);
expect(result).toHaveLength(2);
if (!result[0] || !result[1]) {
assert(false);
return; // Appease the type checker
}
expect(result[0].firstLine).toEqual(0);
expect(result[0].lastLine).toEqual(2);
expect(result[0].block).toEqual('line1\nline2\nline3');
Expand Down Expand Up @@ -543,6 +568,10 @@ describe('parsing a ledger file', () => {
},
};
expect(txCache.parsingErrors.length).toEqual(1);
if (!txCache.parsingErrors[0]) {
assert(false);
return; // Appease the type checker
}
expect(txCache.parsingErrors[0].message).toEqual(
'Failed to parse block in ledger file',
);
Expand Down Expand Up @@ -668,6 +697,11 @@ alias b=Banking
2021/04/20 Obsidian
e:Spending Money $20.00
b:CreditUnion`;
const contentLines = contents.split('\n');
if (!contentLines[0] || !contentLines[1]) {
assert(false);
return; // Appease the type checker
}
const txCache = parse(contents, settings);
const expected: EnhancedTransaction = {
type: 'tx',
Expand Down Expand Up @@ -704,7 +738,7 @@ alias b=Banking
block: {
firstLine: 0,
lastLine: 0,
block: contents.split('\n')[0],
block: contentLines[0],
},
value: {
left: 'e',
Expand All @@ -717,7 +751,7 @@ alias b=Banking
block: {
firstLine: 1,
lastLine: 1,
block: contents.split('\n')[1],
block: contentLines[1],
},
value: {
left: 'b',
Expand All @@ -736,6 +770,11 @@ alias b=Banking
2021/04/20 Obsidian
e:Spending Money $20.00
b:CreditUnion`;
const contentLines = contents.split('\n');
if (!contentLines[0]) {
assert(false);
return; // Appease the type checker
}
const txCache = parse(contents, settings);
const expected: EnhancedTransaction = {
type: 'tx',
Expand Down Expand Up @@ -772,7 +811,7 @@ alias b=Banking
block: {
firstLine: 0,
lastLine: 0,
block: contents.split('\n')[0],
block: contentLines[0],
},
value: {
left: 'e',
Expand Down
11 changes: 10 additions & 1 deletion tests/transaction-utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { EnhancedTransaction, FileBlock,parse } from '../src/parser';
import { EnhancedTransaction, FileBlock, parse } from '../src/parser';
import { settingsWithDefaults } from '../src/settings';
import {
filterByAccount,
Expand All @@ -11,6 +11,7 @@ import {
Node,
sortAccountTree,
} from '../src/transaction-utils';
import { assert } from 'console';
import * as moment from 'moment';

window.moment = moment;
Expand All @@ -29,6 +30,10 @@ describe('formatting a transaction into ledger', () => {
b:CreditUnion`;
const txCache = parse(contents, settingsWithDefaults({}));
expect(txCache.parsingErrors).toEqual([]);
if (txCache.transactions.length !== 1 || !txCache.transactions[0]) {
assert(false);
return; // Appease the type checker
}
const output = formatTransaction(txCache.transactions[0], '$');
expect(output).toEqual('\n' + contents);
});
Expand All @@ -38,6 +43,10 @@ describe('formatting a transaction into ledger', () => {
! b:CreditUnion`;
const txCache = parse(contents, settingsWithDefaults({}));
expect(txCache.parsingErrors).toEqual([]);
if (txCache.transactions.length !== 1 || !txCache.transactions[0]) {
assert(false);
return; // Appease the type checker
}
const output = formatTransaction(txCache.transactions[0], '$');
expect(output).toEqual('\n' + contents);
});
Expand Down
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"include": [ "src/**/*", "tests/**/*" ],
"compilerOptions": {
"strict": true,
"baseUrl": ".",
"allowSyntheticDefaultImports": true,
"inlineSources": true,
Expand Down

0 comments on commit bf88103

Please sign in to comment.