-
Notifications
You must be signed in to change notification settings - Fork 138
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
80d7e3f
commit 9d04977
Showing
11 changed files
with
480 additions
and
133 deletions.
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
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
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
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
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
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,103 +1,69 @@ | ||
import Papa from "papaparse"; | ||
import * as XLSX from "xlsx"; | ||
import { parser } from "mathjs"; | ||
import { history, redoDepth, undoDepth } from "@codemirror/commands"; | ||
import { javascript } from "@codemirror/lang-javascript"; | ||
import { lintGutter } from "@codemirror/lint"; | ||
import type { Text } from "@codemirror/state"; | ||
import { EditorView } from "codemirror"; | ||
import _ from "lodash"; | ||
import { format } from "./journal"; | ||
import { pdf2array } from "./pdf"; | ||
import { sheetEditorState } from "../store"; | ||
import { basicSetup } from "./editor/base"; | ||
import { schedulePlugin } from "./transaction_tag"; | ||
import { formatCurrency, type SheetLineResult } from "./utils"; | ||
|
||
interface Result { | ||
data: string[][]; | ||
} | ||
export function createEditor(content: string, dom: Element) { | ||
return new EditorView({ | ||
extensions: [ | ||
basicSetup, | ||
EditorView.contentAttributes.of({ "data-enable-grammarly": "false" }), | ||
javascript(), | ||
lintGutter(), | ||
history(), | ||
EditorView.updateListener.of((viewUpdate) => { | ||
const doc = viewUpdate.state.doc.toString(); | ||
const currentLine = viewUpdate.state.doc.lineAt(viewUpdate.state.selection.main.head); | ||
sheetEditorState.update((current) => { | ||
let results = current.results; | ||
if (current.doc !== doc) { | ||
results = evaluate(viewUpdate.state.doc); | ||
} | ||
|
||
export function parse(file: File): Promise<Result> { | ||
let extension = file.name.split(".").pop(); | ||
extension = extension?.toLowerCase(); | ||
if (extension === "csv" || extension === "txt") { | ||
return parseCSV(file); | ||
} else if (extension === "xlsx" || extension === "xls") { | ||
return parseXLSX(file); | ||
} else if (extension === "pdf") { | ||
return parsePDF(file); | ||
} | ||
throw new Error(`Unsupported file type ${extension}`); | ||
} | ||
|
||
export function asRows(result: Result): Array<Record<string, any>> { | ||
return _.map(result.data, (row, i) => { | ||
return _.chain(row) | ||
.map((cell, j) => { | ||
return [String.fromCharCode(65 + j), cell]; | ||
}) | ||
.concat([["index", i as any]]) | ||
.fromPairs() | ||
.value(); | ||
return _.assign({}, current, { | ||
results: results, | ||
doc: doc, | ||
currentLine: currentLine.number, | ||
hasUnsavedChanges: current.hasUnsavedChanges || viewUpdate.docChanged, | ||
undoDepth: undoDepth(viewUpdate.state), | ||
redoDepth: redoDepth(viewUpdate.state) | ||
}); | ||
}); | ||
}), | ||
schedulePlugin | ||
], | ||
doc: content, | ||
parent: dom | ||
}); | ||
} | ||
|
||
const COLUMN_REFS = _.chain(_.range(65, 90)) | ||
.map((i) => String.fromCharCode(i)) | ||
.map((a) => [a, a]) | ||
.fromPairs() | ||
.value(); | ||
|
||
export function render( | ||
rows: Array<Record<string, any>>, | ||
template: Handlebars.TemplateDelegate, | ||
options: { reverse?: boolean } = {} | ||
) { | ||
const output: string[] = []; | ||
_.each(rows, (row) => { | ||
const rendered = _.trim(template(_.assign({ ROW: row, SHEET: rows }, COLUMN_REFS))); | ||
if (!_.isEmpty(rendered)) { | ||
output.push(rendered); | ||
function evaluate(doc: Text) { | ||
const results: SheetLineResult[] = []; | ||
const p = parser(); | ||
for (let i = 0; i < doc.lines; i++) { | ||
const line = doc.line(i + 1); | ||
console.log(line.text); | ||
try { | ||
let result = ""; | ||
const text = line.text.trim(); | ||
if (!_.isEmpty(text) && !text.startsWith("//")) { | ||
result = p.evaluate(line.text); | ||
} | ||
if (_.isNumber(result)) { | ||
result = formatCurrency(result); | ||
} | ||
results.push({ line: i + 1, error: false, result }); | ||
} catch (e) { | ||
results.push({ line: i + 1, error: true, result: e.message }); | ||
} | ||
}); | ||
if (options.reverse) { | ||
output.reverse(); | ||
console.log(results[i]); | ||
} | ||
return format(output.join("\n\n")); | ||
} | ||
|
||
function parseCSV(file: File): Promise<Result> { | ||
return new Promise((resolve, reject) => { | ||
Papa.parse<string[]>(file, { | ||
skipEmptyLines: true, | ||
complete: function (results) { | ||
resolve(results); | ||
}, | ||
error: function (error) { | ||
reject(error); | ||
}, | ||
delimitersToGuess: [",", "\t", "|", ";", Papa.RECORD_SEP, Papa.UNIT_SEP, "^"] | ||
}); | ||
}); | ||
} | ||
|
||
async function parseXLSX(file: File): Promise<Result> { | ||
const buffer = await readFile(file); | ||
const sheet = XLSX.read(buffer, { type: "binary" }); | ||
const json = XLSX.utils.sheet_to_json<string[]>(sheet.Sheets[sheet.SheetNames[0]], { | ||
header: 1, | ||
blankrows: false, | ||
rawNumbers: false | ||
}); | ||
return { data: json }; | ||
} | ||
|
||
async function parsePDF(file: File): Promise<Result> { | ||
const buffer = await readFile(file); | ||
const array = await pdf2array(buffer); | ||
return { data: array }; | ||
} | ||
|
||
function readFile(file: File): Promise<ArrayBuffer> { | ||
return new Promise((resolve, reject) => { | ||
const reader = new FileReader(); | ||
reader.onload = (event) => { | ||
resolve(event.target.result as ArrayBuffer); | ||
}; | ||
reader.onerror = (event) => { | ||
reject(event); | ||
}; | ||
reader.readAsArrayBuffer(file); | ||
}); | ||
return results; | ||
} |
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 |
---|---|---|
@@ -0,0 +1,103 @@ | ||
import Papa from "papaparse"; | ||
import * as XLSX from "xlsx"; | ||
import _ from "lodash"; | ||
import { format } from "./journal"; | ||
import { pdf2array } from "./pdf"; | ||
|
||
interface Result { | ||
data: string[][]; | ||
} | ||
|
||
export function parse(file: File): Promise<Result> { | ||
let extension = file.name.split(".").pop(); | ||
extension = extension?.toLowerCase(); | ||
if (extension === "csv" || extension === "txt") { | ||
return parseCSV(file); | ||
} else if (extension === "xlsx" || extension === "xls") { | ||
return parseXLSX(file); | ||
} else if (extension === "pdf") { | ||
return parsePDF(file); | ||
} | ||
throw new Error(`Unsupported file type ${extension}`); | ||
} | ||
|
||
export function asRows(result: Result): Array<Record<string, any>> { | ||
return _.map(result.data, (row, i) => { | ||
return _.chain(row) | ||
.map((cell, j) => { | ||
return [String.fromCharCode(65 + j), cell]; | ||
}) | ||
.concat([["index", i as any]]) | ||
.fromPairs() | ||
.value(); | ||
}); | ||
} | ||
|
||
const COLUMN_REFS = _.chain(_.range(65, 90)) | ||
.map((i) => String.fromCharCode(i)) | ||
.map((a) => [a, a]) | ||
.fromPairs() | ||
.value(); | ||
|
||
export function render( | ||
rows: Array<Record<string, any>>, | ||
template: Handlebars.TemplateDelegate, | ||
options: { reverse?: boolean } = {} | ||
) { | ||
const output: string[] = []; | ||
_.each(rows, (row) => { | ||
const rendered = _.trim(template(_.assign({ ROW: row, SHEET: rows }, COLUMN_REFS))); | ||
if (!_.isEmpty(rendered)) { | ||
output.push(rendered); | ||
} | ||
}); | ||
if (options.reverse) { | ||
output.reverse(); | ||
} | ||
return format(output.join("\n\n")); | ||
} | ||
|
||
function parseCSV(file: File): Promise<Result> { | ||
return new Promise((resolve, reject) => { | ||
Papa.parse<string[]>(file, { | ||
skipEmptyLines: true, | ||
complete: function (results) { | ||
resolve(results); | ||
}, | ||
error: function (error) { | ||
reject(error); | ||
}, | ||
delimitersToGuess: [",", "\t", "|", ";", Papa.RECORD_SEP, Papa.UNIT_SEP, "^"] | ||
}); | ||
}); | ||
} | ||
|
||
async function parseXLSX(file: File): Promise<Result> { | ||
const buffer = await readFile(file); | ||
const sheet = XLSX.read(buffer, { type: "binary" }); | ||
const json = XLSX.utils.sheet_to_json<string[]>(sheet.Sheets[sheet.SheetNames[0]], { | ||
header: 1, | ||
blankrows: false, | ||
rawNumbers: false | ||
}); | ||
return { data: json }; | ||
} | ||
|
||
async function parsePDF(file: File): Promise<Result> { | ||
const buffer = await readFile(file); | ||
const array = await pdf2array(buffer); | ||
return { data: array }; | ||
} | ||
|
||
function readFile(file: File): Promise<ArrayBuffer> { | ||
return new Promise((resolve, reject) => { | ||
const reader = new FileReader(); | ||
reader.onload = (event) => { | ||
resolve(event.target.result as ArrayBuffer); | ||
}; | ||
reader.onerror = (event) => { | ||
reject(event); | ||
}; | ||
reader.readAsArrayBuffer(file); | ||
}); | ||
} |
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
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
Oops, something went wrong.