aboutsummaryrefslogtreecommitdiff
path: root/src/background/repositories/FindRepository.ts
blob: 3492759d6f92b57ab57cf05eec766526f929b7d0 (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
import { injectable } from "tsyringe";
import MemoryStorage from "../infrastructures/MemoryStorage";

const FIND_GLOBAL_KEYWORD_KEY = "find-global-keyword";
const FIND_LOCAL_KEYWORD_KEY = "find-local-keyword";

export type FindState = {
  keyword: string;
  frameId: number;
};

export default interface FindRepository {
  getGlobalKeyword(): Promise<string | undefined>;

  setGlobalKeyword(keyword: string): Promise<void>;

  getLocalState(tabId: number): Promise<undefined | FindState>;

  setLocalState(tabId: number, state: FindState): Promise<void>;

  deleteLocalState(tabId: number): Promise<void>;
}

@injectable()
export class FindRepositoryImpl implements FindRepository {
  private cache: MemoryStorage;

  constructor() {
    this.cache = new MemoryStorage();
  }

  getGlobalKeyword(): Promise<string | undefined> {
    return Promise.resolve(this.cache.get(FIND_GLOBAL_KEYWORD_KEY));
  }

  setGlobalKeyword(keyword: string): Promise<void> {
    this.cache.set(FIND_GLOBAL_KEYWORD_KEY, keyword);
    return Promise.resolve();
  }

  getLocalState(tabId: number): Promise<FindState | undefined> {
    let states = this.cache.get(FIND_LOCAL_KEYWORD_KEY);
    if (typeof states === "undefined") {
      states = {};
    }
    return Promise.resolve(states[tabId]);
  }

  setLocalState(tabId: number, state: FindState): Promise<void> {
    let states = this.cache.get(FIND_LOCAL_KEYWORD_KEY);
    if (typeof states === "undefined") {
      states = {};
    }
    states[tabId] = state;
    this.cache.set(FIND_LOCAL_KEYWORD_KEY, states);
    return Promise.resolve();
  }

  deleteLocalState(tabId: number): Promise<void> {
    const states = this.cache.get(FIND_LOCAL_KEYWORD_KEY);
    if (typeof states === "undefined") {
      return Promise.resolve();
    }
    delete states[tabId];
    this.cache.set(FIND_LOCAL_KEYWORD_KEY, states);
    return Promise.resolve();
  }
}