Skip to content

Commit

Permalink
calculate file sizes
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkE16 committed Mar 3, 2025
1 parent a0f2e91 commit bb89502
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 40 deletions.
6 changes: 3 additions & 3 deletions components/Canvas/Canvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ const Canvas: FC<CanvasProps> = ({ isGrabbing }) => {
}))
);

const { references, add } = useLayerReferences();
const { references, add, getActiveLayer } = useLayerReferences();
const { get, remove } = useIndexed();

const isDrawing = useRef<boolean>(false);
Expand Down Expand Up @@ -268,7 +268,7 @@ const Canvas: FC<CanvasProps> = ({ isGrabbing }) => {
"Tried to get file from temporary storage, there was no file."
);
} else {
const ref = references.current[0]; // The first layer is always the main canvas.
const ref = getActiveLayer();
const canvasWidth = Number(ref.style.width.replace("px", ""));
const canvasHeight = Number(ref.style.height.replace("px", ""));
const ctx = ref.getContext("2d");
Expand Down Expand Up @@ -360,7 +360,7 @@ const Canvas: FC<CanvasProps> = ({ isGrabbing }) => {
}

updateLayers();
}, [setLayers, get, references]);
}, [setLayers, get, references, getActiveLayer, remove]);

useEffect(() => {
const refs = references.current;
Expand Down
2 changes: 1 addition & 1 deletion components/IndexedDBProvider/IndexedDBProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useEffect, createContext, useRef, useCallback, useMemo } from "react";
// Types
import type { FC, PropsWithChildren } from "react";

const STORES = ["layers", "elements", "temp"];
const STORES = ["layers", "elements", "temp", "fileSizes"];
const VERSION = 1; // Bump this up when the schema changes.

type IndexedUtils = {
Expand Down
33 changes: 7 additions & 26 deletions components/SaveCanvasButton/SaveCanvasButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,35 +26,14 @@ const SaveCanvasButton: FC = () => {
throw new Error(
"Cannot export canvas: no references found. This is a bug."
);
let sizeBytes = 0;
const urlParams = new URLSearchParams(window.location.search);
const fileId = urlParams.get("f");

if (!fileId) {
throw new Error("No file ID found in the URL. This is a bug.");

Check failure on line 34 in components/SaveCanvasButton/SaveCanvasButton.tsx

View workflow job for this annotation

GitHub Actions / Execute Vite tests

Unhandled error

Error: No file ID found in the URL. This is a bug. ❯ components/SaveCanvasButton/SaveCanvasButton.tsx:34:10 ❯ processDispatchQueue node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom-client.development.js:16122:17 ❯ node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom-client.development.js:16725:9 ❯ batchedUpdates$1 node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom-client.development.js:3129:40 ❯ dispatchEventForPluginEventSystem node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom-client.development.js:16281:7 ❯ dispatchEvent node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom-client.development.js:20353:11 ❯ dispatchDiscreteEvent node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom-client.development.js:20321:11 ❯ HTMLDivElement.callTheUserObjectsOperation node_modules/.pnpm/[email protected]/node_modules/jsdom/lib/jsdom/living/generated/EventListener.js:26:30 ❯ innerInvokeEventListeners node_modules/.pnpm/[email protected]/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:350:25 ❯ invokeEventListeners node_modules/.pnpm/[email protected]/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:286:3 This error originated in "tests/integration/SaveCanvasButton.test.tsx" test file. It doesn't mean the error was thrown inside the file itself, but while it was running. The latest test that might've caused the error is "should indicate that the canvas was saved on the tooltip after keyboard shortcut". It might mean one of the following: - The error was thrown, while Vitest was running this test. - If the error occurred after the test had been completed, this was the last documented test before it was thrown.

Check failure on line 34 in components/SaveCanvasButton/SaveCanvasButton.tsx

View workflow job for this annotation

GitHub Actions / Execute Vite tests

Unhandled error

Error: No file ID found in the URL. This is a bug. ❯ components/SaveCanvasButton/SaveCanvasButton.tsx:34:10 ❯ handleKeyboardSave components/SaveCanvasButton/SaveCanvasButton.tsx:90:5 ❯ callTheUserObjectsOperation node_modules/.pnpm/[email protected]/node_modules/jsdom/lib/jsdom/living/generated/EventListener.js:26:30 ❯ innerInvokeEventListeners node_modules/.pnpm/[email protected]/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:350:25 ❯ invokeEventListeners node_modules/.pnpm/[email protected]/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:286:3 ❯ EventTargetImpl._dispatch node_modules/.pnpm/[email protected]/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:233:9 ❯ EventTargetImpl.dispatchEvent node_modules/.pnpm/[email protected]/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:104:17 ❯ dispatchEvent node_modules/.pnpm/[email protected]/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:241:34 ❯ node_modules/.pnpm/@testing-library[email protected]/node_modules/@testing-library/dom/dist/events.js:19:20 ❯ node_modules/.pnpm/@testing-library[email protected]_@[email protected]_@[email protected]_@types+reac_75pw4xbvzl4m4awzelcfrgu7ka/node_modules/@testing-library/react/dist/pure.js:108:16 This error originated in "tests/integration/SaveCanvasButton.test.tsx" test file. It doesn't mean the error was thrown inside the file itself, but while it was running. The latest test that might've caused the error is "tests/integration/SaveCanvasButton.test.tsx". It might mean one of the following: - The error was thrown, while Vitest was running this test. - If the error occurred after the test had been completed, this was the last documented test before it was thrown.
}

// const elements = Array.from(document.getElementsByClassName("element"));
// references.current.forEach((canvas, index) => {
// if (canvas === null) {
// remove(index);
// return;
// }
// canvas.toBlob(async (blob) => {
// if (!blob) {
// throw new Error(
// `Failed to save canvas with id: ${canvas.id} and name: ${canvas.getAttribute("data-name")}.`
// );
// }

// await set("layers", fileId, {
// [canvas.id]: {
// name: canvas.getAttribute("data-name"),
// image: blob,
// position: index
// }
// });
// });
// });
const canvasAsJSON = references.current.map((canvas, index) => {
if (canvas === null) {
remove(index);
Expand All @@ -69,6 +48,8 @@ const SaveCanvasButton: FC = () => {
);
}

sizeBytes += blob.size;

resolve({
name: canvas.getAttribute("data-name"),
image: blob,
Expand All @@ -79,10 +60,6 @@ const SaveCanvasButton: FC = () => {
});
});

const layers = await Promise.all(canvasAsJSON);

await set("layers", fileId, layers);

const allUnfocused = elements.current.map<Omit<CanvasElement, "focused">>(
(element) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
Expand All @@ -92,6 +69,10 @@ const SaveCanvasButton: FC = () => {
}
);

const layers = await Promise.all(canvasAsJSON);

await set("fileSizes", fileId, sizeBytes);
await set("layers", fileId, layers);
await set("elements", fileId, allUnfocused);

// Update the UI to indicate that the canvas has been saved
Expand Down
40 changes: 30 additions & 10 deletions pages/home/index.page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import shared_file_logo from "../../assets/icons/icons_151918.png";
import archived_logo from "../../assets/icons/icons_417061.png";
import exclamation from "../../assets/icons/exclamation.png";
import del from "../../assets/icons/delete.svg";
import { useRef } from "react";
import { useEffect, useRef, useState } from "react";
import { navigateTo } from "../../utils";
import { v4 as uuidv4 } from "uuid";
import useIndexed from "../../state/hooks/useIndexed";
Expand Down Expand Up @@ -122,13 +122,18 @@ const outlets: Record<string, FC<{ files: unknown[] }>> = {
shared: Shared
};

const BYTES_PER_MEGABYTE = 1_048_576;
const MAX_BYTES_SIZE = BYTES_PER_MEGABYTE * 300; // 300 megabytes.
const MAX_MEGABYTES = MAX_BYTES_SIZE / BYTES_PER_MEGABYTE;

const Page: FC = () => {
const { set } = useIndexed();
const [usedBytes, setUsedBytes] = useState<number>(0);
const { set, get } = useIndexed();
const fileDialogRef = useRef<HTMLInputElement>(null);
const canvases = new Array(10).fill(null);
const usedMB = 200;
const maxMB = 300;
const barWidth = `${(usedMB / maxMB) * 100}%`;
const barWidth = `${(usedBytes / MAX_BYTES_SIZE) * 100}%`;
const usedMegaBytes = (usedBytes / BYTES_PER_MEGABYTE).toFixed(2);

let page = undefined;
let pageTitle = undefined;
if (typeof window !== "undefined") {
Expand Down Expand Up @@ -158,16 +163,31 @@ const Page: FC = () => {
throw new Error("No file was uploaded when opening a file.");
}

const [name, ext] = file.name.split(".");

const fileId = uuidv4();

// Probably a better way to handle this.
await set("temp", fileId, file);
await set("temp", fileId, file);

navigateTo(`/editor?f=${fileId}&open=1`);
};

// Get the files to display as well as get
// the current size accumulated by all files.
useEffect(() => {
async function getFilesAndSize() {
const sizes = await get<[string, number][]>("fileSizes");

if (!sizes) {
console.error("Cant update size count.");
} else {
const total = sizes.reduce((acc, [, size]) => acc + size, 0);
setUsedBytes(total);
}
}

getFilesAndSize();
}, [get]);

const Outlet = outlets[page || "projects"];

return (
Expand Down Expand Up @@ -255,7 +275,7 @@ const Page: FC = () => {
></div>
</div>
<p className="amountLeft">
{usedMB} MB of {maxMB} MB Used
{usedMegaBytes} MB of {MAX_MEGABYTES} MB Used
</p>
<a
href=""
Expand Down

0 comments on commit bb89502

Please sign in to comment.