MCPcopy Create free account
hub / github.com/GraphiteEditor/Graphite / upload

Function upload

frontend/src/utility-functions/files.ts:36–81  ·  view source on GitHub ↗
(
	accept: string,
	textOrData: "text" | "data" | "both",
	multiple = false,
)

Source from the content-addressed store, hash-verified

34export async function upload(accept: string, textOrData: "both"): Promise<UploadResult<{ text: string; data: Uint8Array }>>;
35export async function upload(accept: string, textOrData: "data", multiple: true): Promise<UploadResult<Uint8Array>[]>;
36export async function upload(
37 accept: string,
38 textOrData: "text" | "data" | "both",
39 multiple = false,
40): Promise<UploadResult<string | Uint8Array | { text: string; data: Uint8Array }> | UploadResult<Uint8Array>[]> {
41 return new Promise((resolve) => {
42 const element = document.createElement("input");
43 element.type = "file";
44 element.accept = accept;
45 element.multiple = multiple;
46
47 element.addEventListener(
48 "change",
49 async () => {
50 if (!element.files?.length) return;
51
52 // The `multiple: true` overload constrains `textOrData` to "data", so we know each file produces a Uint8Array
53 if (multiple) {
54 const results = await Promise.all(
55 Array.from(element.files).map(async (file) => ({
56 filename: file.name,
57 type: file.type,
58 content: new Uint8Array(await file.arrayBuffer()),
59 })),
60 );
61 resolve(results);
62 return;
63 }
64
65 const file = element.files[0];
66 const content =
67 textOrData === "text"
68 ? await file.text()
69 : textOrData === "data"
70 ? new Uint8Array(await file.arrayBuffer())
71 : { text: await file.text(), data: new Uint8Array(await file.arrayBuffer()) };
72 resolve({ filename: file.name, type: file.type, content });
73 },
74 { capture: false, once: true },
75 );
76
77 element.click();
78
79 // Once `element` goes out of scope, it has no references so it gets garbage collected along with its event listener, so `removeEventListener` is not needed
80 });
81}
82export type UploadResult<T> = { filename: string; type: string; content: T };
83
84export async function pasteFile(item: DataTransferItem, editor: EditorWrapper, mouse?: [number, number], insertParentId?: bigint, insertIndex?: number) {

Callers 1

createPortfolioStoreFunction · 0.90

Calls 4

clickMethod · 0.80
allMethod · 0.45
fromMethod · 0.45
textMethod · 0.45

Tested by

no test coverage detected