first draft
This commit is contained in:
73
src/lib/server/sync/core/tree.ts
Normal file
73
src/lib/server/sync/core/tree.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import type { ItemState } from './model';
|
||||
|
||||
type ParentOf = (item: ItemState) => string | null;
|
||||
|
||||
const desiredParent: ParentOf = (item) => item.desired.parentSourceId;
|
||||
const syncedParent: ParentOf = (item) => item.synced.parentSourceId;
|
||||
|
||||
/**
|
||||
* Read-only view over a project's items. Reads the map live, so it reflects
|
||||
* entries replaced after construction.
|
||||
*/
|
||||
export class ItemTree {
|
||||
constructor(
|
||||
private readonly rootId: string,
|
||||
private readonly items: ReadonlyMap<string, ItemState>
|
||||
) {}
|
||||
|
||||
/** Desired ancestors, nearest first, stopping before the root. Cycle-safe. */
|
||||
ancestors(sourceId: string): ItemState[] {
|
||||
const result: ItemState[] = [];
|
||||
const seen = new Set([sourceId]);
|
||||
let parentId = this.items.get(sourceId)?.desired.parentSourceId;
|
||||
while (parentId && parentId !== this.rootId && !seen.has(parentId)) {
|
||||
const parent = this.items.get(parentId);
|
||||
if (!parent) break;
|
||||
result.push(parent);
|
||||
seen.add(parentId);
|
||||
parentId = parent.desired.parentSourceId;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
depth(sourceId: string): number {
|
||||
return this.ancestors(sourceId).length;
|
||||
}
|
||||
|
||||
/** Display path relative to the project root, e.g. `Drawings/Level 1/plan.pdf`. */
|
||||
path(sourceId: string): string {
|
||||
const item = this.items.get(sourceId);
|
||||
if (!item) return sourceId;
|
||||
return [...this.ancestors(sourceId).reverse(), item].map((i) => i.desired.name).join('/');
|
||||
}
|
||||
|
||||
/** Items under `folderId` according to SharePoint. */
|
||||
desiredDescendants(folderId: string): ItemState[] {
|
||||
return this.descendants(folderId, desiredParent);
|
||||
}
|
||||
|
||||
/** Items under `folderId` as they currently sit in ACC. */
|
||||
syncedDescendants(folderId: string): ItemState[] {
|
||||
return this.descendants(folderId, syncedParent);
|
||||
}
|
||||
|
||||
private descendants(folderId: string, parentOf: ParentOf): ItemState[] {
|
||||
const children = new Map<string, ItemState[]>();
|
||||
for (const item of this.items.values()) {
|
||||
const parentId = parentOf(item);
|
||||
if (parentId) children.set(parentId, [...(children.get(parentId) ?? []), item]);
|
||||
}
|
||||
const result: ItemState[] = [];
|
||||
const seen = new Set([folderId]);
|
||||
const queue = [folderId];
|
||||
while (queue.length > 0) {
|
||||
for (const child of children.get(queue.shift()!) ?? []) {
|
||||
if (seen.has(child.sourceId)) continue;
|
||||
seen.add(child.sourceId);
|
||||
result.push(child);
|
||||
queue.push(child.sourceId);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user