Allow editing var decls and function decls

This commit is contained in:
2022-04-10 00:21:56 -05:00
parent 73010a2a4a
commit c9cc778333
8 changed files with 271 additions and 32 deletions

View File

@@ -0,0 +1,97 @@
<script setup lang="ts">
import {MathStatement} from '../support/parse'
import {onMounted, ref} from 'vue'
import {v4 as uuidv4} from 'uuid'
import {StatementID} from '../support/types'
import Katex from './Katex.vue'
const props = defineProps<{
statement?: MathStatement,
}>()
const emit = defineEmits<{
(eventName: 'save', statement: MathStatement): void,
}>()
const functionPreview = ref(MathStatement.temp(''))
let functionPreviewKey = ref(uuidv4())
const functionError = ref<string|undefined>(undefined)
const functionValue = ref('')
const updateFunctionPreview = () => {
const previewStmt = MathStatement.temp(functionValue.value)
if ( previewStmt.isValid() ) {
functionPreview.value = MathStatement.temp(functionValue.value)
functionPreviewKey.value = uuidv4()
}
}
const validateFunction = () => {
if ( !functionValue.value ) {
return 'Missing function declaration'
}
const stmt = MathStatement.temp(functionValue.value)
if ( !stmt.isValid() || !stmt.isFunctionDeclaration() ) {
return 'Function definition is invalid'
}
if ( !stmt.isNotRecursive() ) {
return 'A function may not reference itself'
}
}
const saveFunction = () => {
functionError.value = validateFunction()
if ( functionError.value ) {
return
}
if ( props.statement ) {
props.statement.raw = functionValue.value
emit('save', props.statement)
} else {
emit('save', new MathStatement(
uuidv4() as StatementID,
functionValue.value
))
}
}
onMounted(() => {
if ( props.statement ) {
functionValue.value = props.statement.raw
updateFunctionPreview()
}
})
</script>
<template>
<q-card>
<q-card-section>
<div style="display: flex; justify-content: center">
<Katex
:key="functionPreviewKey"
:statement="functionPreview"
/>
</div>
</q-card-section>
<q-card-section v-if="functionError">
<div style="color: darkred; font-weight: bold">{{ functionError }}</div>
</q-card-section>
<q-card-section>
<q-input
v-model="functionValue"
v-on:update:model-value="() => updateFunctionPreview()"
outlined
type="textarea"
autogrow
label="Value"
/>
</q-card-section>
<q-card-actions align="right" class="text-primary">
<q-btn flat label="Cancel" v-close-popup></q-btn>
<q-btn flat label="Save" @click="() => saveFunction()"></q-btn>
</q-card-actions>
</q-card>
</template>

View File

