xref: /aosp_15_r20/external/perfetto/ui/src/frontend/file_drop_handler.ts (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1// Copyright (C) 2018 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import {AppImpl} from '../core/app_impl';
16
17let lastDragTarget: EventTarget | null = null;
18
19export function installFileDropHandler() {
20  window.ondragenter = (evt: DragEvent) => {
21    evt.preventDefault();
22    evt.stopPropagation();
23    lastDragTarget = evt.target;
24    if (dragEventHasFiles(evt)) {
25      document.body.classList.add('filedrag');
26    }
27  };
28
29  window.ondragleave = (evt: DragEvent) => {
30    evt.preventDefault();
31    evt.stopPropagation();
32    if (evt.target === lastDragTarget) {
33      document.body.classList.remove('filedrag');
34    }
35  };
36
37  window.ondrop = (evt: DragEvent) => {
38    evt.preventDefault();
39    evt.stopPropagation();
40    document.body.classList.remove('filedrag');
41    if (evt.dataTransfer && dragEventHasFiles(evt)) {
42      const file = evt.dataTransfer.files[0];
43      // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
44      if (file) {
45        AppImpl.instance.openTraceFromFile(file);
46      }
47    }
48    evt.preventDefault();
49  };
50
51  window.ondragover = (evt: DragEvent) => {
52    evt.preventDefault();
53    evt.stopPropagation();
54  };
55}
56
57function dragEventHasFiles(event: DragEvent): boolean {
58  // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
59  if (event.dataTransfer && event.dataTransfer.types) {
60    for (const type of event.dataTransfer.types) {
61      if (type === 'Files') return true;
62    }
63  }
64  return false;
65}
66