Kalk_web type-safety for kalk module and scientific notation printing

This commit is contained in:
PaddiM8 2021-01-04 20:15:28 +01:00
parent dd3ddced66
commit 433750f85f

View File

@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import { afterUpdate } from "svelte"; import { afterUpdate } from "svelte";
import type { Context } from "@paddim8/kalk";
export let identifierColor = "cornflowerblue"; export let identifierColor = "cornflowerblue";
export let operatorColor = "darkorange"; export let operatorColor = "darkorange";
@ -8,9 +9,11 @@
export let hintColor = "#9c9c9c"; export let hintColor = "#9c9c9c";
export let linkColor = "cornflowerblue"; export let linkColor = "cornflowerblue";
type Kalk = typeof import("@paddim8/kalk");
let outputLines: [value: string, byUser: boolean][] = []; let outputLines: [value: string, byUser: boolean][] = [];
let outputElement: HTMLElement; let outputElement: HTMLElement;
let kalkContext; let kalkContext: Context;
let selectedLineOffset: number = 0; let selectedLineOffset: number = 0;
afterUpdate(() => { afterUpdate(() => {
@ -20,7 +23,27 @@
].scrollIntoView(false); ].scrollIntoView(false);
}); });
function handleKeyDown(event: KeyboardEvent, kalk) { function calculate(
kalk: Kalk,
input: string
): [result: string, error: string] {
try {
if (!kalkContext) kalkContext = new kalk.Context();
const result = kalkContext.evaluate(input) ?? "";
if (result) {
const sciNot = result.toScientificNotation();
if (sciNot.exponent > 7 || sciNot.exponent < -6) {
return [sciNot.toString(), null];
}
}
return [result.toString(), null];
} catch (err) {
return [undefined, err];
}
}
function handleKeyDown(event: KeyboardEvent, kalk: Kalk) {
if (event.key == "Enter") { if (event.key == "Enter") {
selectedLineOffset = 0; selectedLineOffset = 0;
const target = event.target as HTMLInputElement; const target = event.target as HTMLInputElement;
@ -32,14 +55,10 @@
href="https://kalk.netlify.app/#usage" href="https://kalk.netlify.app/#usage"
target="blank">Link to usage guide</a>`; target="blank">Link to usage guide</a>`;
} else { } else {
// Calculate const [result, err] = calculate(kalk, input);
if (!kalkContext) kalkContext = new kalk.Context(); output =
try { result ??
const result = kalkContext.evaluate(input); `<span style="color: ${errorColor}">${err}</span>`;
if (result) output = result.toString();
} catch (err) {
output = `<span style="color: ${errorColor}">${err}</span>`;
}
} }
outputLines = output outputLines = output