@@ -10,6 +10,7 @@ import ExpressionEditor from './ExpressionEditor.vue'
import TextBox from '../components/TextBox.vue'
import {RichTextBox} from '../support/types'
import { stepX, stepY } from '../support/const'
import FunctionEditor from '../components/FunctionEditor.vue'
const math = new MathPage(uuidv4());
const statements = ref<MathStatement[]>([]);
@@ -33,20 +34,35 @@ const variableListingColumns = [
const variableListingRows = ref<({name: string, value: string})[]>([])
const functionListingColumns = [
{
name: 'value',
field: 'value',
label: 'Function',
},
]
const functionListingRows = ref<({name: string, value: string})[]>([])
function toggleLeftDrawer() {
leftDrawerOpen.value = !leftDrawerOpen.value;
leftDrawerOpen.value = !leftDrawerOpen.value
}
const newVariableModalOpen = ref(false);
const newVariableModalOpen = ref(false)
const openNewVariableDeclModal = () => {
newVariableModalOpen.value = true;
newVariableModalOpen.value = true
};
const newExpressionModalOpen = ref(false);
const newExpressionModalOpen = ref(false)
const openNewExpressionModal = () => {
newExpressionModalOpen.value = true;
newExpressionModalOpen.value = true
};
const newFunctionModalOpen = ref(false)
const openNewFunctionModal = () => {
newFunctionModalOpen.value = true
}
const editingStatement = ref<MathStatement|undefined>()
const editExpressionModalOpen = ref(false)
const openEditExpressionModal = () => {
@@ -58,6 +74,11 @@ const openEditVarDeclModal = () => {
editVarDeclModalOpen.value = true
}
const editFunctionModalOpen = ref(false)
const openEditFunctionModal = () => {
editFunctionModalOpen.value = true
}
const updateStatements = () => {
statements.value = math.getStatements();
try {
@@ -71,7 +92,8 @@ const updateStatements = () => {
let value = String(evaluation.value!.variables[name] ?? '')
try {
value = MathStatement.temp(value).toHTMLString()
const stmt = MathStatement.temp(value)
value = stmt.toHTMLString()
} catch (_) {}
variableValues.push({
@@ -81,32 +103,51 @@ const updateStatements = () => {
}
variableListingRows.value = variableValues
const functionValues: ({name: string, value: string})[] = []
for ( const stmt of math.functions() ) {
const node = stmt.parse() as math.FunctionAssignmentNode
functionValues.push({
name: node.name,
value: stmt.toHTMLString(),
})
}
functionListingRows.value = functionValues
} catch (_) {
evaluation.value = undefined;
console.error(_)
evaluation.value = undefined
}
statementsKey.value = uuidv4();
statementsKey.value = uuidv4()
};
onMounted(updateStatements)
const saveNewVariable = (stmt: MathStatement) => {
math.addStatement(stmt);
newVariableModalOpen.value = false;
updateStatements();
math.addStatement(stmt)
newVariableModalOpen.value = false
updateStatements()
};
const saveNewExpression = (stmt: MathStatement) => {
math.addStatement(stmt);
newExpressionModalOpen.value = false;
updateStatements();
math.addStatement(stmt)
newExpressionModalOpen.value = false
updateStatements()
};
const saveNewFunction = (stmt: MathStatement) => {
math.addStatement(stmt)
newFunctionModalOpen.value = false
updateStatements()
}
const editStatement = (stmt: MathStatement) => {
editingStatement.value = stmt
if ( stmt.isDeclaration() ) {
console.log('editStatement', stmt)
if ( stmt.isFunctionDeclaration() ) {
openEditFunctionModal()
} else if ( stmt.isDeclaration() ) {
openEditVarDeclModal()
} else if ( stmt.isFunctionDeclaration() ) {
} else {
openEditExpressionModal()
}
@@ -119,6 +160,8 @@ const removeStatement = (stmt: MathStatement) => {
const finishEditStatement = () => {
editExpressionModalOpen.value = false
editVarDeclModalOpen.value = false
editFunctionModalOpen.value = false
updateStatements()
}
@@ -134,7 +177,7 @@ const makeNewRichTextBox = () => {
console.log("editing statement",richEditID.value, richEditModal);
};
const richTextStatements = ref([new RichTextBox("Hello World")]);
const richTextStatements = ref([]);
const richEditModal = ref(false);
const richEditExpression = ref("");
@@ -205,17 +248,17 @@ const removeRichTextBox = (id: number) => {
<q-table
flat
title="Functions"
:rows="functionListingRows"
:columns="functionListingColumns"
row-key="name"
hide-no-data
hide-bottom
hide-header
:pagination="{rowsPerPage: 10000}"
style="height: 100%; border-top: 1px solid lightgrey; border-radius: 0"
>
<template v-slot:body="props">
<q-tr :props="props">
<q-td key="name" :props="props">
{{ props.row.name }}
</q-td>
<q-td key="value" :props="props">
<div v-html="props.row.value"></div>
</q-td>
@@ -269,6 +312,19 @@ const removeRichTextBox = (id: number) => {
/>
</q-dialog>
<q-dialog v-model="newFunctionModalOpen">
<FunctionEditor
v-on:save="(s) => saveNewFunction(s)"
/>
</q-dialog>
<q-dialog v-model="editFunctionModalOpen">
<FunctionEditor
:statement="editingStatement"
v-on:save="() => finishEditStatement()"
/>
</q-dialog>
<q-page-sticky position="bottom-right" :offset="[32, 32]">
<q-fab color="primary" icon="add" direction="left">
<q-fab-action
@@ -279,15 +335,21 @@ const removeRichTextBox = (id: number) => {
@click="() => openNewVariableDeclModal()"
/>
<q-fab-action
color="secondary"
icon="code"
title="Add an expression"
@click="() => openNewExpressionModal()"
color="secondary"
icon="code"
title="Add an expression"
@click="() => openNewExpressionModal()"
/>
<q-fab-action
color="secondary"
icon="functions"
title="Add a new function"
@click="() => openNewFunctionModal()"
/>
<q-fab-action
color="secondary"
icon="text"
title="Add a Text Box"
title="Add a text box"
@click="() => makeNewRichTextBox()"
/>
</q-fab>

View File

@@ -32,8 +32,8 @@ const validateExpression = () => {
return 'The expression is invalid'
}
if ( stmt.defines().length > 0 ) {
return 'Expressions cannot declare variables'
if ( stmt.defines().length > 0 || stmt.isFunctionDeclaration() ) {
return 'Expressions cannot declare variables or functions'
}
}

View File

@@ -1,4 +1,5 @@
<script setup lang="ts">
import * as math from 'mathjs'
import {onMounted, ref} from 'vue'
import {MathStatement} from '../support/parse'
import {v4 as uuidv4} from 'uuid'
@@ -67,7 +68,9 @@ onMounted(() => {
if ( props.statement ) {
const [ define ] = props.statement.defines()
newVariableName.value = define.name
newVariableValue.value = props.statement.raw
const [_, ...rest] = props.statement.raw.split('=')
newVariableValue.value = rest.join('=')
updateNewVariablePreview()
}
})

View File

@@ -2,7 +2,7 @@ import {MathStatement} from './parse'
import * as math from 'mathjs'
import {DepGraph} from 'dependency-graph'
import { v4 as uuidv4 } from 'uuid'
import {EvaluationResult, Maybe, StatementID, VariableName} from './types'
import {EvaluationResult, hasOwnProperty, Maybe, StatementID, VariableName} from './types'
/**
* Wrapper for a page containing multiple interrelated mathematical statements.
@@ -82,6 +82,12 @@ export class MathPage {
dependencies(): DepGraph<MathStatement> {
const graph = new DepGraph<MathStatement>()
const defined: Record<VariableName, MathStatement> = this.definers()
const definedFunctions: Record<VariableName, MathStatement> = {}
for ( const sym of this.functions() ) {
const node = sym.parse() as math.FunctionAssignmentNode
definedFunctions[node.name as VariableName] = sym
}
for ( const statement of Object.values(this.statements) ) {
graph.addNode(statement.id, statement)
@@ -89,6 +95,12 @@ export class MathPage {
for ( const statement of Object.values(this.statements) ) {
for ( const symbol of statement.uses() ) {
const functionProvider = definedFunctions[symbol.name as VariableName]
if ( functionProvider ) {
graph.addDependency(statement.id, functionProvider.id)
continue
}
const provider = defined[symbol.name as VariableName]
if ( !provider ) {
throw new Error('No provider for undefined symbol: ' + symbol.name)
@@ -101,11 +113,32 @@ export class MathPage {
return graph
}
/** Returns true if the given variable name is a function definition. */
isFunctionKey(name: VariableName): boolean {
return this.functions()
.some(stmt => {
const node = stmt.parse() as math.FunctionAssignmentNode
return node.name === name
})
}
/** Get all the statements defining functions. */
functions(): MathStatement[] {
return Object.values(this.statements)
.filter(x => x.isFunctionDeclaration())
}
/** Evaluate the current state of the page and get the result. */
evaluate(): EvaluationResult {
const evaluations: Record<StatementID, any> = {}
const scope: Record<VariableName, any> = {}
const graph = this.dependencies()
const definers = this.definers()
for ( const stmt of this.functions() ) {
const node = stmt.parse() as math.FunctionAssignmentNode
scope[node.name as VariableName] = stmt.parse().evaluate()
}
for ( const node of graph.overallOrder() ) {
const stmt = this.statements[node as StatementID]
@@ -114,8 +147,19 @@ export class MathPage {
.evaluate(scope)
}
const nonFunctionalScope: Record<VariableName, any> = {}
for ( const key in scope ) {
if ( !hasOwnProperty(scope, key) ) {
continue
}
if ( definers[key as VariableName] ) {
nonFunctionalScope[key as VariableName] = scope[key]
}
}
return {
variables: scope,
variables: nonFunctionalScope,
statements: evaluations,
}
}

View File

@@ -117,6 +117,7 @@ export class SymbolWalk extends MathNodeWalk<math.SymbolNode[]> {
walkFunctionAssignmentNode(node: math.FunctionAssignmentNode): math.SymbolNode[] {
return this.walk(node.expr)
.filter(sym => !node.params.includes(sym.name))
}
walkFunctionNode(node: math.FunctionNode): math.SymbolNode[] {
@@ -350,6 +351,6 @@ export class MathStatement {
}
isFunctionDeclaration(): boolean {
return false
return math.isFunctionAssignmentNode(this.parse())
}
}