Add a level selector
continuous-integration/drone/push Build is passing Details

main
Clément FRÉVILLE 6 months ago
parent 987388b714
commit b68f84bc98

@ -8,7 +8,11 @@
<link rel="stylesheet" href="src/style.css" />
</head>
<body>
<div id="app">
<div id="automaton-selector">
<h1>Select an automaton</h1>
<div id="automaton-collection"></div>
</div>
<div id="app" hidden="hidden">
<div class="input">
<input type="text" id="word-input" autocapitalize="off" spellcheck="false" />
<div id="light"></div>
@ -20,6 +24,6 @@
<pre id="pen"></pre>
<pre id="state-graph"></pre>
</div>
<script type="module" src="src/fsm.js"></script>
<script type="module" src="src/main.js"></script>
</body>
</html>

@ -4,6 +4,43 @@
* @property {boolean} [accepting]
*/
/**
* @type {State[]}
*/
export const STARTS_ENDS_A = [
{ transitions: { a: 1, b: 3 } },
{ transitions: { a: 2, b: 1 } },
{ transitions: { a: 2, b: 1 }, accepting: true },
{ transitions: { a: 3, b: 3 } },
];
/**
* @type {State[]}
*/
export const STARTS_BB = [
{ transitions: { a: 3, b: 1 } },
{ transitions: { a: 3, b: 2 } },
{ transitions: { a: 2, b: 2 }, accepting: true },
{ transitions: { a: 3, b: 3 } },
];
/**
* @type {State[]}
*/
export const EXACTLY_ONE_B = [
{ transitions: { a: 0, b: 1 } },
{ transitions: { a: 1, b: 2 }, accepting: true },
{ transitions: { a: 2, b: 2 } },
];
/**
* @type {State[]}
*/
export const ODD_NUMBER_OF_A = [
{ transitions: { a: 1, b: 0 } },
{ transitions: { a: 0, b: 1 }, accepting: true },
];
/**
* @type {State[]}
*/
@ -12,3 +49,11 @@ export const ENDS_WITH_TWO_B = [
{ transitions: { a: 0, b: 2 } },
{ transitions: { a: 0, b: 2 }, accepting: true },
];
export const AUTOMATONS = {
'Starts and ends with a': STARTS_ENDS_A,
'Starts with bb': STARTS_BB,
'Exactly one b': EXACTLY_ONE_B,
'Odd number of a': ODD_NUMBER_OF_A,
'Ends with two b': ENDS_WITH_TWO_B,
};

