aboutsummaryrefslogtreecommitdiffstats
path: root/packages/excalidraw/tests/helpers/polyfills.ts
blob: 967e8d4e82b283cfb03456615ff1a69efd06d2b1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { URL } from "node:url";

class ClipboardEvent {
  constructor(
    type: "paste" | "copy",
    eventInitDict: {
      clipboardData: DataTransfer;
    },
  ) {
    return Object.assign(
      new Event("paste", {
        bubbles: true,
        cancelable: true,
        composed: true,
      }),
      {
        clipboardData: eventInitDict.clipboardData,
      },
    ) as any as ClipboardEvent;
  }
}

type DataKind = "string" | "file";

class DataTransferItem {
  kind: DataKind;
  type: string;
  data: string | Blob;

  constructor(kind: DataKind, type: string, data: string | Blob) {
    this.kind = kind;
    this.type = type;
    this.data = data;
  }

  getAsString(callback: (data: string) => void): void {
    if (this.kind === "string") {
      callback(this.data as string);
    }
  }

  getAsFile(): File | null {
    if (this.kind === "file" && this.data instanceof File) {
      return this.data;
    }
    return null;
  }
}

class DataTransferList {
  items: DataTransferItem[] = [];

  add(data: string | File, type: string = ""): void {
    if (typeof data === "string") {
      this.items.push(new DataTransferItem("string", type, data));
    } else if (data instanceof File) {
      this.items.push(new DataTransferItem("file", type, data));
    }
  }

  clear(): void {
    this.items = [];
  }
}

class DataTransfer {
  public items: DataTransferList = new DataTransferList();
  private _types: Record<string, string> = {};

  get files() {
    return this.items.items
      .filter((item) => item.kind === "file")
      .map((item) => item.getAsFile()!);
  }

  add(data: string | File, type: string = ""): void {
    this.items.add(data, type);
  }

  setData(type: string, value: string) {
    this._types[type] = value;
  }

  getData(type: string) {
    return this._types[type] || "";
  }
}

export const testPolyfills = {
  ClipboardEvent,
  DataTransfer,
  DataTransferItem,
  // https://github.com/vitest-dev/vitest/pull/4164#issuecomment-2172729965
  URL,
};