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

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

@ -8,7 +8,11 @@
<link rel="stylesheet" href="src/style.css" /> <link rel="stylesheet" href="src/style.css" />
</head> </head>
<body> <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"> <div class="input">
<input type="text" id="word-input" autocapitalize="off" spellcheck="false" /> <input type="text" id="word-input" autocapitalize="off" spellcheck="false" />
<div id="light"></div> <div id="light"></div>
@ -20,6 +24,6 @@
<pre id="pen"></pre> <pre id="pen"></pre>
<pre id="state-graph"></pre> <pre id="state-graph"></pre>
</div> </div>
<script type="module" src="src/fsm.js"></script> <script type="module" src="src/main.js"></script>
</body> </body>
</html> </html>

@ -4,6 +4,43 @@
* @property {boolean} [accepting] * @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[]} * @type {State[]}
*/ */
@ -12,3 +49,11 @@ export const ENDS_WITH_TWO_B = [
{ transitions: { a: 0, b: 2 } }, { transitions: { a: 0, b: 2 } },
{ transitions: { a: 0, b: 2 }, accepting: true }, { 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 mermaid from 'mermaid';
import { ENDS_WITH_TWO_B } from './examples.js';
const IS_VALID = 'is-valid'; const IS_VALID = 'is-valid';
const IS_INVALID = 'is-invalid'; const IS_INVALID = 'is-invalid';
@ -14,112 +13,99 @@ mermaid.initialize({
startOnLoad: false, 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() { export async function selectAutomaton(states) {
wordInput.value = builder; let state = 0;
if (state === -1 || !states[state].accepting) { let builder = '';
light.classList.remove(IS_VALID);
light.classList.add(IS_INVALID); // Build the mermaid graph definition
} else { let graphDefinition = 'stateDiagram-v2\n classDef acceptingnode font-weight:bold,stroke-width:2px,stroke:yellow';
light.classList.remove(IS_INVALID); for (let i = 0; i < states.length; ++i) {
light.classList.add(IS_VALID); 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')); const graph = /** @type {HTMLDivElement} */ (document.getElementById('pen'));
if (state in nodes) { const { svg } = await mermaid.render('state-graph', graphDefinition);
nodes[state].classList.add('current-node'); 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. * Steps the FSM with the given letter.
* *
* @param {string} letter * @param {string} letter
*/ */
function step(letter) { function step(letter) {
if (state === -1) { if (state === -1) {
return; return;
}
builder += letter;
state = states[state].transitions[letter] ?? -1;
updateUIState();
} }
builder += letter;
state = states[state].transitions[letter] ?? -1;
updateUIState();
}
/** // Dynamically create buttons for each letter in the alphabet
* Gets the integer value of the given attribute on the given element. /**
* * @type {string[]}
* @param {Element} element */
* @param {string} attribute const alphabet = Array.from(states.reduce((acc, current) => {
* @returns {number} Object.keys(current.transitions).forEach(current => acc.add(current));
*/ return acc;
function getIntAttribute(element, attribute) { }, new Set())).sort();
return parseInt(/** @type {string} */ (element.getAttribute(attribute))); 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 // Reacts to input in the text box
/** wordInput.addEventListener('input', () => {
* @type {string[]} const value = wordInput.value;
*/ builder = '';
const alphabet = Array.from(states.reduce((acc, current) => { state = 0;
Object.keys(current.transitions).forEach(current => acc.add(current)); for (const letter of value) {
return acc; step(letter);
}, new Set())).sort(); }
for (const letter of alphabet) { if (!value.length) {
const button = document.createElement('button'); updateUIState();
button.innerText = letter; }
button.addEventListener('click', () => step(letter)); });
buttons.appendChild(button);
}
// Reacts to input in the text box clearButton.addEventListener('click', () => {
wordInput.addEventListener('input', () => { wordInput.value = '';
const value = wordInput.value; builder = '';
builder = ''; state = 0;
state = 0;
for (const letter of value) {
step(letter);
}
if (!value.length) {
updateUIState(); updateUIState();
} });
});
clearButton.addEventListener('click', () => {
wordInput.value = '';
builder = '';
state = 0;
updateUIState(); 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; fill: red !important;
} }
.accepting-node { .accepting-node {
outline: 1px solid #81B1DB; stroke: yellow;
outline-offset: 2px; }
border-radius: 0.1em;
#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) { @media (prefers-color-scheme: light) {

Loading…
Cancel
Save