Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 38 additions & 15 deletions src/background/undo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,28 +139,51 @@ export function popUndoIfKind(

// ---- Utilities -----------------------------------------------------------

/** Walk all spaces to find the windowId that owns a given folderId. */
export function findWindowIdForFolder(
const folderWindowIdCache = new WeakMap<
Awaited<ReturnType<typeof loadStore>>,
Map<FolderId, number>
>()

function getFolderWindowIdMap(
store: Awaited<ReturnType<typeof loadStore>>,
folderId: FolderId,
): number | undefined {
// BFS from every space root.
for (const sp of Object.values(store.spaces)) {
): Map<FolderId, number> {
let map = folderWindowIdCache.get(store)
if (!map) {
map = new Map<FolderId, number>()
const stack: { id: FolderId; windowId: number }[] = []

for (const sp of Object.values(store.spaces)) {
stack.push({ id: sp.rootFolderId, windowId: sp.windowId })
}

const visited = new Set<FolderId>()
const queue: FolderId[] = [sp.rootFolderId]
while (queue.length) {
const id = queue.shift()!
if (visited.has(id)) continue
visited.add(id)
if (id === folderId) return sp.windowId
const f = store.folders[id]
while (stack.length) {
const curr = stack.pop()!
if (visited.has(curr.id)) continue
visited.add(curr.id)

map.set(curr.id, curr.windowId)

const f = store.folders[curr.id]
if (!f) continue

for (const it of f.items) {
if (it.kind === 'folder') queue.push(it.folderId)
if (it.kind === 'folder') {
stack.push({ id: it.folderId, windowId: curr.windowId })
}
}
}
folderWindowIdCache.set(store, map)
}
return undefined
return map
}

/** Walk all spaces to find the windowId that owns a given folderId. */
export function findWindowIdForFolder(
store: Awaited<ReturnType<typeof loadStore>>,
folderId: FolderId,
): number | undefined {
return getFolderWindowIdMap(store).get(folderId)
}

/** Walk all spaces to find the windowId that owns a given ItemRef. */
Expand Down