Introduce the FSM editor

This commit is contained in:
2024-02-06 21:20:02 +01:00
parent be1cd8b39f
commit 877b162eaa
6 changed files with 142 additions and 56 deletions

View File

@@ -1,5 +1,5 @@
import { Graph } from './editor/d3/graph.ts';
import { GraphEditor } from './editor/GraphEditor.ts';
import { createGraph, createStateList } from './editor/mapper.ts';
const IS_VALID = 'is-valid';
const IS_INVALID = 'is-invalid';
@@ -11,30 +11,23 @@ const light = /** @type {HTMLDivElement} */ (document.getElementById('light'));
/**
* @param {import('./examples.js').State[]} states
* @param {boolean} [editable]
*/
export async function selectAutomaton(states) {
let state = 0;
export function openAutomaton(states, editable = false) {
let state = findStart(states);
let builder = '';
const viewer = new GraphEditor();
viewer.readonly = true;
const graph = new Graph();
for (let i = 0; i < states.length; i++) {
const node = graph.createNode(i);
if (states[i].accepting) {
node.accepting = true;
viewer.readonly = !editable;
const graph = createGraph(states);
viewer.addEventListener('change', () => {
try {
states = createStateList(graph);
type();
} catch (e) {
console.error(e);
}
if (i === 0) {
node.start = true;
}
}
for (let i = 0; i < states.length; i++) {
const state = states[i];
for (const [letter, target] of Object.entries(state.transitions)) {
graph.createLink(i, target, letter);
}
}
});
const container = /** @type {HTMLDivElement} */ (document.getElementById('state-graph'));
container.appendChild(viewer);
viewer.graph = graph;
@@ -44,7 +37,7 @@ export async function selectAutomaton(states) {
*/
function updateUIState() {
wordInput.value = builder;
if (state === -1 || !states[state].accepting) {
if (state === -1 || states.length === 0 || !states[state].accepting) {
light.classList.remove(IS_VALID);
light.classList.add(IS_INVALID);
} else {
@@ -58,6 +51,18 @@ export async function selectAutomaton(states) {
viewer.restart();
}
function type() {
const value = wordInput.value;
builder = '';
state = findStart(states);
for (const letter of value) {
step(letter);
}
if (!value.length) {
updateUIState();
}
}
/**
* Steps the FSM with the given letter.
*
@@ -88,24 +93,22 @@ export async function selectAutomaton(states) {
}
// Reacts to input in the text box
wordInput.addEventListener('input', () => {
const value = wordInput.value;
builder = '';
state = 0;
for (const letter of value) {
step(letter);
}
if (!value.length) {
updateUIState();
}
});
wordInput.addEventListener('input', () => type());
clearButton.addEventListener('click', () => {
wordInput.value = '';
builder = '';
state = 0;
state = findStart(states);
updateUIState();
});
updateUIState();
}
/**
* @param {import('./examples.js').State[]} states
*/
function findStart(states) {
let state = states.findIndex(state => state.start);
return Math.max(state, 0);
}