feat: éditeur tableur — grille A → Z par blocs, barre de menus Sheets, panneau de couleurs, création .xlsx (#180 → #186)
CI / lint (push) Successful in 2m43s
CI / security (push) Successful in 1m33s
CI / test (push) Canceled after 0s
CI / build (push) Canceled after 0s
CI / e2e (push) Canceled after 0s

Restaure et termine le lot tableur resté non committé. Il n'existait que dans un
`git stash` (24 fichiers suivis) et en fichiers non suivis (menus.js, formula.js,
color-picker.js, tests, fiches) : la 2.53.3 livrée ne le contenait donc pas. Le
stash, créé avant le commit BUG-108, n'a jamais été restauré.

#180 Redimensionnement au curseur (en-tête de bord miroité + classe de repaint),
grille thémée sur les 15 thèmes et les modes contraste élevé / sépia, menu
Fichier au niveau des onglets, barre épinglée pleine largeur.

#181 Modèle de saisie Google Sheets : sélection ≠ édition (caret masqué sans
quitter contenteditable, double-clic / F2 / première frappe qui remplace,
Entrée contextuelle, Échap qui restaure) + inventaire priorisé des écarts.

#182 Désélection fiable (clic simple sans dépendre du focus), contours de plage
non empilés (sélecteur de classes sans point), couleurs texte/fond sur une
plage, clic droit qui préserve la sélection multiple.

#183 Panneau de couleurs façon Google Sheets : palette 8 × 10, STANDARD,
PERSONNALISÉ, coche selon la luminance, sortie `#rrggbb` (une valeur HSL était
rejetée par normHex).

#184 Peinture de format complète (toutes propriétés, source sans format =
réinitialisation), sélection multi-lignes/colonnes depuis les marges, grille
étendue : colonnes A → Z d'emblée, lignes ajoutées PAR BLOCS DE 100 au
défilement jusqu'à 1000 — matérialiser 1000 lignes d'un coup = ~26 000 cellules
câblées par feuille, ce qui épuisait le tas de la suite JSDOM ; index de
cellules `ref → td`, court-circuits formule/styles, marqueur data-wired.

#185 Barre de menus : les 10 menus Google Sheets (161 entrées, 125 câblées, 36
annoncées indisponibles), ruban façon Sheets, grille unie 1 px dérivée du thème.

#186 « Créer un fichier » propose .xlsx et construit un vrai classeur OPC
(openpyxl) au lieu d'une charge utile texte illisible.

Corrections trouvées en restaurant et en exerçant le lot :
- fuite mémoire : écouteur `click` anonyme posé sur #content-area à chaque
  rendu, jamais retiré — sa fermeture retenait la grille précédente en entier ;
- sorties Markdown / HTML / Imprimer de la barre de menus inertes
  (`data-xlsx-export` jamais réparti, seul `data-xlsx-action` l'était) ;
- collision de classe `.xlsx-structure-menu` entre la barre de menus et le menu
  Structure de la barre d'outils (toute requête tombait sur un nœud masqué) ;
- curseur col/row-resize absent quand le pointeur est sur la table elle-même ;
- l'export emportait les lignes et colonnes vides du quadrillage (CSV, Markdown,
  HTML, impression) ;
- clic extérieur avalé par la grâce de 250 ms du menu contextuel (destinée au
  seul appui long tactile) ;
- une entrée indisponible laissait la barre de menus ouverte.