@ -1,5 +1,4 @@
import mermaid from 'mermaid';
import { ENDS_WITH_TWO_B } from './examples.js';
const IS_VALID = 'is-valid';
const IS_INVALID = 'is-invalid';
@ -14,112 +13,99 @@ mermaid.initialize({
startOnLoad: false,
});
const states = ENDS_WITH_TWO_B;
let state = 0;
let builder = '';
// Build the mermaid graph definition
let graphDefinition = 'stateDiagram-v2';
for (let i = 0; i < states.length; ++i) {
graphDefinition += `\n s${i} : ${i}`;
for (const [transition, destination] of Object.entries(states[i].transitions)) {
graphDefinition += `\n s${i} --> s${destination}: ${transition}`;
}
}
const graph = /** @type {HTMLDivElement} */ (document.getElementById('pen'));
const { svg } = await mermaid.render('state-graph', graphDefinition);
graph.innerHTML = svg;
const nodes = graph.querySelectorAll('.label-container');
for (let i = 0; i < nodes.length; ++i) {
if (states[i].accepting) {
nodes[i].classList.add('accepting-node');
}
}
// Create a triangular arrow pointing to the initial state
const arrow = document.createElementNS('http://www.w3.org/2000/svg', 'path');
const x = -(getIntAttribute(nodes[0], 'x') - 20);
const y = -getIntAttribute(nodes[0], 'y');
arrow.setAttribute('d', 'M 0 0 L 10 5 L 0 10 z');
arrow.setAttribute('transform', `translate(${x}, ${y})`);
arrow.setAttribute('fill', 'currentColor');
(/** @type {Element} */ (graph.querySelector('.edgePaths'))).appendChild(arrow);
/**
* Updates the UI to reflect the current state.
* @param {import('./examples.js').State[]} states
*/
function updateUIState() {
wordInput.value = builder;
if (state === -1 || !states[state].accepting) {
light.classList.remove(IS_VALID);
light.classList.add(IS_INVALID);
} else {
light.classList.remove(IS_INVALID);
light.classList.add(IS_VALID);
export async function selectAutomaton(states) {
let state = 0;
let builder = '';
// Build the mermaid graph definition
let graphDefinition = 'stateDiagram-v2\n classDef acceptingnode font-weight:bold,stroke-width:2px,stroke:yellow';
for (let i = 0; i < states.length; ++i) {
graphDefinition += `\n s${i} : ${i}`;
if (i === 0) {
graphDefinition += '\n [*] --> s0';
}
if (states[i].accepting) {
graphDefinition += `\n s${i} --> [*]`;
graphDefinition += `\n class s${i} acceptingnode`;
}
for (const [transition, destination] of Object.entries(states[i].transitions)) {
graphDefinition += `\n s${i} --> s${destination}: ${transition}`;
}
}
nodes.forEach((node) => node.classList.remove('current-node'));
if (state in nodes) {
nodes[state].classList.add('current-node');
const graph = /** @type {HTMLDivElement} */ (document.getElementById('pen'));
const { svg } = await mermaid.render('state-graph', graphDefinition);
graph.innerHTML = svg;
const nodes = graph.querySelectorAll('.label-container');
/**
* Updates the UI to reflect the current state.
*/
function updateUIState() {
wordInput.value = builder;
if (state === -1 || !states[state].accepting) {
light.classList.remove(IS_VALID);
light.classList.add(IS_INVALID);
} else {
light.classList.remove(IS_INVALID);
light.classList.add(IS_VALID);
}
nodes.forEach((node) => node.classList.remove('current-node'));
if (state in nodes) {
nodes[state].classList.add('current-node');
}
}
}
/**
* Steps the FSM with the given letter.
*
* @param {string} letter
*/
function step(letter) {
if (state === -1) {
return;
/**
* Steps the FSM with the given letter.
*
* @param {string} letter
*/
function step(letter) {
if (state === -1) {
return;
}
builder += letter;
state = states[state].transitions[letter] ?? -1;
updateUIState();
}
builder += letter;
state = states[state].transitions[letter] ?? -1;
updateUIState();
}
/**
* Gets the integer value of the given attribute on the given element.
*
* @param {Element} element
* @param {string} attribute
* @returns {number}
*/
function getIntAttribute(element, attribute) {
return parseInt(/** @type {string} */ (element.getAttribute(attribute)));
}
// Dynamically create buttons for each letter in the alphabet
/**
* @type {string[]}
*/
const alphabet = Array.from(states.reduce((acc, current) => {
Object.keys(current.transitions).forEach(current => acc.add(current));
return acc;
}, new Set())).sort();
for (const letter of alphabet) {
const button = document.createElement('button');
button.innerText = letter;
button.addEventListener('click', () => step(letter));
buttons.appendChild(button);
}
// Dynamically create buttons for each letter in the alphabet
/**
* @type {string[]}
*/
const alphabet = Array.from(states.reduce((acc, current) => {
Object.keys(current.transitions).forEach(current => acc.add(current));
return acc;
}, new Set())).sort();
for (const letter of alphabet) {
const button = document.createElement('button');
button.innerText = letter;
button.addEventListener('click', () => step(letter));
buttons.appendChild(button);
}
// 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();
}
});
// 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) {
clearButton.addEventListener('click', () => {
wordInput.value = '';
builder = '';
state = 0;
updateUIState();
}
});
});
clearButton.addEventListener('click', () => {
wordInput.value = '';
builder = '';
state = 0;
updateUIState();
});
updateUIState();
}

@ -0,0 +1,31 @@
import { AUTOMATONS } from './examples.js';
import { selectAutomaton } from './fsm.js';
const automatonSelector = /** @type {HTMLDivElement} */ (document.getElementById('automaton-selector'));
const automatonCollection = /** @type {HTMLDivElement} */ (document.getElementById('automaton-collection'));
const app = /** @type {HTMLDivElement} */ (document.getElementById('app'));
for (const [displayName, automaton] of Object.entries(AUTOMATONS)) {
const card = document.createElement('div');
card.setAttribute('tabindex', '0');
card.setAttribute('role', 'button');
card.classList.add('card');
card.innerHTML = `
<div class="card-body">
<h5 class="card-title">${displayName}</h5>
<p class="card-text">${automaton.length} states</p>
</div>
`;
async function handleEvent() {
automatonSelector.setAttribute('hidden', 'hidden');
app.removeAttribute('hidden');
await selectAutomaton(automaton);
}
card.addEventListener('click', handleEvent);
card.addEventListener('keydown', async (event) => {
if (event.key === 'Enter' || event.key === ' ') {
await handleEvent();
}
});
automatonCollection.appendChild(card);
}

@ -82,9 +82,34 @@ button:focus-visible {
fill: red !important;
}
.accepting-node {
outline: 1px solid #81B1DB;
outline-offset: 2px;
border-radius: 0.1em;
stroke: yellow;
}
#automaton-selector {
width: 100%;
max-width: 600px;
margin: 0 auto;
}
#automaton-collection {
display: flex;
flex-wrap: wrap;
justify-content: center;
margin: 2em 0;
}
.card {
display: flex;
flex-direction: column;
align-items: center;
padding: 1.5em;
margin: 1em;
border-radius: 8px;
background-color: #1a1a1a;
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1), 0 2px 4px rgba(0, 0, 0, 0.2);
cursor: pointer;
}
.card:hover {
background-color: #2a2a2a;
}
@media (prefers-color-scheme: light) {

Loading…
Cancel
Save