Unify toolbox drag and drop reorder behavior
All checks were successful
Deploy Sokko G / deploy (push) Successful in 7s

This commit is contained in:
Shinuwa 2026-08-01 20:00:47 +02:00
parent a6d35c6e6b
commit 1879b245fb
17 changed files with 1258 additions and 929 deletions

View file

@ -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. 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 ; - 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. - 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 ## Outils toolbox
Chaque outil toolbox doit rester dans son propre fichier dans : Chaque outil toolbox doit rester dans son propre fichier dans :
@ -100,4 +113,6 @@ git diff --stat
npm run check 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. Ne pas faire de refactor large sans bénéfice clair. Garder les corrections pré-push ciblées, vérifiables et faciles à relire.

View file

@ -13,6 +13,7 @@ test("toolbox storage, cards and pages are wired", async () => {
const storageQuota = await readFile("website/src/components/StorageQuota.jsx", "utf8"); const storageQuota = await readFile("website/src/components/StorageQuota.jsx", "utf8");
const importButton = await readFile("website/src/components/ImportButton.jsx", "utf8"); const importButton = await readFile("website/src/components/ImportButton.jsx", "utf8");
const reorderHook = await readFile("website/src/hooks/usePointerReorder.js", "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(`${indexedToolboxesHook}\n${toolboxPages}`, /indexedDbStorage\.js/);
assert.match(source, /features\/toolboxes\/storage\/useIndexedToolboxes\.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 ToolboxIconPicker/);
assert.match(toolboxCard, /export function ToolboxGameIcon/); assert.match(toolboxCard, /export function ToolboxGameIcon/);
assert.match(toolboxCard, /toolbox-card-drag-handle/); assert.match(toolboxCard, /toolbox-card-drag-handle/);
assert.match(toolboxCard, /reorder\.getItemProps/);
assert.match(toolboxCard, /toolbox-card-cover-link/); assert.match(toolboxCard, /toolbox-card-cover-link/);
assert.match(toolboxCard, /toolbox-icon-cover/); assert.match(toolboxCard, /toolbox-icon-cover/);
assert.match(toolboxPages, /\.\/ToolboxCard\.jsx/); assert.match(toolboxPages, /\.\/ToolboxCard\.jsx/);
assert.match(toolboxPages, /updateToolboxOrder/); 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\/StorageQuota\.jsx/);
assert.match(toolboxPages, /components\/ImportButton\.jsx/); assert.match(toolboxPages, /components\/ImportButton\.jsx/);
assert.match(toolboxPages, /import-icon-button/); 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, /moduleColumns/);
assert.match(toolboxPages, /normalizeCombosData/); assert.match(toolboxPages, /normalizeCombosData/);
assert.match(toolboxPages, /function ToolboxView/); assert.match(toolboxPages, /function ToolboxView/);
assert.match(toolboxPages, /usePointerReorder/); assert.doesNotMatch(toolboxPages, /usePointerReorder/);
assert.match(storageQuota, /export function StorageQuota/); assert.match(storageQuota, /export function StorageQuota/);
assert.match(storageQuota, /role="progressbar"/); assert.match(storageQuota, /role="progressbar"/);
assert.match(importButton, /export function ImportButton/); 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, /export function usePointerReorder/);
assert.match(reorderHook, /setPointerCapture/); assert.match(reorderHook, /setPointerCapture/);
assert.match(reorderHook, /elementFromPoint/); 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 () => { 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, /Annotation d'images/);
assert.match(moduleRegistry, /editable: false/); assert.match(moduleRegistry, /editable: false/);
assert.match(moduleRegistry, /module-edit-button/); assert.match(moduleRegistry, /module-edit-button/);
assert.match(moduleRegistry, /onDragStart/); assert.match(moduleRegistry, /itemReorder\.startDrag/);
assert.match(moduleRegistry, /onPointerDown/); assert.match(moduleRegistry, /onPointerDown/);
assert.match(moduleRegistry, /usePointerReorder/); assert.match(moduleRegistry, /useGroupedReorder/);
assert.match(moduleRegistry, /tool-add-card/); assert.match(moduleRegistry, /tool-add-card/);
assert.match(moduleRegistry, /tool-quick-add-button/); assert.match(moduleRegistry, /tool-quick-add-button/);
assert.match(moduleRegistry, /tool-add-quick-toggle/); 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, /ComboSequence/);
assert.match(combosModule, /keyboardLayout/); assert.match(combosModule, /keyboardLayout/);
assert.match(combosModule, /simultaneousMode/); 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, /export function CalculatorModule/);
assert.match(calculatorModule, /calculateExpression/); assert.match(calculatorModule, /calculateExpression/);
assert.match(calculatorModule, /activeParentId/); assert.match(calculatorModule, /activeParentId/);
assert.match(calculatorModule, /parentId/); assert.match(calculatorModule, /parentId/);
assert.match(calculatorModule, /useGroupedReorder/);
assert.match(calculatorModule, /calculator-drag-handle/);
assert.match(calculatorModule, /scrollResults/); assert.match(calculatorModule, /scrollResults/);
assert.match(calculatorModule, /tool-split-scroll-toggle/); assert.match(calculatorModule, /tool-split-scroll-toggle/);
assert.match(calculatorModule, /EditableCalculatorLabel/); 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, /categoryOrder/);
assert.match(taskPlannerModule, /categoryLabel/); assert.match(taskPlannerModule, /categoryLabel/);
assert.match(taskPlannerModule, /task-planner-warning/); 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, /export function ChecklistModule/);
assert.match(checklistModule, /TextImportModal/); assert.match(checklistModule, /TextImportModal/);
assert.match(checklistModule, /Icon name="import"/); 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, /Number\.parseInt/);
assert.match(checklistModule, /checklist-qty-current/); assert.match(checklistModule, /checklist-qty-current/);
assert.match(checklistModule, /checklist-delete-button danger/); assert.match(checklistModule, /checklist-delete-button danger/);
assert.doesNotMatch(checklistModule, /useGroupedReorder/);
assert.match(textImportModal, /createPortal/); assert.match(textImportModal, /createPortal/);
assert.match(textImportModal, /lockBodyScroll/); assert.match(textImportModal, /lockBodyScroll/);
assert.match(imagesModule, /export function ImagesModule/); assert.match(imagesModule, /export function ImagesModule/);
assert.match(imagesModule, /useGroupedReorder/);
assert.match(imagesModule, /orientation: "horizontal"/);
assert.match(imagesModule, /editing &&/); assert.match(imagesModule, /editing &&/);
assert.match(imagesModule, /clipboardData/); assert.match(imagesModule, /clipboardData/);
assert.match(imagesModule, /createImageAnnotationModule/); 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, /copyText/);
assert.match(linksModule, /parseColonImportLines/); assert.match(linksModule, /parseColonImportLines/);
assert.match(linksModule, /context\.normalizeUrl/); assert.match(linksModule, /context\.normalizeUrl/);
assert.match(linksModule, /useGroupedReorder/);
assert.match(linksModule, /link-drag-handle/);
assert.match(countersModule, /export function CountersModule/); assert.match(countersModule, /export function CountersModule/);
assert.match(countersModule, /editing &&/); assert.match(countersModule, /editing &&/);
assert.match(countersModule, /counter-actions/); 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, /export function parseColonImportLines/);
assert.match(textImport, /line\.indexOf\(":\"\)/); assert.match(textImport, /line\.indexOf\(":\"\)/);
assert.match(imageViewer, /image-viewer-media/); assert.match(imageViewer, /image-viewer-media/);

View file

@ -5,6 +5,7 @@ import { evaluateTableCell } from "../website/src/features/toolboxes/modules/tab
import { parseColonImportLines } from "../website/src/features/toolboxes/modules/textImport.js"; import { parseColonImportLines } from "../website/src/features/toolboxes/modules/textImport.js";
import { getTimePatternRecurrenceMs, getTimePatternTargetMs } from "../website/src/features/toolboxes/modules/timerUtils.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 { 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", () => { test("colon text import keeps urls intact after the first separator", () => {
assert.deepEqual(parseColonImportLines("Build:https://example.com/build?class=rogue\nPotion:10"), [ 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); 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", () => { test("combos storage normalizes devices, steps and compact export ids", () => {
const longText = "x".repeat(120); const longText = "x".repeat(120);
const normalized = normalizeCombosData({ const normalized = normalizeCombosData({

View file

@ -20,25 +20,23 @@ export function formatDate(value) {
return new Intl.DateTimeFormat("fr-FR", { dateStyle: "medium", timeStyle: "short" }).format(new Date(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 gameCoverImage = getGameCardCover(game);
const coverImage = gameCoverImage || toolbox.icon || DEFAULT_TOOLBOX_ICON; const coverImage = gameCoverImage || toolbox.icon || DEFAULT_TOOLBOX_ICON;
const isDragging = draggingToolboxId === toolbox.id;
const isDropTarget = dropTarget.id === toolbox.id;
const className = [ const className = [
"card", "card",
"toolbox-card", "toolbox-card",
isDragging ? "is-dragging" : "", reorder.isItemDragging(toolbox.id) ? "is-dragging" : "",
isDropTarget ? "is-drop-target" : "", reorder.isItemDropTarget(toolbox.id) ? "is-drop-target" : "",
isDropTarget && dropTarget.placement === "after" ? "drop-after" : "" reorder.getDropPlacement("item", toolbox.id) === "after" ? "drop-after" : ""
].filter(Boolean).join(" "); ].filter(Boolean).join(" ");
return ( return (
<article className={className} data-toolbox-id={toolbox.id}> <article className={className} {...reorder.getItemProps({ itemId: toolbox.id })}>
<button <button
className="toolbox-card-drag-handle" className="toolbox-card-drag-handle"
type="button" type="button"
onPointerDown={(event) => onDragStart(event, toolbox.id)} onPointerDown={(event) => reorder.itemReorder.startDrag(event, toolbox.id)}
aria-label={`Déplacer ${toolbox.name}`} aria-label={`Déplacer ${toolbox.name}`}
title="Déplacer" title="Déplacer"
> >

View file

@ -4,7 +4,7 @@ import { Icon } from "../../components/Icon.jsx";
import { ImportButton } from "../../components/ImportButton.jsx"; import { ImportButton } from "../../components/ImportButton.jsx";
import { StorageQuota } from "../../components/StorageQuota.jsx"; import { StorageQuota } from "../../components/StorageQuota.jsx";
import { ToastPositionSwitch } from "../../components/ToastPositionSwitch.jsx"; import { ToastPositionSwitch } from "../../components/ToastPositionSwitch.jsx";
import { usePointerReorder } from "../../hooks/usePointerReorder.js"; import { useGroupedReorder } from "../../hooks/useGroupedReorder.js";
import { compressImage } from "../../utils/imageCompression.js"; import { compressImage } from "../../utils/imageCompression.js";
import { getSetting as dbGetSetting, setSetting as dbSetSetting } from "../../utils/indexedDbStorage.js"; import { getSetting as dbGetSetting, setSetting as dbSetSetting } from "../../utils/indexedDbStorage.js";
import { getGameCardCover, ToolboxCard, ToolboxGameIcon, ToolboxIconPicker } from "./ToolboxCard.jsx"; import { getGameCardCover, ToolboxCard, ToolboxGameIcon, ToolboxIconPicker } from "./ToolboxCard.jsx";
@ -40,20 +40,24 @@ async function copyText(value) {
export function ToolboxesPage({ siteContent, toolboxes, getToolboxGame, actions, storageUsage, toastPosition, setToastPosition }) { export function ToolboxesPage({ siteContent, toolboxes, getToolboxGame, actions, storageUsage, toastPosition, setToastPosition }) {
const content = siteContent.toolboxes; const content = siteContent.toolboxes;
const { const {
draggingId: draggingToolboxId, itemReorder,
dropTarget, getItemProps,
startDrag: startToolboxDrag isItemDragging,
} = usePointerReorder({ isItemDropTarget,
targetSelector: ".toolbox-card", getDropPlacement
getTargetId: (target) => target.dataset.toolboxId, } = useGroupedReorder({
namespace: "toolbox-cards",
items: toolboxes,
getItemId: (toolbox) => toolbox.id,
orientation: "horizontal",
getPlacement: (event, target) => { getPlacement: (event, target) => {
const rect = target.getBoundingClientRect(); const rect = target.getBoundingClientRect();
return event.clientY > rect.top + rect.height / 2 || event.clientX > rect.left + rect.width / 2 ? "after" : "before"; return event.clientY > rect.top + rect.height / 2 || event.clientX > rect.left + rect.width / 2 ? "after" : "before";
}, },
onMove: (draggingId, targetId, placement) => { onItemMove: (operation) => {
const nextIds = toolboxes.map((toolbox) => toolbox.id).filter((id) => id !== draggingId); const nextIds = toolboxes.map((toolbox) => toolbox.id).filter((id) => id !== operation.sourceId);
const targetIndex = nextIds.indexOf(targetId); const targetIndex = nextIds.indexOf(operation.targetId);
nextIds.splice(placement === "after" ? targetIndex + 1 : targetIndex, 0, draggingId); nextIds.splice(operation.placement === "after" ? targetIndex + 1 : targetIndex, 0, operation.sourceId);
actions.updateToolboxOrder(nextIds); actions.updateToolboxOrder(nextIds);
} }
}); });
@ -100,9 +104,7 @@ export function ToolboxesPage({ siteContent, toolboxes, getToolboxGame, actions,
toolbox={toolbox} toolbox={toolbox}
game={getToolboxGame(toolbox)} game={getToolboxGame(toolbox)}
actions={actions} actions={actions}
draggingToolboxId={draggingToolboxId} reorder={{ itemReorder, getItemProps, isItemDragging, isItemDropTarget, getDropPlacement }}
dropTarget={dropTarget}
onDragStart={startToolboxDrag}
/> />
)) : ( )) : (
<div className="empty"><h2>{content.emptyTitle}</h2><p>{content.emptyText}</p></div> <div className="empty"><h2>{content.emptyTitle}</h2><p>{content.emptyText}</p></div>

View file

@ -1,6 +1,7 @@
// Rôle : fournit l'outil calculateur avec résultats enregistrés en arborescence. // Rôle : fournit l'outil calculateur avec résultats enregistrés en arborescence.
import { useLayoutEffect, useMemo, useRef, useState } from "react"; import { useLayoutEffect, useMemo, useRef, useState } from "react";
import { Icon } from "../../../components/Icon.jsx"; import { Icon } from "../../../components/Icon.jsx";
import { moveItem, useGroupedReorder } from "../../../hooks/useGroupedReorder.js";
function calculateExpression(expression) { function calculateExpression(expression) {
const normalized = String(expression || "").replaceAll(",", ".").trim(); const normalized = String(expression || "").replaceAll(",", ".").trim();
@ -43,6 +44,17 @@ export function CalculatorModule({ toolboxId, moduleId, context }) {
const calculatorCardRef = useRef(null); const calculatorCardRef = useRef(null);
const result = useMemo(() => calculateExpression(expression), [expression]); const result = useMemo(() => calculateExpression(expression), [expression]);
const activeParent = data.entries.find((entry) => entry.id === activeParentId); const activeParent = data.entries.find((entry) => entry.id === activeParentId);
const scopeParentId = (parentId = "") => `${moduleId}:${parentId}`;
const reorder = useGroupedReorder({
namespace: "calculator",
items: data.entries,
getItemId: (entry) => entry.id,
getParentId: (entry) => scopeParentId(entry.parentId || ""),
onItemMove: (operation) => {
save(moveItem(data.entries, operation.sourceId, operation.targetId, operation.placement));
},
hierarchy: { enabled: true, stickyParents: true }
});
useLayoutEffect(() => { useLayoutEffect(() => {
const element = calculatorCardRef.current; const element = calculatorCardRef.current;
@ -165,7 +177,7 @@ export function CalculatorModule({ toolboxId, moduleId, context }) {
</div> </div>
<div className={`tool-split-tree calculator-tree ${data.scrollResults ? "is-scrollable legacy-scrollbar" : ""}`}> <div className={`tool-split-tree calculator-tree ${data.scrollResults ? "is-scrollable legacy-scrollbar" : ""}`}>
{data.entries.length ? ( {data.entries.length ? (
<CalculatorEntries entries={data.entries} parentId="" activeParentId={activeParentId} textContent={textContent} onUse={useEntry} onRename={renameEntry} onDelete={deleteEntry} /> <CalculatorEntries entries={data.entries} parentId="" getScopedParentId={scopeParentId} activeParentId={activeParentId} textContent={textContent} reorder={reorder} onUse={useEntry} onRename={renameEntry} onDelete={deleteEntry} />
) : ( ) : (
<p className="muted">{textContent.emptyResults || "Aucun résultat enregistré."}</p> <p className="muted">{textContent.emptyResults || "Aucun résultat enregistré."}</p>
)} )}
@ -175,16 +187,34 @@ export function CalculatorModule({ toolboxId, moduleId, context }) {
); );
} }
function CalculatorEntries({ entries, parentId, activeParentId, textContent, onUse, onRename, onDelete }) { function CalculatorEntries({ entries, parentId, getScopedParentId, activeParentId, textContent, reorder, onUse, onRename, onDelete }) {
const children = getChildren(entries, parentId); const children = getChildren(entries, parentId);
const [editingId, setEditingId] = useState(""); const [editingId, setEditingId] = useState("");
if (!children.length) return null; if (!children.length) return null;
return ( return (
<ul className="tool-split-entry-list calculator-entry-list"> <ul className="tool-split-entry-list calculator-entry-list">
{children.map((entry) => ( {children.map((entry) => {
<li className={`${entry.id === activeParentId ? "active" : ""} ${entry.id === editingId ? "is-editing" : ""}`} key={entry.id}> const className = [
<div className="tool-split-entry calculator-entry"> entry.id === activeParentId ? "active" : "",
entry.id === editingId ? "is-editing" : "",
reorder.isItemDragging(entry.id) ? "is-dragging" : "",
reorder.isItemDropTarget(entry.id) ? "is-drop-target" : "",
reorder.getDropPlacement("item", entry.id, parentId) === "after" ? "drop-after" : ""
].filter(Boolean).join(" ");
return (
<li className={className} key={entry.id} {...reorder.getItemProps({ itemId: entry.id, parentId: getScopedParentId(parentId) })}>
<div className="tool-split-entry calculator-entry has-drag-handle">
<button
className="calculator-drag-handle"
type="button"
onPointerDown={(event) => reorder.itemReorder.startDrag(event, entry.id)}
aria-label={`${textContent.reorderTitle || "Déplacer"} ${entry.label || formatResult(entry.value)}`}
title={textContent.reorderTitle || "Déplacer"}
>
<Icon name="drag" />
</button>
{entry.id === editingId ? ( {entry.id === editingId ? (
<> <>
<span className="tool-split-entry-value is-readonly" title={textContent.readonlyValueTitle || "Quantité non modifiable"}> <span className="tool-split-entry-value is-readonly" title={textContent.readonlyValueTitle || "Quantité non modifiable"}>
@ -204,9 +234,10 @@ function CalculatorEntries({ entries, parentId, activeParentId, textContent, onU
<Icon name="trash" /> <Icon name="trash" />
</button> </button>
</div> </div>
<CalculatorEntries entries={entries} parentId={entry.id} activeParentId={activeParentId} textContent={textContent} onUse={onUse} onRename={onRename} onDelete={onDelete} /> <CalculatorEntries entries={entries} parentId={entry.id} getScopedParentId={getScopedParentId} activeParentId={activeParentId} textContent={textContent} reorder={reorder} onUse={onUse} onRename={onRename} onDelete={onDelete} />
</li> </li>
))} );
})}
</ul> </ul>
); );
} }

View file

@ -1,11 +1,11 @@
// Rôle : fournit l'outil Combos avec palettes d'inputs et rendu visuel par périphérique. // Rôle : fournit l'outil Combos avec palettes d'inputs et rendu visuel par périphérique.
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { Icon } from "../../../components/Icon.jsx"; import { Icon } from "../../../components/Icon.jsx";
import { usePointerReorder } from "../../../hooks/usePointerReorder.js"; import {
applyGroupedReorderOperation,
const UNCATEGORIZED_DROP_ID = "combos:uncategorized"; getGroupedEntries,
const CATEGORY_SECTION_PREFIX = "combos:category"; useGroupedReorder
const CATEGORY_BOUNDARY_DROP_PREFIX = "combos:category-boundary"; } from "../../../hooks/useGroupedReorder.js";
const DEVICE_OPTIONS = [ const DEVICE_OPTIONS = [
{ value: "playstation", label: "PlayStation" }, { value: "playstation", label: "PlayStation" },
@ -142,358 +142,13 @@ function getComboCategory(combo) {
return String(combo?.category || "").trim(); return String(combo?.category || "").trim();
} }
function getCategoryGroups(combos, categoryOrder) { function setComboCategory(combo, category) {
const categories = []; const nextCombo = { ...combo };
combos.forEach((combo) => { if (category) nextCombo.category = category;
const category = getComboCategory(combo); else delete nextCombo.category;
if (category && !categories.includes(category)) categories.push(category); return nextCombo;
});
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 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 }) { function ComboInputToken({ input, device, palette = false, onClick, onDragStart }) {
const label = getInputLabel(input); 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 paletteGroups = useMemo(() => getPaletteGroups(data.device, keyboardLayout), [data.device, keyboardLayout]);
const paletteColumns = useMemo(() => getPaletteColumns(paletteGroups), [paletteGroups]); const paletteColumns = useMemo(() => getPaletteColumns(paletteGroups), [paletteGroups]);
const cleanDraftInputs = draftInputs.map((step) => step.filter(Boolean)).filter((step) => step.length); const cleanDraftInputs = draftInputs.map((step) => step.filter(Boolean)).filter((step) => step.length);
const entries = getCategoryGroups(data.combos, data.categoryOrder); const entries = getGroupedEntries(data.combos, {
const { groupOrder: data.categoryOrder,
draggingId: draggingCategoryId, getItemGroup: getComboCategory,
dropTarget: categoryDropTarget, groupIdKey: "category",
startDrag: startCategoryDrag groupItemKey: "combos"
} = usePointerReorder({
targetSelector: ".combos-category, .combo-card, .combos-root-drop-zone, .combos-category-boundary-drop-zone",
getTargetId: getCategoryTargetId,
canDropOn: canDropCategoryOnTarget,
getPlacement: getCategoryDropPlacement,
onMove: moveCategory
}); });
const { const {
draggingId: draggingComboId, itemReorder,
dropTarget: comboDropTarget, groupReorder,
startDrag: startComboDrag getItemProps,
} = usePointerReorder({ getGroupProps,
targetSelector: ".combo-card, .combos-category, .combos-root-drop-zone, .combos-category-boundary-drop-zone", getGroupBoundaryProps,
getTargetId: getComboTargetId, isItemDragging,
canDropOn: (target, draggingId) => canDropComboOnTarget(target, draggingId, data.combos), isItemDropTarget,
getPlacement: getComboDropPlacement, isGroupDragging,
onMove: moveCombo 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) { function save(nextData) {
@ -666,39 +339,15 @@ export function CombosModule({ toolboxId, moduleId, context, editing }) {
}); });
} }
function moveCategory(fromId, toId, placement) { function applyComboReorder(operation) {
const fromCategory = parseCategorySectionId(fromId); save(applyGroupedReorderOperation(data, {
const movingIds = getCategoryComboIds(data.combos, fromCategory); operation,
if (!movingIds.length) return; itemsKey: "combos",
if (isUncategorizedDropId(toId) || isCategoryBoundaryDropId(toId)) { groupOrderKey: "categoryOrder",
save(moveCategoryBoundary(data, fromCategory, toId)); collapsedGroupsKey: "collapsedCategories",
return; getItemGroup: getComboCategory,
} setItemGroup: setComboCategory
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 addInputToStep(kind, value, stepIndex) { function addInputToStep(kind, value, stepIndex) {
@ -880,16 +529,16 @@ export function CombosModule({ toolboxId, moduleId, context, editing }) {
const comboClassName = [ const comboClassName = [
"combo-card", "combo-card",
"is-editing", "is-editing",
draggingComboId === combo.id ? "is-dragging" : "", isItemDragging(combo.id) ? "is-dragging" : "",
comboDropTarget.id === combo.id || categoryDropTarget.id === combo.id ? "is-drop-target" : "", isItemDropTarget(combo.id) ? "is-drop-target" : "",
(comboDropTarget.id === combo.id && comboDropTarget.placement === "after") || (categoryDropTarget.id === combo.id && categoryDropTarget.placement === "after") ? "drop-after" : "" getDropPlacement("item", combo.id) === "after" ? "drop-after" : ""
].filter(Boolean).join(" "); ].filter(Boolean).join(" ");
return ( return (
<article className={comboClassName} key={combo.id} data-combo-id={combo.id} data-combo-category={category}> <article className={comboClassName} key={combo.id} {...getItemProps({ itemId: combo.id, groupId: category })}>
<button <button
className="task-planner-drag-handle combo-drag-handle" className="task-planner-drag-handle combo-drag-handle"
type="button" type="button"
onPointerDown={(event) => startComboDrag(event, combo.id)} onPointerDown={(event) => itemReorder.startDrag(event, combo.id)}
aria-label={`${textContent.reorderComboTitle || "Déplacer le combo"} ${combo.name}`} aria-label={`${textContent.reorderComboTitle || "Déplacer le combo"} ${combo.name}`}
title={textContent.reorderComboTitle || "Déplacer le combo"} title={textContent.reorderComboTitle || "Déplacer le combo"}
> >
@ -918,41 +567,38 @@ export function CombosModule({ toolboxId, moduleId, context, editing }) {
function renderCategory(group) { function renderCategory(group) {
const category = group.category; const category = group.category;
const categoryId = getCategorySectionId(category);
const beforeDropId = getCategoryBoundaryDropId(category, "before");
const afterDropId = getCategoryBoundaryDropId(category, "after");
const isCollapsed = data.collapsedCategories.includes(category); const isCollapsed = data.collapsedCategories.includes(category);
const categoryClassName = [ const categoryClassName = [
"combos-category checklist-section is-grouped", "combos-category checklist-section is-grouped",
isCollapsed ? "is-collapsed" : "", isCollapsed ? "is-collapsed" : "",
draggingCategoryId === categoryId ? "is-dragging" : "", isGroupDragging(category) ? "is-dragging" : "",
categoryDropTarget.id === categoryId || comboDropTarget.id === categoryId ? "is-drop-target" : "", isGroupDropTarget(category) ? "is-drop-target" : "",
(categoryDropTarget.id === categoryId && categoryDropTarget.placement === "after") || (comboDropTarget.id === categoryId && comboDropTarget.placement === "after") ? "drop-after" : "" getDropPlacement("group", category) === "after" ? "drop-after" : ""
].filter(Boolean).join(" "); ].filter(Boolean).join(" ");
const showBoundaryDropZones = Boolean(draggingComboId || draggingCategoryId); const showBoundaryDropZones = shouldShowGroupBoundaries();
const beforeDropZone = showBoundaryDropZones ? ( const beforeDropZone = showBoundaryDropZones ? (
<div <div
className={`combos-category-boundary-drop-zone ${getDropEdgeClass(categoryDropTarget, comboDropTarget, category, "start")}`} className={`combos-category-boundary-drop-zone ${isBoundaryDropTarget({ groupId: category, placement: "before" }) ? "is-drop-target" : ""}`}
key={`${category}:before-drop`} key={`${category}:before-drop`}
data-drop-id={beforeDropId} {...getGroupBoundaryProps({ groupId: category, placement: "before" })}
/> />
) : null; ) : null;
const afterDropZone = showBoundaryDropZones ? ( const afterDropZone = showBoundaryDropZones ? (
<div <div
className={`combos-category-boundary-drop-zone ${getDropEdgeClass(categoryDropTarget, comboDropTarget, category, "end")}`} className={`combos-category-boundary-drop-zone ${isBoundaryDropTarget({ groupId: category, placement: "after" }) ? "is-drop-target" : ""}`}
key={`${category}:after-drop`} key={`${category}:after-drop`}
data-drop-id={afterDropId} {...getGroupBoundaryProps({ groupId: category, placement: "after" })}
/> />
) : null; ) : null;
return [ return [
beforeDropZone, beforeDropZone,
<section className={categoryClassName} key={category} data-category={category}> <section className={categoryClassName} key={category} {...getGroupProps({ groupId: category })}>
<div className="checklist-section-header combos-category-header"> <div className="checklist-section-header combos-category-header">
<div className="combos-category-title"> <div className="combos-category-title">
<button <button
className="task-planner-category-drag-handle" className="task-planner-category-drag-handle"
type="button" type="button"
onPointerDown={(event) => startCategoryDrag(event, categoryId)} onPointerDown={(event) => groupReorder.startDrag(event, { groupId: category })}
aria-label={`${textContent.reorderCategoryTitle || "Déplacer la catégorie"} ${category}`} aria-label={`${textContent.reorderCategoryTitle || "Déplacer la catégorie"} ${category}`}
title={textContent.reorderCategoryTitle || "Déplacer la catégorie"} title={textContent.reorderCategoryTitle || "Déplacer la catégorie"}
> >
@ -984,17 +630,6 @@ export function CombosModule({ toolboxId, moduleId, context, editing }) {
]; ];
} }
function renderUncategorizedDropZone() {
const draggingCombo = draggingComboId ? data.combos.find((combo) => combo.id === draggingComboId) : null;
const draggingCategory = parseCategorySectionId(draggingCategoryId);
if ((!draggingCombo || !getComboCategory(draggingCombo)) && !draggingCategory) return null;
return (
<div className={`combos-root-drop-zone is-visible ${comboDropTarget.id === UNCATEGORIZED_DROP_ID || categoryDropTarget.id === UNCATEGORIZED_DROP_ID ? "is-drop-target" : ""}`} data-drop-id={UNCATEGORIZED_DROP_ID}>
{textContent.noCategoryLabel || "Sans catégorie"}
</div>
);
}
return ( return (
<div className="combos-module"> <div className="combos-module">
{(editing || editingComboId) && ( {(editing || editingComboId) && (
@ -1115,8 +750,7 @@ export function CombosModule({ toolboxId, moduleId, context, editing }) {
)} )}
<div className="combos-category-list"> <div className="combos-category-list">
{renderUncategorizedDropZone()} {entries.map((entry) => entry.type === "group" ? renderCategory(entry.group) : renderCombo(entry.item))}
{entries.map((entry) => entry.type === "category" ? renderCategory(entry.group) : renderCombo(entry.combo))}
</div> </div>
</div> </div>
); );

View file

@ -1,11 +1,27 @@
// Rôle : fournit l'outil compteurs personnalisables. // Rôle : fournit l'outil compteurs personnalisables.
import { useState } from "react"; import { useState } from "react";
import { Icon } from "../../../components/Icon.jsx"; import { Icon } from "../../../components/Icon.jsx";
import { moveItem, useGroupedReorder } from "../../../hooks/useGroupedReorder.js";
export function CountersModule({ toolboxId, moduleId, context, editing }) { export function CountersModule({ toolboxId, moduleId, context, editing }) {
const data = context.normalizeCountersData(context.getModuleData(toolboxId, moduleId, { counters: [] })); const data = context.normalizeCountersData(context.getModuleData(toolboxId, moduleId, { counters: [] }));
const textContent = context.moduleText?.counters || {}; const textContent = context.moduleText?.counters || {};
const [label, setLabel] = useState(""); const [label, setLabel] = useState("");
const {
itemReorder,
getItemProps,
isItemDragging,
isItemDropTarget,
getDropPlacement
} = useGroupedReorder({
namespace: "counters",
items: data.counters,
getItemId: (counter) => counter.id,
getParentId: () => moduleId,
orientation: "horizontal",
onItemMove: (operation) => save(moveItem(data.counters, operation.sourceId, operation.targetId, operation.placement)),
hierarchy: { enabled: true, stickyParents: true }
});
function save(counters) { function save(counters) {
context.setModuleData(toolboxId, moduleId, { counters }); context.setModuleData(toolboxId, moduleId, { counters });
@ -33,8 +49,25 @@ export function CountersModule({ toolboxId, moduleId, context, editing }) {
</form> </form>
)} )}
<div className="counters-grid"> <div className="counters-grid">
{data.counters.map((counter) => ( {data.counters.map((counter) => {
<article className="counter-item" key={counter.id}> const className = [
"counter-item",
isItemDragging(counter.id) ? "is-dragging" : "",
isItemDropTarget(counter.id) ? "is-drop-target" : "",
getDropPlacement("item", counter.id) === "after" ? "drop-after" : ""
].filter(Boolean).join(" ");
return (
<article className={className} key={counter.id} {...getItemProps({ itemId: counter.id, parentId: moduleId })}>
<button
className="counter-drag-handle"
type="button"
onPointerDown={(event) => itemReorder.startDrag(event, counter.id)}
aria-label={`${textContent.reorderTitle || "Déplacer"} ${counter.label}`}
title={textContent.reorderTitle || "Déplacer"}
>
<Icon name="drag" />
</button>
<div> <div>
<strong>{counter.value}</strong> <strong>{counter.value}</strong>
<span>{counter.label}</span> <span>{counter.label}</span>
@ -50,7 +83,8 @@ export function CountersModule({ toolboxId, moduleId, context, editing }) {
</button> </button>
</div> </div>
</article> </article>
))} );
})}
</div> </div>
</> </>
); );

View file

@ -1,7 +1,7 @@
// Rôle : fournit l'outil images avec import, collage, libellés et annotation rapide. // Rôle : fournit l'outil images avec import, collage, libellés et annotation rapide.
import { useState } from "react"; import { useState } from "react";
import { Icon } from "../../../components/Icon.jsx"; 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 }) { export function ImagesModule({ toolboxId, moduleId, context, editing }) {
const data = context.getModuleData(toolboxId, moduleId, { images: [] }); const data = context.getModuleData(toolboxId, moduleId, { images: [] });
@ -9,24 +9,23 @@ export function ImagesModule({ toolboxId, moduleId, context, editing }) {
const [dragOver, setDragOver] = useState(false); const [dragOver, setDragOver] = useState(false);
const pastePlaceholder = textContent.pastePlaceholder || "Coller une image ici"; const pastePlaceholder = textContent.pastePlaceholder || "Coller une image ici";
const { const {
draggingId: draggingImageId, itemReorder,
dropTarget, getItemProps,
startDrag isItemDragging,
} = usePointerReorder({ isItemDropTarget,
targetSelector: "[data-image-id]", getDropPlacement
getTargetId: (target) => target.dataset.imageId, } = useGroupedReorder({
canDropOn: (target) => target.dataset.imageModuleId === moduleId, namespace: "images",
getPlacement: (event, target) => { items: data.images,
const rect = target.getBoundingClientRect(); getItemId: (image) => image.id,
return event.clientX > rect.left + rect.width / 2 ? "after" : "before"; getParentId: () => moduleId,
orientation: "horizontal",
onItemMove: (operation) => {
context.setModuleData(toolboxId, moduleId, {
images: moveItem(data.images, operation.sourceId, operation.targetId, operation.placement)
});
}, },
onMove: (draggingId, targetId, placement) => { hierarchy: { enabled: true, stickyParents: true }
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) });
}
}); });
async function addFiles(files) { async function addFiles(files) {
@ -90,20 +89,18 @@ export function ImagesModule({ toolboxId, moduleId, context, editing }) {
)} )}
<div className="images"> <div className="images">
{data.images.map((image) => { {data.images.map((image) => {
const isDragging = draggingImageId === image.id;
const isDropTarget = dropTarget.id === image.id;
const className = [ const className = [
isDragging ? "is-dragging" : "", isItemDragging(image.id) ? "is-dragging" : "",
isDropTarget ? "is-drop-target" : "", isItemDropTarget(image.id) ? "is-drop-target" : "",
isDropTarget && dropTarget.placement === "after" ? "drop-after" : "" getDropPlacement("item", image.id) === "after" ? "drop-after" : ""
].filter(Boolean).join(" "); ].filter(Boolean).join(" ");
return ( return (
<figure key={image.id} className={className} data-image-id={image.id} data-image-module-id={moduleId}> <figure key={image.id} className={className} {...getItemProps({ itemId: image.id, parentId: moduleId })}>
<button <button
className="image-drag-handle" className="image-drag-handle"
type="button" type="button"
onPointerDown={(event) => startDrag(event, image.id)} onPointerDown={(event) => itemReorder.startDrag(event, image.id)}
aria-label={textContent.reorderAriaLabel || "Déplacer l'image"} aria-label={textContent.reorderAriaLabel || "Déplacer l'image"}
title={textContent.reorderTitle || "Déplacer"} title={textContent.reorderTitle || "Déplacer"}
> >

View file

@ -1,6 +1,7 @@
// Rôle : fournit l'outil liens avec ajout manuel et import texte. // Rôle : fournit l'outil liens avec ajout manuel et import texte.
import { useCallback, useState } from "react"; import { useCallback, useState } from "react";
import { Icon } from "../../../components/Icon.jsx"; import { Icon } from "../../../components/Icon.jsx";
import { moveItem, useGroupedReorder } from "../../../hooks/useGroupedReorder.js";
import { TextImportModal } from "./TextImportModal.jsx"; import { TextImportModal } from "./TextImportModal.jsx";
import { parseColonImportLines } from "./textImport.js"; import { parseColonImportLines } from "./textImport.js";
@ -13,6 +14,20 @@ export function LinksModule({ toolboxId, moduleId, context, editing }) {
const [importOpen, setImportOpen] = useState(false); const [importOpen, setImportOpen] = useState(false);
const [copiedId, setCopiedId] = useState(""); const [copiedId, setCopiedId] = useState("");
const closeImportModal = useCallback(() => setImportOpen(false), []); const closeImportModal = useCallback(() => setImportOpen(false), []);
const {
itemReorder,
getItemProps,
isItemDragging,
isItemDropTarget,
getDropPlacement
} = useGroupedReorder({
namespace: "links",
items: data.links,
getItemId: (link) => link.id,
getParentId: () => moduleId,
onItemMove: (operation) => save(moveItem(data.links, operation.sourceId, operation.targetId, operation.placement)),
hierarchy: { enabled: true, stickyParents: true }
});
function save(links) { function save(links) {
context.setModuleData(toolboxId, moduleId, { links }); context.setModuleData(toolboxId, moduleId, { links });
@ -88,8 +103,25 @@ export function LinksModule({ toolboxId, moduleId, context, editing }) {
/> />
)} )}
<ul className="links-list"> <ul className="links-list">
{data.links.map((link) => ( {data.links.map((link) => {
<li className="link-item" key={link.id}> const className = [
"link-item",
isItemDragging(link.id) ? "is-dragging" : "",
isItemDropTarget(link.id) ? "is-drop-target" : "",
getDropPlacement("item", link.id) === "after" ? "drop-after" : ""
].filter(Boolean).join(" ");
return (
<li className={className} key={link.id} {...getItemProps({ itemId: link.id, parentId: moduleId })}>
<button
className="link-drag-handle"
type="button"
onPointerDown={(event) => itemReorder.startDrag(event, link.id)}
aria-label={`${textContent.reorderTitle || "Déplacer"} ${link.title || link.url}`}
title={textContent.reorderTitle || "Déplacer"}
>
<Icon name="drag" />
</button>
<a href={link.url} target="_blank" rel="noreferrer" title={link.url}> <a href={link.url} target="_blank" rel="noreferrer" title={link.url}>
<strong>{link.title || context.hostnameFromUrl(link.url)}</strong> <strong>{link.title || context.hostnameFromUrl(link.url)}</strong>
<span>{link.url}</span> <span>{link.url}</span>
@ -103,7 +135,8 @@ export function LinksModule({ toolboxId, moduleId, context, editing }) {
</button> </button>
</div> </div>
</li> </li>
))} );
})}
</ul> </ul>
</> </>
); );

View file

@ -2,11 +2,9 @@
import { useEffect, useMemo, useRef, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import { Icon } from "../../../components/Icon.jsx"; import { Icon } from "../../../components/Icon.jsx";
import { InlineNotice } from "../../../components/AppOverlays.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 TASK_TYPES = ["daily", "weekly", "unique"];
const UNCATEGORIZED_DROP_ID = "task-planner:uncategorized";
const CATEGORY_BOUNDARY_DROP_PREFIX = "task-planner:category-boundary";
const WEEK_DAYS = [ const WEEK_DAYS = [
{ value: 1, label: "Lundi" }, { value: 1, label: "Lundi" },
{ value: 2, label: "Mardi" }, { value: 2, label: "Mardi" },
@ -78,56 +76,12 @@ function moveTask(tasks, fromTaskId, toTaskId, placement = "before") {
return nextTasks; 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) { function getBoundaryTaskId(tasks, taskIds, placement) {
const ids = new Set(taskIds); const ids = new Set(taskIds);
const orderedTasks = tasks.filter((task) => ids.has(task.id)); const orderedTasks = tasks.filter((task) => ids.has(task.id));
return placement === "after" ? orderedTasks.at(-1)?.id || "" : orderedTasks[0]?.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) { function getTaskTitle(tasks, taskId) {
return tasks.find((task) => task.id === taskId)?.title || "Tâche supprimée"; 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) { function getRootTaskIdsForCategory(tasks, parentMap, category) {
return tasks return tasks
.filter((task) => !parentMap.get(task.id) && getTaskCategory(task) === category) .filter((task) => !parentMap.get(task.id) && getTaskCategory(task) === category)
.map((task) => task.id); .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 }) { export function TaskPlannerModule({ toolboxId, moduleId, context, editing }) {
const data = context.normalizeTaskPlannerData(context.getModuleData(toolboxId, moduleId, { tasks: [] })); const data = context.normalizeTaskPlannerData(context.getModuleData(toolboxId, moduleId, { tasks: [] }));
const textContent = context.moduleText?.taskPlanner || {}; const textContent = context.moduleText?.taskPlanner || {};
@ -322,32 +231,40 @@ export function TaskPlannerModule({ toolboxId, moduleId, context, editing }) {
const prerequisiteNoticeTimeouts = useRef(new Map()); const prerequisiteNoticeTimeouts = useRef(new Map());
const parentMap = useMemo(() => getTaskParentMap(data.tasks, data.relations), [data.tasks, data.relations]); const parentMap = useMemo(() => getTaskParentMap(data.tasks, data.relations), [data.tasks, data.relations]);
const { const {
draggingId, itemReorder,
dropTarget, groupReorder,
startDrag getItemProps,
} = usePointerReorder({ getGroupProps,
targetSelector: ".task-planner-item, .task-planner-category-section, .task-planner-uncategorized-drop-zone, .task-planner-category-boundary-drop-zone", getGroupBoundaryProps,
getTargetId: (target) => target.dataset.dropId || target.dataset.taskId || getCategorySectionId(target.dataset.parentId || "", target.dataset.category || ""), isItemDragging,
canDropOn: (target, draggingTaskId) => { isItemDropTarget,
const draggingTask = data.tasks.find((task) => task.id === draggingTaskId); isGroupDragging,
if (!draggingTask) return false; isGroupDropTarget,
const draggingParentId = parentMap.get(draggingTaskId) || ""; isBoundaryDropTarget,
const draggingCategory = getTaskCategoryDataset(draggingTask, data.tasks, parentMap); getDropPlacement,
if (target.classList.contains("task-planner-category-boundary-drop-zone")) { shouldShowGroupBoundaries
const boundary = parseCategoryBoundaryDropId(target.dataset.dropId); } = useGroupedReorder({
return !draggingParentId && !boundary.parentId && Boolean(boundary.category); 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); const fromTask = data.tasks.find((task) => task.id === fromTaskId);
if (!fromTask) return; if (!fromTask) return;
function setRootTaskCategory(tasks, category) { function setRootTaskCategory(tasks, category) {
@ -359,7 +276,7 @@ export function TaskPlannerModule({ toolboxId, moduleId, context, editing }) {
return nextTask; return nextTask;
}); });
} }
function moveToCategory(category) { function moveToCategory(category, placement = operation.placement) {
const nextTasks = setRootTaskCategory(data.tasks, category); const nextTasks = setRootTaskCategory(data.tasks, category);
const targetIds = category const targetIds = category
? getRootTaskIdsForCategory(data.tasks, parentMap, category).filter((taskId) => taskId !== fromTaskId) ? 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); const boundaryTaskId = getBoundaryTaskId(data.tasks, targetIds, placement);
save({ ...data, tasks: boundaryTaskId ? moveTask(nextTasks, fromTaskId, boundaryTaskId, placement) : nextTasks }); save({ ...data, tasks: boundaryTaskId ? moveTask(nextTasks, fromTaskId, boundaryTaskId, placement) : nextTasks });
} }
if (isUncategorizedDropId(toId)) { if (operation.targetType === "boundary") {
moveToCategory(""); const targetIds = getRootTaskIdsForCategory(data.tasks, parentMap, operation.targetGroup);
return; const boundaryTaskId = getBoundaryTaskId(data.tasks, targetIds, operation.placement);
}
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) return; if (!boundaryTaskId) return;
const sourceCategory = getTaskCategoryDataset(fromTask, data.tasks, parentMap); const sourceCategory = getTaskCategoryDataset(fromTask, data.tasks, parentMap);
const tasks = sourceCategory ? setRootTaskCategory(data.tasks, "") : data.tasks; 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; return;
} }
if (isCategorySectionId(toId)) { if (operation.targetType === "group") {
const targetCategory = parseCategorySectionId(toId).category; const targetCategory = operation.targetGroup;
const sourceCategory = getTaskCategoryDataset(fromTask, data.tasks, parentMap); const sourceCategory = getTaskCategoryDataset(fromTask, data.tasks, parentMap);
if (!sourceCategory) { if (!sourceCategory) {
const targetIds = getRootTaskIdsForCategory(data.tasks, parentMap, targetCategory); const targetIds = getRootTaskIdsForCategory(data.tasks, parentMap, targetCategory);
const boundaryTaskId = getBoundaryTaskId(data.tasks, targetIds, placement); const boundaryTaskId = getBoundaryTaskId(data.tasks, targetIds, operation.placement);
if (boundaryTaskId) save({ ...data, tasks: moveTask(data.tasks, fromTaskId, boundaryTaskId, placement) }); if (boundaryTaskId) save({ ...data, tasks: moveTask(data.tasks, fromTaskId, boundaryTaskId, operation.placement) });
return; return;
} }
moveToCategory(targetCategory); moveToCategory(targetCategory);
return; 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 targetCategory = targetTask ? getTaskCategoryDataset(targetTask, data.tasks, parentMap) : "";
const sourceCategory = getTaskCategoryDataset(fromTask, 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; const tasks = shouldChangeRootCategory ? setRootTaskCategory(data.tasks, targetCategory) : data.tasks;
save({ ...data, tasks: moveTask(tasks, fromTaskId, toId, placement) }); save({ ...data, tasks: moveTask(tasks, fromTaskId, operation.targetId, operation.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;
}, },
onMove: (fromId, toId, placement) => { onGroupMove: (operation) => {
const fromCategory = parseCategorySectionId(fromId).category; save(applyGroupedReorderOperation(data, {
const movingIds = getRootTaskIdsForCategory(data.tasks, parentMap, fromCategory); operation,
if (!movingIds.length) return; itemsKey: "tasks",
const rootCategories = getRootCategories(data.tasks, parentMap); groupOrderKey: "categoryOrder",
if (isUncategorizedDropId(toId)) { getItemGroup: (task) => parentMap.get(task.id) ? "" : getTaskCategory(task),
const targetIds = data.tasks setItemGroup: (task) => task
.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)); hierarchy: { enabled: true, stickyParents: true }
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) });
}
}); });
const reorder = {
itemReorder,
groupReorder,
getItemProps,
getGroupProps,
getGroupBoundaryProps,
isItemDragging,
isItemDropTarget,
isGroupDragging,
isGroupDropTarget,
isBoundaryDropTarget,
getDropPlacement,
shouldShowGroupBoundaries
};
function save(nextData) { function save(nextData) {
context.setModuleData(toolboxId, moduleId, nextData, "taskPlanner"); context.setModuleData(toolboxId, moduleId, nextData, "taskPlanner");
@ -684,16 +552,11 @@ export function TaskPlannerModule({ toolboxId, moduleId, context, editing }) {
parentMap={parentMap} parentMap={parentMap}
tasks={data.tasks} tasks={data.tasks}
data={data} data={data}
draggingId={draggingId} reorder={reorder}
dropTarget={dropTarget}
draggingCategoryId={draggingCategoryId}
categoryDropTarget={categoryDropTarget}
textContent={textContent} textContent={textContent}
openDescriptions={openDescriptions} openDescriptions={openDescriptions}
openTaskSettings={openTaskSettings} openTaskSettings={openTaskSettings}
prerequisiteNoticeTaskIds={prerequisiteNoticeTaskIds} prerequisiteNoticeTaskIds={prerequisiteNoticeTaskIds}
onDragStart={startDrag}
onCategoryDragStart={startCategoryDrag}
onToggleDescription={(taskId) => toggleSet(setOpenDescriptions, taskId)} onToggleDescription={(taskId) => toggleSet(setOpenDescriptions, taskId)}
onToggleSettings={(taskId) => toggleSet(setOpenTaskSettings, taskId)} onToggleSettings={(taskId) => toggleSet(setOpenTaskSettings, taskId)}
onPrerequisiteNotice={showPrerequisiteNotice} onPrerequisiteNotice={showPrerequisiteNotice}
@ -718,16 +581,11 @@ function TaskPlannerBranch({
parentMap, parentMap,
tasks, tasks,
data, data,
draggingId, reorder,
dropTarget,
draggingCategoryId,
categoryDropTarget,
textContent, textContent,
openDescriptions, openDescriptions,
openTaskSettings, openTaskSettings,
prerequisiteNoticeTaskIds, prerequisiteNoticeTaskIds,
onDragStart,
onCategoryDragStart,
onToggleDescription, onToggleDescription,
onToggleSettings, onToggleSettings,
onPrerequisiteNotice, onPrerequisiteNotice,
@ -744,16 +602,7 @@ function TaskPlannerBranch({
const children = [...groupedTasks.uncategorized, ...groupedTasks.categories.flatMap((group) => group.tasks)].filter((task) => !visited.has(task.id)); const children = [...groupedTasks.uncategorized, ...groupedTasks.categories.flatMap((group) => group.tasks)].filter((task) => !visited.has(task.id));
if (!children.length) return null; if (!children.length) return null;
const nextVisited = new Set([...visited, ...children.map((task) => task.id)]); const nextVisited = new Set([...visited, ...children.map((task) => task.id)]);
const draggingTask = draggingId ? getTaskById(tasks, draggingId) : null; const showCategoryBoundaryDropZones = !parentId && reorder.shouldShowGroupBoundaries({ parentId });
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)
);
function hasVisibleDescendants(taskId, seen = new Set()) { function hasVisibleDescendants(taskId, seen = new Set()) {
if (seen.has(taskId)) return false; if (seen.has(taskId)) return false;
@ -769,16 +618,11 @@ function TaskPlannerBranch({
parentMap={parentMap} parentMap={parentMap}
tasks={tasks} tasks={tasks}
data={data} data={data}
draggingId={draggingId} reorder={reorder}
dropTarget={dropTarget}
draggingCategoryId={draggingCategoryId}
categoryDropTarget={categoryDropTarget}
textContent={textContent} textContent={textContent}
openDescriptions={openDescriptions} openDescriptions={openDescriptions}
openTaskSettings={openTaskSettings} openTaskSettings={openTaskSettings}
prerequisiteNoticeTaskIds={prerequisiteNoticeTaskIds} prerequisiteNoticeTaskIds={prerequisiteNoticeTaskIds}
onDragStart={onDragStart}
onCategoryDragStart={onCategoryDragStart}
onToggleDescription={onToggleDescription} onToggleDescription={onToggleDescription}
onToggleSettings={onToggleSettings} onToggleSettings={onToggleSettings}
onPrerequisiteNotice={onPrerequisiteNotice} onPrerequisiteNotice={onPrerequisiteNotice}
@ -808,14 +652,11 @@ function TaskPlannerBranch({
data={data} data={data}
parentMap={parentMap} parentMap={parentMap}
parentId={parentId} parentId={parentId}
draggingId={draggingId} reorder={reorder}
dropTarget={dropTarget}
categoryDropTarget={categoryDropTarget}
textContent={textContent} textContent={textContent}
descriptionOpen={openDescriptions.has(task.id)} descriptionOpen={openDescriptions.has(task.id)}
settingsOpen={openTaskSettings.has(task.id)} settingsOpen={openTaskSettings.has(task.id)}
prerequisiteNoticeVisible={prerequisiteNoticeTaskIds.has(task.id)} prerequisiteNoticeVisible={prerequisiteNoticeTaskIds.has(task.id)}
onDragStart={onDragStart}
onToggleDescription={() => onToggleDescription(task.id)} onToggleDescription={() => onToggleDescription(task.id)}
onToggleSettings={() => onToggleSettings(task.id)} onToggleSettings={() => onToggleSettings(task.id)}
onPrerequisiteNotice={onPrerequisiteNotice} onPrerequisiteNotice={onPrerequisiteNotice}
@ -837,41 +678,38 @@ function TaskPlannerBranch({
if (data.hideCompleted && isTaskTreeComplete(groupTasks.map((task) => task.id), tasks, parentMap)) return null; if (data.hideCompleted && isTaskTreeComplete(groupTasks.map((task) => task.id), tasks, parentMap)) return null;
const groupCount = countTaskTree(groupTasks.map((task) => task.id), tasks, parentMap); const groupCount = countTaskTree(groupTasks.map((task) => task.id), tasks, parentMap);
const groupCompletedCount = countCompletedTaskTree(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 isCollapsed = data.collapsedCategories.includes(group.category);
const sectionClassName = [ const sectionClassName = [
"task-planner-category-section", "task-planner-category-section",
groupCompletedCount === groupCount ? "is-complete" : "", groupCompletedCount === groupCount ? "is-complete" : "",
isCollapsed ? "is-collapsed" : "", isCollapsed ? "is-collapsed" : "",
draggingCategoryId === categoryId ? "is-dragging" : "", reorder.isGroupDragging(group.category, parentId) ? "is-dragging" : "",
categoryDropTarget.id === categoryId || dropTarget.id === categoryId ? "is-drop-target" : "", reorder.isGroupDropTarget(group.category, parentId) ? "is-drop-target" : "",
(categoryDropTarget.id === categoryId && categoryDropTarget.placement === "after") || (dropTarget.id === categoryId && dropTarget.placement === "after") ? "drop-after" : "" reorder.getDropPlacement("group", group.category, parentId) === "after" ? "drop-after" : ""
].filter(Boolean).join(" "); ].filter(Boolean).join(" ");
const beforeDropZone = showCategoryBoundaryDropZones ? ( const beforeDropZone = showCategoryBoundaryDropZones ? (
<li <li
className={`task-planner-category-boundary-drop-zone ${dropTarget.id === beforeDropId || categoryDropTarget.id === beforeDropId ? "is-drop-target" : ""}`} className={`task-planner-category-boundary-drop-zone ${reorder.isBoundaryDropTarget({ groupId: group.category, parentId, placement: "before" }) ? "is-drop-target" : ""}`}
key={`${parentId || "root"}:${group.category}:before-drop`} key={`${parentId || "root"}:${group.category}:before-drop`}
data-drop-id={beforeDropId} {...reorder.getGroupBoundaryProps({ groupId: group.category, parentId, placement: "before" })}
/> />
) : null; ) : null;
const afterDropZone = showCategoryBoundaryDropZones ? ( const afterDropZone = showCategoryBoundaryDropZones ? (
<li <li
className={`task-planner-category-boundary-drop-zone ${dropTarget.id === afterDropId || categoryDropTarget.id === afterDropId ? "is-drop-target" : ""}`} className={`task-planner-category-boundary-drop-zone ${reorder.isBoundaryDropTarget({ groupId: group.category, parentId, placement: "after" }) ? "is-drop-target" : ""}`}
key={`${parentId || "root"}:${group.category}:after-drop`} key={`${parentId || "root"}:${group.category}:after-drop`}
data-drop-id={afterDropId} {...reorder.getGroupBoundaryProps({ groupId: group.category, parentId, placement: "after" })}
/> />
) : null; ) : null;
return [ return [
beforeDropZone, beforeDropZone,
<li className={sectionClassName} key={`${parentId || "root"}:${group.category}`} data-parent-id={parentId} data-category={group.category}> <li className={sectionClassName} key={`${parentId || "root"}:${group.category}`} {...reorder.getGroupProps({ groupId: group.category, parentId })}>
<div className="checklist-section-header task-planner-category-header"> <div className="checklist-section-header task-planner-category-header">
<div className="task-planner-category-title"> <div className="task-planner-category-title">
<button <button
className="task-planner-category-drag-handle" className="task-planner-category-drag-handle"
type="button" type="button"
onPointerDown={(event) => onCategoryDragStart(event, categoryId)} onPointerDown={(event) => reorder.groupReorder.startDrag(event, { groupId: group.category, parentId })}
aria-label={`${textContent.categoryReorderTitle || "Déplacer la catégorie"} ${group.category}`} aria-label={`${textContent.categoryReorderTitle || "Déplacer la catégorie"} ${group.category}`}
title={textContent.categoryReorderTitle || "Déplacer la catégorie"} title={textContent.categoryReorderTitle || "Déplacer la catégorie"}
> >
@ -907,18 +745,7 @@ function TaskPlannerBranch({
if (entry.type === "task") return visited.has(entry.task.id) ? null : renderTask(entry.task); if (entry.type === "task") return visited.has(entry.task.id) ? null : renderTask(entry.task);
return renderCategory(entry.group); return renderCategory(entry.group);
}).filter(Boolean); }).filter(Boolean);
if (!showUncategorizedDropZone) return entries; return entries;
const dropZoneClassName = [
"task-planner-uncategorized-drop-zone",
dropTarget.id === UNCATEGORIZED_DROP_ID ? "is-drop-target" : "",
dropTarget.id === UNCATEGORIZED_DROP_ID && dropTarget.placement === "after" ? "drop-after" : ""
].filter(Boolean).join(" ");
return [
<li className={dropZoneClassName} key={UNCATEGORIZED_DROP_ID} data-drop-id={UNCATEGORIZED_DROP_ID}>
{textContent.uncategorizedDropTitle || "Sans catégorie"}
</li>,
...entries
];
} }
function TaskPlannerItem({ function TaskPlannerItem({
@ -927,14 +754,11 @@ function TaskPlannerItem({
data, data,
parentMap, parentMap,
parentId, parentId,
draggingId, reorder,
dropTarget,
categoryDropTarget,
textContent, textContent,
descriptionOpen, descriptionOpen,
settingsOpen, settingsOpen,
prerequisiteNoticeVisible, prerequisiteNoticeVisible,
onDragStart,
onToggleDescription, onToggleDescription,
onToggleSettings, onToggleSettings,
onPrerequisiteNotice, onPrerequisiteNotice,
@ -961,9 +785,9 @@ function TaskPlannerItem({
"task-planner-item", "task-planner-item",
task.checked ? "is-complete" : "", task.checked ? "is-complete" : "",
missingPrerequisites.length ? "has-missing-prerequisite" : "", missingPrerequisites.length ? "has-missing-prerequisite" : "",
draggingId === task.id ? "is-dragging" : "", reorder.isItemDragging(task.id) ? "is-dragging" : "",
dropTarget.id === task.id || categoryDropTarget.id === task.id ? "is-drop-target" : "", reorder.isItemDropTarget(task.id) ? "is-drop-target" : "",
(dropTarget.id === task.id && dropTarget.placement === "after") || (categoryDropTarget.id === task.id && categoryDropTarget.placement === "after") ? "drop-after" : "" reorder.getDropPlacement("item", task.id) === "after" ? "drop-after" : ""
].filter(Boolean).join(" "); ].filter(Boolean).join(" ");
function updateChecked(event) { function updateChecked(event) {
@ -1005,12 +829,12 @@ function TaskPlannerItem({
} }
return ( return (
<li className={className} data-task-id={task.id} data-parent-id={parentId} data-category={getTaskCategoryDataset(task, tasks, parentMap)}> <li className={className} {...reorder.getItemProps({ itemId: task.id, groupId: getTaskCategoryDataset(task, tasks, parentMap), parentId })}>
<div className="task-planner-line"> <div className="task-planner-line">
<button <button
className="task-planner-drag-handle" className="task-planner-drag-handle"
type="button" type="button"
onPointerDown={(event) => onDragStart(event, task.id)} onPointerDown={(event) => reorder.itemReorder.startDrag(event, task.id)}
aria-label={`${textContent.reorderTitle || "Déplacer"} ${task.title}`} aria-label={`${textContent.reorderTitle || "Déplacer"} ${task.title}`}
title={textContent.reorderTitle || "Déplacer"} title={textContent.reorderTitle || "Déplacer"}
> >

View file

@ -2,6 +2,7 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { Icon } from "../../../components/Icon.jsx"; import { Icon } from "../../../components/Icon.jsx";
import { Tabs } from "../../../components/Tabs.jsx"; import { Tabs } from "../../../components/Tabs.jsx";
import { moveItem, useGroupedReorder } from "../../../hooks/useGroupedReorder.js";
import { import {
formatDuration, formatDuration,
formatDurationWithCentiseconds, formatDurationWithCentiseconds,
@ -93,6 +94,18 @@ export function TimerModule({ toolboxId, moduleId, context }) {
if (!data.sortResults) return countdowns; if (!data.sortResults) return countdowns;
return [...countdowns].sort((a, b) => (a.targetMs || Number.POSITIVE_INFINITY) - (b.targetMs || Number.POSITIVE_INFINITY)); return [...countdowns].sort((a, b) => (a.targetMs || Number.POSITIVE_INFINITY) - (b.targetMs || Number.POSITIVE_INFINITY));
}, [data.countdowns, data.sortResults, nowMs]); }, [data.countdowns, data.sortResults, nowMs]);
const countdownReorder = useGroupedReorder({
namespace: "timer-countdowns",
items: data.countdowns,
getItemId: (countdown) => countdown.id,
getParentId: () => moduleId,
canMoveItem: () => !data.sortResults,
onItemMove: (operation) => {
if (data.sortResults) return;
save({ ...data, countdowns: moveItem(data.countdowns, operation.sourceId, operation.targetId, operation.placement) });
},
hierarchy: { enabled: true, stickyParents: true }
});
function save(nextData) { function save(nextData) {
context.setModuleData(toolboxId, moduleId, nextData); context.setModuleData(toolboxId, moduleId, nextData);
@ -300,7 +313,7 @@ export function TimerModule({ toolboxId, moduleId, context }) {
{activeTab === "stopwatch" ? ( {activeTab === "stopwatch" ? (
<StopwatchLapList laps={data.stopwatch.laps} textContent={textContent} onRename={renameLap} onDelete={deleteLap} /> <StopwatchLapList laps={data.stopwatch.laps} textContent={textContent} onRename={renameLap} onDelete={deleteLap} />
) : ( ) : (
<CountdownList countdowns={visibleCountdowns} nowMs={nowMs} textContent={textContent} onRename={renameCountdown} onAlertModeChange={setCountdownAlertMode} onReset={resetCountdown} onDelete={deleteCountdown} /> <CountdownList countdowns={visibleCountdowns} nowMs={nowMs} textContent={textContent} reorder={countdownReorder} reorderEnabled={!data.sortResults} parentId={moduleId} onRename={renameCountdown} onAlertModeChange={setCountdownAlertMode} onReset={resetCountdown} onDelete={deleteCountdown} />
)} )}
</div> </div>
</section> </section>
@ -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(""); const [editingId, setEditingId] = useState("");
if (!countdowns.length) return <p className="muted">{textContent.emptyCountdowns || "Aucun compte à rebours configuré."}</p>; if (!countdowns.length) return <p className="muted">{textContent.emptyCountdowns || "Aucun compte à rebours configuré."}</p>;
return ( return (
@ -482,9 +495,30 @@ function CountdownList({ countdowns, nowMs, textContent, onRename, onAlertModeCh
const canReset = countdown.type === "duration" const canReset = countdown.type === "duration"
|| countdown.type === "interval" || countdown.type === "interval"
|| (countdown.type === "daily_time" && expired); || (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 ( return (
<li key={countdown.id} className={`timer-list-item ${expired ? "is-expired" : ""} ${editingId === countdown.id ? "is-editing" : ""}`}> <li key={countdown.id} className={className} {...reorderProps}>
<div className={`tool-split-entry timer-entry has-single-action ${editingId !== countdown.id ? "has-inline-controls" : ""} ${canReset && editingId !== countdown.id ? "has-inline-reset" : ""}`}> <div className={`tool-split-entry timer-entry has-single-action ${reorderEnabled ? "has-drag-handle" : ""} ${editingId !== countdown.id ? "has-inline-controls" : ""} ${canReset && editingId !== countdown.id ? "has-inline-reset" : ""}`}>
{reorderEnabled && (
<button
className="timer-drag-handle"
type="button"
onPointerDown={(event) => reorder.itemReorder.startDrag(event, countdown.id)}
aria-label={`${textContent.reorderTitle || "Déplacer"} ${countdown.label}`}
title={textContent.reorderTitle || "Déplacer"}
>
<Icon name="drag" />
</button>
)}
{editingId === countdown.id ? ( {editingId === countdown.id ? (
<EditableTimerLabel <EditableTimerLabel
value={countdown.label} value={countdown.label}

View file

@ -3,7 +3,7 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom"; import { createPortal } from "react-dom";
import { CompactDropdown } from "../../../components/CompactDropdown.jsx"; import { CompactDropdown } from "../../../components/CompactDropdown.jsx";
import { Icon } from "../../../components/Icon.jsx"; import { Icon } from "../../../components/Icon.jsx";
import { usePointerReorder } from "../../../hooks/usePointerReorder.js"; import { useGroupedReorder } from "../../../hooks/useGroupedReorder.js";
import { lockBodyScroll } from "../../../utils/bodyScrollLock.js"; import { lockBodyScroll } from "../../../utils/bodyScrollLock.js";
import { CalculatorModule } from "./CalculatorModule.jsx"; import { CalculatorModule } from "./CalculatorModule.jsx";
import { ChecklistModule } from "./ChecklistModule.jsx"; import { ChecklistModule } from "./ChecklistModule.jsx";
@ -180,14 +180,18 @@ export function ToolboxModules({ toolbox, moduleColumns, context, onRename, onUp
const moduleElementsRef = useRef(new Map()); const moduleElementsRef = useRef(new Map());
const moduleIdSignature = useMemo(() => toolbox.modules.map((module) => module.id).join("|"), [toolbox.modules]); const moduleIdSignature = useMemo(() => toolbox.modules.map((module) => module.id).join("|"), [toolbox.modules]);
const { const {
draggingId: draggingModuleId, itemReorder,
dropTarget, getItemProps,
startDrag: startModuleDrag isItemDragging,
} = usePointerReorder({ isItemDropTarget,
targetSelector: ".module", getDropPlacement
getTargetId: (target) => target.dataset.moduleId, } = useGroupedReorder({
canDropOn: (target) => target.dataset.toolboxId === toolbox.id, namespace: "toolbox-modules",
onMove 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(() => { useEffect(() => {
@ -246,9 +250,7 @@ export function ToolboxModules({ toolbox, moduleColumns, context, onRename, onUp
toolbox={toolbox} toolbox={toolbox}
module={module} module={module}
context={context} context={context}
draggingModuleId={draggingModuleId} reorder={{ itemReorder, getItemProps, isItemDragging, isItemDropTarget, getDropPlacement }}
dropTarget={dropTarget}
onDragStart={startModuleDrag}
onRename={onRename} onRename={onRename}
onUpdateModule={onUpdateModule} onUpdateModule={onUpdateModule}
onDelete={onDelete} onDelete={onDelete}
@ -273,9 +275,7 @@ export function ToolboxModules({ toolbox, moduleColumns, context, onRename, onUp
toolbox={toolbox} toolbox={toolbox}
module={module} module={module}
context={context} context={context}
draggingModuleId={draggingModuleId} reorder={{ itemReorder, getItemProps, isItemDragging, isItemDropTarget, getDropPlacement }}
dropTarget={dropTarget}
onDragStart={startModuleDrag}
onRename={onRename} onRename={onRename}
onUpdateModule={onUpdateModule} onUpdateModule={onUpdateModule}
onDelete={onDelete} 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 definition = MODULE_COMPONENTS[module.type] || MODULE_COMPONENTS.notepad;
const Component = definition.Component; const Component = definition.Component;
const label = definition.label || module.type; const label = definition.label || module.type;
const [editing, setEditing] = useState(false); const [editing, setEditing] = useState(false);
const scrollable = definition.scrollable && module.scrollable === true; const scrollable = definition.scrollable && module.scrollable === true;
const isDragging = draggingModuleId === module.id;
const isDropTarget = dropTarget.id === module.id;
const className = [ const className = [
"module", "module",
isDragging ? "is-dragging" : "", reorder.isItemDragging(module.id) ? "is-dragging" : "",
isDropTarget ? "is-drop-target" : "", reorder.isItemDropTarget(module.id) ? "is-drop-target" : "",
isDropTarget && dropTarget.placement === "after" ? "drop-after" : "", reorder.getDropPlacement("item", module.id) === "after" ? "drop-after" : "",
scrollable ? "is-scrollable" : "" scrollable ? "is-scrollable" : ""
].filter(Boolean).join(" "); ].filter(Boolean).join(" ");
return ( return (
<article <article
className={className} className={className}
data-toolbox-id={toolbox.id} {...reorder.getItemProps({ itemId: module.id, parentId: toolbox.id })}
data-module-id={module.id}
ref={(element) => registerModuleElement?.(module.id, element)} ref={(element) => registerModuleElement?.(module.id, element)}
> >
<header> <header>
@ -317,7 +314,7 @@ function ModuleShell({ toolbox, module, context, draggingModuleId, dropTarget, o
<button <button
className="module-drag-handle" className="module-drag-handle"
type="button" type="button"
onPointerDown={(event) => onDragStart(event, module.id)} onPointerDown={(event) => reorder.itemReorder.startDrag(event, module.id)}
aria-label={`Déplacer ${module.title || label}`} aria-label={`Déplacer ${module.title || label}`}
title="Déplacer" title="Déplacer"
> >

View file

@ -0,0 +1,590 @@
// Rôle : fournit la couche applicative de réorganisation pour items, groupes,
// catégories, boundaries, parent/enfant et orientations verticale/horizontale.
// S'appuie sur usePointerReorder pour le suivi bas niveau du pointeur.
import { useMemo } from "react";
import { usePointerReorder } from "./usePointerReorder.js";
const TARGET_ITEM = "item";
const TARGET_GROUP = "group";
const TARGET_BOUNDARY = "boundary";
const TARGET_UNGROUPED = "ungrouped";
const DEFAULT_HIERARCHY = { enabled: false, stickyParents: false };
const DEFAULT_CAN_MOVE = () => true;
function cleanText(value) {
return String(value || "");
}
function encodeTarget(target) {
return JSON.stringify({
kind: cleanText(target.kind),
itemId: cleanText(target.itemId),
groupId: cleanText(target.groupId),
parentId: cleanText(target.parentId),
placement: cleanText(target.placement)
});
}
function parseTarget(value) {
try {
const target = JSON.parse(String(value || "{}"));
return {
kind: cleanText(target.kind),
itemId: cleanText(target.itemId),
groupId: cleanText(target.groupId),
parentId: cleanText(target.parentId),
placement: cleanText(target.placement)
};
} catch {
return { kind: "", itemId: "", groupId: "", parentId: "", placement: "" };
}
}
function getElementTargetId(target) {
return encodeTarget({
kind: target.dataset.reorderTarget,
itemId: target.dataset.reorderItemId,
groupId: target.dataset.reorderGroupId,
parentId: target.dataset.reorderParentId,
placement: target.dataset.reorderPlacement
});
}
function getPointerPlacement(event, target, orientation = "vertical") {
const placement = target.dataset.reorderPlacement;
if (placement === "before" || placement === "after") return placement;
const rect = target.getBoundingClientRect();
if (orientation === "horizontal") return event.clientX > rect.left + rect.width / 2 ? "after" : "before";
return event.clientY > rect.top + rect.height / 2 ? "after" : "before";
}
function getConfiguredPlacement(target) {
const placement = target.dataset.reorderPlacement;
return placement === "after" ? "after" : "before";
}
function targetId(target) {
if (target.kind === TARGET_ITEM) return target.itemId;
if (target.kind === TARGET_GROUP || target.kind === TARGET_BOUNDARY) return target.groupId;
return "";
}
function buildOperation(kind, sourceId, targetIdValue, placement) {
const source = parseTarget(sourceId);
const target = parseTarget(targetIdValue);
return {
type: kind,
sourceId: kind === TARGET_ITEM ? source.itemId : source.groupId,
targetId: targetId(target),
targetType: target.kind,
placement: target.placement || placement,
sourceGroup: source.groupId,
targetGroup: target.kind === TARGET_UNGROUPED ? "" : target.groupId,
sourceParentId: source.parentId,
targetParentId: target.parentId
};
}
function sameParent(target, parentId = "") {
return target.parentId === cleanText(parentId);
}
function canMoveWithinHierarchy(operation, hierarchy) {
if (!hierarchy?.enabled || !hierarchy?.stickyParents) return true;
return operation.sourceParentId === operation.targetParentId;
}
function canMoveToDistinctTarget(operation) {
if (operation.type === TARGET_ITEM && operation.targetType === TARGET_ITEM) return operation.sourceId !== operation.targetId;
if (operation.type === TARGET_GROUP && (operation.targetType === TARGET_GROUP || operation.targetType === TARGET_BOUNDARY)) {
return operation.sourceGroup && operation.sourceGroup !== operation.targetGroup;
}
return true;
}
const DEFAULT_REORDER_FEATURES = {
item: {
reorder: true,
groupChange: false,
boundaryDrop: false,
ungroupedDrop: false,
rootOnly: false
},
group: {
reorder: false,
boundaryDrop: false,
ungroupedDrop: false,
itemDrop: false,
itemDropRequiresUngroupedTarget: true,
rootOnly: false
}
};
function getReorderFeatures(features = {}) {
return {
item: { ...DEFAULT_REORDER_FEATURES.item, ...(features.item || {}) },
group: { ...DEFAULT_REORDER_FEATURES.group, ...(features.group || {}) }
};
}
function isRootScoped(operation) {
return !operation.sourceParentId && !operation.targetParentId;
}
function canMoveByFeatures(operation, features) {
if (operation.type === TARGET_ITEM) {
const item = features.item;
const rootAllowed = !item.rootOnly || isRootScoped(operation);
if (!rootAllowed) return false;
if (operation.targetType === TARGET_ITEM) {
return item.reorder && (operation.targetGroup === operation.sourceGroup || item.groupChange);
}
if (operation.targetType === TARGET_GROUP) {
return item.groupChange && Boolean(operation.targetGroup) && operation.targetGroup !== operation.sourceGroup;
}
if (operation.targetType === TARGET_BOUNDARY) {
return item.boundaryDrop && Boolean(operation.targetGroup);
}
if (operation.targetType === TARGET_UNGROUPED) {
return item.ungroupedDrop && Boolean(operation.sourceGroup);
}
return false;
}
if (operation.type === TARGET_GROUP) {
const group = features.group;
const rootAllowed = !group.rootOnly || isRootScoped(operation);
if (!rootAllowed || !operation.sourceGroup) return false;
if (operation.targetType === TARGET_GROUP) {
return group.reorder && Boolean(operation.targetGroup);
}
if (operation.targetType === TARGET_BOUNDARY) {
return group.boundaryDrop && Boolean(operation.targetGroup);
}
if (operation.targetType === TARGET_UNGROUPED) {
return group.ungroupedDrop;
}
if (operation.targetType === TARGET_ITEM) {
return group.itemDrop && (!group.itemDropRequiresUngroupedTarget || !operation.targetGroup);
}
return false;
}
return false;
}
export function completeGroupOrder(groupOrder = [], groups = []) {
return [
...groupOrder.filter((group) => groups.includes(group)),
...groups.filter((group) => !groupOrder.includes(group))
];
}
export function getGroupedEntries(items, { groupOrder = [], getItemGroup, groupItemKey = "items", groupIdKey = "id" } = {}) {
const groups = [];
const itemsByGroup = new Map();
items.forEach((item) => {
const group = cleanText(getItemGroup?.(item));
if (!group) return;
if (!itemsByGroup.has(group)) {
groups.push(group);
itemsByGroup.set(group, []);
}
itemsByGroup.get(group).push(item);
});
const orderedGroups = completeGroupOrder(groupOrder, groups);
const groupEntries = new Map(orderedGroups.map((group) => [group, {
[groupIdKey]: group,
[groupItemKey]: itemsByGroup.get(group) || []
}]));
const renderedGroups = new Set();
return items.map((item) => {
const group = cleanText(getItemGroup?.(item));
if (!group) return { type: "item", item };
if (renderedGroups.has(group)) return null;
renderedGroups.add(group);
return { type: "group", group: groupEntries.get(group) };
}).filter(Boolean);
}
export function moveItem(items, fromItemId, toItemId, placement = "before", getItemId = (item) => item.id) {
const nextItems = [...items];
const fromIndex = nextItems.findIndex((item) => getItemId(item) === fromItemId);
const toIndex = nextItems.findIndex((item) => getItemId(item) === toItemId);
if (fromIndex < 0 || toIndex < 0 || fromItemId === toItemId) return items;
const [moved] = nextItems.splice(fromIndex, 1);
const targetIndex = nextItems.findIndex((item) => getItemId(item) === toItemId);
nextItems.splice(placement === "after" ? targetIndex + 1 : targetIndex, 0, moved);
return nextItems;
}
export function moveItemGroup(items, movingItemIds, toItemId, placement = "before", getItemId = (item) => item.id) {
const movingIds = new Set(movingItemIds);
if (!movingIds.size || movingIds.has(toItemId)) return items;
const movingItems = items.filter((item) => movingIds.has(getItemId(item)));
const remainingItems = items.filter((item) => !movingIds.has(getItemId(item)));
const targetIndex = remainingItems.findIndex((item) => getItemId(item) === toItemId);
if (targetIndex < 0) return items;
remainingItems.splice(placement === "after" ? targetIndex + 1 : targetIndex, 0, ...movingItems);
return remainingItems;
}
export function getBoundaryItemId(items, itemIds, placement = "before", getItemId = (item) => item.id) {
const ids = new Set(itemIds);
const orderedItems = items.filter((item) => ids.has(getItemId(item)));
return placement === "after" ? getItemId(orderedItems.at(-1) || {}) || "" : getItemId(orderedItems[0] || {}) || "";
}
export function moveGroupOrder(groupOrder, groups, fromGroup, toGroup, placement = "before") {
const nextOrder = completeGroupOrder(groupOrder, groups);
const index = nextOrder.indexOf(fromGroup);
const targetIndex = nextOrder.indexOf(toGroup);
if (index < 0 || targetIndex < 0 || fromGroup === toGroup) return nextOrder;
const [moved] = nextOrder.splice(index, 1);
const nextTargetIndex = nextOrder.indexOf(toGroup);
nextOrder.splice(placement === "after" ? nextTargetIndex + 1 : nextTargetIndex, 0, moved);
return nextOrder;
}
export function moveGroupOrderToStart(groupOrder, groups, fromGroup) {
return [fromGroup, ...completeGroupOrder(groupOrder, groups).filter((group) => group !== fromGroup)];
}
export function moveGroupOrderToEnd(groupOrder, groups, fromGroup) {
return [...completeGroupOrder(groupOrder, groups).filter((group) => group !== fromGroup), fromGroup];
}
function getGroupsFromItems(items, getItemGroup) {
const groups = [];
items.forEach((item) => {
const group = cleanText(getItemGroup(item));
if (group && !groups.includes(group)) groups.push(group);
});
return groups;
}
function getGroupItemIds(items, group, getItemId, getItemGroup) {
return items.filter((item) => cleanText(getItemGroup(item)) === group).map(getItemId);
}
function setItemGroup(items, itemId, group, getItemId, setItemGroupValue) {
return items.map((item) => (getItemId(item) === itemId ? setItemGroupValue(item, group) : item));
}
function getItemGroupById(items, itemId, getItemId, getItemGroup) {
const item = items.find((entry) => getItemId(entry) === itemId);
return item ? cleanText(getItemGroup(item)) : "";
}
function moveItemsToEdge(items, movingIds, edge, getItemId) {
const movingSet = new Set(movingIds);
const movingItems = items.filter((item) => movingSet.has(getItemId(item)));
const remainingItems = items.filter((item) => !movingSet.has(getItemId(item)));
return edge === "start" ? [...movingItems, ...remainingItems] : [...remainingItems, ...movingItems];
}
function compactGroupOrder(groupOrder, items, getItemGroup) {
return completeGroupOrder(groupOrder, getGroupsFromItems(items, getItemGroup));
}
export function applyGroupedReorderOperation(data, {
operation,
itemsKey = "items",
groupOrderKey = "groupOrder",
collapsedGroupsKey = "",
getItemId = (item) => item.id,
getItemGroup,
setItemGroup: setItemGroupValue
}) {
const items = Array.isArray(data?.[itemsKey]) ? data[itemsKey] : [];
const groupOrder = Array.isArray(data?.[groupOrderKey]) ? data[groupOrderKey] : [];
const getGroup = getItemGroup || (() => "");
const setGroup = setItemGroupValue || ((item) => item);
const allGroups = () => getGroupsFromItems(items, getGroup);
function withItems(nextItems, nextGroupOrder = compactGroupOrder(groupOrder, nextItems, getGroup), openedGroup = "") {
const nextData = {
...data,
[itemsKey]: nextItems,
[groupOrderKey]: nextGroupOrder
};
if (collapsedGroupsKey && openedGroup && Array.isArray(data?.[collapsedGroupsKey])) {
nextData[collapsedGroupsKey] = data[collapsedGroupsKey].filter((group) => group !== openedGroup);
}
return nextData;
}
function moveItemToEdge(group = "") {
const groupedItems = setItemGroup(items, operation.sourceId, group, getItemId, setGroup);
const movedItems = moveItemsToEdge(groupedItems, [operation.sourceId], operation.placement === "after" ? "end" : "start", getItemId);
return withItems(movedItems, compactGroupOrder(groupOrder, movedItems, getGroup), group);
}
function moveItemAroundItem() {
const targetGroup = getItemGroupById(items, operation.targetId, getItemId, getGroup);
const groupedItems = setItemGroup(items, operation.sourceId, targetGroup, getItemId, setGroup);
const movedItems = moveItemGroup(groupedItems, [operation.sourceId], operation.targetId, operation.placement, getItemId);
return withItems(movedItems, compactGroupOrder(groupOrder, movedItems, getGroup), targetGroup);
}
function moveItemIntoGroup(group, placement) {
if (!group) return moveItemToEdge("");
const groupedItems = setItemGroup(items, operation.sourceId, group, getItemId, setGroup);
const targetIds = getGroupItemIds(items, group, getItemId, getGroup).filter((id) => id !== operation.sourceId);
const boundaryItemId = getBoundaryItemId(items, targetIds, placement, getItemId);
const movedItems = boundaryItemId ? moveItemGroup(groupedItems, [operation.sourceId], boundaryItemId, placement, getItemId) : groupedItems;
return withItems(movedItems, compactGroupOrder(groupOrder, movedItems, getGroup), group);
}
function moveItemOutsideGroup() {
const groupedItems = setItemGroup(items, operation.sourceId, "", getItemId, setGroup);
const targetIds = getGroupItemIds(items, operation.targetGroup, getItemId, getGroup).filter((id) => id !== operation.sourceId);
const boundaryItemId = getBoundaryItemId(items, targetIds, operation.placement, getItemId);
const movedItems = boundaryItemId ? moveItemGroup(groupedItems, [operation.sourceId], boundaryItemId, operation.placement, getItemId) : groupedItems;
return withItems(movedItems, compactGroupOrder(groupOrder, movedItems, getGroup));
}
function moveGroupToEdge() {
const movingIds = getGroupItemIds(items, operation.sourceGroup, getItemId, getGroup);
if (!movingIds.length) return data;
const movedItems = moveItemsToEdge(items, movingIds, operation.placement === "after" ? "end" : "start", getItemId);
const nextGroupOrder = operation.placement === "after"
? moveGroupOrderToEnd(groupOrder, allGroups(), operation.sourceGroup)
: moveGroupOrderToStart(groupOrder, allGroups(), operation.sourceGroup);
return withItems(movedItems, nextGroupOrder);
}
function moveGroupAroundGroup(targetGroup) {
if (!operation.sourceGroup || !targetGroup || operation.sourceGroup === targetGroup) return data;
const movingIds = getGroupItemIds(items, operation.sourceGroup, getItemId, getGroup);
const targetIds = getGroupItemIds(items, targetGroup, getItemId, getGroup);
const boundaryItemId = getBoundaryItemId(items, targetIds, operation.placement, getItemId);
if (!movingIds.length || !boundaryItemId) return data;
return withItems(
moveItemGroup(items, movingIds, boundaryItemId, operation.placement, getItemId),
moveGroupOrder(groupOrder, allGroups(), operation.sourceGroup, targetGroup, operation.placement)
);
}
function moveGroupAroundItem() {
const movingIds = getGroupItemIds(items, operation.sourceGroup, getItemId, getGroup);
if (!movingIds.length || !operation.targetId) return data;
return withItems(moveItemGroup(items, movingIds, operation.targetId, operation.placement, getItemId));
}
if (operation.type === TARGET_ITEM) {
if (operation.targetType === TARGET_ITEM) return moveItemAroundItem();
if (operation.targetType === TARGET_GROUP) return moveItemIntoGroup(operation.targetGroup, operation.placement);
if (operation.targetType === TARGET_BOUNDARY) return moveItemOutsideGroup();
if (operation.targetType === TARGET_UNGROUPED) return moveItemToEdge("");
}
if (operation.type === TARGET_GROUP) {
if (operation.targetType === TARGET_GROUP || operation.targetType === TARGET_BOUNDARY) return moveGroupAroundGroup(operation.targetGroup);
if (operation.targetType === TARGET_ITEM) return moveGroupAroundItem();
if (operation.targetType === TARGET_UNGROUPED) return moveGroupToEdge();
}
return data;
}
export function useGroupedReorder({
namespace,
items = [],
getItemId = (item) => item.id,
getItemGroup = () => "",
getParentId = () => "",
getEffectiveGroup = getItemGroup,
reorderFeatures = {},
canMoveItem = DEFAULT_CAN_MOVE,
canMoveGroup = DEFAULT_CAN_MOVE,
orientation = "vertical",
getPlacement = (event, target) => getPointerPlacement(event, target, orientation),
onItemMove,
onGroupMove,
hierarchy = DEFAULT_HIERARCHY
}) {
const targetSelector = useMemo(() => `[data-reorder-namespace="${namespace}"]`, [namespace]);
const features = useMemo(() => getReorderFeatures(reorderFeatures), [reorderFeatures]);
const itemById = useMemo(() => new Map(items.map((item) => [getItemId(item), item])), [getItemId, items]);
const itemReorder = usePointerReorder({
targetSelector,
getTargetId: getElementTargetId,
getPlacement,
canDropOn: (target, draggingId) => {
const source = parseTarget(draggingId);
const targetIdValue = getElementTargetId(target);
const targetValue = parseTarget(targetIdValue);
if (source.kind !== TARGET_ITEM) return false;
const operation = buildOperation(TARGET_ITEM, draggingId, targetIdValue, getConfiguredPlacement(target));
if (!canMoveToDistinctTarget(operation)) return false;
if (!canMoveWithinHierarchy(operation, hierarchy)) return false;
if (!canMoveByFeatures(operation, features)) return false;
return canMoveItem(operation, { source, target: targetValue, features, hierarchy });
},
onMove: (sourceId, targetIdValue, placement) => {
onItemMove?.(buildOperation(TARGET_ITEM, sourceId, targetIdValue, placement));
}
});
const groupReorder = usePointerReorder({
targetSelector,
getTargetId: getElementTargetId,
getPlacement,
canDropOn: (target, draggingId) => {
const source = parseTarget(draggingId);
const targetIdValue = getElementTargetId(target);
const targetValue = parseTarget(targetIdValue);
if (source.kind !== TARGET_GROUP) return false;
const operation = buildOperation(TARGET_GROUP, draggingId, targetIdValue, getConfiguredPlacement(target));
if (!canMoveToDistinctTarget(operation)) return false;
if (!canMoveByFeatures(operation, features)) return false;
return canMoveGroup(operation, { source, target: targetValue, features, hierarchy });
},
onMove: (sourceId, targetIdValue, placement) => {
onGroupMove?.(buildOperation(TARGET_GROUP, sourceId, targetIdValue, placement));
}
});
function getItemProps({ itemId, groupId = "", parentId = "" }) {
return {
"data-reorder-namespace": namespace,
"data-reorder-target": TARGET_ITEM,
"data-reorder-item-id": itemId,
"data-reorder-group-id": groupId,
"data-reorder-parent-id": parentId,
"data-reorder-orientation": orientation
};
}
function getGroupProps({ groupId, parentId = "" }) {
return {
"data-reorder-namespace": namespace,
"data-reorder-target": TARGET_GROUP,
"data-reorder-group-id": groupId,
"data-reorder-parent-id": parentId,
"data-reorder-orientation": orientation
};
}
function getGroupBoundaryProps({ groupId, parentId = "", placement }) {
return {
"data-reorder-namespace": namespace,
"data-reorder-target": TARGET_BOUNDARY,
"data-reorder-group-id": groupId,
"data-reorder-parent-id": parentId,
"data-reorder-placement": placement,
"data-reorder-orientation": orientation
};
}
function getUngroupedDropProps({ parentId = "" } = {}) {
return {
"data-reorder-namespace": namespace,
"data-reorder-target": TARGET_UNGROUPED,
"data-reorder-parent-id": parentId,
"data-reorder-orientation": orientation
};
}
function startItemDrag(event, itemId) {
const item = itemById.get(itemId);
itemReorder.startDrag(event, encodeTarget({
kind: TARGET_ITEM,
itemId,
groupId: cleanText(item ? getEffectiveGroup(item) : ""),
parentId: cleanText(item ? getParentId(item) : "")
}));
}
function startGroupDrag(event, { groupId, parentId = "" }) {
groupReorder.startDrag(event, encodeTarget({ kind: TARGET_GROUP, groupId, parentId }));
}
function isItemDragging(itemId) {
const target = parseTarget(itemReorder.draggingId);
return target.kind === TARGET_ITEM && target.itemId === itemId;
}
function isGroupDragging(groupId, parentId = "") {
const target = parseTarget(groupReorder.draggingId);
return target.kind === TARGET_GROUP && target.groupId === groupId && sameParent(target, parentId);
}
function isItemDropTarget(itemId) {
return [itemReorder.dropTarget, groupReorder.dropTarget].some((dropTarget) => {
const target = parseTarget(dropTarget.id);
return target.kind === TARGET_ITEM && target.itemId === itemId;
});
}
function isGroupDropTarget(groupId, parentId = "") {
return [itemReorder.dropTarget, groupReorder.dropTarget].some((dropTarget) => {
const target = parseTarget(dropTarget.id);
return target.kind === TARGET_GROUP && target.groupId === groupId && sameParent(target, parentId);
});
}
function isBoundaryDropTarget({ groupId, parentId = "", placement }) {
return [itemReorder.dropTarget, groupReorder.dropTarget].some((dropTarget) => {
const target = parseTarget(dropTarget.id);
return target.kind === TARGET_BOUNDARY && target.groupId === groupId && target.placement === placement && sameParent(target, parentId);
});
}
function isUngroupedDropTarget(parentId = "") {
return [itemReorder.dropTarget, groupReorder.dropTarget].some((dropTarget) => {
const target = parseTarget(dropTarget.id);
return target.kind === TARGET_UNGROUPED && sameParent(target, parentId);
});
}
function getDropPlacement(targetType, id, parentId = "") {
const dropTarget = [itemReorder.dropTarget, groupReorder.dropTarget].find((currentTarget) => {
const target = parseTarget(currentTarget.id);
if (target.kind !== targetType) return false;
if (targetType === TARGET_ITEM) return target.itemId === id;
return target.groupId === id && sameParent(target, parentId);
});
return dropTarget?.placement || "";
}
function shouldShowUngroupedDropZone({ parentId = "" } = {}) {
const draggingItem = parseTarget(itemReorder.draggingId);
const draggingGroup = parseTarget(groupReorder.draggingId);
return (
draggingItem.kind === TARGET_ITEM && draggingItem.groupId && sameParent(draggingItem, parentId)
) || (
draggingGroup.kind === TARGET_GROUP && draggingGroup.groupId && sameParent(draggingGroup, parentId)
);
}
function shouldShowGroupBoundaries({ parentId = "" } = {}) {
const draggingItem = parseTarget(itemReorder.draggingId);
const draggingGroup = parseTarget(groupReorder.draggingId);
return (
draggingItem.kind === TARGET_ITEM && sameParent(draggingItem, parentId)
) || (
draggingGroup.kind === TARGET_GROUP && sameParent(draggingGroup, parentId)
);
}
return {
itemReorder: { ...itemReorder, startDrag: startItemDrag },
groupReorder: { ...groupReorder, startDrag: startGroupDrag },
getItemProps,
getGroupProps,
getGroupBoundaryProps,
getUngroupedDropProps,
isItemDragging,
isItemDropTarget,
isGroupDragging,
isGroupDropTarget,
isBoundaryDropTarget,
isUngroupedDropTarget,
getDropPlacement,
shouldShowUngroupedDropZone,
shouldShowGroupBoundaries
};
}

View file

@ -1,4 +1,6 @@
// Rôle : fournit la réorganisation par pointeur pour listes et grilles locales. // Rôle : fournit le moteur bas niveau de drag par pointeur.
// Gère uniquement la cible DOM, before/after et le cycle pointer down/move/up.
// Préférer useGroupedReorder pour les réorganisations applicatives d'outils.
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
function getDefaultPlacement(event, element) { function getDefaultPlacement(event, element) {
@ -28,11 +30,15 @@ export function usePointerReorder({
const { getTargetId, canDropOn, getPlacement } = optionsRef.current; const { getTargetId, canDropOn, getPlacement } = optionsRef.current;
const element = document.elementFromPoint(event.clientX, event.clientY); const element = document.elementFromPoint(event.clientX, event.clientY);
const target = element?.closest?.(targetSelector); const target = element?.closest?.(targetSelector);
if (!target || !canDropOn(target, draggingId) || getTargetId(target) === draggingId) { if (!target || !canDropOn(target, draggingId)) {
return { id: "", placement: "before" };
}
const targetId = getTargetId(target);
if (targetId === draggingId) {
return { id: "", placement: "before" }; return { id: "", placement: "before" };
} }
return { return {
id: getTargetId(target), id: targetId,
placement: getPlacement(event, target) placement: getPlacement(event, target)
}; };
} }
@ -44,7 +50,7 @@ export function usePointerReorder({
function handlePointerUp(event) { function handlePointerUp(event) {
const { onMove } = optionsRef.current; const { onMove } = optionsRef.current;
const target = getDropTarget(event); const target = getDropTarget(event);
if (target.id) onMove(draggingId, target.id, target.placement); if (target.id) onMove?.(draggingId, target.id, target.placement);
setDraggingId(""); setDraggingId("");
setDropTarget({ id: "", placement: "before" }); setDropTarget({ id: "", placement: "before" });
} }

View file

@ -148,6 +148,8 @@
} }
.toolbox-card { .toolbox-card {
--reorder-drop-shadow: var(--shadow-sm);
position: relative; position: relative;
display: flex; display: flex;
min-height: 292px; min-height: 292px;
@ -225,24 +227,6 @@
cursor: grabbing; cursor: grabbing;
} }
.toolbox-card.is-dragging {
cursor: grabbing;
opacity: 0.58;
transform: scale(0.99);
}
.toolbox-card.is-drop-target {
box-shadow:
var(--shadow-sm),
inset 3px 0 0 rgba(246, 196, 83, 0.82);
}
.toolbox-card.is-drop-target.drop-after {
box-shadow:
var(--shadow-sm),
inset -3px 0 0 rgba(246, 196, 83, 0.82);
}
.toolbox-page { .toolbox-page {
display: flex; display: flex;
min-height: calc(100vh - 68px - var(--space-8) - var(--space-12)); min-height: calc(100vh - 68px - var(--space-8) - var(--space-12));

View file

@ -423,6 +423,8 @@
} }
.module { .module {
--reorder-drop-shadow: var(--shadow-sm);
position: relative; position: relative;
contain: paint; contain: paint;
overflow: hidden; overflow: hidden;
@ -459,23 +461,33 @@
linear-gradient(180deg, transparent 0 30%, rgba(139, 92, 246, 0.08) 42%, rgba(139, 92, 246, 0.32) 72%, rgba(196, 181, 253, 0.5) 100%); linear-gradient(180deg, transparent 0 30%, rgba(139, 92, 246, 0.08) 42%, rgba(139, 92, 246, 0.32) 72%, rgba(196, 181, 253, 0.5) 100%);
} }
.module.is-dragging { [data-reorder-target="item"].is-dragging,
[data-reorder-target="group"].is-dragging {
cursor: grabbing; cursor: grabbing;
opacity: 0.58; opacity: 0.58;
transform: scale(0.99); transform: scale(0.99);
} }
.module.is-drop-target { [data-reorder-target="item"][data-reorder-orientation="vertical"].is-drop-target,
[data-reorder-target="group"][data-reorder-orientation="vertical"].is-drop-target {
border-color: rgba(246, 196, 83, 0.72); border-color: rgba(246, 196, 83, 0.72);
box-shadow: box-shadow: var(--reorder-drop-shadow, none), inset 0 3px 0 rgba(246, 196, 83, 0.8);
var(--shadow-sm),
inset 0 3px 0 rgba(246, 196, 83, 0.8);
} }
.module.is-drop-target.drop-after { [data-reorder-target="item"][data-reorder-orientation="vertical"].is-drop-target.drop-after,
box-shadow: [data-reorder-target="group"][data-reorder-orientation="vertical"].is-drop-target.drop-after {
var(--shadow-sm), box-shadow: var(--reorder-drop-shadow, none), inset 0 -3px 0 rgba(246, 196, 83, 0.8);
inset 0 -3px 0 rgba(246, 196, 83, 0.8); }
[data-reorder-target="item"][data-reorder-orientation="horizontal"].is-drop-target,
[data-reorder-target="group"][data-reorder-orientation="horizontal"].is-drop-target {
border-color: rgba(246, 196, 83, 0.72);
box-shadow: var(--reorder-drop-shadow, none), inset 3px 0 0 rgba(246, 196, 83, 0.86);
}
[data-reorder-target="item"][data-reorder-orientation="horizontal"].is-drop-target.drop-after,
[data-reorder-target="group"][data-reorder-orientation="horizontal"].is-drop-target.drop-after {
box-shadow: var(--reorder-drop-shadow, none), inset -3px 0 0 rgba(246, 196, 83, 0.86);
} }
.module header { .module header {
@ -1857,31 +1869,6 @@ textarea:focus {
text-align: center; text-align: center;
} }
.task-planner-uncategorized-drop-zone {
padding: 9px 12px;
border: 1px dashed rgba(165, 180, 252, 0.22);
border-radius: var(--radius-md);
background: rgba(15, 23, 42, 0.26);
color: var(--color-text-muted);
font-size: var(--font-size-xs);
font-weight: 900;
text-align: center;
text-transform: uppercase;
}
.task-planner-uncategorized-drop-zone.is-drop-target {
border-color: rgba(246, 196, 83, 0.72);
background:
linear-gradient(135deg, rgba(246, 196, 83, 0.08), transparent 56%),
rgba(15, 23, 42, 0.34);
color: var(--color-accent-gold);
box-shadow: inset 0 3px 0 rgba(246, 196, 83, 0.8);
}
.task-planner-uncategorized-drop-zone.is-drop-target.drop-after {
box-shadow: inset 0 -3px 0 rgba(246, 196, 83, 0.8);
}
.task-planner-category-boundary-drop-zone { .task-planner-category-boundary-drop-zone {
min-height: 10px; min-height: 10px;
border: 1px dashed rgba(165, 180, 252, 0.16); border: 1px dashed rgba(165, 180, 252, 0.16);
@ -1987,21 +1974,6 @@ textarea:focus {
rgba(5, 7, 17, 0.36); rgba(5, 7, 17, 0.36);
} }
.task-planner-item.is-dragging {
cursor: grabbing;
opacity: 0.58;
transform: scale(0.99);
}
.task-planner-item.is-drop-target {
border-color: rgba(246, 196, 83, 0.72);
box-shadow: inset 0 3px 0 rgba(246, 196, 83, 0.8);
}
.task-planner-item.is-drop-target.drop-after {
box-shadow: inset 0 -3px 0 rgba(246, 196, 83, 0.8);
}
.task-planner-line { .task-planner-line {
display: grid; display: grid;
grid-template-columns: 30px 24px minmax(0, 1fr) 134px auto auto; grid-template-columns: 30px 24px minmax(0, 1fr) 134px auto auto;
@ -2486,33 +2458,6 @@ textarea:focus {
gap: 6px; gap: 6px;
} }
.combos-root-drop-zone {
display: none;
padding: 9px 12px;
border: 1px dashed rgba(165, 180, 252, 0.22);
border-radius: var(--radius-md);
background: rgba(15, 23, 42, 0.26);
color: var(--color-text-muted);
font-size: var(--font-size-xs);
font-weight: 900;
text-align: center;
text-transform: uppercase;
}
.combos-root-drop-zone.is-visible,
.combos-root-drop-zone.is-drop-target {
display: block;
}
.combos-root-drop-zone.is-drop-target {
border-color: rgba(246, 196, 83, 0.72);
background:
linear-gradient(135deg, rgba(246, 196, 83, 0.08), transparent 56%),
rgba(15, 23, 42, 0.34);
color: var(--color-accent-gold);
box-shadow: inset 0 3px 0 rgba(246, 196, 83, 0.8);
}
.combos-category-boundary-drop-zone { .combos-category-boundary-drop-zone {
min-height: 6px; min-height: 6px;
border-radius: 999px; border-radius: 999px;
@ -2546,24 +2491,6 @@ textarea:focus {
grid-template-columns: 30px minmax(0, 1fr) auto; grid-template-columns: 30px minmax(0, 1fr) auto;
} }
.combo-card.is-dragging,
.combos-category.is-dragging {
cursor: grabbing;
opacity: 0.58;
transform: scale(0.99);
}
.combo-card.is-drop-target,
.combos-category.is-drop-target {
border-color: rgba(246, 196, 83, 0.72);
box-shadow: inset 0 3px 0 rgba(246, 196, 83, 0.8);
}
.combo-card.is-drop-target.drop-after,
.combos-category.is-drop-target.drop-after {
box-shadow: inset 0 -3px 0 rgba(246, 196, 83, 0.8);
}
.combo-drag-handle { .combo-drag-handle {
align-self: start; align-self: start;
} }
@ -2971,9 +2898,10 @@ button.combo-input-token.combo-input-mouse {
} }
.counter-item { .counter-item {
position: relative;
display: grid; display: grid;
gap: 12px; gap: 12px;
padding: 12px; padding: 12px 52px 12px 12px;
border: 1px solid rgba(165, 180, 252, 0.12); border: 1px solid rgba(165, 180, 252, 0.12);
border-radius: var(--radius-md); border-radius: var(--radius-md);
background: background:
@ -2981,6 +2909,22 @@ button.combo-input-token.combo-input-mouse {
rgba(7, 10, 24, 0.42); rgba(7, 10, 24, 0.42);
} }
.counter-drag-handle {
position: absolute;
top: 10px;
right: 10px;
display: inline-grid;
width: 34px;
min-width: 34px;
min-height: 34px;
place-items: center;
padding: 0;
color: var(--color-text-muted);
cursor: grab;
touch-action: none;
user-select: none;
}
.counter-item > div:first-child { .counter-item > div:first-child {
display: grid; display: grid;
gap: 3px; gap: 3px;
@ -3340,10 +3284,29 @@ button.combo-input-token.combo-input-mouse {
grid-template-columns: minmax(0, 1fr) 34px; grid-template-columns: minmax(0, 1fr) 34px;
} }
.timer-entry.has-drag-handle {
grid-template-columns: 30px minmax(0, 1fr) 34px;
}
.tool-split-entry-list li.is-editing > .timer-entry.has-single-action { .tool-split-entry-list li.is-editing > .timer-entry.has-single-action {
grid-template-columns: auto minmax(0, 1fr) 34px; grid-template-columns: auto minmax(0, 1fr) 34px;
} }
.tool-split-entry-list li.is-editing > .timer-entry.has-drag-handle {
grid-template-columns: 30px auto minmax(0, 1fr) 34px;
}
.timer-drag-handle {
width: 30px;
min-width: 30px;
min-height: 36px;
padding: 0;
color: var(--color-text-muted);
cursor: grab;
touch-action: none;
user-select: none;
}
.timer-inline-reset { .timer-inline-reset {
width: 26px; width: 26px;
min-width: 26px; min-width: 26px;
@ -3428,6 +3391,25 @@ button.combo-input-token.combo-input-mouse {
max-width: 100%; max-width: 100%;
} }
.calculator-entry.has-drag-handle {
grid-template-columns: 30px minmax(0, 1fr) 34px 34px;
}
.tool-split-entry-list li.is-editing > .calculator-entry.has-drag-handle {
grid-template-columns: 30px auto minmax(0, 1fr) 34px 34px;
}
.calculator-drag-handle {
width: 30px;
min-width: 30px;
min-height: 36px;
padding: 0;
color: var(--color-text-muted);
cursor: grab;
touch-action: none;
user-select: none;
}
.calculator-form label span, .calculator-form label span,
.calculator-result span, .calculator-result span,
.tool-split-root-button { .tool-split-root-button {
@ -4073,7 +4055,7 @@ button.combo-input-token.combo-input-mouse {
.link-item { .link-item {
display: grid; display: grid;
grid-template-columns: minmax(0, 1fr) auto; grid-template-columns: 34px minmax(0, 1fr) auto;
gap: 10px; gap: 10px;
align-items: center; align-items: center;
padding: 10px; padding: 10px;
@ -4082,6 +4064,17 @@ button.combo-input-token.combo-input-mouse {
background: rgba(7, 10, 24, 0.42); background: rgba(7, 10, 24, 0.42);
} }
.link-drag-handle {
width: 34px;
min-width: 34px;
min-height: 34px;
padding: 0;
color: var(--color-text-muted);
cursor: grab;
touch-action: none;
user-select: none;
}
.link-item a { .link-item a {
display: grid; display: grid;
min-width: 0; min-width: 0;
@ -4116,6 +4109,12 @@ button.combo-input-token.combo-input-mouse {
min-height: 40px; min-height: 40px;
} }
.link-item .link-drag-handle {
width: 34px;
min-width: 34px;
min-height: 34px;
}
.dropzone { .dropzone {
display: grid; display: grid;
min-height: 74px; min-height: 74px;
@ -4327,18 +4326,8 @@ button.combo-input-token.combo-input-mouse {
background: rgba(5, 7, 17, 0.38); background: rgba(5, 7, 17, 0.38);
} }
.images figure.is-dragging { .images figure {
opacity: 0.42; --reorder-drop-shadow: 0 0 18px rgba(246, 196, 83, 0.12);
}
.images figure.is-drop-target {
border-color: rgba(246, 196, 83, 0.72);
box-shadow: 0 0 0 1px rgba(246, 196, 83, 0.26), 0 0 18px rgba(246, 196, 83, 0.12);
}
.images figure.is-drop-target.drop-after {
border-color: rgba(112, 89, 255, 0.82);
box-shadow: 0 0 0 1px rgba(164, 124, 255, 0.3), 0 0 18px rgba(112, 89, 255, 0.16);
} }
.image-drag-handle { .image-drag-handle {