示例工程 33-clipboard-dnd-fs
33-clipboard-dnd-fs/demo-02-file-gate/gate.ts
type DropFile = { name: string; size: number };
type Result = {
accepted: DropFile[];
rejected: Array<{ name: string; reason: string }>;
};
const ALLOWED = [".md", ".txt", ".json", ".log"];
const MAX = 1024 * 1024;
function extension(name: string): string {
const index = name.lastIndexOf(".");
return index === -1 ? "" : name.slice(index).toLowerCase();
}
function gate(files: DropFile[]): Result {
const accepted: DropFile[] = [];
const rejected: Result["rejected"] = [];
for (const file of files) {
const ext = extension(file.name);
if (!ALLOWED.includes(ext)) {
rejected.push({ name: file.name, reason: "BAD_EXTENSION" });
continue;
}
if (!Number.isFinite(file.size) || file.size <= 0) {
rejected.push({ name: file.name, reason: "BAD_SIZE" });
continue;
}
if (file.size > MAX) {
rejected.push({ name: file.name, reason: "TOO_LARGE" });
continue;
}
accepted.push(file);
}
return { accepted, rejected };
}
function parseText(text: string): string | null {
if (text.length === 0 || text.length > 1024 * 1024) return null;
if (/[\u0000\u0001-\u0008\u000b\u000c\u000e-\u001f]/.test(text)) return null;
return text;
}
const result = gate([
{ name: "notes.md", size: 1024 },
{ name: "image.png", size: 2048 },
{ name: "big.txt", size: MAX + 1 },
{ name: "empty.json", size: 0 },
{ name: "CONFIG.JSON", size: 500 },
]);
console.log(
JSON.stringify({
evt: "smoke",
ok:
result.accepted.length === 2 &&
result.accepted[0]?.name === "notes.md" &&
result.accepted[1]?.name === "CONFIG.JSON" &&
result.rejected.length === 3 &&
result.rejected[0]?.reason === "BAD_EXTENSION" &&
result.rejected[1]?.reason === "TOO_LARGE" &&
result.rejected[2]?.reason === "BAD_SIZE" &&
parseText("hello") === "hello" &&
parseText("bad\u0000text") === null &&
parseText("") === null,
accepted: result.accepted,
rejected: result.rejected,
}),
);