Open source CapCut alternative.
TypeScript
fix(site): count subfolders in a folder's size
David Leeb37e516ef96
diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsxindex adb3cfca..49eeabeb 100644--- a/site/src/cut/components/ProjectsHome.tsx+++ b/site/src/cut/components/ProjectsHome.tsx@@ -1,6 +1,6 @@"use client";-import { useCallback, useEffect, useRef, useState, useSyncExternalStore, type RefObject } from "react";+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type RefObject } from "react";import { useQueryClient } from "@tanstack/react-query";import { useLocale, useTranslations } from "next-intl";import { useRouter, useSearchParams } from "next/navigation";@@ -88,7 +88,7 @@ import {} from "@/cut/lib/types";import { cn } from "@/lib/utils";import { setObjectDragImage } from "@/cut/lib/assetDrag";-import { childrenOf, folderTrail, folderWithin, parentOf, subtreeOf } from "@/cut/lib/folderTree";+import { childrenOf, folderTrail, folderWithin, parentOf, subtreeItems, subtreeOf, subtreeTotals } from "@/cut/lib/folderTree";import { PICKED_RING } from "@/cut/lib/assetPick";import { projectsHomeView } from "@/cut/lib/projectsHomeView";import { errorFromBody } from "@/cut/lib/userError";@@ -304,6 +304,18 @@ export function ProjectsHome() {cloud: asSection(cloudSection),browser: asSection(browserSection),};+ // Every folder's size with its subfolders, one pass per listing, kept until+ // a listing changes.+ const folderBytes = useMemo(() => {+ const bytes = new Map<string, number>();+ for (const q of [localSection.data, cloudSection.data, browserSection.data]) {+ const totals = subtreeTotals(q?.folders ?? [], q?.projects ?? [], (p) => p.sizeBytes ?? 0);+ for (const [id, n] of totals) {+ bytes.set(id, n);+ }+ }+ return bytes;+ }, [localSection.data, cloudSection.data, browserSection.data]);// Optimistic edits to a section's cached listing; the next revalidation// reconciles whatever the server actually did.@@ -404,11 +416,11 @@ export function ProjectsHome() {const deleteFolder = async (r: Residency, id: string) => {if (!live(r)) return;const tree = new Set(subtreeOf(data[r].folders, id));- const inTree = (p: ProjectSummary) => !!p.folderId && tree.has(p.folderId);- const held = (data[r].projects ?? []).filter(inTree);+ const held = subtreeItems(data[r].folders, data[r].projects ?? [], id);+ const heldIds = new Set(held.map((p) => p.id));patch(r, (s) => ({folders: s.folders.filter((f) => !tree.has(f.id)),- projects: s.projects.filter((p) => !inTree(p)),+ projects: s.projects.filter((p) => !heldIds.has(p.id)),}));const res = await backendFor(r).fetch(`/api/cut/projects/folders/${id}`, { method: "DELETE" })@@ -424,8 +436,7 @@ export function ProjectsHome() {const heldBy = (fs: ProjectFolder[]) =>fs.reduce((n, f) => {const r = residencyOfFolder(f.id);- const tree = new Set(subtreeOf(data[r].folders, f.id));- return n + (data[r].projects ?? []).filter((p) => !!p.folderId && tree.has(p.folderId)).length;+ return n + subtreeItems(data[r].folders, data[r].projects ?? [], f.id).length;}, 0);// File folders under a folder (or out to the root, parentId null). A folder@@ -801,7 +812,7 @@ export function ProjectsHome() {const items = (data[r].projects ?? []).filter((p) => (p.folderId ?? null) === id);return {count: items.length + childrenOf(data[r].folders, id).length,- size: items.reduce((n, p) => n + (p.sizeBytes ?? 0), 0),+ size: folderBytes.get(id) ?? 0,};}}picked={selected}diff --git a/site/src/cut/lib/folderTree.test.ts b/site/src/cut/lib/folderTree.test.tsindex 0c777e4a..938bf48c 100644--- a/site/src/cut/lib/folderTree.test.ts+++ b/site/src/cut/lib/folderTree.test.ts@@ -1,5 +1,5 @@import { describe, expect, test } from "bun:test";-import { childrenOf, folderWithin, resolveParent, subtreeOf } from "./folderTree";+import { childrenOf, folderWithin, resolveParent, subtreeItems, subtreeOf, subtreeTotals } from "./folderTree";// A shelf three deep, with a branch beside the one being deleted.const folders = [@@ -41,3 +41,41 @@ describe("where a folder may file", () => {expect(childrenOf(folders, null).map((f) => f.id)).toEqual(["a", "e"]);});});++describe("what a folder holds", () => {+ test("every item filed under it, however deep", () => {+ const items = [+ { id: 1, folderId: "a" },+ { id: 2, folderId: "c" },+ { id: 3, folderId: "d" },+ { id: 4, folderId: "e" },+ { id: 5, folderId: null },+ { id: 6 },+ ];+ expect(subtreeItems(folders, items, "a").map((i) => i.id)).toEqual([1, 2, 3]);+ expect(subtreeItems(folders, items, "b").map((i) => i.id)).toEqual([2]);+ });+});++describe("what every folder weighs", () => {+ test("each item counts toward its folder and every folder above it", () => {+ const items = [+ { folderId: "a", sizeBytes: 1 },+ { folderId: "c", sizeBytes: 10 },+ { folderId: "d", sizeBytes: 100 },+ { folderId: "e", sizeBytes: 1000 },+ { folderId: null, sizeBytes: 10000 },+ ];+ const totals = subtreeTotals(folders, items, (i) => i.sizeBytes);+ expect(Object.fromEntries(totals)).toEqual({ a: 111, b: 10, c: 10, d: 100, e: 1000 });+ });++ test("a loop two offline devices made counts each item once per folder", () => {+ const looped = [+ { id: "x", parentId: "y" },+ { id: "y", parentId: "x" },+ ];+ const totals = subtreeTotals(looped, [{ folderId: "x", sizeBytes: 5 }], (i) => i.sizeBytes);+ expect(Object.fromEntries(totals)).toEqual({ x: 5, y: 5 });+ });+});diff --git a/site/src/cut/lib/folderTree.ts b/site/src/cut/lib/folderTree.tsindex cac000d0..da90db04 100644--- a/site/src/cut/lib/folderTree.ts+++ b/site/src/cut/lib/folderTree.ts@@ -81,6 +81,49 @@ export function subtreeOf(folders: readonly TreeFolder[], id: string): string[]return tree;}+/** The items filed in `id` or any folder under it, however deep: what the+ * folder holds. */+export function subtreeItems<T extends { folderId?: string | null }>(+ folders: readonly TreeFolder[],+ items: readonly T[],+ id: string,+): T[] {+ const tree = new Set(subtreeOf(folders, id));+ return items.filter((item) => !!item.folderId && tree.has(item.folderId));+}++/** Every folder's total of `weigh` over the items filed in it or anywhere+ * under it, in one pass: each folder's own sum climbs to every folder above+ * it. A loop in the listing is climbed once. */+export function subtreeTotals<T extends { folderId?: string | null }>(+ folders: readonly TreeFolder[],+ items: readonly T[],+ weigh: (item: T) => number,+): Map<string, number> {+ // Each folder's own sum, before anything climbs.+ const own = new Map<string, number>();+ for (const item of items) {+ if (!item.folderId) {+ continue;+ }+ own.set(item.folderId, (own.get(item.folderId) ?? 0) + weigh(item));+ }++ // Climb each sum up the parent chain, stopping at a folder already passed.+ const parents = new Map(folders.map((f) => [f.id, parentOf(f)]));+ const totals = new Map<string, number>(folders.map((f) => [f.id, 0]));+ for (const [id, sum] of own) {+ const seen = new Set<string>();+ let cur: string | null = id;+ while (cur && parents.has(cur) && !seen.has(cur)) {+ seen.add(cur);+ totals.set(cur, (totals.get(cur) ?? 0) + sum);+ cur = parents.get(cur) ?? null;+ }+ }+ return totals;+}+/** The folders filed right under `parentId` (null for the top level). */export function childrenOf<F extends TreeFolder>(folders: readonly F[],