import type { Marks } from "./marks"; type Move = { from: string; to: string }; const parent = (path: string) => path.split("/").slice(0, -1).join("/"); const name = (path: string) => path.split("/").at(-1)!; export function moveMarks(current: Marks, from: string, to: string): Marks { const map = (path: string) => path === from || path.startsWith(from + "/") ? to + path.slice(from.length) : path; const order = Object.fromEntries(Object.entries(current.order).map(([key, value]) => [map(key), [...value]])); if (parent(from) === parent(to)) { const list = order[parent(from)]; if (list) order[parent(from)] = list.map(item => item === name(from) ? name(to) : item); } else { if (order[parent(from)]) order[parent(from)] = order[parent(from)].filter(item => item !== name(from)); if (order[parent(to)] && !order[parent(to)].includes(name(to))) order[parent(to)].push(name(to)); } return { pins: current.pins.map(map), bookmarks: current.bookmarks.map(map), order }; } export function replayMoveMarks(current: Marks, before: Marks, after: Marks, moves: Move[], redo: boolean): Marks { let result = current; for (const move of redo ? moves : [...moves].reverse()) result = moveMarks(result, redo ? move.from : move.to, redo ? move.to : move.from); const target = redo ? after : before; const order = { ...result.order }; for (const folder of new Set([...Object.keys(before.order), ...Object.keys(after.order)])) { if (JSON.stringify(before.order[folder]) === JSON.stringify(after.order[folder])) continue; const known = new Set([...(before.order[folder] ?? []), ...(after.order[folder] ?? [])]); const added = (order[folder] ?? []).filter(item => !known.has(item)); order[folder] = [...(target.order[folder] ?? []), ...added]; } return { ...result, order }; }