Add library tools to local toolboxes
This commit is contained in:
parent
daa5eba8bd
commit
ec7a4a4c1d
15 changed files with 650 additions and 9 deletions
|
|
@ -99,3 +99,4 @@
|
|||
{"id":"int-75bf6b86c4294cd87f5f531f67811981","kind":"field_change","created_at":"2026-10-15T08:25:01.763951145Z","actor":"Shinuwa","issue_id":"sokko-g-g5r","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Simplified the sidebar to Backup and Import, reorganized the automatic backup modal, and validated the updated flows."}}
|
||||
{"id":"int-6e375006679c170d1c15f030fb97219f","kind":"field_change","created_at":"2026-10-15T13:47:11.966147358Z","actor":"Shinuwa","issue_id":"sokko-g-fn8","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"État IndexedDB fiable ajouté avec attente, confirmation, erreur et conflit ; brouillons et sauvegarde fichier distingués. Imports confirmés avant réattribution, export manuel disponible, échecs et écritures concurrentes couverts. Validation : npm run check, 191 E2E développement et 2 E2E production."}}
|
||||
{"id":"int-d049168ad7eab1d1daad24400929ef44","kind":"field_change","created_at":"2026-10-15T14:24:13.868561069Z","actor":"Shinuwa","issue_id":"sokko-g-koc","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Reprise ciblée ajoutée pour site.json, games.json et les données de chaque jeu, sans rechargement du document. Les tentatives obsolètes sont annulées et leurs réponses ignorées, avec conservation des données déjà chargées. Validation : npm run check, 194 E2E développement et 2 E2E production."}}
|
||||
{"id":"int-a7f31afcb66a0c2f9a2802ec7fcb0f25","kind":"field_change","created_at":"2026-10-22T20:52:18.039208354Z","actor":"Shinuwa","issue_id":"sokko-g-203","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Ajout Librairie vers toolbox livré avec copie vide/état courant, création transactionnelle, remappage des IDs et dépendances, tests unitaires et Playwright."}}
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ Checklist à suivre lors de l'ajout ou de la modification d'un outil, d'une page
|
|||
- Déclarer ses métadonnées et son chargeur dans `website/src/features/toolboxes/toolboxModuleRegistry.js`. Le registre React `modules/toolboxModuleComponents.jsx` est partagé par la toolbox et la Librairie ; `modules/index.jsx` expose le shell.
|
||||
- Vérifier le chargement à la demande en toolbox et dans chaque catégorie de la Librairie.
|
||||
- Dans la Librairie, vérifier les liens directs vers un outil, les changements d'ancre et le retour navigateur ; une nouvelle sélection ou une sortie de page doit annuler les défilements différés précédents.
|
||||
- Pour « Ajouter à une toolbox », vérifier l'outil vide et l'état actuellement présenté, le choix de la toolbox et de l'espace, la création de la première toolbox sans perdre l'intention, l'annulation sans écriture et le message de réussite après commit. Les identifiants internes doivent être renouvelés, une modification ultérieure de la démonstration ne doit pas atteindre la copie et toute dépendance d'outil doit être copiée puis remappée sans référence orpheline.
|
||||
- Ajouter les textes nécessaires dans `website/public/data/site.json`.
|
||||
- Mettre à jour la validation de `site.json` dans `tests/helpers/data-validation.mjs`.
|
||||
- Pour chaque type du registre, fournir une description non vide dans `toolboxes.addToolDescriptions` et vérifier que la fenêtre « Ajouter un outil » affiche le nom complet et la courte phrase d'usage aux largeurs compactes validées. Vérifier sa largeur réelle jusqu'à `900px`, les cartes compactes avec icône à gauche du titre, les 4 et 5 colonnes selon la largeur, les cinq sections sans onglets, les couleurs et dimensions de `scrollbar-control`, ainsi que les infobulles de l'ajout rapide au survol comme au focus.
|
||||
|
|
|
|||
|
|
@ -118,6 +118,15 @@ registre. Les imports annoncent leur succès seulement après le commit. Une err
|
|||
synchrone pendant la préparation ou l'écriture abandonne l'ensemble de la
|
||||
transaction.
|
||||
|
||||
L'ajout depuis la Librairie utilise le même snapshot transactionnel. Chaque copie
|
||||
reçoit un nouvel identifiant d'outil et de nouveaux identifiants internes ; les
|
||||
données affichées dans la démonstration et la copie ne partagent donc aucune
|
||||
référence. Une copie de Mémos liée à un planificateur copie aussi ce planificateur
|
||||
et remappe la liaison. Si aucune toolbox n'existe, la création, ses outils de
|
||||
démarrage et l'ajout demandé sont confirmés dans une seule transaction. Une
|
||||
annulation ne prépare aucune écriture et le message de réussite n'apparaît qu'après
|
||||
le commit.
|
||||
|
||||
Après un commit, un canal `BroadcastChannel` signale les ressources touchées aux
|
||||
autres pages. Elles relisent le registre et les données ordinaires après leurs
|
||||
écritures déjà en attente. Un média est relu uniquement s'il était déjà ouvert ;
|
||||
|
|
|
|||
|
|
@ -57,6 +57,8 @@ Fichiers : `hooks/useAppData.js`, `features/games/loaders.js`, pages d'erreur/je
|
|||
|
||||
Constat F02. Effort moyen. Dépend de C01, C02 et S01.
|
||||
|
||||
**État au 22 octobre 2026 : réalisé.** Chaque exemple annonce son isolation et propose un ajout vers une toolbox et un espace précis, soit vide, soit avec l'état actuellement présenté. La première toolbox peut être créée dans la même transaction sans perdre la demande. Les identifiants d'outil et de données sont renouvelés ; une liaison Mémos vers un planificateur copie aussi ce dernier et remappe sa référence. La réussite est affichée après confirmation IndexedDB avec une action d'ouverture. Les tests couvrent l'annulation, l'échec d'écriture, les deux modes de copie, l'espace choisi, la dépendance, l'indépendance après mutation et la persistance après rechargement à `768 × 720`.
|
||||
|
||||
1. Ajouter près de l'exemple un accès « Ajouter à une toolbox » ; la démonstration doit indiquer que ses essais restent séparés des données personnelles.
|
||||
2. Choisir une toolbox et un espace existants, puis « outil vide » ou « exemple présenté ». Préciser si la copie reprend l'exemple d'origine ou l'état essayé ; orientation initiale : état actuellement présenté, annoncé dans le libellé.
|
||||
3. En l'absence de toolbox, réutiliser sa création puis poursuivre l'ajout sans perdre l'intention de départ.
|
||||
|
|
|
|||
|
|
@ -2,6 +2,25 @@
|
|||
/* global window, document */
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { LIBRARY_CATEGORY_DEFINITIONS } from "../website/src/features/toolboxes/toolboxModuleRegistry.js";
|
||||
import { resetSokkoStorage } from "./helpers/storage.js";
|
||||
|
||||
async function readStoredLibraryCopy(page) {
|
||||
return page.evaluate(async () => new Promise((resolve, reject) => {
|
||||
const request = window.indexedDB.open("sokkog", 1);
|
||||
request.onerror = () => reject(request.error);
|
||||
request.onsuccess = () => {
|
||||
const db = request.result;
|
||||
const transaction = db.transaction(["kv", "modules"], "readonly");
|
||||
const toolboxesRequest = transaction.objectStore("kv").get("toolboxes");
|
||||
const modulesRequest = transaction.objectStore("modules").getAll();
|
||||
transaction.oncomplete = () => {
|
||||
db.close();
|
||||
resolve({ toolboxes: toolboxesRequest.result || [], modules: modulesRequest.result || [] });
|
||||
};
|
||||
transaction.onerror = () => reject(transaction.error);
|
||||
};
|
||||
}));
|
||||
}
|
||||
|
||||
test("loads every library tool through the shared component registry", async ({ page }) => {
|
||||
const errors = [];
|
||||
|
|
@ -74,3 +93,43 @@ test("library cancels obsolete scroll retries on selection and unmount", async (
|
|||
await page.clock.runFor(700);
|
||||
expect(await page.evaluate(() => window.libraryScrolls)).toEqual([]);
|
||||
});
|
||||
|
||||
test("creates a first toolbox and persists the currently presented library example", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 768, height: 720 });
|
||||
await resetSokkoStorage(page);
|
||||
await page.goto("/#/library#library-tool-m5");
|
||||
const example = page.locator('[data-module-type="counters"]');
|
||||
await expect(example).toBeVisible();
|
||||
await example.getByRole("button", { name: "Incrémenter Top 1", exact: true }).click();
|
||||
await expect(example.locator(".counter-item").filter({ hasText: "Top 1" }).locator("strong")).toHaveText("4");
|
||||
|
||||
const section = page.locator("#library-tool-m5");
|
||||
await section.getByRole("button", { name: "Ajouter à une toolbox", exact: true }).click();
|
||||
let dialog = page.getByRole("dialog", { name: "Ajouter Compteurs", exact: true });
|
||||
await expect(dialog.getByText("Copier l’état actuellement présenté", { exact: true })).toBeVisible();
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth)).toBe(true);
|
||||
await dialog.getByRole("button", { name: "Annuler", exact: true }).click();
|
||||
await expect(dialog).toHaveCount(0);
|
||||
expect((await readStoredLibraryCopy(page)).toolboxes).toHaveLength(0);
|
||||
|
||||
await section.getByRole("button", { name: "Ajouter à une toolbox", exact: true }).click();
|
||||
dialog = page.getByRole("dialog", { name: "Ajouter Compteurs", exact: true });
|
||||
await dialog.getByRole("textbox", { name: /Nom de la nouvelle toolbox/ }).fill("Depuis la librairie");
|
||||
await dialog.getByRole("button", { name: "Créer et ajouter", exact: true }).click();
|
||||
await expect(page.getByText("Outil ajouté dans « Depuis la librairie ».", { exact: true })).toBeVisible();
|
||||
|
||||
await expect.poll(async () => (await readStoredLibraryCopy(page)).toolboxes.length).toBe(1);
|
||||
const stored = await readStoredLibraryCopy(page);
|
||||
const copiedModule = stored.toolboxes[0].modules.find((module) => module.type === "counters");
|
||||
const copiedData = stored.modules.find((entry) => entry.key === `${stored.toolboxes[0].id}:${copiedModule.id}`).data;
|
||||
expect(copiedModule.id).not.toBe("m5");
|
||||
expect(copiedData.counters.find((counter) => counter.label === "Top 1").value).toBe(4);
|
||||
expect(copiedData.counters.find((counter) => counter.label === "Top 1").id).not.toBe("c1");
|
||||
|
||||
await page.getByRole("button", { name: "Ouvrir", exact: true }).click();
|
||||
await expect(page).toHaveURL(new RegExp(`#\\/toolbox\\/${stored.toolboxes[0].id}$`));
|
||||
const copiedTool = page.locator(`[data-module-id="${copiedModule.id}"]`);
|
||||
await expect(copiedTool.locator(".counter-item").filter({ hasText: "Top 1" }).locator("strong")).toHaveText("4");
|
||||
await page.reload();
|
||||
await expect(copiedTool.locator(".counter-item").filter({ hasText: "Top 1" }).locator("strong")).toHaveText("4");
|
||||
});
|
||||
|
|
|
|||
|
|
@ -175,6 +175,29 @@ export function validateSiteContent(site) {
|
|||
"library.copyExampleLabel",
|
||||
"library.copyExampleSuccess",
|
||||
"library.controlLegendHeading",
|
||||
"library.copyToToolbox.triggerLabel",
|
||||
"library.copyToToolbox.isolationHelp",
|
||||
"library.copyToToolbox.eyebrow",
|
||||
"library.copyToToolbox.title",
|
||||
"library.copyToToolbox.description",
|
||||
"library.copyToToolbox.toolboxLabel",
|
||||
"library.copyToToolbox.spaceLabel",
|
||||
"library.copyToToolbox.newToolboxLabel",
|
||||
"library.copyToToolbox.newToolboxPlaceholder",
|
||||
"library.copyToToolbox.newToolboxHelp",
|
||||
"library.copyToToolbox.modeLabel",
|
||||
"library.copyToToolbox.currentLabel",
|
||||
"library.copyToToolbox.currentHelp",
|
||||
"library.copyToToolbox.emptyLabel",
|
||||
"library.copyToToolbox.emptyHelp",
|
||||
"library.copyToToolbox.dependencyNotice",
|
||||
"library.copyToToolbox.cancelLabel",
|
||||
"library.copyToToolbox.addLabel",
|
||||
"library.copyToToolbox.createAndAddLabel",
|
||||
"library.copyToToolbox.savingLabel",
|
||||
"library.copyToToolbox.failure",
|
||||
"library.copyToToolbox.success",
|
||||
"library.copyToToolbox.openLabel",
|
||||
"library.categories.notesTracking",
|
||||
"library.categories.references",
|
||||
"library.categories.calculationData",
|
||||
|
|
|
|||
135
tests/library-copy.test.mjs
Normal file
135
tests/library-copy.test.mjs
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
// Rôle : vérifie la copie transactionnelle et indépendante des exemples de librairie.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { useToolboxActions } from "../website/src/features/toolboxes/useToolboxActions.js";
|
||||
|
||||
function toolbox(id = "destination") {
|
||||
return {
|
||||
id,
|
||||
name: "Destination",
|
||||
modules: [],
|
||||
spaces: [
|
||||
{ id: "main", name: "Principal", moduleOrder: { one: [], two: [[], []] } },
|
||||
{ id: "build", name: "Build", moduleOrder: { one: [], two: [[], []] } }
|
||||
],
|
||||
defaultSpaceId: "main",
|
||||
activeSpaceId: "main",
|
||||
updatedAt: "2026-10-22T08:00:00.000Z"
|
||||
};
|
||||
}
|
||||
|
||||
function createHarness(initial, { fail = false } = {}) {
|
||||
let state = structuredClone(initial);
|
||||
let writes = 0;
|
||||
const actions = useToolboxActions({
|
||||
store: {
|
||||
ready: true,
|
||||
persistToolboxSnapshot: async (updater) => {
|
||||
writes += 1;
|
||||
const next = updater(state);
|
||||
if (fail) return false;
|
||||
state = structuredClone(next);
|
||||
return true;
|
||||
}
|
||||
},
|
||||
notify() {}
|
||||
});
|
||||
return { actions, getState: () => state, getWrites: () => writes };
|
||||
}
|
||||
|
||||
test("a library example copies fresh ids into the selected space and remains independent", async () => {
|
||||
const harness = createHarness({ toolboxes: [toolbox()], links: {}, moduleData: {} });
|
||||
const sourceData = { counters: [{ id: "library-counter", label: "Essais", value: 4 }] };
|
||||
const result = await harness.actions.addLibraryToolToToolbox({
|
||||
sourceModule: { id: "library-module", type: "counters", data: sourceData },
|
||||
sourceData,
|
||||
toolboxId: "destination",
|
||||
spaceId: "build",
|
||||
copyData: true
|
||||
});
|
||||
|
||||
assert.ok(result);
|
||||
const storedToolbox = harness.getState().toolboxes[0];
|
||||
const storedModule = storedToolbox.modules.find((module) => module.type === "counters");
|
||||
const storedData = harness.getState().moduleData[`destination:${storedModule.id}`];
|
||||
assert.notEqual(storedModule.id, "library-module");
|
||||
assert.notEqual(storedData.counters[0].id, "library-counter");
|
||||
assert.equal(storedData.counters[0].value, 4);
|
||||
assert.deepEqual(storedToolbox.spaces.find((space) => space.id === "build").moduleOrder.one, [storedModule.id]);
|
||||
assert.equal(storedToolbox.activeSpaceId, "build");
|
||||
|
||||
sourceData.counters[0].value = 99;
|
||||
assert.equal(harness.getState().moduleData[`destination:${storedModule.id}`].counters[0].value, 4);
|
||||
|
||||
const emptyResult = await harness.actions.addLibraryToolToToolbox({
|
||||
sourceModule: { id: "library-empty", type: "counters", data: sourceData },
|
||||
sourceData,
|
||||
toolboxId: "destination",
|
||||
spaceId: "main",
|
||||
copyData: false
|
||||
});
|
||||
const emptyModuleId = emptyResult.moduleIds[0];
|
||||
assert.equal(harness.getState().moduleData[`destination:${emptyModuleId}`], undefined);
|
||||
assert.deepEqual(harness.getState().toolboxes[0].spaces.find((space) => space.id === "main").moduleOrder.one, [emptyModuleId]);
|
||||
});
|
||||
|
||||
test("a linked memo copies its planner and remaps every business reference", async () => {
|
||||
const harness = createHarness({ toolboxes: [toolbox()], links: {}, moduleData: {} });
|
||||
const result = await harness.actions.addLibraryToolToToolbox({
|
||||
sourceModule: {
|
||||
id: "library-memos",
|
||||
type: "memos",
|
||||
data: { plannerLink: "library-planner", items: [{ id: "library-memo", text: "Raid", color: "#f6c453" }] }
|
||||
},
|
||||
sourceData: { plannerLink: "library-planner" },
|
||||
dependencyModules: [{
|
||||
id: "library-planner",
|
||||
type: "taskPlanner",
|
||||
data: {
|
||||
tasks: [{ id: "library-task-a", title: "Parent", type: "unique" }, { id: "library-task-b", title: "Enfant", type: "daily" }],
|
||||
relations: [{ id: "library-relation", fromTaskId: "library-task-b", toTaskId: "library-task-a" }]
|
||||
}
|
||||
}],
|
||||
toolboxId: "destination",
|
||||
spaceId: "main",
|
||||
copyData: true
|
||||
});
|
||||
|
||||
assert.equal(result.moduleIds.length, 2);
|
||||
const stored = harness.getState();
|
||||
const memosModule = stored.toolboxes[0].modules.find((module) => module.type === "memos");
|
||||
const plannerModule = stored.toolboxes[0].modules.find((module) => module.type === "taskPlanner");
|
||||
const memosData = stored.moduleData[`destination:${memosModule.id}`];
|
||||
const plannerData = stored.moduleData[`destination:${plannerModule.id}`];
|
||||
assert.equal(memosData.plannerLink, plannerModule.id);
|
||||
assert.notEqual(memosData.items[0].id, "library-memo");
|
||||
assert.notEqual(plannerData.tasks[0].id, "library-task-a");
|
||||
assert.equal(plannerData.relations[0].fromTaskId, plannerData.tasks[1].id);
|
||||
assert.equal(plannerData.relations[0].toTaskId, plannerData.tasks[0].id);
|
||||
});
|
||||
|
||||
test("creating a first toolbox continues the copy, while a failed write confirms nothing", async () => {
|
||||
const initial = { toolboxes: [], links: {}, moduleData: {} };
|
||||
const createdHarness = createHarness(initial);
|
||||
const created = await createdHarness.actions.addLibraryToolToToolbox({
|
||||
sourceModule: { id: "library-counter", type: "counters", data: { counters: [{ id: "counter", label: "Test", value: 1 }] } },
|
||||
sourceData: { counters: [{ id: "counter", label: "Test", value: 1 }] },
|
||||
newToolboxName: "Depuis la librairie",
|
||||
copyData: true
|
||||
});
|
||||
assert.ok(created);
|
||||
assert.equal(createdHarness.getState().toolboxes[0].name, "Depuis la librairie");
|
||||
assert.deepEqual(createdHarness.getState().toolboxes[0].modules.map((module) => module.type), ["memos", "links", "counters"]);
|
||||
|
||||
const failedHarness = createHarness({ toolboxes: [toolbox()], links: {}, moduleData: {} }, { fail: true });
|
||||
const failed = await failedHarness.actions.addLibraryToolToToolbox({
|
||||
sourceModule: { id: "library-counter", type: "counters", data: {} },
|
||||
sourceData: {},
|
||||
toolboxId: "destination",
|
||||
spaceId: "main",
|
||||
copyData: false
|
||||
});
|
||||
assert.equal(failed, null);
|
||||
assert.equal(failedHarness.getWrites(), 1);
|
||||
assert.deepEqual(failedHarness.getState(), { toolboxes: [toolbox()], links: {}, moduleData: {} });
|
||||
});
|
||||
|
|
@ -49,6 +49,31 @@
|
|||
"copyExampleLabel": "Copier l'exemple",
|
||||
"copyExampleSuccess": "Exemple copié.",
|
||||
"controlLegendHeading": "Repères",
|
||||
"copyToToolbox": {
|
||||
"triggerLabel": "Ajouter à une toolbox",
|
||||
"isolationHelp": "Cet exemple reste séparé de vos toolboxes : vos essais ici ne modifient aucune donnée personnelle.",
|
||||
"eyebrow": "Depuis la librairie",
|
||||
"title": "Ajouter {tool}",
|
||||
"description": "Choisissez la destination et le contenu à créer. La copie devient indépendante de cet exemple.",
|
||||
"toolboxLabel": "Toolbox",
|
||||
"spaceLabel": "Espace",
|
||||
"newToolboxLabel": "Nom de la nouvelle toolbox",
|
||||
"newToolboxPlaceholder": "Ma toolbox",
|
||||
"newToolboxHelp": "La toolbox sera créée avec son espace par défaut, puis l’outil y sera ajouté.",
|
||||
"modeLabel": "Contenu de l’outil",
|
||||
"currentLabel": "Copier l’état actuellement présenté",
|
||||
"currentHelp": "Reprend aussi les changements effectués dans cette démonstration.",
|
||||
"emptyLabel": "Créer un outil vide",
|
||||
"emptyHelp": "Ajoute seulement l’outil, sans les données de l’exemple.",
|
||||
"dependencyNotice": "Le planificateur de tâches lié sera également copié pour conserver le fonctionnement des mémos.",
|
||||
"cancelLabel": "Annuler",
|
||||
"addLabel": "Ajouter",
|
||||
"createAndAddLabel": "Créer et ajouter",
|
||||
"savingLabel": "Enregistrement…",
|
||||
"failure": "L’ajout n’a pas pu être enregistré. Vérifiez le stockage local puis réessayez.",
|
||||
"success": "Outil ajouté dans « {toolbox} ».",
|
||||
"openLabel": "Ouvrir"
|
||||
},
|
||||
"categories": {
|
||||
"notesTracking": "Notes & suivi",
|
||||
"references": "Références",
|
||||
|
|
|
|||
108
website/src/components/LibraryCopyModal.jsx
Normal file
108
website/src/components/LibraryCopyModal.jsx
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
// Rôle : choisit la destination et le contenu lors de la copie d'un exemple de la librairie.
|
||||
import { useId, useState } from "react";
|
||||
import { Modal } from "./Modal.jsx";
|
||||
|
||||
export function LibraryCopyModal({ content, toolTitle, toolboxes, hasDependency, onClose, onConfirm }) {
|
||||
const titleId = useId();
|
||||
const descriptionId = useId();
|
||||
const [toolboxId, setToolboxId] = useState(toolboxes[0]?.id || "");
|
||||
const initialToolbox = toolboxes.find((toolbox) => toolbox.id === toolboxId);
|
||||
const [spaceId, setSpaceId] = useState(initialToolbox?.activeSpaceId || initialToolbox?.defaultSpaceId || "");
|
||||
const [newToolboxName, setNewToolboxName] = useState("");
|
||||
const [copyData, setCopyData] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const selectedToolbox = toolboxes.find((toolbox) => toolbox.id === toolboxId);
|
||||
const createsToolbox = toolboxes.length === 0;
|
||||
|
||||
async function submit(event) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError("");
|
||||
const success = await onConfirm({ toolboxId, spaceId, newToolboxName: newToolboxName.trim(), copyData });
|
||||
if (!success) {
|
||||
setError(content.failure);
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
rootClassName="confirm-modal-root library-copy-modal-root"
|
||||
dialogClassName="confirm-modal nds-modal library-copy-modal"
|
||||
labelledBy={titleId}
|
||||
describedBy={descriptionId}
|
||||
onRequestClose={onClose}
|
||||
canClose={!busy}
|
||||
>
|
||||
<header>
|
||||
<p className="eyebrow">{content.eyebrow}</p>
|
||||
<h2 id={titleId}>{content.title.replace("{tool}", toolTitle)}</h2>
|
||||
</header>
|
||||
<p id={descriptionId} className="library-copy-description">{content.description}</p>
|
||||
<form onSubmit={submit}>
|
||||
{createsToolbox ? (
|
||||
<label className="field library-copy-field">
|
||||
<span>{content.newToolboxLabel}</span>
|
||||
<input
|
||||
className="nds-input"
|
||||
data-size="sm"
|
||||
type="text"
|
||||
autoComplete="off"
|
||||
placeholder={content.newToolboxPlaceholder}
|
||||
required
|
||||
value={newToolboxName}
|
||||
onChange={(event) => setNewToolboxName(event.target.value)}
|
||||
data-modal-initial-focus=""
|
||||
/>
|
||||
<small>{content.newToolboxHelp}</small>
|
||||
</label>
|
||||
) : (
|
||||
<div className="library-copy-destination">
|
||||
<label className="field library-copy-field">
|
||||
<span>{content.toolboxLabel}</span>
|
||||
<select
|
||||
className="nds-select"
|
||||
data-size="sm"
|
||||
value={toolboxId}
|
||||
onChange={(event) => {
|
||||
const nextToolbox = toolboxes.find((toolbox) => toolbox.id === event.target.value);
|
||||
setToolboxId(event.target.value);
|
||||
setSpaceId(nextToolbox?.activeSpaceId || nextToolbox?.defaultSpaceId || "");
|
||||
}}
|
||||
data-modal-initial-focus=""
|
||||
>
|
||||
{toolboxes.map((toolbox) => <option key={toolbox.id} value={toolbox.id}>{toolbox.name}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
<label className="field library-copy-field">
|
||||
<span>{content.spaceLabel}</span>
|
||||
<select className="nds-select" data-size="sm" value={spaceId} onChange={(event) => setSpaceId(event.target.value)}>
|
||||
{(selectedToolbox?.spaces || []).map((space) => <option key={space.id} value={space.id}>{space.name}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
<fieldset className="library-copy-mode">
|
||||
<legend>{content.modeLabel}</legend>
|
||||
<label className={copyData ? "is-selected" : ""}>
|
||||
<input type="radio" name="copy-mode" value="current" checked={copyData} onChange={() => setCopyData(true)} />
|
||||
<span><strong>{content.currentLabel}</strong><small>{content.currentHelp}</small></span>
|
||||
</label>
|
||||
<label className={!copyData ? "is-selected" : ""}>
|
||||
<input type="radio" name="copy-mode" value="empty" checked={!copyData} onChange={() => setCopyData(false)} />
|
||||
<span><strong>{content.emptyLabel}</strong><small>{content.emptyHelp}</small></span>
|
||||
</label>
|
||||
</fieldset>
|
||||
{copyData && hasDependency && <p className="nds-inline-notice" data-variant="info">{content.dependencyNotice}</p>}
|
||||
{error && <p className="nds-inline-notice" data-variant="danger" role="alert">{error}</p>}
|
||||
<footer className="nds-modal-footer">
|
||||
<button className="nds-button" data-size="sm" type="button" disabled={busy} onClick={onClose}>{content.cancelLabel}</button>
|
||||
<button className="nds-button" data-size="sm" data-variant="primary" type="submit" disabled={busy || (createsToolbox ? !newToolboxName.trim() : !toolboxId || !spaceId)}>
|
||||
{busy ? content.savingLabel : createsToolbox ? content.createAndAddLabel : content.addLabel}
|
||||
</button>
|
||||
</footer>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
|
@ -476,6 +476,10 @@ function remapModuleDataForExport(type, data, nextId, moduleIdMap) {
|
|||
return compact;
|
||||
}
|
||||
|
||||
export function copyModuleDataWithFreshIds(type, data, moduleIdMap = new Map()) {
|
||||
return remapModuleDataForExport(type, data, uid, moduleIdMap);
|
||||
}
|
||||
|
||||
export function createToolboxExportPayload(toolbox, moduleData) {
|
||||
const source = normalizeToolbox(toolbox);
|
||||
const nextId = createExportIdFactory();
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ export const TOOLBOX_MODULE_DEFINITIONS = {
|
|||
icon: "memos",
|
||||
editable: true,
|
||||
scrollable: true,
|
||||
copyDependency: { type: "taskPlanner", dataField: "plannerLink" },
|
||||
libraryCategory: "notesTracking"
|
||||
},
|
||||
checklist: {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
// Rôle : regroupe les actions métier de création, import/export, lien et édition toolbox.
|
||||
import {
|
||||
compactModuleDataForStorage,
|
||||
copyModuleDataWithFreshIds,
|
||||
createGlobalExportPayload,
|
||||
createToolboxExportPayload,
|
||||
globalModuleKey,
|
||||
|
|
@ -55,8 +56,7 @@ export function useToolboxActions({ store, notify, creationTemplate, importConte
|
|||
});
|
||||
}
|
||||
|
||||
function createToolbox(name, gameId = "", options = {}) {
|
||||
if (!store.ready) return null;
|
||||
function buildToolboxCreation(name, options = {}) {
|
||||
const now = new Date().toISOString();
|
||||
const memosModuleId = uid("mod");
|
||||
const linksModuleId = uid("mod");
|
||||
|
|
@ -78,16 +78,101 @@ export function useToolboxActions({ store, notify, creationTemplate, importConte
|
|||
if (options.tutorial === true) toolbox.tutorial = true;
|
||||
const memos = compactModuleDataForStorage("memos", { items: [{ id: uid("memo"), text: welcomeText, color: "#f6c453", updatedAt: now }] });
|
||||
const links = compactModuleDataForStorage("links", { links: [libraryLink] });
|
||||
void store.persistToolboxSnapshot((current) => ({
|
||||
toolboxes: [toolbox, ...current.toolboxes],
|
||||
links: gameId ? { ...current.links, [gameId]: toolbox.id } : current.links,
|
||||
return {
|
||||
toolbox,
|
||||
moduleData: {
|
||||
...current.moduleData,
|
||||
[globalModuleKey(toolbox.id, memosModuleId)]: memos,
|
||||
[globalModuleKey(toolbox.id, linksModuleId)]: links
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function createToolbox(name, gameId = "", options = {}) {
|
||||
if (!store.ready) return null;
|
||||
const creation = buildToolboxCreation(name, options);
|
||||
void store.persistToolboxSnapshot((current) => ({
|
||||
toolboxes: [creation.toolbox, ...current.toolboxes],
|
||||
links: gameId ? { ...current.links, [gameId]: creation.toolbox.id } : current.links,
|
||||
moduleData: { ...current.moduleData, ...creation.moduleData }
|
||||
}));
|
||||
return toolbox;
|
||||
return creation.toolbox;
|
||||
}
|
||||
|
||||
async function addLibraryToolToToolbox({
|
||||
sourceModule,
|
||||
sourceData,
|
||||
dependencyModules = [],
|
||||
copyData = true,
|
||||
toolboxId = "",
|
||||
spaceId = "",
|
||||
newToolboxName = ""
|
||||
}) {
|
||||
if (!store.ready || !sourceModule?.type) return null;
|
||||
|
||||
const sources = [sourceModule, ...dependencyModules]
|
||||
.filter((module, index, modules) => module?.id && module?.type && modules.findIndex((item) => item.id === module.id) === index);
|
||||
const moduleIdMap = new Map(sources.map((module) => [module.id, uid("mod")]));
|
||||
if (copyData && sourceModule.type === "memos") {
|
||||
const plannerLink = String(sourceData?.plannerLink || "");
|
||||
if (plannerLink && plannerLink !== "all" && !moduleIdMap.has(plannerLink)) return null;
|
||||
}
|
||||
|
||||
const modulesToAdd = sources.map((module) => {
|
||||
const copiedModule = { id: moduleIdMap.get(module.id), type: module.type };
|
||||
if (module.title) copiedModule.title = module.title;
|
||||
return copiedModule;
|
||||
});
|
||||
const copiedData = copyData
|
||||
? Object.fromEntries(sources.map((module) => [
|
||||
moduleIdMap.get(module.id),
|
||||
copyModuleDataWithFreshIds(module.type, module.data, moduleIdMap)
|
||||
]).filter(([, data]) => data != null))
|
||||
: {};
|
||||
const requestedToolboxId = String(toolboxId || "");
|
||||
const requestedSpaceId = String(spaceId || "");
|
||||
const createNew = !requestedToolboxId && Boolean(String(newToolboxName || "").trim());
|
||||
const creation = createNew ? buildToolboxCreation(newToolboxName) : null;
|
||||
let result = null;
|
||||
|
||||
try {
|
||||
const saved = await store.persistToolboxSnapshot((current) => {
|
||||
const destination = creation?.toolbox || current.toolboxes.find((toolbox) => toolbox.id === requestedToolboxId);
|
||||
if (!destination) return current;
|
||||
const destinationSpaceId = creation
|
||||
? destination.defaultSpaceId
|
||||
: destination.spaces.some((space) => space.id === requestedSpaceId) ? requestedSpaceId : "";
|
||||
if (!destinationSpaceId) return current;
|
||||
|
||||
const updatedAt = new Date().toISOString();
|
||||
const updatedToolbox = {
|
||||
...modulesToAdd.reduce(
|
||||
(toolbox, module) => addModuleToToolboxSpace(toolbox, module, destinationSpaceId),
|
||||
destination
|
||||
),
|
||||
activeSpaceId: destinationSpaceId
|
||||
};
|
||||
const nextModuleData = { ...(creation?.moduleData || {}) };
|
||||
Object.entries(copiedData).forEach(([moduleId, data]) => {
|
||||
nextModuleData[globalModuleKey(destination.id, moduleId)] = data;
|
||||
});
|
||||
result = {
|
||||
toolboxId: destination.id,
|
||||
toolboxName: destination.name,
|
||||
spaceId: destinationSpaceId,
|
||||
moduleIds: modulesToAdd.map((module) => module.id)
|
||||
};
|
||||
return {
|
||||
...current,
|
||||
toolboxes: creation
|
||||
? [{ ...updatedToolbox, updatedAt }, ...current.toolboxes]
|
||||
: current.toolboxes.map((toolbox) => toolbox.id === destination.id ? { ...updatedToolbox, updatedAt } : toolbox),
|
||||
moduleData: { ...current.moduleData, ...nextModuleData }
|
||||
};
|
||||
});
|
||||
return saved ? result : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function updateToolbox(nextToolbox) {
|
||||
|
|
@ -301,6 +386,7 @@ export function useToolboxActions({ store, notify, creationTemplate, importConte
|
|||
|
||||
return {
|
||||
createToolbox,
|
||||
addLibraryToolToToolbox,
|
||||
updateToolbox,
|
||||
deleteToolbox,
|
||||
linkToolboxToGame,
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
// Rôle : affiche la librairie des outils avec des exemples locaux non persistés.
|
||||
import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Icon } from "../components/Icon.jsx";
|
||||
import { LibraryCopyModal } from "../components/LibraryCopyModal.jsx";
|
||||
import { LIBRARY_CATEGORY_DEFINITIONS, getToolboxModuleDefinition } from "../features/toolboxes/toolboxModuleRegistry.js";
|
||||
import { MODULE_COMPONENTS } from "../features/toolboxes/modules/toolboxModuleComponents.jsx";
|
||||
import { navigate } from "../router/hashRouter.js";
|
||||
import {
|
||||
clampQty,
|
||||
hostnameFromUrl,
|
||||
|
|
@ -116,11 +118,12 @@ function getLibraryCategories(modules, content) {
|
|||
})).filter((category) => category.modules.length);
|
||||
}
|
||||
|
||||
export function LibraryPage({ siteContent, actions }) {
|
||||
export function LibraryPage({ siteContent, actions, toolboxes = [], storageReady = true }) {
|
||||
const content = siteContent.library;
|
||||
const [libraryPayload, setLibraryPayload] = useState(null);
|
||||
const [libraryError, setLibraryError] = useState("");
|
||||
const [moduleData, setModuleData] = useState({});
|
||||
const [copyRequest, setCopyRequest] = useState(null);
|
||||
const [navigation, setNavigation] = useState(() => ({ anchorId: getCurrentLibraryAnchor(), behavior: "auto" }));
|
||||
const libraryCategories = useMemo(() => getLibraryCategories(libraryPayload?.toolbox?.modules || [], content), [content, libraryPayload]);
|
||||
const activeCategory = findCategoryForAnchor(libraryCategories, navigation.anchorId) || libraryCategories[0] || null;
|
||||
|
|
@ -216,6 +219,29 @@ export function LibraryPage({ siteContent, actions }) {
|
|||
}
|
||||
}), [actions, libraryPayload, moduleData, selectAnchor, siteContent.toolboxes.modules]);
|
||||
|
||||
const openCopyModal = useCallback((module) => {
|
||||
const sourceData = cloneData(moduleData[`${LIBRARY_TOOLBOX_ID}:${module.id}`] || libraryPayload?.modules?.[module.id] || {});
|
||||
const dependencyDefinition = getToolboxModuleDefinition(module.type).copyDependency;
|
||||
const dependencyId = dependencyDefinition && sourceData[dependencyDefinition.dataField] && sourceData[dependencyDefinition.dataField] !== "all"
|
||||
? sourceData[dependencyDefinition.dataField]
|
||||
: "";
|
||||
const dependency = dependencyId
|
||||
? libraryPayload?.toolbox?.modules?.find((item) => item.id === dependencyId && item.type === dependencyDefinition.type)
|
||||
: null;
|
||||
setCopyRequest({
|
||||
toolTitle: module.title || getToolboxModuleDefinition(module.type).label || "Outil",
|
||||
sourceModule: { id: module.id, type: module.type, title: module.title || "", data: sourceData },
|
||||
sourceData,
|
||||
dependencyModules: dependency ? [{
|
||||
id: dependency.id,
|
||||
type: dependency.type,
|
||||
title: dependency.title || "",
|
||||
data: cloneData(moduleData[`${LIBRARY_TOOLBOX_ID}:${dependency.id}`] || libraryPayload?.modules?.[dependency.id] || {})
|
||||
}] : [],
|
||||
missingDependency: Boolean(dependencyId && !dependency)
|
||||
});
|
||||
}, [libraryPayload, moduleData]);
|
||||
|
||||
return (
|
||||
<div className="library-page">
|
||||
<section className="page-hero nds-page-hero library-hero">
|
||||
|
|
@ -279,6 +305,9 @@ export function LibraryPage({ siteContent, actions }) {
|
|||
advancedCopySuccess={content.copyExampleSuccess}
|
||||
controlLegendHeading={content.controlLegendHeading}
|
||||
context={moduleContext}
|
||||
copyContent={content.copyToToolbox}
|
||||
storageReady={storageReady}
|
||||
onCopy={() => openCopyModal(module)}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
|
|
@ -287,6 +316,29 @@ export function LibraryPage({ siteContent, actions }) {
|
|||
</div>
|
||||
</>
|
||||
)}
|
||||
{copyRequest && <LibraryCopyModal
|
||||
content={content.copyToToolbox}
|
||||
toolTitle={copyRequest.toolTitle}
|
||||
toolboxes={toolboxes}
|
||||
hasDependency={copyRequest.dependencyModules.length > 0}
|
||||
onClose={() => setCopyRequest(null)}
|
||||
onConfirm={async (selection) => {
|
||||
if (copyRequest.missingDependency) return false;
|
||||
const result = await actions.addLibraryToolToToolbox({
|
||||
sourceModule: copyRequest.sourceModule,
|
||||
sourceData: copyRequest.sourceData,
|
||||
dependencyModules: selection.copyData ? copyRequest.dependencyModules : [],
|
||||
...selection
|
||||
});
|
||||
if (!result) return false;
|
||||
setCopyRequest(null);
|
||||
actions.notify(content.copyToToolbox.success.replace("{toolbox}", result.toolboxName), {
|
||||
actionLabel: content.copyToToolbox.openLabel,
|
||||
onAction: () => navigate(`/toolbox/${result.toolboxId}`)
|
||||
});
|
||||
return true;
|
||||
}}
|
||||
/>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -335,7 +387,7 @@ function LibraryDocNav({ content, categories, activeCategoryKey, onSelectCategor
|
|||
);
|
||||
}
|
||||
|
||||
function LibraryToolExample({ module, sourceData, description, categoryTitle, docs, featureHeading, advancedHeading, advancedCopyLabel, advancedCopySuccess, controlLegendHeading, context }) {
|
||||
function LibraryToolExample({ module, sourceData, description, categoryTitle, docs, featureHeading, advancedHeading, advancedCopyLabel, advancedCopySuccess, controlLegendHeading, context, copyContent, storageReady, onCopy }) {
|
||||
const definition = getToolboxModuleDefinition(module.type);
|
||||
const { Component } = MODULE_COMPONENTS[module.type] || MODULE_COMPONENTS.notepad;
|
||||
const [scrollable, setScrollable] = useState(false);
|
||||
|
|
@ -354,6 +406,13 @@ function LibraryToolExample({ module, sourceData, description, categoryTitle, do
|
|||
</div>
|
||||
<span className="library-tool-badge nds-badge">{categoryTitle}</span>
|
||||
{description && <p>{description}</p>}
|
||||
<div className="library-tool-copy-action">
|
||||
<p>{copyContent.isolationHelp}</p>
|
||||
<button className="nds-button" data-size="sm" data-variant="primary" type="button" disabled={!storageReady} onClick={onCopy}>
|
||||
<Icon name="add" />
|
||||
{copyContent.triggerLabel}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className={`library-example-layout ${Array.isArray(docs?.controls) && docs.controls.length ? "has-legend" : ""}`}>
|
||||
|
|
|
|||
|
|
@ -5,3 +5,4 @@
|
|||
@use "library/tool-cards";
|
||||
@use "library/examples";
|
||||
@use "library/previews";
|
||||
@use "library/copy";
|
||||
|
|
|
|||
127
website/src/styles/home/library/_copy.scss
Normal file
127
website/src/styles/home/library/_copy.scss
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
// Rôle : met en page l'action et la modale de copie des exemples de la librairie.
|
||||
.library-tool-copy-action {
|
||||
display: flex;
|
||||
max-width: 860px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-4);
|
||||
margin-top: var(--space-4);
|
||||
padding-top: var(--space-3);
|
||||
border-top: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.library-tool-copy-action p {
|
||||
color: var(--color-text-muted);
|
||||
font-size: var(--font-size-sm);
|
||||
}
|
||||
|
||||
.library-tool-copy-action .nds-button {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.library-copy-modal {
|
||||
width: min(580px, calc(100vw - var(--space-6)));
|
||||
}
|
||||
|
||||
.library-copy-modal header .eyebrow,
|
||||
.library-copy-modal header h2,
|
||||
.library-copy-description {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.library-copy-modal header {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.library-copy-description {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.library-copy-modal form {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.library-copy-destination {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.library-copy-field {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.library-copy-field > span,
|
||||
.library-copy-mode legend {
|
||||
color: var(--color-text-primary);
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.library-copy-field small,
|
||||
.library-copy-mode small {
|
||||
color: var(--color-text-muted);
|
||||
font-size: var(--font-size-xs);
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.library-copy-mode {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
gap: var(--space-2);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.library-copy-mode legend {
|
||||
margin-bottom: var(--space-2);
|
||||
}
|
||||
|
||||
.library-copy-mode label {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
align-items: start;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-3);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--color-bg-surface);
|
||||
cursor: pointer;
|
||||
transition: border-color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard);
|
||||
}
|
||||
|
||||
.library-copy-mode label:hover,
|
||||
.library-copy-mode label.is-selected {
|
||||
border-color: var(--color-primary-border);
|
||||
background: var(--color-primary-soft);
|
||||
}
|
||||
|
||||
.library-copy-mode input {
|
||||
margin-top: 3px;
|
||||
accent-color: var(--color-primary);
|
||||
}
|
||||
|
||||
.library-copy-mode label > span {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.library-copy-mode strong {
|
||||
color: var(--color-text-primary);
|
||||
font-size: var(--font-size-sm);
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.library-tool-copy-action {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.library-copy-destination {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue