aboutsummaryrefslogtreecommitdiff
path: root/src/content/presenters/FocusPresenter.ts
blob: 359103995cfc979c0821ee857cc2056feed8efd0 (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
import * as doms from "../../shared/utils/dom";

export default interface FocusPresenter {
  focusFirstElement(): boolean;
}

export class FocusPresenterImpl implements FocusPresenter {
  focusFirstElement(): boolean {
    const inputTypes = ["email", "number", "search", "tel", "text", "url"];
    const inputSelector = inputTypes
      .map((type) => `input[type=${type}]`)
      .join(",");
    const targets = window.document.querySelectorAll(
      inputSelector + ",input:not([type]),textarea"
    );
    const target = Array.from(targets).find(doms.isVisible);
    if (target instanceof HTMLInputElement) {
      target.focus();
      return true;
    } else if (target instanceof HTMLTextAreaElement) {
      target.focus();
      return true;
    }
    return false;
  }
}