aboutsummaryrefslogtreecommitdiff
path: root/src/background/usecases/StartFindUseCase.ts
blob: 066d930b928dba3cd6f4e376fc3daeeb11822827 (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
import { inject, injectable } from "tsyringe";
import ConsoleClient from "../infrastructures/ConsoleClient";
import FindRepositoryImpl from "../repositories/FindRepository";
import FindClient from "../clients/FindClient";
import FramePresenter from "../presenters/FramePresenter";

@injectable()
export default class StartFindUseCase {
  constructor(
    @inject("FindClient")
    private readonly findClient: FindClient,
    @inject("FindRepository")
    private readonly findRepository: FindRepositoryImpl,
    @inject("ConsoleClient")
    private readonly consoleClient: ConsoleClient,
    @inject("FramePresenter")
    private readonly framePresenter: FramePresenter
  ) {}

  async startFind(tabId: number, keyword?: string): Promise<void> {
    if (typeof keyword === "undefined") {
      keyword = (await this.findRepository.getLocalState(tabId))?.keyword;
    }
    if (typeof keyword === "undefined") {
      keyword = await this.findRepository.getGlobalKeyword();
    }
    if (typeof keyword === "undefined") {
      await this.consoleClient.showError(tabId, "No previous search keywords");
      return;
    }

    this.findRepository.setGlobalKeyword(keyword);

    const frameIds = await this.framePresenter.getAllFrameIds(tabId);
    for (const frameId of frameIds) {
      await this.findClient.clearSelection(tabId, frameId);
    }

    for (let framePos = 0; framePos < frameIds.length; ++framePos) {
      const found = await this.findClient.findNext(
        tabId,
        frameIds[framePos],
        keyword
      );
      if (found) {
        await this.findRepository.setLocalState(tabId, {
          frameIds,
          framePos,
          keyword,
        });
        await this.consoleClient.showInfo(tabId, "Pattern found: " + keyword);
        return;
      }
    }
    this.consoleClient.showError(tabId, "Pattern not found: " + keyword);
  }
}