Tests : pytest 1595 passés / 2 ignorés ; ruff et mypy 0 erreur ; bandit 0 ;
33 suites frontend vertes (xlsx-viewer 163/163, xlsx-menus 19/19,
xlsx-formula 14/14) ; E2E complet 132 passés / 12 ignorés ; E2E xlsx-viewer
19/19.
This commit is contained in:
2026-10-08 12:00:15 -04:00
parent ce1944d437
commit 634ba8a272
39 changed files with 9996 additions and 491 deletions
+200 -15
View File
@@ -41,6 +41,8 @@ const FIXTURE = 'sample-xlsx-lossy.xlsx';
// the viewer must SAY so. Generated once with openpyxl (header + 519 lines) and
// committed next to the other fixture; nothing in the suite writes to it.
const LARGE = 'sample-xlsx-large.xlsx';
const LARGE_PATH = path.resolve(process.cwd(), 'test_vault', LARGE);
let originalLargeBytes = null;
// Playwright runs from the repository root (run-e2e-local.* / CI both do).
const FIXTURE_PATH = path.resolve(process.cwd(), 'test_vault', FIXTURE);
@@ -85,19 +87,17 @@ test.describe('Excel viewer — garde-fous d\'écriture et valeurs calculées (#
// the viewer rewrites the workbook and an openpyxl round-trip drops the cached
// formula results (BUG-085), so the shadow line only exists on a pristine
// fixture.
test('affiche la valeur calculée en cache sous la formule (#153 A12)', async ({ page }) => {
test('calcule les formules à l’écran, garde le texte en barre (#153 A12)', async ({ page }) => {
await login(page);
await openFixture(page);
// B2 is "=B1*2" and the package keeps its last result (<v>200</v>).
// B2 is "=B1*2" and the package keeps its last result (<v>200</v>): the
// local engine computes it, so the cell shows the value (not the shadow).
const formulaCell = page.locator('#content-area td[data-cell="B2"]');
await expect(formulaCell).toContainText('=B1*2');
const cached = formulaCell.locator('.xlsx-cached');
await expect(cached).toHaveCount(1);
await expect(cached).toHaveText('200');
// The tooltip is translated client-side, never hardcoded by the backend.
await expect(cached).toHaveAttribute('title', /Excel/);
await expect(formulaCell).toHaveText('200');
await expect(formulaCell.locator('.xlsx-cached')).toHaveCount(0);
await formulaCell.click();
await expect(page.locator('#xlsx-formula-input')).toHaveValue('=B1*2');
// A plain value cell must not be duplicated with a shadow line.
await expect(page.locator('#content-area td[data-cell="B1"] .xlsx-cached')).toHaveCount(0);
@@ -286,11 +286,12 @@ test.describe('Excel viewer — presse-papiers, clavier et zone Nom (#156 P1)',
// — A6 : Ctrl+A sélectionne la feuille rendue, Ctrl+Home/End ses coins.
await cellOf('B12').click();
await page.keyboard.press('Control+a');
await expect(nameBox).toHaveValue('A1:C500');
// #184 — la feuille rendue va jusqu'à Z (la grille est posée A → Z).
await expect(nameBox).toHaveValue('A1:Z500');
await page.keyboard.press('Control+Home');
await expect(nameBox).toHaveValue('A1');
await page.keyboard.press('Control+End');
await expect(nameBox).toHaveValue('C500');
await expect(nameBox).toHaveValue('Z500');
// — A5 : copier une plage puis la coller ailleurs. Le menu contextuel
// utilise le presse-papiers interne de la grille : aucune permission
@@ -358,27 +359,160 @@ test.describe('Excel viewer — menus à icônes et fermeture au focus (#179)',
await login(page);
await openFixture(page);
await page.locator('#xlsx-structure-btn').click();
const toggle = page.locator('#xlsx-structure-btn');
await toggle.click();
const menu = page.locator('.xlsx-structure-menu');
await expect(menu).toBeVisible();
await expect(menu.locator('.xlsx-structure-item i[data-lucide], .xlsx-structure-item svg').first()).toBeAttached();
// The menu opens right under its button, inside the toolbar width.
const [btnBox, menuBox, toolbarBox] = await Promise.all([
toggle.boundingBox(), menu.boundingBox(),
page.locator('#content-area .xlsx-toolbar').boundingBox(),
]);
expect(menuBox.y).toBeGreaterThanOrEqual(btnBox.y + btnBox.height - 2);
expect(menuBox.y).toBeLessThanOrEqual(btnBox.y + btnBox.height + 24);
// Le menu reste DANS la barre : près du bord droit il est décalé vers la
// gauche (clamp de anchorUnder) au lieu de dépasser.
expect(menuBox.x).toBeGreaterThanOrEqual(toolbarBox.x - 2);
expect(menuBox.x + menuBox.width).toBeLessThanOrEqual(toolbarBox.x + toolbarBox.width + 2);
// Clic dans la grille = le focus quitte le menu → fermeture.
await page.locator('#content-area td[data-cell="A1"]').click();
await expect(page.locator('.xlsx-structure-menu')).toHaveCount(0);
await expect(page.locator('#xlsx-structure-btn')).toHaveAttribute('aria-expanded', 'false');
});
test('le menu Export se ferme au clic extérieur', async ({ page }) => {
test('le menu Fichier (Télécharger/CSV/Export) se ferme au clic extérieur', async ({ page }) => {
await login(page);
await openFixture(page);
await page.locator('#xlsx-export-btn').click();
const menu = page.locator('#xlsx-export-menu');
await page.locator('#xlsx-file-btn').click();
const menu = page.locator('#xlsx-file-menu');
await expect(menu).toBeVisible();
// Les 5 sorties sont réunies dans ce seul menu (#185 : il est passé dans
// la barre de menus, au-dessus du ruban), repliées dans la section
// « Télécharger » — les sections du menu sont des accordéons.
await menu.locator('.xlsx-menu-item', { hasText: 'Télécharger' }).first().click();
await expect(menu.locator('#xlsx-download-btn')).toBeVisible();
await expect(menu.locator('#xlsx-csv-btn')).toBeVisible();
await expect(page.locator('#content-area .xlsx-sheetbar-end #xlsx-save-btn')).toBeVisible();
await page.locator('#content-area td[data-cell="A1"]').click();
await expect(menu).toBeHidden();
});
test('#185 : les 10 menus Google Sheets au-dessus du ruban, et leurs sections', async ({ page }) => {
await login(page);
await openFixture(page);
const bar = page.locator('#content-area .xlsx-menubar');
await expect(bar).toBeVisible();
await expect(bar.locator('.xlsx-menubtn')).toHaveText([
'Fichier', 'Modifier', 'Affichage', 'Insertion', 'Format',
'Données', 'Outils', 'Gemini', 'Extensions', 'Aide',
]);
// Le ruban est bien SOUS les menus.
const [barBox, ribbonBox] = await Promise.all([
bar.boundingBox(),
page.locator('#content-area .xlsx-cmdbar').boundingBox(),
]);
expect(ribbonBox.y).toBeGreaterThan(barBox.y);
// Une section s'ouvre en accordéon, comme dans Sheets.
await page.locator('#content-area [data-xlsx-menu="format"]').click();
const format = page.locator('#xlsx-menu-format');
await expect(format).toBeVisible();
const number = format.locator('.xlsx-menu-item', { hasText: 'Nombre' }).first();
await number.click();
await expect(number).toHaveAttribute('aria-expanded', 'true');
await expect(format.locator('[data-xlsx-action="numfmt"]').first()).toBeVisible();
// Une option non implémentée le dit au lieu de ne rien faire.
const ghost = format.locator('[data-xlsx-unavailable]').first();
await ghost.click();
await expect(page.locator('.toast').first()).toBeVisible();
await expect(format).toBeHidden();
});
test('#185 : la grille est unie (1px sur les quatre côtés) et se masque', async ({ page }) => {
await login(page);
await openFixture(page);
const cell = page.locator('#content-area td[data-cell="B2"]');
const sides = await cell.evaluate((td) => {
const cs = getComputedStyle(td);
return [cs.borderTopWidth, cs.borderRightWidth, cs.borderBottomWidth, cs.borderLeftWidth];
});
expect(new Set(sides).size).toBe(1);
expect(sides[0]).toBe('1px');
await page.locator('#content-area [data-xlsx-menu="view"]').click();
const view = page.locator('#xlsx-menu-view');
await expect(view).toBeVisible();
// Les entrées d'affichage vivent dans la section « Afficher » (accordéon).
await view.locator('.xlsx-menu-item', { hasText: 'Afficher' }).first().click();
await page.locator('#xlsx-menu-view [data-xlsx-action="toggle-grid"]').click();
await expect(page.locator('#content-area .xlsx-viewer')).toHaveClass(/xlsx-no-grid/);
const hidden = await cell.evaluate((td) => getComputedStyle(td).borderTopWidth);
expect(hidden).toBe('0px');
});
// Mon seul test mutant : restaure la fixture comme le bloc lossy.
test.beforeAll(() => {
if (existsSync(LARGE_PATH)) originalLargeBytes = readFileSync(LARGE_PATH);
});
test.afterAll(() => {
if (originalLargeBytes) writeFileSync(LARGE_PATH, originalLargeBytes);
});
test('insère une colonne à droite et une ligne en fin de feuille', async ({ page }) => {
await login(page);
await openXlsx(page, LARGE);
// #184 — la grille posée va jusqu'à Z : le compte d'en-têtes ne peut plus
// témoigner de l'insertion (un re-rendu re-complète à 26 colonnes). Le
// toast est le signal de l'opération, la fixture restaurée sa preuve.
const headers = () => page.locator('#content-area .xlsx-table thead th:not(.xlsx-corner)');
await expect(headers()).toHaveCount(26);
await headers().nth(2).click({ button: 'right' });
await page.locator('.xlsx-context-item', { hasText: 'droite' }).click();
await expect(page.locator('.toast-success')).toBeVisible({ timeout: 10000 });
// Insérée localement (pas de re-rendu complet) : la colonne s'ajoute à
// la grille posée, 26 → 27.
await expect(headers()).toHaveCount(27);
// La ligne 501 dépasse le plafond de rendu : l'insertion réussit
// (toast) même si la ligne reste hors champ.
await page.locator('#content-area th.xlsx-rownum').nth(499).click({ button: 'right' });
await page.locator('.xlsx-context-item', { hasText: 'dessous' }).click();
await expect(page.locator('.toast-success')).toBeVisible({ timeout: 10000 });
});
test('la barre façon Sheets expose ses contrôles et agit', async ({ page }) => {
await login(page);
await openXlsx(page, LARGE);
for (const id of ['#xs-search', '#xs-print', '#xs-paint', '#xs-zoom', '#xs-cur', '#xs-pct',
'#xs-numfmt', '#xs-b', '#xs-i', '#xs-s', '#xs-u', '#xs-borders', '#xs-merge',
'#xs-alignh', '#xs-alignv', '#xs-wrap', '#xs-rot', '#xs-more', '#xlsx-save-btn']) {
await expect(page.locator(id)).toBeVisible();
}
// Zoom : la grille suit le sélecteur.
await page.locator('#xs-zoom').selectOption('150');
await expect.poll(async () => page.locator('#content-area .xlsx-panels').evaluate(
(el) => el.style.zoom || '100%')).toBe('150%');
await page.locator('#xs-zoom').selectOption('100');
// Gras via la barre : PUT + toast, sans dialogue.
await page.locator('#content-area td[data-cell="A1"]').click();
await page.locator('#xs-b').click();
await expect(page.locator('.toast-success')).toBeVisible({ timeout: 10000 });
// Mini-barre contextuelle sur une plage.
await page.locator('#content-area td[data-cell="A1"]').click();
await page.locator('#content-area td[data-cell="B2"]').click({ modifiers: ['Shift'] });
await expect(page.locator('#xlsx-minibar')).toBeVisible();
});
test('mobile : ruban sans débordement et cibles tactiles 44px', async ({ page, viewport }) => {
test.skip((viewport?.width ?? 9999) > 768, 'Mobile viewport required');
await login(page);
@@ -402,3 +536,54 @@ test.describe('Excel viewer — menus à icônes et fermeture au focus (#179)',
expect(itemBox.height).toBeGreaterThanOrEqual(44);
});
});
// ── #186 — création d'un classeur depuis la modale « Créer un fichier » ──────
test.describe('Excel viewer — création depuis l\'UI (#186)', () => {
// Le nom saisi dans la modale ne porte que le nom court : le dossier parent
// (« IT ») est déjà choisi par le menu contextuel.
const stem = `e2e-cree-${Date.now()}`;
const CREATED = `IT/${stem}.xlsx`;
async function cleanup(request) {
await request.fetch(
`${BASE}/api/file/${VAULT}?path=${encodeURIComponent(CREATED)}`,
{ method: 'DELETE' },
).catch(() => {});
}
test('la liste des types propose Excel et le classeur créé s\'ouvre dans la visionneuse', async ({ page, request }) => {
await cleanup(request);
await login(page);
// Menu contextuel du dossier « IT » → « Nouveau fichier ici ».
await page.locator('.tree-item.vault-item[data-vault="TestVault"]').first().click();
await page.locator('.tree-item[data-vault="TestVault"][data-path="IT"]').first()
.click({ button: 'right' });
const menu = page.locator('#context-menu.active');
await expect(menu).toBeVisible({ timeout: 5000 });
await menu.locator('.context-menu-item', { hasText: 'Nouveau fichier ici' }).click();
await page.locator('.obsigate-modal-overlay.active').waitFor({ state: 'visible', timeout: 5000 });
const extSelect = page.locator('#file-ext-select');
// L'option Excel existe, et son libellé vient des locales (jamais du dur).
await expect(extSelect.locator('option[value=".xlsx"]')).toHaveText('Excel (.xlsx)');
await extSelect.selectOption('.xlsx');
await page.fill('#file-name-input', stem);
await page.click('#file-create-btn');
// Le classeur s'ouvre dans la visionneuse : une grille, pas une erreur.
await expect(page.locator('#content-area .xlsx-table')).toBeVisible({ timeout: 15000 });
await expect(page.locator('#content-area .xlsx-tab', { hasText: 'Feuille1' })).toBeVisible();
// Et c'est un vrai classeur : l'API le sert en tableur, avec sa feuille.
const body = await request
.get(`${BASE}/api/file/${VAULT}?path=${encodeURIComponent(CREATED)}`)
.then((r) => r.json());
expect(body.is_xlsx).toBe(true);
expect(body.xlsx_sheets.map((s) => s.name)).toEqual(['Feuille1']);
await cleanup(request);
});
});
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env node
/**
* ObsiGate — unit tests for the spreadsheet formula engine
* (frontend/js/xlsx/formula.js). Pure logic, no DOM needed.
*
* Usage: node tests/frontend/xlsx-formula.test.mjs
*/
import { strict as assert } from "node:assert";
import { fileURLToPath, pathToFileURL } from "node:url";
import path from "node:path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const REPO_ROOT = path.resolve(__dirname, "..", "..");
const modUrl = pathToFileURL(
path.join(REPO_ROOT, "frontend", "js", "xlsx", "formula.js")
).href;
const {
isFormulaText, parseFormula, evaluate, createScope, displayValue,
colToIndex, indexToCol, parseA1,
} = await import(modUrl);
let testCount = 0;
let passCount = 0;
async function test(name, fn) {
testCount++;
try {
await fn();
passCount++;
console.log(` ✓ ${name}`);
} catch (e) {
console.error(` ✗ ${name}`);
console.error(e);
process.exitCode = 1;
}
}
/** Evaluate `text` against a fake sheet {ref: raw}. */
function run(text, cells = {}, locale = "en") {
const scope = createScope({
readRaw: (_sheet, ref) => {
const hit = Object.entries(cells).find(
([k]) => k.toUpperCase() === String(ref).toUpperCase()
);
return hit ? hit[1] : null;
},
sheet: "F",
locale,
});
return displayValue(evaluate(parseFormula(text), scope), locale);
}
await test("detects formula text", () => {
assert.ok(isFormulaText("=1+1"));
assert.ok(isFormulaText(" @A1 "));
assert.ok(!isFormulaText("hello"));
assert.ok(!isFormulaText("="));
});
await test("refs helpers", () => {
assert.equal(colToIndex("A"), 1);
assert.equal(colToIndex("Z"), 26);
assert.equal(colToIndex("AA"), 27);
assert.equal(indexToCol(28), "AB");
assert.deepEqual(parseA1("$B$12"), { col: 2, row: 12 });
assert.equal(parseA1("ZZZ"), null);
});
await test("arithmetic and Excel precedence (-2^2 = 4)", () => {
assert.equal(run("=1+2*3"), "7");
assert.equal(run("=(1+2)*3"), "9");
assert.equal(run("=2^3"), "8");
assert.equal(run("=-2^2"), "4");
assert.equal(run("=10/4"), "2.5");
assert.equal(run("=50%"), "0.5");
assert.equal(run("=5*10%"), "0.5");
});
await test("comparisons and concatenation", () => {
assert.equal(run("=1+1=2"), "TRUE");
assert.equal(run('="a"&"b"'), "ab");
assert.equal(run("=3>2"), "TRUE");
assert.equal(run("=1<>1"), "FALSE");
});
await test("cell refs and ranges", () => {
const cells = { A1: 2, A2: 4, B1: "x" };
assert.equal(run("=A1*3", cells), "6");
assert.equal(run("=SOMME(A1:A2)", cells), "6");
assert.equal(run("=SUM(A1:A2)", cells), "6");
assert.equal(run("=MOYENNE(A1:A2)", cells), "3");
assert.equal(run("=A1&B1", cells), "2x");
});
await test("French decimal comma with ; separator", () => {
assert.equal(run("=1,5+1", {}, "fr"), "2.5");
assert.equal(run("=SOMME(1;2;3)"), "6");
assert.equal(run("=SI(1>2;10;20)"), "20");
});
await test("functions FR/EN", () => {
assert.equal(run("=MAX(1;5;3)"), "5");
assert.equal(run("=MIN(1;5;3)"), "1");
assert.equal(run("=ABS(-4)"), "4");
assert.equal(run("=ARRONDI(2.456;2)"), "2.46");
assert.equal(run("=RACINE(9)"), "3");
assert.equal(run("=PUISSANCE(2;10)"), "1024");
assert.equal(run("=NB(1;\"x\";3)"), "2");
assert.equal(run("=NBVAL(1;\"x\";3)"), "3");
assert.equal(run("=NBCAR(\"héllo\")"), "5");
assert.equal(run("=MAJUSCULES(\"abc\")"), "ABC");
assert.equal(run("=GAUCHE(\"hello\";2)"), "he");
assert.equal(run("=DROITE(\"hello\";2)"), "lo");
assert.equal(run("=STXT(\"hello\";2;3)"), "ell");
assert.equal(run("=ET(1;1)"), "TRUE");
assert.equal(run("=OU(0;1)"), "TRUE");
assert.equal(run("=NON(1)"), "FALSE");
assert.equal(run('=SIERREUR(1/0;"raté")'), "raté");
assert.equal(run("=MEDIANE(3;1;2)"), "2");
assert.equal(run("=PRODUIT(2;3;4)"), "24");
assert.equal(run("=MOD(7;3)"), "1");
assert.equal(run("=ENT(2.9)"), "2");
});
await test("nested formulas and chained refs", () => {
const cells = { A1: "=B1*2", B1: 21 };
assert.equal(run("=A1+1", cells), "43");
});
await test("errors surface as localized codes", () => {
assert.equal(run("=1/0"), "#DIV/0!");
assert.equal(run("=1/0", {}, "fr"), "#DIV/0!");
assert.equal(run("=NOSUCHFN(1)"), "#NAME?");
assert.equal(run("=NOSUCHFN(1)", {}, "fr"), "#NOM?");
assert.equal(run('="a"+1'), "#VALUE!");
assert.equal(run('="a"+1', {}, "fr"), "#VALEUR!");
assert.equal(run("=A99999999"), "#REF!");
});
await test("cycles are detected", () => {
const cells = { A1: "=B1", B1: "=A1" };
assert.equal(run("=A1", cells), "#CIRC!");
assert.equal(run("=A1", cells, "fr"), "#CYCLE!");
});
await test("booleans localize", () => {
assert.equal(run("=VRAI"), "TRUE");
assert.equal(run("=VRAI", {}, "fr"), "VRAI");
assert.equal(run("=TRUE"), "TRUE");
assert.equal(run("=1=1", {}, "fr"), "VRAI");
});
await test("HYPERLINK yields a link value", async () => {
const scope = createScope({ readRaw: () => null, sheet: "F", locale: "en" });
const v = evaluate(parseFormula('=LIEN("https://x.test";"ici")'), scope);
assert.equal(v.t, "link");
assert.equal(v.url, "https://x.test");
assert.equal(v.label, "ici");
assert.equal(displayValue(v), "ici");
});
await test("garbage is rejected by the parser", () => {
assert.throws(() => parseFormula("=1+"), Error);
assert.throws(() => parseFormula("=SUM("), Error);
assert.throws(() => parseFormula("=(1"), Error);
});
await test("quoted and absolute refs", () => {
const cells = { A1: 5 };
assert.equal(run("=$A$1+1", cells), "6");
});
console.log(`\n${passCount}/${testCount} passed`);
process.exit(process.exitCode || 0);
+175 -14
View File
@@ -1,14 +1,19 @@
#!/usr/bin/env node
/**
* ObsiGate — JSDOM tests for the spreadsheet menus polish (ROADMAP #179).
* ObsiGate — JSDOM tests for the spreadsheet menus (ROADMAP #179, #185).
*
* Covers frontend/js/xlsx/context-menu.js and frontend/js/xlsx/command-bar.js:
* Covers frontend/js/xlsx/context-menu.js, command-bar.js and menus.js:
* - every grid-menu entry renders its representative Lucide icon + safe label;
* - the grid menu closes on Escape / outside click / focus loss / scroll /
* resize, and offers arrow-key navigation with autofocus on open;
* - trackDismissable() gives Structure / Mise en forme / Export the same
* dismissal contract (toggle exempt, custom onClose);
* - the ribbon carries the new icons (save, tab "+", export entries).
* - the ribbon carries its icons (save, tab "+", gridlines);
* - #185: the menu bar lists the ten Google Sheets menus, every entry is
* actionable or honestly flagged unavailable, labels come from the catalog,
* editing entries disappear on a read-only workbook, and the historical
* Fichier ids (#xlsx-file-btn / -menu / #xlsx-download-btn / #xlsx-csv-btn)
* survive the move from the sheet strip.
*
* Usage: node tests/frontend/xlsx-menus.test.mjs
*/
@@ -43,6 +48,18 @@ globalThis.localStorage = w.localStorage;
globalThis.sessionStorage = w.sessionStorage;
globalThis.requestAnimationFrame = (cb) => setTimeout(() => cb(Date.now()), 0);
// #185 — the menu bar renders localized labels, so the real FR catalog has to
// be reachable: serve /static/locales/*.json from disk and nothing else.
const { readFileSync } = await import("node:fs");
globalThis.fetch = async (url) => {
const href = String(url);
if (href.includes("/static/locales/")) {
const file = path.join(REPO_ROOT, "frontend", "locales", "fr.json");
return { ok: true, status: 200, json: async () => JSON.parse(readFileSync(file, "utf8")) };
}
return { ok: true, status: 200, json: async () => ({}), text: async () => "" };
};
// ── Module under test ───────────────────────────────────────────────────────
const ctxMenuUrl = pathToFileURL(
path.join(REPO_ROOT, "frontend", "js", "xlsx", "context-menu.js")
@@ -50,9 +67,17 @@ const ctxMenuUrl = pathToFileURL(
const cmdBarUrl = pathToFileURL(
path.join(REPO_ROOT, "frontend", "js", "xlsx", "command-bar.js")
).href;
const menusUrl = pathToFileURL(
path.join(REPO_ROOT, "frontend", "js", "xlsx", "menus.js")
).href;
const { openContextMenu, closeContextMenu, isContextMenuOpen, trackDismissable } =
await import(ctxMenuUrl);
const { buildCommandBar } = await import(cmdBarUrl);
const { buildMenuBar, SHEETS_MENUS } = await import(menusUrl);
const { initI18n } = await import(
pathToFileURL(path.join(REPO_ROOT, "frontend", "js", "i18n.js")).href
);
await initI18n();
// ── Mini runner ─────────────────────────────────────────────────────────────
let testCount = 0;
@@ -163,13 +188,32 @@ await test("focus leaving the menu closes it, focus inside keeps it", () => {
outside.remove();
});
await test("scroll and resize close the menu", () => {
openContextMenu(10, 10, itemsOf());
window.dispatchEvent(new w.Event("scroll"));
assert.ok(!isContextMenuOpen(), "scroll closes");
await test("double close never throws and a late click still runs its action", () => {
// Regression: in a real browser, remove() fires focusout synchronously,
// which re-entered closeContextMenu — the second remove() threw
// NotFoundError and aborted the item's onClick before it ran.
let runs = 0;
const menu = openContextMenu(10, 10, [{ icon: "copy", label: "Copy", onClick: () => { runs++; } }]);
const btn = menu.querySelector(".xlsx-context-item");
closeContextMenu();
closeContextMenu(); // idempotent: no-op, no throw
assert.ok(!isContextMenuOpen());
btn.dispatchEvent(new w.MouseEvent("click", { bubbles: true }));
assert.equal(runs, 1, "click on the detached entry still runs its action");
});
await test("scroll and resize close the menu", async () => {
openContextMenu(10, 10, itemsOf());
window.dispatchEvent(new w.Event("resize"));
assert.ok(!isContextMenuOpen(), "resize closes");
openContextMenu(10, 10, itemsOf());
// The smooth-scroll tail of the opening gesture is forgiven…
window.dispatchEvent(new w.Event("scroll"));
assert.ok(isContextMenuOpen(), "immediate scroll does not close");
// …but a later scroll detaches the menu.
await sleep(450);
window.dispatchEvent(new w.Event("scroll"));
assert.ok(!isContextMenuOpen(), "later scroll closes");
});
// ── trackDismissable (Structure / Format / Export) ──────────────────────────
@@ -226,26 +270,143 @@ await test("trackDismissable: Escape and focus loss dismiss", () => {
toggle.remove();
});
// ── Ribbon icons ────────────────────────────────────────────────────────────
await test("the ribbon carries save, tab-plus and export icons", () => {
const { actionsHtml, tabs } = buildCommandBar({
// ── Ribbon icons (#185: the File menu moved to the menu bar) ────────────────
await test("the ribbon carries save, tab-plus and gridline icons", () => {
const { actionsHtml, tabs, fileHtml } = buildCommandBar({
sheets: [{ name: "F1" }],
isCsv: false,
readOnly: false,
editable: true,
});
const host = document.createElement("div");
host.innerHTML = tabs + actionsHtml;
host.innerHTML = tabs + actionsHtml + fileHtml;
const saveIcon = host.querySelector("#xlsx-save-btn i[data-lucide]");
assert.ok(saveIcon, "save button has an icon");
assert.equal(saveIcon.getAttribute("data-lucide"), "save");
const plusIcon = host.querySelector("#xlsx-tab-add i[data-lucide]");
assert.ok(plusIcon, "tab + button has an icon");
assert.equal(plusIcon.getAttribute("data-lucide"), "plus");
const exportIcons = [...host.querySelectorAll("#xlsx-export-menu i[data-lucide]")].map((i) =>
i.getAttribute("data-lucide")
const gridIcon = host.querySelector("#xs-grid i[data-lucide]");
assert.ok(gridIcon, "gridline switch has an icon");
assert.equal(gridIcon.getAttribute("data-lucide"), "grid-3x3");
// #185 — the sheet strip keeps Save only; the file outputs live in the menu bar.
assert.equal(host.querySelector("#xlsx-file-btn"), null, "no file dropdown left on the strip");
});
// ── #185 — the menu bar itself ──────────────────────────────────────────────
await test("buildMenuBar renders the ten Sheets menus with their labels", () => {
assert.deepEqual(
SHEETS_MENUS.map((m) => m.id),
["file", "edit", "view", "insert", "format", "data", "tools", "gemini", "extensions", "help"],
);
assert.deepEqual(exportIcons, ["file-text", "code", "printer"]);
const html = buildMenuBar({ editable: true, readOnly: false });
const host = document.createElement("div");
host.innerHTML = html;
const menus = [...host.querySelectorAll(".xlsx-menubar > .xlsx-menuwrap")];
assert.deepEqual(
menus.map((w) => w.querySelector(".xlsx-menubtn").textContent.trim()),
["Fichier", "Modifier", "Affichage", "Insertion", "Format", "Données", "Outils", "Gemini", "Extensions", "Aide"],
);
// Every button controls its own dropdown, hidden until opened.
menus.forEach((w) => {
const btn = w.querySelector(".xlsx-menubtn");
const drop = host.querySelector(`#${btn.getAttribute("aria-controls")}`);
assert.ok(drop, `${btn.dataset.xlsxMenu} has a dropdown`);
assert.equal(drop.getAttribute("role"), "menu");
assert.equal(drop.style.display, "none", "dropdown starts closed");
assert.equal(btn.getAttribute("aria-expanded"), "false");
});
});
await test("the Fichier menu keeps the historical ids and export markers", () => {
const host = document.createElement("div");
host.innerHTML = buildMenuBar({ editable: true, readOnly: false });
assert.ok(host.querySelector("#xlsx-file-btn"), "file button id kept");
assert.ok(host.querySelector("#xlsx-file-menu"), "file menu id kept");
assert.ok(host.querySelector("#xlsx-download-btn"), "download entry kept its id");
assert.ok(host.querySelector("#xlsx-csv-btn"), "csv entry kept its id");
assert.deepEqual(
[...host.querySelectorAll("#xlsx-file-menu [data-xlsx-export]")].map((n) => n.dataset.xlsxExport),
["md", "html", "print"],
);
});
await test("every menu entry is either actionable or honestly flagged", () => {
const host = document.createElement("div");
host.innerHTML = buildMenuBar({ editable: true, readOnly: false });
const rows = [...host.querySelectorAll(".xlsx-menu-item")];
assert.ok(rows.length > 120, `all Sheets entries are listed (${rows.length})`);
rows.forEach((row) => {
const actionable = row.hasAttribute("data-xlsx-action") || row.hasAttribute("data-xlsx-export");
const flagged = row.hasAttribute("data-xlsx-unavailable");
assert.ok(actionable || flagged || row.hasAttribute("aria-haspopup"),
`"${row.textContent.trim()}" is actionable, a section, or flagged unavailable`);
});
// A declared action always resolves against the viewer's registry (#185).
const ACTIONS = [
"share", "download", "export-csv", "rename", "trash", "history", "details", "settings", "print",
"undo", "redo", "cut", "copy", "paste", "paste-values", "delete-rows", "delete-cols",
"clear-contents", "select-all", "find-replace", "freeze", "freeze-row", "freeze-col",
"unfreeze", "toggle-formula-bar", "toggle-grid", "toggle-headers", "dashboard", "zoom",
"fullscreen", "insert-rows-above", "insert-rows-below", "insert-cols-left",
"insert-cols-right", "insert-cells", "link", "comment", "function", "numfmt", "theme-menu",
"bold", "italic", "underline", "strike", "fontsize", "align", "valign",
"wrap-on", "wrap-off", "rotate", "clear-format", "banded", "sort-asc", "sort-desc",
"sort-reset", "filter-column", "named-ranges", "cleanup-dupes", "cleanup-trim",
"split-text", "autocomplete", "a11y", "gemini", "help", "whatsnew", "shortcuts", "report",
];
const declared = new Set(
[...host.querySelectorAll("[data-xlsx-action]")].map((n) => n.dataset.xlsxAction),
);
ACTIONS.forEach((name) => assert.ok(declared.has(name), `menu declares "${name}"`));
// "apply-theme" is deliberately absent: the theme list is built on demand.
assert.equal(declared.has("apply-theme"), false, "themes are not hard-coded in the markup");
});
await test("Format ▸ Thème is an empty section the viewer fills on demand (#185)", () => {
const host = document.createElement("div");
host.innerHTML = buildMenuBar({ editable: true, readOnly: false });
const row = host.querySelector('[data-xlsx-menu="format"]')
.closest(".xlsx-menuwrap")
.querySelector('[data-xlsx-action="theme-menu"]');
assert.ok(row, "the Thème section exists");
const sub = row.nextElementSibling;
assert.equal(sub.className, "xlsx-menu-sub", "it is a section, not a leaf");
assert.equal(sub.hidden, true, "collapsed");
assert.equal(sub.children.length, 0, "empty until the viewer fills it");
assert.equal(row.getAttribute("aria-expanded"), "false");
// The next entry is untouched by the empty section.
assert.ok(host.querySelector('[data-xlsx-action="bold"]'), "Bold still listed");
});
await test("editing entries disappear on a read-only workbook, view entries stay", () => {
const host = document.createElement("div");
host.innerHTML = buildMenuBar({ editable: false, readOnly: true });
assert.equal(host.querySelector('[data-xlsx-action="bold"]'), null, "no Bold");
assert.equal(host.querySelector('[data-xlsx-action="insert-cells"]'), null, "no Insert cells");
assert.equal(host.querySelector('[data-xlsx-action="undo"]'), null, "no Undo");
assert.ok(host.querySelector('[data-xlsx-action="copy"]'), "Copy stays available");
assert.ok(host.querySelector('[data-xlsx-action="zoom"]'), "Zoom stays available");
assert.ok(host.querySelector('[data-xlsx-action="toggle-grid"]'), "Gridlines stay available");
});
await test("menu labels come from the i18n catalog, never from raw text", () => {
const host = document.createElement("div");
host.innerHTML = buildMenuBar({ editable: true, readOnly: false });
const labels = [...host.querySelectorAll(".xlsx-menu-label")].map((n) => n.textContent);
assert.ok(labels.length > 100);
assert.equal(labels.some((l) => /xlsx\./.test(l)), false, "no unresolved key is rendered");
assert.ok(labels.includes("Nouveau"), "Google Sheets' own wording is kept");
assert.ok(labels.includes("Couleurs alternées"));
assert.ok(labels.includes("Diviser le texte en colonnes"));
});
await test("a sheet name or cell value cannot leak HTML into a menu label", () => {
const host = document.createElement("div");
host.innerHTML = buildMenuBar({ editable: true, readOnly: false });
host.querySelectorAll(".xlsx-menu-label").forEach((n) => {
assert.equal(n.querySelector("img, script"), null, "labels stay text nodes");
});
});
console.log(`\n${passCount}/${testCount} passed`);
File diff suppressed because it is too large Load Diff
+42
View File
@@ -1,6 +1,9 @@
# tests/test_api_main.py — Integration tests for main.py API endpoints
# Uses the existing app_with_vault / client fixtures from conftest.py
from pathlib import Path
import pytest
# ═══════════════════════════════════════════════════════════════════
# Health & Metadata
@@ -200,6 +203,45 @@ class TestFileCRUD:
data = resp.json()
assert data["success"] is True
def test_create_xlsx_empty_workbook(self, client, test_vault_dir):
"""#186 - "Create a file" > Excel must produce a readable workbook.
An .xlsx is a ZIP archive, not a text file: writing the empty payload
of the modal as text would leave a file the viewer cannot open.
"""
openpyxl = pytest.importorskip("openpyxl")
resp = client.post("/api/file/TestVault", json={
"path": "nouveau.xlsx",
"content": "",
})
assert resp.status_code == 200
assert resp.json()["success"] is True
# The archive is a real workbook: one empty sheet, loadable by openpyxl.
wb = openpyxl.load_workbook(Path(test_vault_dir) / "nouveau.xlsx")
assert wb.sheetnames == ["Feuille1"]
# And the viewer serves it as a spreadsheet.
resp2 = client.get("/api/file/TestVault", params={"path": "nouveau.xlsx"})
assert resp2.status_code == 200
body = resp2.json()
assert body["is_xlsx"] is True
assert [s["name"] for s in body["xlsx_sheets"]] == ["Feuille1"]
def test_create_xlsx_in_new_subdir(self, client):
"""#186 - same in a subdirectory that does not exist yet."""
pytest.importorskip("openpyxl")
resp = client.post("/api/file/TestVault", json={
"path": "Tableaux/annee.xlsx",
"content": "",
})
assert resp.status_code == 200
resp2 = client.get("/api/file/TestVault", params={"path": "Tableaux/annee.xlsx"})
assert resp2.status_code == 200
assert resp2.json()["is_xlsx"] is True
def test_save_file(self, client):
"""Save (update) an existing file"""
resp = client.put("/api/file/TestVault/save?path=note1.md", json={
+30
View File
@@ -129,6 +129,36 @@ class TestRowColOps:
assert wb["Data"]["B1"].value == "Valeur"
wb.close()
def test_insert_past_the_last_row_and_column_takes_effect(self, client, book):
# openpyxl's sparse model silently ignores inserts past the used
# extent: the service materialises the missing rows/columns first so
# « below the last row » / « right of the last column » behave.
wb = openpyxl.load_workbook(book)
last_row, last_col = wb["Data"].max_row, wb["Data"].max_column
wb.close()
assert _put(client, actions=[
{"op": "col_insert", "sheet": "Data", "at": last_col + 1},
]).status_code == 200
assert _put(client, actions=[
{"op": "row_insert", "sheet": "Data", "at": last_row + 1},
]).status_code == 200
wb = openpyxl.load_workbook(book)
ws = wb["Data"]
assert ws.max_column == last_col + 1, "one blank column appended"
assert ws.max_row == last_row + 1, "one blank row appended"
wb.close()
def test_insert_far_past_the_extent_extends_the_sheet(self, client, book):
wb = openpyxl.load_workbook(book)
last_row = wb["Data"].max_row
wb.close()
assert _put(client, actions=[
{"op": "row_insert", "sheet": "Data", "at": last_row + 3},
]).status_code == 200
wb = openpyxl.load_workbook(book)
assert wb["Data"].max_row >= last_row + 3
wb.close()
class TestGuards:
def test_unknown_sheet_is_400(self, client, book):
+109
View File
@@ -250,6 +250,115 @@ class TestStyleWriting:
assert backups, "the rewrite is backed up first"
class TestExtendedStyles:
"""Nouvelles clés de style (barre façon Sheets) : taille, barré,
alignements verticaux, retour ligne, rotation, bordures — et commentaires."""
def _style(self, client, path, ops, **extra):
return client.put(
f"/api/file/{VAULT}/xlsx/style",
params={"path": path},
json={"ops": ops, **extra},
)
def test_font_size_strike_valign_wrap_rotation(self, client, plain_book):
resp = self._style(client, "plain.xlsx", [
{
"op": "cell", "sheet": "Data", "range": "A1",
"style": {
"font_size": 14, "strike": True, "valign": "middle",
"wrap": True, "rotation": -45,
},
},
])
assert resp.status_code == 200
wb = openpyxl.load_workbook(plain_book)
cell = wb["Data"]["A1"]
assert cell.font.size == 14
assert cell.font.strike is True
assert cell.alignment.vertical == "center"
assert cell.alignment.wrap_text is True
assert cell.alignment.textRotation == 135
wb.close()
resp = client.get(f"/api/file/{VAULT}", params={"path": "plain.xlsx"})
sheet = resp.json()["xlsx_sheets"][0]
assert "font-size:14pt" in sheet["styles"]["A1"]
assert "line-through" in sheet["styles"]["A1"]
assert "vertical-align:middle" in sheet["styles"]["A1"]
assert "white-space:normal" in sheet["styles"]["A1"]
# La diagonale (-45° → 135 OOXML) est relue en `rotate()` CSS.
assert "transform:rotate(45deg)" in sheet["styles"]["A1"]
def test_borders_all_outer_none(self, client, plain_book):
resp = self._style(client, "plain.xlsx", [
{"op": "cell", "sheet": "Data", "range": "A1:B2",
"style": {"border": "all", "border_color": "#112233"}},
])
assert resp.status_code == 200
wb = openpyxl.load_workbook(plain_book)
side = wb["Data"]["A1"].border.left
assert side.style == "thin" and side.color.rgb == "FF112233"
wb.close()
resp = self._style(client, "plain.xlsx", [
{"op": "cell", "sheet": "Data", "range": "A1:B2", "style": {"border": "none"}},
])
assert resp.status_code == 200
wb = openpyxl.load_workbook(plain_book)
cleared = wb["Data"]["A1"].border.left
assert cleared is None or cleared.style is None
wb.close()
def test_comment_set_clear_and_readback(self, client, plain_book):
resp = self._style(client, "plain.xlsx", [
{"op": "comment_set", "sheet": "Data", "ref": "B2", "text": "À vérifier"},
])
assert resp.status_code == 200
wb = openpyxl.load_workbook(plain_book)
assert wb["Data"]["B2"].comment.text == "À vérifier"
wb.close()
resp = client.get(f"/api/file/{VAULT}", params={"path": "plain.xlsx"})
assert resp.json()["xlsx_sheets"][0]["comments"]["B2"] == "À vérifier"
resp = self._style(client, "plain.xlsx", [
{"op": "comment_clear", "sheet": "Data", "ref": "B2"},
])
assert resp.status_code == 200
wb = openpyxl.load_workbook(plain_book)
assert wb["Data"]["B2"].comment is None
wb.close()
def test_formats_map_lists_number_formats(self, client, plain_book):
self._style(client, "plain.xlsx", [
{"op": "cell", "sheet": "Data", "range": "B2", "style": {"number_format": "0.00"}},
])
resp = client.get(f"/api/file/{VAULT}", params={"path": "plain.xlsx"})
assert resp.json()["xlsx_sheets"][0]["formats"]["B2"] == "0.00"
def test_extended_invalid_inputs_are_refused(self, client, plain_book):
style = lambda s: self._style(client, "plain.xlsx", [
{"op": "cell", "sheet": "Data", "range": "A1", "style": s},
]).status_code
assert style({"font_size": 200}) == 400
assert style({"font_size": "grand"}) == 400
assert style({"valign": "diagonal"}) == 400
# 180° (texte vertical retourné, relu tel quel) est accepté — seules
# les valeurs vraiment hors bornes sont refusées.
assert style({"rotation": 180}) == 200
assert style({"rotation": 181}) == 400
assert style({"rotation": -91}) == 400
assert style({"border": "dotted-circle"}) == 400
assert style({"border_style": "wavy"}) == 400
assert self._style(client, "plain.xlsx", [
{"op": "comment_set", "sheet": "Data", "ref": "B2", "text": ""},
]).status_code == 400
assert self._style(client, "plain.xlsx", [
{"op": "comment_set", "sheet": "Data", "ref": "B2:C3", "text": "x"},
]).status_code == 400
class TestEndpointWiring:
def test_read_response_carries_styles_merges_freeze(self, client, styled_book):
resp = client.get(f"/api/file/{VAULT}", params={"path": "styles.xlsx"})