aboutsummaryrefslogtreecommitdiff
path: root/src/content/actions/find.ts
blob: 53e03ae95112774cc00bfc9879042002535d98ca (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
96
97
98
99
100
//
// window.find(aString, aCaseSensitive, aBackwards, aWrapAround,
//             aWholeWord, aSearchInFrames);
//
// NOTE: window.find is not standard API
// https://developer.mozilla.org/en-US/docs/Web/API/Window/find

import * as messages from '../../shared/messages';
import * as actions from './index';
import * as consoleFrames from '../console-frames';

interface MyWindow extends Window {
  find(
    aString: string,
    aCaseSensitive?: boolean,
    aBackwards?: boolean,
    aWrapAround?: boolean,
    aWholeWord?: boolean,
    aSearchInFrames?: boolean,
    aShowDialog?: boolean): boolean;
}

// eslint-disable-next-line no-var, vars-on-top, init-declarations
declare var window: MyWindow;

const find = (str: string, backwards: boolean): boolean => {
  let caseSensitive = false;
  let wrapScan = true;


  // NOTE: aWholeWord dows not implemented, and aSearchInFrames does not work
  // because of same origin policy

  // eslint-disable-next-line no-extra-parens
  let found = window.find(str, caseSensitive, backwards, wrapScan);
  if (found) {
    return found;
  }
  let sel = window.getSelection();
  if (sel) {
    sel.removeAllRanges();
  }

  // eslint-disable-next-line no-extra-parens
  return window.find(str, caseSensitive, backwards, wrapScan);
};

// eslint-disable-next-line max-statements
const findNext = async(
  currentKeyword: string, reset: boolean, backwards: boolean,
): Promise<actions.FindAction> => {
  if (reset) {
    let sel = window.getSelection();
    if (sel) {
      sel.removeAllRanges();
    }
  }

  let keyword = currentKeyword;
  if (currentKeyword) {
    browser.runtime.sendMessage({
      type: messages.FIND_SET_KEYWORD,
      keyword: currentKeyword,
    });
  } else {
    keyword = await browser.runtime.sendMessage({
      type: messages.FIND_GET_KEYWORD,
    });
  }
  if (!keyword) {
    await consoleFrames.postError('No previous search keywords');
    return { type: actions.NOOP };
  }
  let found = find(keyword, backwards);
  if (found) {
    consoleFrames.postInfo('Pattern found: ' + keyword);
  } else {
    consoleFrames.postError('Pattern not found: ' + keyword);
  }

  return {
    type: actions.FIND_SET_KEYWORD,
    keyword,
    found,
  };
};

const next = (
  currentKeyword: string, reset: boolean,
): Promise<actions.FindAction> => {
  return findNext(currentKeyword, reset, false);
};

const prev = (
  currentKeyword: string, reset: boolean,
): Promise<actions.FindAction> => {
  return findNext(currentKeyword, reset, true);
};

export { next, prev };