diff --git a/AGENTS.md b/AGENTS.md index dcaec48..2c76df4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,9 +29,22 @@ Ne pas réintroduire de fallback massif type `DEFAULT_SITE_CONTENT` dans le code Chaque nouveau fichier source ou test doit commencer par un commentaire court `Rôle : ...` décrivant ce qu'il gère. - mettre cet en-tête à jour si la responsabilité du fichier change ; -- garder l'intro concise, une ou deux lignes maximum ; +- garder l'intro concise, une à trois lignes maximum selon la complexité du fichier ; +- quand un fichier existant est modifié, vérifier si son en-tête mérite d'être précisé au-delà de la ligne générique initiale ; +- enrichir l'en-tête quand le fichier porte une logique transverse, un hook partagé, un format de données ou un comportement réutilisable ; +- ne pas allonger mécaniquement les en-têtes des fichiers simples : la précision doit aider à comprendre la responsabilité réelle du fichier ; - utiliser `// Rôle : ...` dans les fichiers JS, JSX, MJS et SCSS. +## Hooks et comportements partagés + +Quand un comportement est déjà couvert par un hook ou un helper partagé, privilégier son utilisation plutôt qu'une réimplémentation locale afin de garder une expérience homogène. + +- pour la réorganisation par drag & drop, utiliser `useGroupedReorder` dès qu'il s'agit d'items, groupes, catégories, boundaries, parent/enfant ou listes horizontales/verticales ; +- réserver `usePointerReorder` au moteur bas niveau ou aux cas DOM très spécifiques qui ne correspondent pas au modèle applicatif de `useGroupedReorder` ; +- si une variation est nécessaire, vérifier d'abord si elle doit devenir une option du hook partagé ; +- demander ou expliciter le choix uniquement quand la variation est réellement métier et pourrait alourdir le hook ; +- éviter de dupliquer dans un outil une règle de reorder générique déjà prise en charge par le hook. + ## Outils toolbox Chaque outil toolbox doit rester dans son propre fichier dans : @@ -100,4 +113,6 @@ git diff --stat npm run check ``` +Après lecture du diff pré-push, proposer un exemple de message de commit en anglais, concis et représentatif des changements réellement présents. + Ne pas faire de refactor large sans bénéfice clair. Garder les corrections pré-push ciblées, vérifiables et faciles à relire. diff --git a/tests/static-toolboxes.test.mjs b/tests/static-toolboxes.test.mjs index 4a57960..3ad9a09 100644 --- a/tests/static-toolboxes.test.mjs +++ b/tests/static-toolboxes.test.mjs @@ -13,6 +13,7 @@ test("toolbox storage, cards and pages are wired", async () => { const storageQuota = await readFile("website/src/components/StorageQuota.jsx", "utf8"); const importButton = await readFile("website/src/components/ImportButton.jsx", "utf8"); const reorderHook = await readFile("website/src/hooks/usePointerReorder.js", "utf8"); + const groupedReorderHook = await readFile("website/src/hooks/useGroupedReorder.js", "utf8"); assert.match(`${indexedToolboxesHook}\n${toolboxPages}`, /indexedDbStorage\.js/); assert.match(source, /features\/toolboxes\/storage\/useIndexedToolboxes\.js/); @@ -48,11 +49,13 @@ test("toolbox storage, cards and pages are wired", async () => { assert.match(toolboxCard, /export function ToolboxIconPicker/); assert.match(toolboxCard, /export function ToolboxGameIcon/); assert.match(toolboxCard, /toolbox-card-drag-handle/); + assert.match(toolboxCard, /reorder\.getItemProps/); assert.match(toolboxCard, /toolbox-card-cover-link/); assert.match(toolboxCard, /toolbox-icon-cover/); assert.match(toolboxPages, /\.\/ToolboxCard\.jsx/); assert.match(toolboxPages, /updateToolboxOrder/); - assert.match(toolboxPages, /draggingToolboxId/); + assert.match(toolboxPages, /useGroupedReorder/); + assert.match(toolboxPages, /orientation: "horizontal"/); assert.match(toolboxPages, /components\/StorageQuota\.jsx/); assert.match(toolboxPages, /components\/ImportButton\.jsx/); assert.match(toolboxPages, /import-icon-button/); @@ -65,7 +68,7 @@ test("toolbox storage, cards and pages are wired", async () => { assert.match(toolboxPages, /moduleColumns/); assert.match(toolboxPages, /normalizeCombosData/); assert.match(toolboxPages, /function ToolboxView/); - assert.match(toolboxPages, /usePointerReorder/); + assert.doesNotMatch(toolboxPages, /usePointerReorder/); assert.match(storageQuota, /export function StorageQuota/); assert.match(storageQuota, /role="progressbar"/); assert.match(importButton, /export function ImportButton/); @@ -73,6 +76,12 @@ test("toolbox storage, cards and pages are wired", async () => { assert.match(reorderHook, /export function usePointerReorder/); assert.match(reorderHook, /setPointerCapture/); assert.match(reorderHook, /elementFromPoint/); + assert.match(groupedReorderHook, /export function useGroupedReorder/); + assert.match(groupedReorderHook, /usePointerReorder/); + assert.match(groupedReorderHook, /export function getGroupedEntries/); + assert.match(groupedReorderHook, /export function applyGroupedReorderOperation/); + assert.match(groupedReorderHook, /data-reorder-orientation/); + assert.match(groupedReorderHook, /operation\.sourceParentId === operation\.targetParentId/); }); test("toolbox module registry and modules expose expected behavior", async () => { @@ -114,9 +123,9 @@ test("toolbox module registry and modules expose expected behavior", async () => assert.match(moduleRegistry, /Annotation d'images/); assert.match(moduleRegistry, /editable: false/); assert.match(moduleRegistry, /module-edit-button/); - assert.match(moduleRegistry, /onDragStart/); + assert.match(moduleRegistry, /itemReorder\.startDrag/); assert.match(moduleRegistry, /onPointerDown/); - assert.match(moduleRegistry, /usePointerReorder/); + assert.match(moduleRegistry, /useGroupedReorder/); assert.match(moduleRegistry, /tool-add-card/); assert.match(moduleRegistry, /tool-quick-add-button/); assert.match(moduleRegistry, /tool-add-quick-toggle/); @@ -134,10 +143,16 @@ test("toolbox module registry and modules expose expected behavior", async () => assert.match(combosModule, /ComboSequence/); assert.match(combosModule, /keyboardLayout/); assert.match(combosModule, /simultaneousMode/); + assert.match(combosModule, /useGroupedReorder/); + assert.match(combosModule, /reorderFeatures/); + assert.doesNotMatch(combosModule, /canMoveItem:/); + assert.doesNotMatch(combosModule, /canMoveGroup:/); assert.match(calculatorModule, /export function CalculatorModule/); assert.match(calculatorModule, /calculateExpression/); assert.match(calculatorModule, /activeParentId/); assert.match(calculatorModule, /parentId/); + assert.match(calculatorModule, /useGroupedReorder/); + assert.match(calculatorModule, /calculator-drag-handle/); assert.match(calculatorModule, /scrollResults/); assert.match(calculatorModule, /tool-split-scroll-toggle/); assert.match(calculatorModule, /EditableCalculatorLabel/); @@ -188,7 +203,10 @@ test("toolbox module registry and modules expose expected behavior", async () => assert.match(taskPlannerModule, /categoryOrder/); assert.match(taskPlannerModule, /categoryLabel/); assert.match(taskPlannerModule, /task-planner-warning/); - assert.match(taskPlannerModule, /usePointerReorder/); + assert.match(taskPlannerModule, /useGroupedReorder/); + assert.match(taskPlannerModule, /reorderFeatures/); + assert.doesNotMatch(taskPlannerModule, /canMoveItem:/); + assert.doesNotMatch(taskPlannerModule, /canMoveGroup:/); assert.match(checklistModule, /export function ChecklistModule/); assert.match(checklistModule, /TextImportModal/); assert.match(checklistModule, /Icon name="import"/); @@ -203,9 +221,12 @@ test("toolbox module registry and modules expose expected behavior", async () => assert.match(checklistModule, /Number\.parseInt/); assert.match(checklistModule, /checklist-qty-current/); assert.match(checklistModule, /checklist-delete-button danger/); + assert.doesNotMatch(checklistModule, /useGroupedReorder/); assert.match(textImportModal, /createPortal/); assert.match(textImportModal, /lockBodyScroll/); assert.match(imagesModule, /export function ImagesModule/); + assert.match(imagesModule, /useGroupedReorder/); + assert.match(imagesModule, /orientation: "horizontal"/); assert.match(imagesModule, /editing &&/); assert.match(imagesModule, /clipboardData/); assert.match(imagesModule, /createImageAnnotationModule/); @@ -226,9 +247,18 @@ test("toolbox module registry and modules expose expected behavior", async () => assert.match(linksModule, /copyText/); assert.match(linksModule, /parseColonImportLines/); assert.match(linksModule, /context\.normalizeUrl/); + assert.match(linksModule, /useGroupedReorder/); + assert.match(linksModule, /link-drag-handle/); assert.match(countersModule, /export function CountersModule/); assert.match(countersModule, /editing &&/); assert.match(countersModule, /counter-actions/); + assert.match(countersModule, /useGroupedReorder/); + assert.match(countersModule, /orientation: "horizontal"/); + assert.match(countersModule, /counter-drag-handle/); + assert.match(timerModule, /useGroupedReorder/); + assert.match(timerModule, /reorderEnabled=\{!data\.sortResults\}/); + assert.match(timerModule, /parentId=\{moduleId\}/); + assert.match(timerModule, /timer-drag-handle/); assert.match(textImport, /export function parseColonImportLines/); assert.match(textImport, /line\.indexOf\(":\"\)/); assert.match(imageViewer, /image-viewer-media/); diff --git a/tests/toolbox-modules.test.mjs b/tests/toolbox-modules.test.mjs index c91d562..e604f32 100644 --- a/tests/toolbox-modules.test.mjs +++ b/tests/toolbox-modules.test.mjs @@ -5,6 +5,7 @@ import { evaluateTableCell } from "../website/src/features/toolboxes/modules/tab import { parseColonImportLines } from "../website/src/features/toolboxes/modules/textImport.js"; import { getTimePatternRecurrenceMs, getTimePatternTargetMs } from "../website/src/features/toolboxes/modules/timerUtils.js"; import { compactModuleDataForStorage, createToolboxExportPayload, normalizeCombosData, normalizeNotepadData, normalizeTableData, normalizeTaskPlannerData } from "../website/src/features/toolboxes/storage/toolboxStorage.js"; +import { applyGroupedReorderOperation, completeGroupOrder, getBoundaryItemId, getGroupedEntries, moveGroupOrder, moveGroupOrderToEnd, moveGroupOrderToStart, moveItem, moveItemGroup } from "../website/src/hooks/useGroupedReorder.js"; test("colon text import keeps urls intact after the first separator", () => { assert.deepEqual(parseColonImportLines("Build:https://example.com/build?class=rogue\nPotion:10"), [ @@ -95,6 +96,136 @@ test("table storage clamps dimensions and compacts non-empty cells", () => { assert.equal(compactModuleDataForStorage("table", { rows: 10, columns: 6, cells: {} }), null); }); +test("grouped reorder helpers group flat items and complete group order", () => { + const items = [ + { id: "a", category: "" }, + { id: "b", category: "Boss" }, + { id: "c", category: "Farm" }, + { id: "d", category: "Boss" } + ]; + + assert.deepEqual(completeGroupOrder(["Farm"], ["Boss", "Farm"]), ["Farm", "Boss"]); + assert.deepEqual(getGroupedEntries(items, { + groupOrder: ["Farm"], + getItemGroup: (item) => item.category, + groupIdKey: "category", + groupItemKey: "items" + }), [ + { type: "item", item: items[0] }, + { type: "group", group: { category: "Boss", items: [items[1], items[3]] } }, + { type: "group", group: { category: "Farm", items: [items[2]] } } + ]); +}); + +test("grouped reorder helpers move items and grouped item blocks", () => { + const items = [{ id: "a" }, { id: "b" }, { id: "c" }, { id: "d" }]; + + assert.deepEqual(moveItem(items, "a", "c", "after").map((item) => item.id), ["b", "c", "a", "d"]); + assert.deepEqual(moveItemGroup(items, ["b", "c"], "a", "before").map((item) => item.id), ["b", "c", "a", "d"]); + assert.equal(getBoundaryItemId(items, ["b", "c"], "before"), "b"); + assert.equal(getBoundaryItemId(items, ["b", "c"], "after"), "c"); +}); + +test("grouped reorder helpers reorder categories at targets and edges", () => { + const groups = ["Neutral", "Advanced", "Punish"]; + + assert.deepEqual(moveGroupOrder(["Neutral", "Advanced", "Punish"], groups, "Punish", "Neutral", "before"), ["Punish", "Neutral", "Advanced"]); + assert.deepEqual(moveGroupOrderToStart(["Neutral", "Advanced", "Punish"], groups, "Punish"), ["Punish", "Neutral", "Advanced"]); + assert.deepEqual(moveGroupOrderToEnd(["Neutral", "Advanced", "Punish"], groups, "Neutral"), ["Advanced", "Punish", "Neutral"]); +}); + +test("grouped reorder operation moves items in and out of categories", () => { + const data = { + categoryOrder: ["Boss"], + collapsedCategories: ["Farm"], + items: [ + { id: "a" }, + { id: "b", category: "Boss" }, + { id: "c", category: "Boss" }, + { id: "d", category: "Farm" } + ] + }; + const config = { + itemsKey: "items", + groupOrderKey: "categoryOrder", + collapsedGroupsKey: "collapsedCategories", + getItemGroup: (item) => item.category || "", + setItemGroup: (item, category) => { + const nextItem = { ...item }; + if (category) nextItem.category = category; + else delete nextItem.category; + return nextItem; + } + }; + + const movedIn = applyGroupedReorderOperation(data, { + ...config, + operation: { + type: "item", + sourceId: "a", + targetId: "Farm", + targetType: "group", + placement: "before", + sourceGroup: "", + targetGroup: "Farm", + sourceParentId: "", + targetParentId: "" + } + }); + + assert.deepEqual(movedIn.items.map((item) => `${item.id}:${item.category || ""}`), ["b:Boss", "c:Boss", "a:Farm", "d:Farm"]); + assert.deepEqual(movedIn.collapsedCategories, []); + + const movedOut = applyGroupedReorderOperation(movedIn, { + ...config, + operation: { + type: "item", + sourceId: "a", + targetId: "Boss", + targetType: "boundary", + placement: "after", + sourceGroup: "Farm", + targetGroup: "Boss", + sourceParentId: "", + targetParentId: "" + } + }); + + assert.deepEqual(movedOut.items.map((item) => `${item.id}:${item.category || ""}`), ["b:Boss", "c:Boss", "a:", "d:Farm"]); +}); + +test("grouped reorder operation moves whole categories", () => { + const data = { + categoryOrder: ["Boss", "Farm"], + items: [ + { id: "a", category: "Boss" }, + { id: "b", category: "Boss" }, + { id: "c", category: "Farm" }, + { id: "d", category: "Farm" }, + { id: "e" } + ] + }; + const moved = applyGroupedReorderOperation(data, { + operation: { + type: "group", + sourceId: "Boss", + targetId: "Farm", + targetType: "group", + placement: "after", + sourceGroup: "Boss", + targetGroup: "Farm", + sourceParentId: "", + targetParentId: "" + }, + groupOrderKey: "categoryOrder", + getItemGroup: (item) => item.category || "", + setItemGroup: (item) => item + }); + + assert.deepEqual(moved.items.map((item) => item.id), ["c", "d", "a", "b", "e"]); + assert.deepEqual(moved.categoryOrder, ["Farm", "Boss"]); +}); + test("combos storage normalizes devices, steps and compact export ids", () => { const longText = "x".repeat(120); const normalized = normalizeCombosData({ diff --git a/website/src/features/toolboxes/ToolboxCard.jsx b/website/src/features/toolboxes/ToolboxCard.jsx index 2a06c60..59a9923 100644 --- a/website/src/features/toolboxes/ToolboxCard.jsx +++ b/website/src/features/toolboxes/ToolboxCard.jsx @@ -20,25 +20,23 @@ export function formatDate(value) { return new Intl.DateTimeFormat("fr-FR", { dateStyle: "medium", timeStyle: "short" }).format(new Date(value)); } -export function ToolboxCard({ toolbox, game, actions, draggingToolboxId, dropTarget, onDragStart }) { +export function ToolboxCard({ toolbox, game, actions, reorder }) { const gameCoverImage = getGameCardCover(game); const coverImage = gameCoverImage || toolbox.icon || DEFAULT_TOOLBOX_ICON; - const isDragging = draggingToolboxId === toolbox.id; - const isDropTarget = dropTarget.id === toolbox.id; const className = [ "card", "toolbox-card", - isDragging ? "is-dragging" : "", - isDropTarget ? "is-drop-target" : "", - isDropTarget && dropTarget.placement === "after" ? "drop-after" : "" + reorder.isItemDragging(toolbox.id) ? "is-dragging" : "", + reorder.isItemDropTarget(toolbox.id) ? "is-drop-target" : "", + reorder.getDropPlacement("item", toolbox.id) === "after" ? "drop-after" : "" ].filter(Boolean).join(" "); return ( -
+
{entry.id === editingId ? ( <> @@ -204,9 +234,10 @@ function CalculatorEntries({ entries, parentId, activeParentId, textContent, onU - + - ))} + ); + })} ); } diff --git a/website/src/features/toolboxes/modules/CombosModule.jsx b/website/src/features/toolboxes/modules/CombosModule.jsx index d12be41..fa82989 100644 --- a/website/src/features/toolboxes/modules/CombosModule.jsx +++ b/website/src/features/toolboxes/modules/CombosModule.jsx @@ -1,11 +1,11 @@ // Rôle : fournit l'outil Combos avec palettes d'inputs et rendu visuel par périphérique. import { useEffect, useMemo, useState } from "react"; import { Icon } from "../../../components/Icon.jsx"; -import { usePointerReorder } from "../../../hooks/usePointerReorder.js"; - -const UNCATEGORIZED_DROP_ID = "combos:uncategorized"; -const CATEGORY_SECTION_PREFIX = "combos:category"; -const CATEGORY_BOUNDARY_DROP_PREFIX = "combos:category-boundary"; +import { + applyGroupedReorderOperation, + getGroupedEntries, + useGroupedReorder +} from "../../../hooks/useGroupedReorder.js"; const DEVICE_OPTIONS = [ { value: "playstation", label: "PlayStation" }, @@ -142,358 +142,13 @@ function getComboCategory(combo) { return String(combo?.category || "").trim(); } -function getCategoryGroups(combos, categoryOrder) { - const categories = []; - combos.forEach((combo) => { - const category = getComboCategory(combo); - if (category && !categories.includes(category)) categories.push(category); - }); - const orderedCategories = [ - ...categoryOrder.filter((category) => categories.includes(category)), - ...categories.filter((category) => !categoryOrder.includes(category)) - ]; - const groups = orderedCategories.map((category) => ({ - category, - combos: combos.filter((combo) => getComboCategory(combo) === category) - })).filter((group) => group.combos.length); - const renderedCategories = new Set(); - return combos.map((combo) => { - const category = getComboCategory(combo); - if (!category) return { type: "combo", combo }; - if (renderedCategories.has(category)) return null; - renderedCategories.add(category); - return { type: "category", group: groups.find((group) => group.category === category) }; - }).filter(Boolean); +function setComboCategory(combo, category) { + const nextCombo = { ...combo }; + if (category) nextCombo.category = category; + else delete nextCombo.category; + return nextCombo; } -function getCategoryComboIds(combos, category) { - return combos.filter((combo) => getComboCategory(combo) === category).map((combo) => combo.id); -} - -function getAllCategories(combos) { - const categories = []; - combos.forEach((combo) => { - const category = getComboCategory(combo); - if (category && !categories.includes(category)) categories.push(category); - }); - return categories; -} - -function getCompleteCategoryOrder(categoryOrder, categories) { - return [ - ...categoryOrder.filter((category) => categories.includes(category)), - ...categories.filter((category) => !categoryOrder.includes(category)) - ]; -} - -function getCategorySectionId(category) { - return `${CATEGORY_SECTION_PREFIX}\n${category}`; -} - -function parseCategorySectionId(id) { - const parts = String(id || "").split("\n"); - if (parts[0] !== CATEGORY_SECTION_PREFIX) return ""; - return parts.slice(1).join("\n"); -} - -function isCategorySectionId(id) { - return String(id || "").startsWith(`${CATEGORY_SECTION_PREFIX}\n`); -} - -function getCategoryBoundaryDropId(category, placement) { - return `${CATEGORY_BOUNDARY_DROP_PREFIX}\n${category}\n${placement}`; -} - -function parseCategoryBoundaryDropId(id) { - const parts = String(id || "").split("\n"); - if (parts[0] !== CATEGORY_BOUNDARY_DROP_PREFIX) return { category: "", placement: "" }; - return { - category: parts[1] || "", - placement: parts[2] === "after" ? "after" : "before" - }; -} - -function isCategoryBoundaryDropId(id) { - return String(id || "").startsWith(`${CATEGORY_BOUNDARY_DROP_PREFIX}\n`); -} - -function isUncategorizedDropId(id) { - return id === UNCATEGORIZED_DROP_ID; -} - -function moveComboGroup(combos, movingIds, targetComboId, placement = "before") { - const movingSet = new Set(movingIds); - if (!movingSet.size || movingSet.has(targetComboId)) return combos; - const movingCombos = combos.filter((combo) => movingSet.has(combo.id)); - const remainingCombos = combos.filter((combo) => !movingSet.has(combo.id)); - const targetIndex = remainingCombos.findIndex((combo) => combo.id === targetComboId); - if (targetIndex < 0) return combos; - remainingCombos.splice(placement === "after" ? targetIndex + 1 : targetIndex, 0, ...movingCombos); - return remainingCombos; -} - -function getBoundaryComboId(combos, comboIds, placement) { - const ids = new Set(comboIds); - const orderedCombos = combos.filter((combo) => ids.has(combo.id)); - return placement === "after" ? orderedCombos.at(-1)?.id || "" : orderedCombos[0]?.id || ""; -} - -function moveCategoryOrder(categoryOrder, categories, fromCategory, toCategory, placement = "before") { - const nextOrder = getCompleteCategoryOrder(categoryOrder, categories); - const index = nextOrder.indexOf(fromCategory); - const targetIndex = nextOrder.indexOf(toCategory); - if (index < 0 || targetIndex < 0 || fromCategory === toCategory) return nextOrder; - const [moved] = nextOrder.splice(index, 1); - const nextTargetIndex = nextOrder.indexOf(toCategory); - nextOrder.splice(placement === "after" ? nextTargetIndex + 1 : nextTargetIndex, 0, moved); - return nextOrder; -} - -function moveCategoryOrderToStart(categoryOrder, categories, fromCategory) { - const nextOrder = getCompleteCategoryOrder(categoryOrder, categories).filter((category) => category !== fromCategory); - return [fromCategory, ...nextOrder]; -} - -function moveCategoryOrderToEnd(categoryOrder, categories, fromCategory) { - const nextOrder = getCompleteCategoryOrder(categoryOrder, categories).filter((category) => category !== fromCategory); - return [...nextOrder, fromCategory]; -} - -function moveComboToCategory(combos, comboId, category) { - return combos.map((combo) => { - if (combo.id !== comboId) return combo; - const nextCombo = { ...combo }; - if (category) nextCombo.category = category; - else delete nextCombo.category; - return nextCombo; - }); -} - -function getFirstComboIdOutsideCategory(combos, category, excludedIds = []) { - const excluded = new Set(excludedIds); - return combos.find((combo) => !excluded.has(combo.id) && getComboCategory(combo) !== category)?.id || ""; -} - -function getLastComboIdOutsideCategory(combos, category, excludedIds = []) { - const excluded = new Set(excludedIds); - return [...combos].reverse().find((combo) => !excluded.has(combo.id) && getComboCategory(combo) !== category)?.id || ""; -} - -function insertCategoryGroupAtBoundary(data, fromCategory, boundary, movingIds) { - const allCategories = getAllCategories(data.combos); - const targetIds = getCategoryComboIds(data.combos, boundary.category); - const boundaryComboId = getBoundaryComboId(data.combos, targetIds, boundary.placement); - if (!boundaryComboId) return data; - return { - ...data, - combos: moveComboGroup(data.combos, movingIds, boundaryComboId, boundary.placement), - categoryOrder: moveCategoryOrder(data.categoryOrder, allCategories, fromCategory, boundary.category, boundary.placement) - }; -} - -function moveCategoryGroupToEdge(data, fromCategory, edge) { - const movingIds = getCategoryComboIds(data.combos, fromCategory); - if (!movingIds.length) return data; - const allCategories = getAllCategories(data.combos); - const boundaryComboId = edge === "start" - ? getFirstComboIdOutsideCategory(data.combos, fromCategory, movingIds) - : getLastComboIdOutsideCategory(data.combos, fromCategory, movingIds); - const combos = boundaryComboId - ? moveComboGroup(data.combos, movingIds, boundaryComboId, edge === "start" ? "before" : "after") - : data.combos; - return { - ...data, - combos, - categoryOrder: edge === "start" - ? moveCategoryOrderToStart(data.categoryOrder, allCategories, fromCategory) - : moveCategoryOrderToEnd(data.categoryOrder, allCategories, fromCategory) - }; -} - -function moveComboToEdge(data, comboId, edge, category = "") { - const nextCombosWithCategory = moveComboToCategory(data.combos, comboId, category); - const boundaryComboId = edge === "start" - ? nextCombosWithCategory.find((combo) => combo.id !== comboId)?.id || "" - : [...nextCombosWithCategory].reverse().find((combo) => combo.id !== comboId)?.id || ""; - const combos = boundaryComboId - ? moveComboGroup(nextCombosWithCategory, [comboId], boundaryComboId, edge === "start" ? "before" : "after") - : nextCombosWithCategory; - return { ...data, combos }; -} - -function moveComboBeforeCategoryBoundary(data, comboId, boundary) { - const nextCombosWithCategory = moveComboToCategory(data.combos, comboId, ""); - const targetIds = getCategoryComboIds(data.combos, boundary.category).filter((id) => id !== comboId); - const boundaryComboId = getBoundaryComboId(data.combos, targetIds, boundary.placement); - return { - ...data, - combos: boundaryComboId ? moveComboGroup(nextCombosWithCategory, [comboId], boundaryComboId, boundary.placement) : nextCombosWithCategory - }; -} - -function addCategoryToOrder(categoryOrder, category) { - return category && !categoryOrder.includes(category) ? [...categoryOrder, category] : categoryOrder; -} - -function cleanCategoryOrder(categoryOrder, combos) { - const categories = getAllCategories(combos); - return getCompleteCategoryOrder(categoryOrder, categories); -} - -function getCategoryEdge(categoryDropTarget, comboDropTarget, category, edge) { - const dropId = getCategoryBoundaryDropId(category, edge === "start" ? "before" : "after"); - return categoryDropTarget.id === dropId || comboDropTarget.id === dropId; -} - -function getDropEdgeClass(categoryDropTarget, comboDropTarget, category, edge) { - return getCategoryEdge(categoryDropTarget, comboDropTarget, category, edge) ? "is-drop-target" : ""; -} - -function getEdgeFromPlacement(placement) { - return placement === "after" ? "end" : "start"; -} - -function insertComboIntoCategory(data, comboId, category, placement) { - const nextCombos = moveComboToCategory(data.combos, comboId, category); - const targetIds = getCategoryComboIds(data.combos, category).filter((id) => id !== comboId); - const boundaryComboId = getBoundaryComboId(data.combos, targetIds, placement); - return { - ...data, - combos: boundaryComboId ? moveComboGroup(nextCombos, [comboId], boundaryComboId, placement) : nextCombos, - categoryOrder: addCategoryToOrder(data.categoryOrder, category), - collapsedCategories: data.collapsedCategories.filter((item) => item !== category) - }; -} - -function moveCategoryGroupAroundCombo(data, fromCategory, targetComboId, placement, movingIds) { - return { - ...data, - combos: moveComboGroup(data.combos, movingIds, targetComboId, placement) - }; -} - -function getCategoryOrderAfterComboMove(categoryOrder, combos) { - return cleanCategoryOrder(categoryOrder, combos); -} - -function moveComboAroundCombo(data, fromComboId, targetComboId, placement) { - const targetCombo = data.combos.find((combo) => combo.id === targetComboId); - if (!targetCombo) return data; - const targetCategory = getComboCategory(targetCombo); - const nextCombos = moveComboToCategory(data.combos, fromComboId, targetCategory); - const movedCombos = moveComboGroup(nextCombos, [fromComboId], targetComboId, placement); - return { - ...data, - combos: movedCombos, - categoryOrder: getCategoryOrderAfterComboMove(data.categoryOrder, movedCombos) - }; -} - -function isBoundaryEdgeTarget(toId, edge) { - if (!isCategoryBoundaryDropId(toId)) return false; - return parseCategoryBoundaryDropId(toId).placement === (edge === "start" ? "before" : "after"); -} - -function moveCategoryBoundary(data, fromCategory, toId) { - if (isUncategorizedDropId(toId)) return moveCategoryGroupToEdge(data, fromCategory, "start"); - if (!isCategoryBoundaryDropId(toId)) return data; - const boundary = parseCategoryBoundaryDropId(toId); - if (!boundary.category || boundary.category === fromCategory) return data; - if (isBoundaryEdgeTarget(toId, "start") && getCompleteCategoryOrder(data.categoryOrder, getAllCategories(data.combos))[0] === boundary.category) { - return moveCategoryGroupToEdge(data, fromCategory, "start"); - } - if (isBoundaryEdgeTarget(toId, "end")) { - const order = getCompleteCategoryOrder(data.categoryOrder, getAllCategories(data.combos)); - if (order.at(-1) === boundary.category) return moveCategoryGroupToEdge(data, fromCategory, "end"); - } - const movingIds = getCategoryComboIds(data.combos, fromCategory); - return insertCategoryGroupAtBoundary(data, fromCategory, boundary, movingIds); -} - -function moveCategoryOrderAroundTarget(categoryOrder, combos, fromCategory, toCategory, placement) { - return moveCategoryOrder(categoryOrder, getAllCategories(combos), fromCategory, toCategory, placement); -} - -function moveCategoryAroundCategory(data, fromCategory, toCategory, placement) { - const movingIds = getCategoryComboIds(data.combos, fromCategory); - const targetIds = getCategoryComboIds(data.combos, toCategory); - const boundaryComboId = getBoundaryComboId(data.combos, targetIds, placement); - if (!boundaryComboId) return data; - return { - ...data, - combos: moveComboGroup(data.combos, movingIds, boundaryComboId, placement), - categoryOrder: moveCategoryOrderAroundTarget(data.categoryOrder, data.combos, fromCategory, toCategory, placement) - }; -} - -function removeComboCategoryAtBoundary(data, comboId, boundary) { - const nextData = moveComboBeforeCategoryBoundary(data, comboId, boundary); - return { - ...nextData, - categoryOrder: cleanCategoryOrder(nextData.categoryOrder, nextData.combos) - }; -} - -function moveComboByBoundary(data, fromComboId, toId) { - const boundary = parseCategoryBoundaryDropId(toId); - if (!boundary.category) return data; - return removeComboCategoryAtBoundary(data, fromComboId, boundary); -} - -function removeComboCategory(data, comboId, placement) { - return moveComboToEdge(data, comboId, getEdgeFromPlacement(placement), ""); -} - -function insertAfterCategory(data, comboId, category, placement) { - return insertComboIntoCategory(data, comboId, category, placement); -} - -function getCategoryTargetId(target) { - if (target.dataset.dropId) return target.dataset.dropId; - if (target.classList.contains("combos-category")) return getCategorySectionId(target.dataset.category || ""); - return target.dataset.comboId || ""; -} - -function getComboTargetId(target) { - if (target.dataset.dropId) return target.dataset.dropId; - if (target.classList.contains("combo-card")) return target.dataset.comboId || ""; - return getCategorySectionId(target.dataset.category || ""); -} - -function canDropComboOnTarget(target, draggingId, combos) { - const draggingCombo = combos.find((combo) => combo.id === draggingId); - if (!draggingCombo) return false; - const draggingCategory = getComboCategory(draggingCombo); - if (target.classList.contains("combos-root-drop-zone")) return Boolean(draggingCategory); - if (target.classList.contains("combos-category-boundary-drop-zone")) return true; - if (target.classList.contains("combos-category")) return target.dataset.category !== draggingCategory; - if (target.classList.contains("combo-card")) return target.dataset.comboId !== draggingId; - return false; -} - -function canDropCategoryOnTarget(target, draggingId) { - const draggingCategory = parseCategorySectionId(draggingId); - if (!draggingCategory) return false; - if (target.classList.contains("combos-root-drop-zone")) return true; - if (target.classList.contains("combos-category-boundary-drop-zone")) { - const boundary = parseCategoryBoundaryDropId(target.dataset.dropId); - return boundary.category && boundary.category !== draggingCategory; - } - if (target.classList.contains("combos-category")) return target.dataset.category && target.dataset.category !== draggingCategory; - return !target.dataset.comboCategory; -} - -function getCategoryDropPlacement(event, target) { - if (target.classList.contains("combos-category-boundary-drop-zone") || target.classList.contains("combos-root-drop-zone")) return "before"; - const rect = target.getBoundingClientRect(); - return event.clientY > rect.top + rect.height / 2 ? "after" : "before"; -} - -function getComboDropPlacement(event, target) { - if (target.classList.contains("combos-category-boundary-drop-zone") || target.classList.contains("combos-root-drop-zone")) return "before"; - const rect = target.getBoundingClientRect(); - return event.clientY > rect.top + rect.height / 2 ? "after" : "before"; -} function ComboInputToken({ input, device, palette = false, onClick, onDragStart }) { const label = getInputLabel(input); @@ -629,28 +284,46 @@ export function CombosModule({ toolboxId, moduleId, context, editing }) { const paletteGroups = useMemo(() => getPaletteGroups(data.device, keyboardLayout), [data.device, keyboardLayout]); const paletteColumns = useMemo(() => getPaletteColumns(paletteGroups), [paletteGroups]); const cleanDraftInputs = draftInputs.map((step) => step.filter(Boolean)).filter((step) => step.length); - const entries = getCategoryGroups(data.combos, data.categoryOrder); - const { - draggingId: draggingCategoryId, - dropTarget: categoryDropTarget, - startDrag: startCategoryDrag - } = usePointerReorder({ - targetSelector: ".combos-category, .combo-card, .combos-root-drop-zone, .combos-category-boundary-drop-zone", - getTargetId: getCategoryTargetId, - canDropOn: canDropCategoryOnTarget, - getPlacement: getCategoryDropPlacement, - onMove: moveCategory + const entries = getGroupedEntries(data.combos, { + groupOrder: data.categoryOrder, + getItemGroup: getComboCategory, + groupIdKey: "category", + groupItemKey: "combos" }); const { - draggingId: draggingComboId, - dropTarget: comboDropTarget, - startDrag: startComboDrag - } = usePointerReorder({ - targetSelector: ".combo-card, .combos-category, .combos-root-drop-zone, .combos-category-boundary-drop-zone", - getTargetId: getComboTargetId, - canDropOn: (target, draggingId) => canDropComboOnTarget(target, draggingId, data.combos), - getPlacement: getComboDropPlacement, - onMove: moveCombo + itemReorder, + groupReorder, + getItemProps, + getGroupProps, + getGroupBoundaryProps, + isItemDragging, + isItemDropTarget, + isGroupDragging, + isGroupDropTarget, + isBoundaryDropTarget, + getDropPlacement, + shouldShowGroupBoundaries + } = useGroupedReorder({ + namespace: "combos", + items: data.combos, + getItemId: (combo) => combo.id, + getItemGroup: getComboCategory, + reorderFeatures: { + item: { + groupChange: true, + boundaryDrop: true, + ungroupedDrop: true + }, + group: { + reorder: true, + boundaryDrop: true, + ungroupedDrop: true, + itemDrop: true + } + }, + onItemMove: applyComboReorder, + onGroupMove: applyComboReorder, + hierarchy: { enabled: false, stickyParents: false } }); function save(nextData) { @@ -666,39 +339,15 @@ export function CombosModule({ toolboxId, moduleId, context, editing }) { }); } - function moveCategory(fromId, toId, placement) { - const fromCategory = parseCategorySectionId(fromId); - const movingIds = getCategoryComboIds(data.combos, fromCategory); - if (!movingIds.length) return; - if (isUncategorizedDropId(toId) || isCategoryBoundaryDropId(toId)) { - save(moveCategoryBoundary(data, fromCategory, toId)); - return; - } - if (isCategorySectionId(toId)) { - save(moveCategoryAroundCategory(data, fromCategory, parseCategorySectionId(toId), placement)); - return; - } - if (data.combos.some((combo) => combo.id === toId)) { - save(moveCategoryGroupAroundCombo(data, fromCategory, toId, placement, movingIds)); - } - } - - function moveCombo(fromComboId, targetId, placement) { - const movedCombo = data.combos.find((combo) => combo.id === fromComboId); - if (!movedCombo) return; - if (isUncategorizedDropId(targetId)) { - save(removeComboCategory(data, fromComboId, placement)); - return; - } - if (isCategoryBoundaryDropId(targetId)) { - save(moveComboByBoundary(data, fromComboId, targetId)); - return; - } - if (isCategorySectionId(targetId)) { - save(insertAfterCategory(data, fromComboId, parseCategorySectionId(targetId), placement)); - return; - } - save(moveComboAroundCombo(data, fromComboId, targetId, placement)); + function applyComboReorder(operation) { + save(applyGroupedReorderOperation(data, { + operation, + itemsKey: "combos", + groupOrderKey: "categoryOrder", + collapsedGroupsKey: "collapsedCategories", + getItemGroup: getComboCategory, + setItemGroup: setComboCategory + })); } function addInputToStep(kind, value, stepIndex) { @@ -880,16 +529,16 @@ export function CombosModule({ toolboxId, moduleId, context, editing }) { const comboClassName = [ "combo-card", "is-editing", - draggingComboId === combo.id ? "is-dragging" : "", - comboDropTarget.id === combo.id || categoryDropTarget.id === combo.id ? "is-drop-target" : "", - (comboDropTarget.id === combo.id && comboDropTarget.placement === "after") || (categoryDropTarget.id === combo.id && categoryDropTarget.placement === "after") ? "drop-after" : "" + isItemDragging(combo.id) ? "is-dragging" : "", + isItemDropTarget(combo.id) ? "is-drop-target" : "", + getDropPlacement("item", combo.id) === "after" ? "drop-after" : "" ].filter(Boolean).join(" "); return ( -
+
{counter.value} {counter.label} @@ -50,7 +83,8 @@ export function CountersModule({ toolboxId, moduleId, context, editing }) {
- ))} + ); + })} ); diff --git a/website/src/features/toolboxes/modules/ImagesModule.jsx b/website/src/features/toolboxes/modules/ImagesModule.jsx index 0d01765..0360e0d 100644 --- a/website/src/features/toolboxes/modules/ImagesModule.jsx +++ b/website/src/features/toolboxes/modules/ImagesModule.jsx @@ -1,7 +1,7 @@ // Rôle : fournit l'outil images avec import, collage, libellés et annotation rapide. import { useState } from "react"; import { Icon } from "../../../components/Icon.jsx"; -import { usePointerReorder } from "../../../hooks/usePointerReorder.js"; +import { moveItem, useGroupedReorder } from "../../../hooks/useGroupedReorder.js"; export function ImagesModule({ toolboxId, moduleId, context, editing }) { const data = context.getModuleData(toolboxId, moduleId, { images: [] }); @@ -9,24 +9,23 @@ export function ImagesModule({ toolboxId, moduleId, context, editing }) { const [dragOver, setDragOver] = useState(false); const pastePlaceholder = textContent.pastePlaceholder || "Coller une image ici"; const { - draggingId: draggingImageId, - dropTarget, - startDrag - } = usePointerReorder({ - targetSelector: "[data-image-id]", - getTargetId: (target) => target.dataset.imageId, - canDropOn: (target) => target.dataset.imageModuleId === moduleId, - getPlacement: (event, target) => { - const rect = target.getBoundingClientRect(); - return event.clientX > rect.left + rect.width / 2 ? "after" : "before"; + itemReorder, + getItemProps, + isItemDragging, + isItemDropTarget, + getDropPlacement + } = useGroupedReorder({ + namespace: "images", + items: data.images, + getItemId: (image) => image.id, + getParentId: () => moduleId, + orientation: "horizontal", + onItemMove: (operation) => { + context.setModuleData(toolboxId, moduleId, { + images: moveItem(data.images, operation.sourceId, operation.targetId, operation.placement) + }); }, - onMove: (draggingId, targetId, placement) => { - const nextImages = data.images.filter((image) => image.id !== draggingId); - const targetIndex = nextImages.findIndex((image) => image.id === targetId); - if (targetIndex === -1) return; - nextImages.splice(placement === "after" ? targetIndex + 1 : targetIndex, 0, data.images.find((image) => image.id === draggingId)); - context.setModuleData(toolboxId, moduleId, { images: nextImages.filter(Boolean) }); - } + hierarchy: { enabled: true, stickyParents: true } }); async function addFiles(files) { @@ -90,20 +89,18 @@ export function ImagesModule({ toolboxId, moduleId, context, editing }) { )}
{data.images.map((image) => { - const isDragging = draggingImageId === image.id; - const isDropTarget = dropTarget.id === image.id; const className = [ - isDragging ? "is-dragging" : "", - isDropTarget ? "is-drop-target" : "", - isDropTarget && dropTarget.placement === "after" ? "drop-after" : "" + isItemDragging(image.id) ? "is-dragging" : "", + isItemDropTarget(image.id) ? "is-drop-target" : "", + getDropPlacement("item", image.id) === "after" ? "drop-after" : "" ].filter(Boolean).join(" "); return ( -
+
{link.title || context.hostnameFromUrl(link.url)} {link.url} @@ -103,7 +135,8 @@ export function LinksModule({ toolboxId, moduleId, context, editing }) {
- ))} + ); + })} ); diff --git a/website/src/features/toolboxes/modules/TaskPlannerModule.jsx b/website/src/features/toolboxes/modules/TaskPlannerModule.jsx index bd4805b..c981696 100644 --- a/website/src/features/toolboxes/modules/TaskPlannerModule.jsx +++ b/website/src/features/toolboxes/modules/TaskPlannerModule.jsx @@ -2,11 +2,9 @@ import { useEffect, useMemo, useRef, useState } from "react"; import { Icon } from "../../../components/Icon.jsx"; import { InlineNotice } from "../../../components/AppOverlays.jsx"; -import { usePointerReorder } from "../../../hooks/usePointerReorder.js"; +import { applyGroupedReorderOperation, useGroupedReorder } from "../../../hooks/useGroupedReorder.js"; const TASK_TYPES = ["daily", "weekly", "unique"]; -const UNCATEGORIZED_DROP_ID = "task-planner:uncategorized"; -const CATEGORY_BOUNDARY_DROP_PREFIX = "task-planner:category-boundary"; const WEEK_DAYS = [ { value: 1, label: "Lundi" }, { value: 2, label: "Mardi" }, @@ -78,56 +76,12 @@ function moveTask(tasks, fromTaskId, toTaskId, placement = "before") { return nextTasks; } -function moveTaskGroup(tasks, fromTaskIds, toTaskId, placement = "before") { - const movingIds = new Set(fromTaskIds); - if (!movingIds.size || movingIds.has(toTaskId)) return tasks; - const targetIndex = tasks.findIndex((task) => task.id === toTaskId); - if (targetIndex < 0) return tasks; - const movingTasks = tasks.filter((task) => movingIds.has(task.id)); - const remainingTasks = tasks.filter((task) => !movingIds.has(task.id)); - const nextTargetIndex = remainingTasks.findIndex((task) => task.id === toTaskId); - remainingTasks.splice(placement === "after" ? nextTargetIndex + 1 : nextTargetIndex, 0, ...movingTasks); - return remainingTasks; -} - function getBoundaryTaskId(tasks, taskIds, placement) { const ids = new Set(taskIds); const orderedTasks = tasks.filter((task) => ids.has(task.id)); return placement === "after" ? orderedTasks.at(-1)?.id || "" : orderedTasks[0]?.id || ""; } -function getRootCategories(tasks, parentMap) { - const categories = []; - tasks.forEach((task) => { - if (parentMap.get(task.id) || !getTaskCategory(task) || categories.includes(task.category)) return; - categories.push(task.category); - }); - return categories; -} - -function getCompleteCategoryOrder(categoryOrder, categories) { - return [ - ...categoryOrder.filter((category) => categories.includes(category)), - ...categories.filter((category) => !categoryOrder.includes(category)) - ]; -} - -function moveCategory(categoryOrder, categories, fromCategory, toCategory, placement = "before") { - const nextOrder = getCompleteCategoryOrder(categoryOrder, categories); - const index = nextOrder.indexOf(fromCategory); - const targetIndex = nextOrder.indexOf(toCategory); - if (index < 0 || targetIndex < 0 || fromCategory === toCategory) return nextOrder; - const [moved] = nextOrder.splice(index, 1); - const nextTargetIndex = nextOrder.indexOf(toCategory); - nextOrder.splice(placement === "after" ? nextTargetIndex + 1 : nextTargetIndex, 0, moved); - return nextOrder; -} - -function moveCategoryToStart(categoryOrder, categories, fromCategory) { - const nextOrder = getCompleteCategoryOrder(categoryOrder, categories).filter((category) => category !== fromCategory); - return [fromCategory, ...nextOrder.filter(Boolean)]; -} - function getTaskTitle(tasks, taskId) { return tasks.find((task) => task.id === taskId)?.title || "Tâche supprimée"; } @@ -258,57 +212,12 @@ function getTaskCategoryGroups(tasks, parentMap, parentId, categoryOrder) { }; } -function getCategorySectionId(parentId, category) { - return `category\n${parentId || ""}\n${category}`; -} - -function parseCategorySectionId(id) { - const parts = String(id || "").split("\n"); - if (parts[0] !== "category") return { parentId: "", category: "" }; - return { - parentId: parts[1] || "", - category: parts.slice(2).join("\n") - }; -} - -function isCategorySectionId(id) { - return String(id || "").startsWith("category\n"); -} - -function isUncategorizedDropId(id) { - return id === UNCATEGORIZED_DROP_ID; -} - -function getCategoryBoundaryDropId(parentId, category, placement) { - return `${CATEGORY_BOUNDARY_DROP_PREFIX}\n${parentId || ""}\n${category}\n${placement}`; -} - -function parseCategoryBoundaryDropId(id) { - const parts = String(id || "").split("\n"); - if (parts[0] !== CATEGORY_BOUNDARY_DROP_PREFIX) return { parentId: "", category: "", placement: "" }; - return { - parentId: parts[1] || "", - category: parts[2] || "", - placement: parts[3] === "after" ? "after" : "before" - }; -} - -function isCategoryBoundaryDropId(id) { - return String(id || "").startsWith(`${CATEGORY_BOUNDARY_DROP_PREFIX}\n`); -} - function getRootTaskIdsForCategory(tasks, parentMap, category) { return tasks .filter((task) => !parentMap.get(task.id) && getTaskCategory(task) === category) .map((task) => task.id); } -function getRootTaskIds(tasks, parentMap) { - return tasks - .filter((task) => !parentMap.get(task.id)) - .map((task) => task.id); -} - export function TaskPlannerModule({ toolboxId, moduleId, context, editing }) { const data = context.normalizeTaskPlannerData(context.getModuleData(toolboxId, moduleId, { tasks: [] })); const textContent = context.moduleText?.taskPlanner || {}; @@ -322,32 +231,40 @@ export function TaskPlannerModule({ toolboxId, moduleId, context, editing }) { const prerequisiteNoticeTimeouts = useRef(new Map()); const parentMap = useMemo(() => getTaskParentMap(data.tasks, data.relations), [data.tasks, data.relations]); const { - draggingId, - dropTarget, - startDrag - } = usePointerReorder({ - targetSelector: ".task-planner-item, .task-planner-category-section, .task-planner-uncategorized-drop-zone, .task-planner-category-boundary-drop-zone", - getTargetId: (target) => target.dataset.dropId || target.dataset.taskId || getCategorySectionId(target.dataset.parentId || "", target.dataset.category || ""), - canDropOn: (target, draggingTaskId) => { - const draggingTask = data.tasks.find((task) => task.id === draggingTaskId); - if (!draggingTask) return false; - const draggingParentId = parentMap.get(draggingTaskId) || ""; - const draggingCategory = getTaskCategoryDataset(draggingTask, data.tasks, parentMap); - if (target.classList.contains("task-planner-category-boundary-drop-zone")) { - const boundary = parseCategoryBoundaryDropId(target.dataset.dropId); - return !draggingParentId && !boundary.parentId && Boolean(boundary.category); + itemReorder, + groupReorder, + getItemProps, + getGroupProps, + getGroupBoundaryProps, + isItemDragging, + isItemDropTarget, + isGroupDragging, + isGroupDropTarget, + isBoundaryDropTarget, + getDropPlacement, + shouldShowGroupBoundaries + } = useGroupedReorder({ + namespace: "task-planner", + items: data.tasks, + getItemId: (task) => task.id, + getParentId: (task) => parentMap.get(task.id) || "", + getItemGroup: (task) => getTaskCategoryDataset(task, data.tasks, parentMap), + getEffectiveGroup: (task) => getTaskCategoryDataset(task, data.tasks, parentMap), + reorderFeatures: { + item: { + groupChange: true, + boundaryDrop: true, + rootOnly: true + }, + group: { + reorder: true, + boundaryDrop: true, + itemDrop: true, + rootOnly: true } - if (target.classList.contains("task-planner-uncategorized-drop-zone")) { - return !draggingParentId && Boolean(draggingCategory); - } - if (target.classList.contains("task-planner-category-section")) { - return !draggingParentId && !target.dataset.parentId && Boolean(target.dataset.category) && target.dataset.category !== draggingCategory; - } - if (target.dataset.parentId !== draggingParentId) return false; - if (target.dataset.category === draggingCategory) return true; - return !draggingParentId; }, - onMove: (fromTaskId, toId, placement) => { + onItemMove: (operation) => { + const fromTaskId = operation.sourceId; const fromTask = data.tasks.find((task) => task.id === fromTaskId); if (!fromTask) return; function setRootTaskCategory(tasks, category) { @@ -359,7 +276,7 @@ export function TaskPlannerModule({ toolboxId, moduleId, context, editing }) { return nextTask; }); } - function moveToCategory(category) { + function moveToCategory(category, placement = operation.placement) { const nextTasks = setRootTaskCategory(data.tasks, category); const targetIds = category ? getRootTaskIdsForCategory(data.tasks, parentMap, category).filter((taskId) => taskId !== fromTaskId) @@ -367,108 +284,59 @@ export function TaskPlannerModule({ toolboxId, moduleId, context, editing }) { const boundaryTaskId = getBoundaryTaskId(data.tasks, targetIds, placement); save({ ...data, tasks: boundaryTaskId ? moveTask(nextTasks, fromTaskId, boundaryTaskId, placement) : nextTasks }); } - if (isUncategorizedDropId(toId)) { - moveToCategory(""); - return; - } - if (isCategoryBoundaryDropId(toId)) { - const boundary = parseCategoryBoundaryDropId(toId); - const targetIds = getRootTaskIdsForCategory(data.tasks, parentMap, boundary.category); - const boundaryTaskId = getBoundaryTaskId(data.tasks, targetIds, boundary.placement); + if (operation.targetType === "boundary") { + const targetIds = getRootTaskIdsForCategory(data.tasks, parentMap, operation.targetGroup); + const boundaryTaskId = getBoundaryTaskId(data.tasks, targetIds, operation.placement); if (!boundaryTaskId) return; const sourceCategory = getTaskCategoryDataset(fromTask, data.tasks, parentMap); const tasks = sourceCategory ? setRootTaskCategory(data.tasks, "") : data.tasks; - save({ ...data, tasks: moveTask(tasks, fromTaskId, boundaryTaskId, boundary.placement) }); + save({ ...data, tasks: moveTask(tasks, fromTaskId, boundaryTaskId, operation.placement) }); return; } - if (isCategorySectionId(toId)) { - const targetCategory = parseCategorySectionId(toId).category; + if (operation.targetType === "group") { + const targetCategory = operation.targetGroup; const sourceCategory = getTaskCategoryDataset(fromTask, data.tasks, parentMap); if (!sourceCategory) { const targetIds = getRootTaskIdsForCategory(data.tasks, parentMap, targetCategory); - const boundaryTaskId = getBoundaryTaskId(data.tasks, targetIds, placement); - if (boundaryTaskId) save({ ...data, tasks: moveTask(data.tasks, fromTaskId, boundaryTaskId, placement) }); + const boundaryTaskId = getBoundaryTaskId(data.tasks, targetIds, operation.placement); + if (boundaryTaskId) save({ ...data, tasks: moveTask(data.tasks, fromTaskId, boundaryTaskId, operation.placement) }); return; } moveToCategory(targetCategory); return; } - const targetTask = data.tasks.find((task) => task.id === toId); + const targetTask = data.tasks.find((task) => task.id === operation.targetId); const targetCategory = targetTask ? getTaskCategoryDataset(targetTask, data.tasks, parentMap) : ""; const sourceCategory = getTaskCategoryDataset(fromTask, data.tasks, parentMap); - const shouldChangeRootCategory = !parentMap.get(fromTaskId) && targetTask && !parentMap.get(toId) && targetCategory !== sourceCategory; + const shouldChangeRootCategory = !parentMap.get(fromTaskId) && targetTask && !parentMap.get(operation.targetId) && targetCategory !== sourceCategory; const tasks = shouldChangeRootCategory ? setRootTaskCategory(data.tasks, targetCategory) : data.tasks; - save({ ...data, tasks: moveTask(tasks, fromTaskId, toId, placement) }); - } - }); - const { - draggingId: draggingCategoryId, - dropTarget: categoryDropTarget, - startDrag: startCategoryDrag - } = usePointerReorder({ - targetSelector: ".task-planner-category-section, .task-planner-item, .task-planner-uncategorized-drop-zone, .task-planner-category-boundary-drop-zone", - getTargetId: (target) => target.dataset.dropId || target.dataset.taskId || getCategorySectionId(target.dataset.parentId || "", target.dataset.category || ""), - canDropOn: (target, draggingIdValue) => { - const draggingCategory = parseCategorySectionId(draggingIdValue); - if (!draggingCategory.category) return false; - if (target.classList.contains("task-planner-uncategorized-drop-zone")) return !draggingCategory.parentId; - if (target.classList.contains("task-planner-category-boundary-drop-zone")) { - const boundary = parseCategoryBoundaryDropId(target.dataset.dropId); - return boundary.parentId === draggingCategory.parentId && boundary.category && boundary.category !== draggingCategory.category; - } - if (target.dataset.parentId !== draggingCategory.parentId) return false; - if (target.classList.contains("task-planner-category-section")) return Boolean(target.dataset.category); - return !target.dataset.category; + save({ ...data, tasks: moveTask(tasks, fromTaskId, operation.targetId, operation.placement) }); }, - onMove: (fromId, toId, placement) => { - const fromCategory = parseCategorySectionId(fromId).category; - const movingIds = getRootTaskIdsForCategory(data.tasks, parentMap, fromCategory); - if (!movingIds.length) return; - const rootCategories = getRootCategories(data.tasks, parentMap); - if (isUncategorizedDropId(toId)) { - const targetIds = data.tasks - .filter((task) => !parentMap.get(task.id) && !getTaskCategory(task) && !movingIds.includes(task.id)) - .map((task) => task.id); - const rootIds = getRootTaskIds(data.tasks, parentMap).filter((taskId) => !movingIds.includes(taskId)); - const boundaryTaskId = getBoundaryTaskId(data.tasks, targetIds, placement) || getBoundaryTaskId(data.tasks, rootIds, "before"); - if (boundaryTaskId) { - save({ - ...data, - tasks: moveTaskGroup(data.tasks, movingIds, boundaryTaskId, "before"), - categoryOrder: moveCategoryToStart(data.categoryOrder, rootCategories, fromCategory) - }); - } - return; - } - if (isCategoryBoundaryDropId(toId)) { - const boundary = parseCategoryBoundaryDropId(toId); - const targetIds = getRootTaskIdsForCategory(data.tasks, parentMap, boundary.category); - const boundaryTaskId = getBoundaryTaskId(data.tasks, targetIds, boundary.placement); - if (boundaryTaskId) { - save({ - ...data, - tasks: moveTaskGroup(data.tasks, movingIds, boundaryTaskId, boundary.placement), - categoryOrder: moveCategory(data.categoryOrder, rootCategories, fromCategory, boundary.category, boundary.placement) - }); - } - return; - } - if (isCategorySectionId(toId)) { - const toCategory = parseCategorySectionId(toId).category; - const targetIds = getRootTaskIdsForCategory(data.tasks, parentMap, toCategory); - const boundaryTaskId = getBoundaryTaskId(data.tasks, targetIds, placement); - if (boundaryTaskId) { - save({ - ...data, - tasks: moveTaskGroup(data.tasks, movingIds, boundaryTaskId, placement), - categoryOrder: moveCategory(data.categoryOrder, rootCategories, fromCategory, toCategory, placement) - }); - } - return; - } - save({ ...data, tasks: moveTaskGroup(data.tasks, movingIds, toId, placement) }); - } + onGroupMove: (operation) => { + save(applyGroupedReorderOperation(data, { + operation, + itemsKey: "tasks", + groupOrderKey: "categoryOrder", + getItemGroup: (task) => parentMap.get(task.id) ? "" : getTaskCategory(task), + setItemGroup: (task) => task + })); + }, + hierarchy: { enabled: true, stickyParents: true } }); + const reorder = { + itemReorder, + groupReorder, + getItemProps, + getGroupProps, + getGroupBoundaryProps, + isItemDragging, + isItemDropTarget, + isGroupDragging, + isGroupDropTarget, + isBoundaryDropTarget, + getDropPlacement, + shouldShowGroupBoundaries + }; function save(nextData) { context.setModuleData(toolboxId, moduleId, nextData, "taskPlanner"); @@ -684,16 +552,11 @@ export function TaskPlannerModule({ toolboxId, moduleId, context, editing }) { parentMap={parentMap} tasks={data.tasks} data={data} - draggingId={draggingId} - dropTarget={dropTarget} - draggingCategoryId={draggingCategoryId} - categoryDropTarget={categoryDropTarget} + reorder={reorder} textContent={textContent} openDescriptions={openDescriptions} openTaskSettings={openTaskSettings} prerequisiteNoticeTaskIds={prerequisiteNoticeTaskIds} - onDragStart={startDrag} - onCategoryDragStart={startCategoryDrag} onToggleDescription={(taskId) => toggleSet(setOpenDescriptions, taskId)} onToggleSettings={(taskId) => toggleSet(setOpenTaskSettings, taskId)} onPrerequisiteNotice={showPrerequisiteNotice} @@ -718,16 +581,11 @@ function TaskPlannerBranch({ parentMap, tasks, data, - draggingId, - dropTarget, - draggingCategoryId, - categoryDropTarget, + reorder, textContent, openDescriptions, openTaskSettings, prerequisiteNoticeTaskIds, - onDragStart, - onCategoryDragStart, onToggleDescription, onToggleSettings, onPrerequisiteNotice, @@ -744,16 +602,7 @@ function TaskPlannerBranch({ const children = [...groupedTasks.uncategorized, ...groupedTasks.categories.flatMap((group) => group.tasks)].filter((task) => !visited.has(task.id)); if (!children.length) return null; const nextVisited = new Set([...visited, ...children.map((task) => task.id)]); - const draggingTask = draggingId ? getTaskById(tasks, draggingId) : null; - const draggingCategory = parseCategorySectionId(draggingCategoryId); - const showUncategorizedDropZone = !parentId && ( - (draggingTask && !parentMap.get(draggingTask.id) && Boolean(getTaskCategoryDataset(draggingTask, tasks, parentMap))) - || Boolean(draggingCategory.category && !draggingCategory.parentId) - ); - const showCategoryBoundaryDropZones = !parentId && ( - (draggingTask && !parentMap.get(draggingTask.id)) - || Boolean(draggingCategory.category && !draggingCategory.parentId) - ); + const showCategoryBoundaryDropZones = !parentId && reorder.shouldShowGroupBoundaries({ parentId }); function hasVisibleDescendants(taskId, seen = new Set()) { if (seen.has(taskId)) return false; @@ -769,16 +618,11 @@ function TaskPlannerBranch({ parentMap={parentMap} tasks={tasks} data={data} - draggingId={draggingId} - dropTarget={dropTarget} - draggingCategoryId={draggingCategoryId} - categoryDropTarget={categoryDropTarget} + reorder={reorder} textContent={textContent} openDescriptions={openDescriptions} openTaskSettings={openTaskSettings} prerequisiteNoticeTaskIds={prerequisiteNoticeTaskIds} - onDragStart={onDragStart} - onCategoryDragStart={onCategoryDragStart} onToggleDescription={onToggleDescription} onToggleSettings={onToggleSettings} onPrerequisiteNotice={onPrerequisiteNotice} @@ -808,14 +652,11 @@ function TaskPlannerBranch({ data={data} parentMap={parentMap} parentId={parentId} - draggingId={draggingId} - dropTarget={dropTarget} - categoryDropTarget={categoryDropTarget} + reorder={reorder} textContent={textContent} descriptionOpen={openDescriptions.has(task.id)} settingsOpen={openTaskSettings.has(task.id)} prerequisiteNoticeVisible={prerequisiteNoticeTaskIds.has(task.id)} - onDragStart={onDragStart} onToggleDescription={() => onToggleDescription(task.id)} onToggleSettings={() => onToggleSettings(task.id)} onPrerequisiteNotice={onPrerequisiteNotice} @@ -837,41 +678,38 @@ function TaskPlannerBranch({ if (data.hideCompleted && isTaskTreeComplete(groupTasks.map((task) => task.id), tasks, parentMap)) return null; const groupCount = countTaskTree(groupTasks.map((task) => task.id), tasks, parentMap); const groupCompletedCount = countCompletedTaskTree(groupTasks.map((task) => task.id), tasks, parentMap); - const categoryId = getCategorySectionId(parentId, group.category); - const beforeDropId = getCategoryBoundaryDropId(parentId, group.category, "before"); - const afterDropId = getCategoryBoundaryDropId(parentId, group.category, "after"); const isCollapsed = data.collapsedCategories.includes(group.category); const sectionClassName = [ "task-planner-category-section", groupCompletedCount === groupCount ? "is-complete" : "", isCollapsed ? "is-collapsed" : "", - draggingCategoryId === categoryId ? "is-dragging" : "", - categoryDropTarget.id === categoryId || dropTarget.id === categoryId ? "is-drop-target" : "", - (categoryDropTarget.id === categoryId && categoryDropTarget.placement === "after") || (dropTarget.id === categoryId && dropTarget.placement === "after") ? "drop-after" : "" + reorder.isGroupDragging(group.category, parentId) ? "is-dragging" : "", + reorder.isGroupDropTarget(group.category, parentId) ? "is-drop-target" : "", + reorder.getDropPlacement("group", group.category, parentId) === "after" ? "drop-after" : "" ].filter(Boolean).join(" "); const beforeDropZone = showCategoryBoundaryDropZones ? (
  • ) : null; const afterDropZone = showCategoryBoundaryDropZones ? (
  • ) : null; return [ beforeDropZone, -
  • +
  • @@ -471,7 +484,7 @@ function StopwatchLapList({ laps, textContent, onRename, onDelete }) { ); } -function CountdownList({ countdowns, nowMs, textContent, onRename, onAlertModeChange, onReset, onDelete }) { +function CountdownList({ countdowns, nowMs, textContent, reorder, reorderEnabled, parentId, onRename, onAlertModeChange, onReset, onDelete }) { const [editingId, setEditingId] = useState(""); if (!countdowns.length) return

    {textContent.emptyCountdowns || "Aucun compte à rebours configuré."}

    ; return ( @@ -482,9 +495,30 @@ function CountdownList({ countdowns, nowMs, textContent, onRename, onAlertModeCh const canReset = countdown.type === "duration" || countdown.type === "interval" || (countdown.type === "daily_time" && expired); + const className = [ + "timer-list-item", + expired ? "is-expired" : "", + editingId === countdown.id ? "is-editing" : "", + reorderEnabled && reorder.isItemDragging(countdown.id) ? "is-dragging" : "", + reorderEnabled && reorder.isItemDropTarget(countdown.id) ? "is-drop-target" : "", + reorderEnabled && reorder.getDropPlacement("item", countdown.id) === "after" ? "drop-after" : "" + ].filter(Boolean).join(" "); + const reorderProps = reorderEnabled ? reorder.getItemProps({ itemId: countdown.id, parentId }) : {}; + return ( -
  • -
    +
  • +
    + {reorderEnabled && ( + + )} {editingId === countdown.id ? ( toolbox.modules.map((module) => module.id).join("|"), [toolbox.modules]); const { - draggingId: draggingModuleId, - dropTarget, - startDrag: startModuleDrag - } = usePointerReorder({ - targetSelector: ".module", - getTargetId: (target) => target.dataset.moduleId, - canDropOn: (target) => target.dataset.toolboxId === toolbox.id, - onMove + itemReorder, + getItemProps, + isItemDragging, + isItemDropTarget, + getDropPlacement + } = useGroupedReorder({ + namespace: "toolbox-modules", + items: toolbox.modules, + getItemId: (module) => module.id, + getParentId: () => toolbox.id, + onItemMove: (operation) => onMove(operation.sourceId, operation.targetId, operation.placement), + hierarchy: { enabled: true, stickyParents: true } }); useEffect(() => { @@ -246,9 +250,7 @@ export function ToolboxModules({ toolbox, moduleColumns, context, onRename, onUp toolbox={toolbox} module={module} context={context} - draggingModuleId={draggingModuleId} - dropTarget={dropTarget} - onDragStart={startModuleDrag} + reorder={{ itemReorder, getItemProps, isItemDragging, isItemDropTarget, getDropPlacement }} onRename={onRename} onUpdateModule={onUpdateModule} onDelete={onDelete} @@ -273,9 +275,7 @@ export function ToolboxModules({ toolbox, moduleColumns, context, onRename, onUp toolbox={toolbox} module={module} context={context} - draggingModuleId={draggingModuleId} - dropTarget={dropTarget} - onDragStart={startModuleDrag} + reorder={{ itemReorder, getItemProps, isItemDragging, isItemDropTarget, getDropPlacement }} onRename={onRename} onUpdateModule={onUpdateModule} onDelete={onDelete} @@ -289,27 +289,24 @@ export function ToolboxModules({ toolbox, moduleColumns, context, onRename, onUp ); } -function ModuleShell({ toolbox, module, context, draggingModuleId, dropTarget, onDragStart, onRename, onUpdateModule, onDelete, registerModuleElement }) { +function ModuleShell({ toolbox, module, context, reorder, onRename, onUpdateModule, onDelete, registerModuleElement }) { const definition = MODULE_COMPONENTS[module.type] || MODULE_COMPONENTS.notepad; const Component = definition.Component; const label = definition.label || module.type; const [editing, setEditing] = useState(false); const scrollable = definition.scrollable && module.scrollable === true; - const isDragging = draggingModuleId === module.id; - const isDropTarget = dropTarget.id === module.id; const className = [ "module", - isDragging ? "is-dragging" : "", - isDropTarget ? "is-drop-target" : "", - isDropTarget && dropTarget.placement === "after" ? "drop-after" : "", + reorder.isItemDragging(module.id) ? "is-dragging" : "", + reorder.isItemDropTarget(module.id) ? "is-drop-target" : "", + reorder.getDropPlacement("item", module.id) === "after" ? "drop-after" : "", scrollable ? "is-scrollable" : "" ].filter(Boolean).join(" "); return (
    registerModuleElement?.(module.id, element)} >
    @@ -317,7 +314,7 @@ function ModuleShell({ toolbox, module, context, draggingModuleId, dropTarget, o