Apply visual identity: palette B, Atkinson/JetBrains fonts, split CSS, syntax-highlighted editor, owl icon

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-16 14:53:50 +02:00
parent 6e63a51a1b
commit 6b4b89a742
27 changed files with 994 additions and 255 deletions
+11 -13
View File
@@ -2,6 +2,7 @@
// Émet les événements 'run' (detail: { code }), 'stop' et 'reset'. Aucune logique d'exécution ici.
import { el, renderInline, uniqueId } from './dom.js';
import { CodeEditor } from './CodeEditor.js';
import { HintPanel } from './HintPanel.js';
export class CellView extends EventTarget {
@@ -33,19 +34,16 @@ export class CellView extends EventTarget {
const editorId = uniqueId('editor');
const outputId = uniqueId('output');
this.#editor = el('textarea', {
id: editorId,
class: 'code-editor',
spellcheck: 'false',
autocapitalize: 'off',
autocomplete: 'off',
autocorrect: 'off',
rows: Math.max(3, starter.split('\n').length + 1),
'aria-label': i18n.t('cell.editor'),
'aria-describedby': `${editorId}-hint`,
onkeydown: (event) => this.#onKeyDown(event),
this.#editor = new CodeEditor({
value: starter,
attrs: {
id: editorId,
rows: Math.max(3, starter.split('\n').length + 1),
'aria-label': i18n.t('cell.editor'),
'aria-describedby': `${editorId}-hint`,
},
onKeyDown: (event) => this.#onKeyDown(event),
});
this.#editor.value = starter;
this.#runButton = el('button', { type: 'button', class: 'btn btn-primary cell-run', text: i18n.t('cell.run'), onclick: () => this.#emitRun() });
this.#stopButton = el('button', {
@@ -79,7 +77,7 @@ export class CellView extends EventTarget {
'section',
{ class: 'cell', tabindex: '-1' },
el('p', { class: 'cell-instruction' }, renderInline(instruction)),
this.#editor,
this.#editor.element,
el('p', { id: `${editorId}-hint`, class: 'cell-shortcut', text: i18n.t('cell.shortcut') }),
el('div', { class: 'cell-actions' }, this.#runButton, this.#stopButton, resetButton, new HintPanel(i18n, hints).element),
this.#output,
+69
View File
@@ -0,0 +1,69 @@
// Éditeur de code coloré. Un <textarea> réel reste le contrôle (clavier, lecteurs d'écran,
// saisie mobile) ; un <pre> placé derrière affiche le même code coloré (aria-hidden).
import { el } from './dom.js';
import { tokenizePython } from './highlightPython.js';
const MIN_ROWS = 3;
export class CodeEditor {
#root;
#textarea;
#highlight;
/**
* @param {object} options
* @param {string} options.value
* @param {Record<string, string>} [options.attrs] Attributs du textarea (id, aria-label…).
* @param {(event: KeyboardEvent) => void} [options.onKeyDown]
*/
constructor({ value, attrs = {}, onKeyDown = () => {} }) {
this.#highlight = el('pre', { class: 'code-highlight', 'aria-hidden': 'true' });
this.#textarea = el('textarea', {
class: 'code-editor',
wrap: 'off',
spellcheck: 'false',
autocapitalize: 'off',
autocomplete: 'off',
autocorrect: 'off',
...attrs,
oninput: () => this.#render(),
onscroll: () => this.#syncScroll(),
onkeydown: onKeyDown,
});
this.#root = el('div', { class: 'code-editor-wrap' }, this.#highlight, this.#textarea);
this.value = value;
}
get element() {
return this.#root;
}
get value() {
return this.#textarea.value;
}
set value(code) {
this.#textarea.value = code;
this.#render();
}
focus() {
this.#textarea.focus();
}
#render() {
const code = this.#textarea.value;
this.#textarea.rows = Math.max(MIN_ROWS, code.split('\n').length + 1);
const nodes = tokenizePython(code).map(({ type, text }) =>
type === 'text' ? document.createTextNode(text) : el('span', { class: `tok-${type}`, text }),
);
this.#highlight.replaceChildren(...nodes);
this.#syncScroll();
}
#syncScroll() {
this.#highlight.scrollTop = this.#textarea.scrollTop;
this.#highlight.scrollLeft = this.#textarea.scrollLeft;
}
}
+70
View File
@@ -0,0 +1,70 @@
// Coloration syntaxique Python minimale, sans dépendance : découpe le code en jetons typés.
// Tolérante (jamais d'exception sur du code incomplet) et sans perte : la concaténation des
// textes des jetons redonne exactement le code d'entrée.
const KEYWORDS = new Set([
'False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield',
]);
const BUILTINS = new Set([
'abs', 'all', 'any', 'bool', 'dict', 'enumerate', 'filter', 'float', 'input', 'int', 'isinstance', 'len', 'list',
'map', 'max', 'min', 'open', 'print', 'range', 'reversed', 'round', 'set', 'sorted', 'str', 'sum', 'tuple', 'type', 'zip',
]);
// Ordre des alternatives = priorité : commentaire, chaîne triple, chaîne simple, nombre, identifiant, autre.
// Les rétro-références comptent aussi les groupes nommés : \3 = guillemets triples, \5 = guillemet simple.
const TOKEN = new RegExp(
[
String.raw`(?<comment>#[^\n]*)`,
String.raw`(?<triple>(?:[rRuUbBfF]{0,2})("""|''')[\s\S]*?(?:\3|$))`,
String.raw`(?<string>(?:[rRuUbBfF]{0,2})(["'])(?:\\.|(?!\5)[^\\\n])*(?:\5|(?=\n)|$))`,
String.raw`(?<number>\d+(?:_\d+)*(?:\.\d+)?(?:[eE][+-]?\d+)?|\.\d+)`,
String.raw`(?<identifier>[A-Za-z_À-ÿ][\wÀ-ÿ]*)`,
String.raw`(?<other>[\s\S])`,
].join('|'),
'y',
);
/**
* @param {string} code
* @returns {{type: 'keyword'|'string'|'number'|'comment'|'builtin'|'def'|'text', text: string}[]}
*/
export function tokenizePython(code) {
const tokens = [];
let expectName = false; // vrai juste après `def` ou `class` : le prochain identifiant est un nom défini
TOKEN.lastIndex = 0;
while (TOKEN.lastIndex < code.length) {
const match = TOKEN.exec(code);
const { comment, triple, string, number, identifier } = match.groups;
let type = 'text';
if (comment !== undefined) {
type = 'comment';
} else if (triple !== undefined || string !== undefined) {
type = 'string';
} else if (number !== undefined) {
type = 'number';
} else if (identifier !== undefined) {
if (KEYWORDS.has(identifier)) {
type = 'keyword';
expectName = identifier === 'def' || identifier === 'class';
} else {
type = expectName ? 'def' : BUILTINS.has(identifier) ? 'builtin' : 'text';
expectName = false;
}
}
// Les espaces entre `def` et le nom ne rompent pas l'attente ; tout autre jeton la rompt.
if (identifier === undefined && !/^\s+$/.test(match[0])) {
expectName = false;
}
// Fusionne les jetons « texte » adjacents pour limiter le nombre de nœuds.
const last = tokens.at(-1);
if (type === 'text' && last?.type === 'text') {
last.text += match[0];
} else {
tokens.push({ type, text: match[0] });
}
}
return tokens;
}