Merge pull request #1451 from tridactyl/tslint_rules_reactivation2

Tslint rules reactivation2
This commit is contained in:
Oliver Blanthorn 2019-04-12 09:06:23 +01:00 committed by GitHub
commit 65523419e5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
39 changed files with 247 additions and 255 deletions

View file

@ -37,8 +37,8 @@ else
fi
# .bracketexpr.generated.ts is needed for metadata generation
"$(npm bin)/nearleyc" src/grammars/bracketexpr.ne \
> src/grammars/.bracketexpr.generated.ts
"$(npm bin)/nearleyc" src/grammars/bracketexpr.ne > \
src/grammars/.bracketexpr.generated.ts
# It's important to generate the metadata before the documentation because
# missing imports might break documentation generation on clean builds

View file

@ -41,7 +41,7 @@ import { AutoContain } from "@src/lib/autocontainers"
// {{{ tri.contentLocation
// When loading the background, use the active tab to know what the current content url is
browser.tabs.query({ currentWindow: true, active: true }).then(t => {
;(window as any).tri.contentLocation = new URL(t[0].url)
(window as any).tri.contentLocation = new URL(t[0].url)
})
// After that, on every tab change, update the current url
let contentLocationCount = 0
@ -51,8 +51,8 @@ browser.tabs.onActivated.addListener(ev => {
browser.tabs.get(ev.tabId).then(t => {
// Note: we're using contentLocationCount and myId in order to make sure that only the last onActivated event is used in order to set contentLocation
// This is needed because otherWise the following chain of execution might happen: onActivated1 => onActivated2 => tabs.get2 => tabs.get1
if (contentLocationCount == myId) {
;(window as any).tri.contentLocation = new URL(t.url)
if (contentLocationCount === myId) {
(window as any).tri.contentLocation = new URL(t.url)
}
})
})
@ -91,7 +91,7 @@ browser.runtime.onStartup.addListener(_ => {
config.getAsync("autocmds", "TriStart").then(aucmds => {
let hosts = Object.keys(aucmds)
// If there's only one rule and it's "all", no need to check the hostname
if (hosts.length == 1 && hosts[0] == ".*") {
if (hosts.length === 1 && hosts[0] === ".*") {
BackgroundController.acceptExCmd(aucmds[hosts[0]])
} else {
native.run("hostname").then(hostname => {

View file

@ -5,7 +5,7 @@ const logger = new Logger("rc")
export async function source(filename = "auto") {
let rctext = ""
if (filename == "auto") {
if (filename === "auto") {
rctext = await Native.getrc()
} else {
rctext = (await Native.read(filename)).content

View file

@ -103,25 +103,25 @@ export async function downloadUrlAs(url: string, saveAs: string) {
// We want to return a promise that will resolve once the file has been moved somewhere else
return new Promise((resolve, reject) => {
let onDownloadComplete = async downloadDelta => {
if (downloadDelta.id != downloadId) {
if (downloadDelta.id !== downloadId) {
return
}
// Note: this might be a little too drastic. For example, files that encounter a problem while being downloaded and the download of which is restarted by a user won't be moved
// This seems acceptable for now as taking all states into account seems quite difficult
if (
downloadDelta.state &&
downloadDelta.state.current != "in_progress"
downloadDelta.state.current !== "in_progress"
) {
browser.downloads.onChanged.removeListener(onDownloadComplete)
let downloadItem = (await browser.downloads.search({
id: downloadId,
}))[0]
if (downloadDelta.state.current == "complete") {
if (downloadDelta.state.current === "complete") {
let operation = await Native.move(
downloadItem.filename,
saveAs,
)
if (operation.code != 0) {
if (operation.code !== 0) {
reject(
new Error(
`'${

View file

@ -13,7 +13,7 @@ export class Parser {
}
feedUntilError(input) {
let lastResult = undefined
let lastResult
let consumedIndex = 0
try {
for (let val of input) {

View file

@ -49,7 +49,7 @@ import * as tri_editor from "@src/lib/editor"
const logger = new Logger("cmdline")
/** @hidden **/
let activeCompletions: Completions.CompletionSource[] = undefined
let activeCompletions: Completions.CompletionSource[]
/** @hidden **/
let completionsDiv = window.document.getElementById("completions")
/** @hidden **/
@ -185,7 +185,7 @@ export function complete() {
let fragment = clInput.value
let matches = state.cmdHistory.filter(key => key.startsWith(fragment))
let mostrecent = matches[matches.length - 1]
if (mostrecent != undefined) clInput.value = mostrecent
if (mostrecent !== undefined) clInput.value = mostrecent
return refresh_completions(clInput.value)
}
@ -275,7 +275,7 @@ clInput.addEventListener("input", () => {
// Make sure the previous computation has ended
await onInputPromise
// If we're not the current completion computation anymore, stop
if (exstr != clInput.value) return
if (exstr !== clInput.value) return
onInputPromise = refresh_completions(exstr)
}, 100)
@ -344,7 +344,7 @@ function history(n) {
let matches = state.cmdHistory.filter(key =>
key.startsWith(HISTORY_SEARCH_STRING),
)
if (cmdline_history_position == 0) {
if (cmdline_history_position === 0) {
cmdline_history_current = clInput.value
}
let clamped_ind = matches.length + n - cmdline_history_position
@ -352,11 +352,11 @@ function history(n) {
const pot_history = matches[clamped_ind]
clInput.value =
pot_history == undefined ? cmdline_history_current : pot_history
pot_history === undefined ? cmdline_history_current : pot_history
// if there was no clampage, update history position
// there's a more sensible way of doing this but that would require more programmer time
if (clamped_ind == matches.length + n - cmdline_history_position)
if (clamped_ind === matches.length + n - cmdline_history_position)
cmdline_history_position = cmdline_history_position - n
}

View file

@ -80,7 +80,7 @@ export abstract class CompletionSource {
shouldRefresh() {
// A completion source should be refreshed if it is not hidden or if it just became hidden
return this._state != "hidden" || this.state != this._prevState
return this._state !== "hidden" || this.state !== this._prevState
}
abstract next(inc?: number): boolean
@ -91,7 +91,7 @@ export abstract class CompletionSource {
deselect() {
this.completion = undefined
if (this.lastFocused != undefined) this.lastFocused.state = "normal"
if (this.lastFocused !== undefined) this.lastFocused.state = "normal"
}
}
@ -284,7 +284,7 @@ export abstract class CompletionSourceFuse extends CompletionSource {
for (const option of this.options) {
/* newContainer.appendChild(option.html) */
if (option.state != "hidden")
if (option.state !== "hidden")
this.optionContainer.appendChild(option.html)
}
@ -296,9 +296,9 @@ export abstract class CompletionSourceFuse extends CompletionSource {
}
next(inc = 1) {
if (this.state != "hidden") {
let visopts = this.options.filter(o => o.state != "hidden")
let currind = visopts.findIndex(o => o.state == "focused")
if (this.state !== "hidden") {
let visopts = this.options.filter(o => o.state !== "hidden")
let currind = visopts.findIndex(o => o.state === "focused")
this.deselect()
// visopts.length + 1 because we want an empty completion at the end
let max = visopts.length + 1

View file

@ -29,7 +29,7 @@ export class FileSystemCompletionSource extends Completions.CompletionSourceFuse
}
public async filter(exstr: string) {
if (!exstr || exstr.indexOf(" ") == -1) {
if (!exstr || exstr.indexOf(" ") === -1) {
this.state = "hidden"
return
}

View file

@ -40,7 +40,7 @@ export class FindCompletionSource extends Completions.CompletionSourceFuse {
// If there's already a promise being executed, wait for it to finish
await this.prevCompletion
// Since we might have awaited for this.prevCompletion, we don't have a guarantee we're the last completion the user asked for anymore
if (id == this.completionCount - 1) {
if (id === this.completionCount - 1) {
// If we are the last completion
this.prevCompletion = this.updateOptions(exstr)
await this.prevCompletion

View file

@ -67,7 +67,7 @@ export class GuisetCompletionSource extends Completions.CompletionSourceFuse {
),
)
}
if (this.options.length == 0) {
if (this.options.length === 0) {
this.options = Object.keys(metaRules)
.concat(Object.keys(potentialRules))
.filter(s => s.startsWith(ruleName))

View file

@ -59,7 +59,7 @@ export class HistoryCompletionSource extends Completions.CompletionSourceFuse {
// Ignoring command-specific arguments
// It's terrible but it's ok because it's just a stopgap until an actual commandline-parsing API is implemented
if (prefix == "tabopen ") {
if (prefix === "tabopen ") {
if (query.startsWith("-c")) {
let args = query.split(" ")
options = args.slice(0, 2).join(" ")
@ -70,7 +70,7 @@ export class HistoryCompletionSource extends Completions.CompletionSourceFuse {
options = args.slice(0, 1).join(" ")
query = args.slice(1).join(" ")
}
} else if (prefix == "winopen " && query.startsWith("-private")) {
} else if (prefix === "winopen " && query.startsWith("-private")) {
options = "-private"
query = query.substring(options.length)
}
@ -102,7 +102,7 @@ export class HistoryCompletionSource extends Completions.CompletionSourceFuse {
private async scoreOptions(query: string, n: number) {
const newtab = (browser.runtime.getManifest()).chrome_url_overrides.newtab
const newtaburl = browser.extension.getURL(newtab)
if (!query || config.get("historyresults") == 0) {
if (!query || config.get("historyresults") === 0) {
return (await browserBg.topSites.get())
.filter(page => page.url !== newtaburl)
.slice(0, n)

View file

@ -53,7 +53,7 @@ export class SettingsCompletionSource extends Completions.CompletionSourceFuse {
// Ignoring command-specific arguments
// It's terrible but it's ok because it's just a stopgap until an actual commandline-parsing API is implemented
// copy pasting code is fun and good
if (prefix == "seturl " || prefix == "unseturl ") {
if (prefix === "seturl " || prefix === "unseturl ") {
let args = query.split(" ")
options = args.slice(0, 1).join(" ")
query = args.slice(1).join(" ")

View file

@ -142,7 +142,7 @@ export class BufferCompletionSource extends Completions.CompletionSourceFuse {
// When the user is asking for tabmove completions, don't autoselect if the query looks like a relative move https://github.com/tridactyl/tridactyl/issues/825
this.shouldSetStateFromScore = !(
prefix == "tabmove " && query.match("^[+-][0-9]+$")
prefix === "tabmove " && query.match("^[+-][0-9]+$")
)
/* console.log('updateOptions', this.optionContainer) */

View file

@ -91,7 +91,7 @@ export class TabAllCompletionSource extends Completions.CompletionSourceFuse {
const options = []
tabs.sort((a, b) => {
if (a.windowId == b.windowId) return a.index - b.index
if (a.windowId === b.windowId) return a.index - b.index
return a.windowId - b.windowId
})
@ -100,7 +100,7 @@ export class TabAllCompletionSource extends Completions.CompletionSourceFuse {
let lastId = 0
let winindex = 0
for (const tab of tabs) {
if (lastId != tab.windowId) {
if (lastId !== tab.windowId) {
lastId = tab.windowId
winindex += 1
}

View file

@ -19,7 +19,7 @@ class WindowCompletionOption extends Completions.CompletionOptionHTML
<td class="id">${win.id}</td>
<td class="title">${win.title}</td>
<td class="tabcount">${win.tabs.length} tab${
win.tabs.length != 1 ? "s" : ""
win.tabs.length !== 1 ? "s" : ""
}</td>
</tr>`
}

View file

@ -4,7 +4,7 @@
if ((window as any).tridactyl_content_lock !== undefined) {
throw Error("Trying to load Tridactyl, but it's already loaded.")
}
;(window as any).tridactyl_content_lock = "locked"
(window as any).tridactyl_content_lock = "locked"
// Be careful: typescript elides imports that appear not to be used if they're
// assigned to a name. If you want an import just for its side effects, make
@ -116,7 +116,7 @@ if (
window.location.pathname === "/static/newtab.html"
) {
config.getAsync("newtab").then(newtab => {
if (newtab == "about:blank") {
if (newtab === "about:blank") {
} else if (newtab) {
excmds.open_quiet(newtab)
} else {
@ -211,7 +211,7 @@ config.getAsync("modeindicator").then(mode => {
let mode = newValue
let suffix = ""
let result = ""
if (property != "mode") {
if (property !== "mode") {
if (property === "suffix") {
mode = oldMode
suffix = newValue
@ -243,7 +243,7 @@ config.getAsync("modeindicator").then(mode => {
result = mode
}
let modeindicatorshowkeys = Config.get("modeindicatorshowkeys")
if (modeindicatorshowkeys === "true" && suffix != "") {
if (modeindicatorshowkeys === "true" && suffix !== "") {
result = mode + " " + suffix
}
logger.debug(
@ -263,12 +263,12 @@ config.getAsync("modeindicator").then(mode => {
// Site specific fix for / on GitHub.com
config.getAsync("leavegithubalone").then(v => {
if (v == "true") return
if (v === "true") return
try {
// On quick loading pages, the document is already loaded
// if (document.location.host == "github.com") {
// if (document.location.host === "github.com") {
document.body.addEventListener("keydown", function(e) {
if ("/".indexOf(e.key) != -1 && contentState.mode == "normal") {
if ("/".indexOf(e.key) !== -1 && contentState.mode === "normal") {
e.cancelBubble = true
e.stopImmediatePropagation()
}
@ -277,9 +277,9 @@ config.getAsync("leavegithubalone").then(v => {
} catch (e) {
// But on slower pages we wait for the document to load
window.addEventListener("DOMContentLoaded", () => {
// if (document.location.host == "github.com") {
// if (document.location.host === "github.com") {
document.body.addEventListener("keydown", function(e) {
if ("/".indexOf(e.key) != -1 && contentState.mode == "normal") {
if ("/".indexOf(e.key) !== -1 && contentState.mode === "normal") {
e.cancelBubble = true
e.stopImmediatePropagation()
}

View file

@ -33,7 +33,7 @@ let enabled = false
/** Initialise the cmdline_iframe element unless the window location is included in a value of config/noiframe */
async function init() {
let noiframe = await config.getAsync("noiframe")
if (noiframe == "false" && !enabled) {
if (noiframe === "false" && !enabled) {
hide()
document.documentElement.appendChild(cmdline_iframe)
enabled = true

View file

@ -73,13 +73,13 @@ class KeyCanceller {
private cancelKey(ke: KeyboardEvent, kes: KeyboardEvent[]) {
let index = kes.findIndex(
ke2 =>
ke.altKey == ke2.altKey &&
ke.code == ke2.code &&
ke.composed == ke2.composed &&
ke.ctrlKey == ke2.ctrlKey &&
ke.metaKey == ke2.metaKey &&
ke.shiftKey == ke2.shiftKey &&
ke.target == ke2.target,
ke.altKey === ke2.altKey &&
ke.code === ke2.code &&
ke.composed === ke2.composed &&
ke.ctrlKey === ke2.ctrlKey &&
ke.metaKey === ke2.metaKey &&
ke.shiftKey === ke2.shiftKey &&
ke.target === ke2.target,
)
if (index >= 0) {
ke.preventDefault()
@ -140,8 +140,7 @@ function* ParserController() {
// unbounded length.
keyEvents.push(keyevent)
let response = undefined
response = parsers[contentState.mode](keyEvents)
let response = parsers[contentState.mode](keyEvents)
logger.debug(
currentMode,
contentState.mode,

View file

@ -20,8 +20,8 @@ export class Match {
function isCommandLineNode(n) {
let url = n.ownerDocument.location.href
return (
url.protocol == "moz-extension:" &&
url.pathname == "/static/commandline.html"
url.protocol === "moz-extension:" &&
url.pathname === "/static/commandline.html"
)
}
@ -51,7 +51,7 @@ let lastMatches = []
export function getMatches(findings, contextLength = 10): Match[] {
let result = []
if (findings.length == 0) return result
if (findings.length === 0) return result
// Checks if a node belongs to the command line
let nodes = getNodes()
@ -130,13 +130,13 @@ export async function find(query, count = -1, reverse = false) {
let findId = findCount
let findcase = await config.getAsync("findcase")
let caseSensitive =
findcase == "sensitive" ||
(findcase == "smart" && query.search(/[A-Z]/) >= 0)
findcase === "sensitive" ||
(findcase === "smart" && query.search(/[A-Z]/) >= 0)
let tabId = await activeTabId()
// No point in searching for something that won't be used anyway
await prevFind
if (findId != findCount) return []
if (findId !== findCount) return []
prevFind = browserBg.find.find(query, {
tabId,
@ -167,7 +167,7 @@ export async function find(query, count = -1, reverse = false) {
let pivot = findings.indexOf(findings.find(finder))
findings = findings.slice(pivot).concat(findings.slice(0, pivot))
if (count != -1 && count < findings.length) return findings.slice(0, count)
if (count !== -1 && count < findings.length) return findings.slice(0, count)
return findings
}
@ -209,7 +209,7 @@ export function findVisibleNode(allMatches, i, direction) {
while (!match.firstNode.ownerDocument.contains(match.firstNode)) {
n += direction
match = lastMatches[n]
if (n == i) return null
if (n === i) return null
}
match.firstNode.parentNode.scrollIntoView()
} while (!DOM.isVisible(match.firstNode.parentNode))
@ -223,7 +223,7 @@ function focusMatch(match: Match) {
if (elem) {
// We found a focusable element, but it's more important to focus anchors, even if they're higher up the DOM. So let's see if we can find one
let newElem = elem
while (newElem && newElem.tagName != "A") newElem = newElem.parentNode
while (newElem && newElem.tagName !== "A") newElem = newElem.parentNode
if (newElem) newElem.focus()
else elem.focus()
}
@ -237,7 +237,7 @@ export async function jumpToMatch(pattern, reverse, startingFrom) {
let match
// When we already computed all the matches, don't recompute them
if (lastMatches[0] && lastMatches[0].rangeData.text == pattern)
if (lastMatches[0] && lastMatches[0].rangeData.text === pattern)
match = lastMatches[startingFrom]
if (!match) {
@ -271,7 +271,7 @@ export function jumpToNextMatch(n: number) {
if (lastMatches.length < 1) {
// Let's try to find new matches
return jumpToMatch(state.lastSearch, n == -1, 0)
return jumpToMatch(state.lastSearch, n === -1, 0)
}
browserBg.find.highlightResults()
@ -281,7 +281,7 @@ export function jumpToNextMatch(n: number) {
n <= 0 ? -1 : 1,
)
if (match == undefined)
if (match === undefined)
throw `No matches found. The pattern looked for doesn't exist or ':find' hasn't been run yet`
for (let rect of match.rectData.rectsAndTexts.rectList) {

View file

@ -93,7 +93,7 @@ class HintState {
}
}
let modeState: HintState = undefined
let modeState: HintState
/** For each hintable element, add a hint */
export function hintPage(
@ -178,7 +178,7 @@ function defaultHintFilter() {
}
function defaultHintChars() {
if (config.get("hintnames") == "numeric") {
if (config.get("hintnames") === "numeric") {
return "1234567890"
}
return config.get("hintchars")
@ -278,7 +278,7 @@ class Hint {
let offsetLeft = 0
if (target.ownerDocument !== document) {
let iframe = DOM.getAllDocumentFrames().find(
frame => frame.contentDocument == target.ownerDocument,
frame => frame.contentDocument === target.ownerDocument,
)
let rect = iframe.getClientRects()[0]
offsetTop += rect.top
@ -288,7 +288,7 @@ class Hint {
const rect = target.getClientRects()[0]
this.flag.textContent = name
this.flag.className = "TridactylHint"
if (config.get("hintuppercase") == "true") {
if (config.get("hintuppercase") === "true") {
this.flag.classList.add("TridactylHintUppercase")
}
this.flag.classList.add("TridactylHint" + target.tagName)
@ -361,7 +361,7 @@ function buildHintsVimperator(els: Element[], onSelect: HintSelectedCallback) {
function elementFilterableText(el: Element): string {
const nodename = el.nodeName.toLowerCase()
let text: string
if (nodename == "input") {
if (nodename === "input") {
text = (el as HTMLInputElement).value
} else if (0 < el.textContent.length) {
text = el.textContent
@ -392,7 +392,7 @@ function filterHintsSimple(fstr) {
active.push(h)
}
}
if (active.length == 1) {
if (active.length === 1) {
selectFocusedHint()
}
}
@ -476,7 +476,7 @@ function filterHintsVimperator(fstr, reflow = false) {
}
// Select focused hint if it's the only match
if (active.length == 1) {
if (active.length === 1) {
selectFocusedHint(true)
}
}

View file

@ -51,7 +51,7 @@ class ScrollingData {
let elapsed = performance.now() - this.startTime
// If the animation should be done, return the position the element should have
if (elapsed >= this.duration || this.elem[this.pos] == this.endPos)
if (elapsed >= this.duration || this.elem[this.pos] === this.endPos)
return this.endPos
let result = ((this.endPos - this.startPos) * elapsed) / this.duration
@ -63,7 +63,7 @@ class ScrollingData {
scrollStep() {
let val = this.elem[this.pos]
this.elem[this.pos] = this.getStep()
return val != this.elem[this.pos]
return val !== this.elem[this.pos]
}
/** Calls this.scrollStep() until the element has been completely scrolled
@ -105,14 +105,14 @@ export async function scroll(
x: number = 0,
y: number = 0,
e: Node,
duration: number = undefined,
duration?: number,
) {
let smooth = await getSmooth()
if (smooth == "false") duration = 0
if (smooth === "false") duration = 0
else if (duration === undefined) duration = await getDuration()
let result = false
if (x != 0) {
if (x !== 0) {
// Don't create a new ScrollingData object if the element is already
// being scrolled
let scrollData = horizontallyScrolling.get(e)
@ -122,7 +122,7 @@ export async function scroll(
}
result = result || scrollData.scroll(x, duration)
}
if (y != 0) {
if (y !== 0) {
let scrollData = verticallyScrolling.get(e)
if (!scrollData) {
scrollData = new ScrollingData(e, "scrollTop")
@ -145,13 +145,13 @@ let lastY = 0
export async function recursiveScroll(
x: number,
y: number,
node: Element = undefined,
stopAt: Element = undefined,
node?: Element,
stopAt?: Element,
) {
let startingFromCached = false
if (!node) {
const sameSignX = x < 0 == lastX < 0
const sameSignY = y < 0 == lastY < 0
const sameSignX = x < 0 === lastX < 0
const sameSignY = y < 0 === lastY < 0
if (lastRecursiveScrolled && sameSignX && sameSignY) {
// We're scrolling in the same direction as the previous time so
// let's try to pick up from where we left

View file

@ -85,7 +85,7 @@ config.addChangeListener("theme", retheme)
let cb = async mutationList => {
let theme = await config.getAsync("theme")
mutationList
.filter(m => m.target.className.search(prefixTheme("")) == -1)
.filter(m => m.target.className.search(prefixTheme("")) === -1)
.forEach(m => m.target.classList.add(prefixTheme(theme)))
}

View file

@ -1,7 +1,4 @@
/* tslint:disable:array-type */
/* tslint:disable:comment-format */
/* tslint:disable:no-consecutive-blank-lines */
/* tslint:disable:quotemark */
// '//#' is a start point for a simple text-replacement-type macro. See excmds_macros.py
/** # Tridactyl help page
@ -56,7 +53,6 @@
All three channels are mirrored together, so it doesn't matter which one you use.
[1]: https://github.com/tridactyl/tridactyl/issues
[2]: https://github.com/tridactyl/tridactyl#readme
[3]: https://github.com/tridactyl/tridactyl/blob/master/doc/troubleshooting.md
@ -134,10 +130,10 @@ export async function getNativeVersion(): Promise<void> {
* This function is used by rssexec and rssexec completions.
*/
//#content
export async function getRssLinks(): Promise<{ type: string; url: string; title: string }[]> {
export async function getRssLinks(): Promise<Array<{ type: string; url: string; title: string }>> {
let seen = new Set<string>()
return Array.from(document.querySelectorAll("a, link[rel='alternate']"))
.filter((e: any) => typeof e.href == "string")
.filter((e: any) => typeof e.href === "string")
.reduce((acc, e: any) => {
let type = ""
// Start by detecting type because url doesn't necessarily contain the words "rss" or "atom"
@ -168,7 +164,7 @@ export async function getRssLinks(): Promise<{ type: string; url: string; title:
*/
//#content
export async function rssexec(url: string, type?: string, ...title: string[]) {
if (!url || url == "") {
if (!url || url === "") {
let links = await getRssLinks()
switch (links.length) {
case 0:
@ -205,7 +201,7 @@ export async function fillinput(selector: string, ...content: string[]) {
let inputToFill = document.querySelector(selector)
if (!inputToFill) inputToFill = DOM.getLastUsedInput()
if ("value" in inputToFill) {
;(inputToFill as HTMLInputElement).value = content.join(" ")
(inputToFill as HTMLInputElement).value = content.join(" ")
} else {
inputToFill.textContent = content.join(" ")
}
@ -379,7 +375,7 @@ export function cssparse(...css: string[]) {
//#background
export async function loadtheme(themename: string) {
if (!(await Native.nativegate("0.1.9"))) return
const separator = (await browserBg.runtime.getPlatformInfo().os) == "win" ? "\\" : "/"
const separator = (await browserBg.runtime.getPlatformInfo().os) === "win" ? "\\" : "/"
// remove the "tridactylrc" bit so that we're left with the directory
const path =
(await Native.getrcpath())
@ -392,7 +388,7 @@ export async function loadtheme(themename: string) {
themename +
".css"
const file = await Native.read(path)
if (file.code != 0) throw new Error("Couldn't read theme " + path)
if (file.code !== 0) throw new Error("Couldn't read theme " + path)
return set("customthemes." + themename, file.content)
}
@ -812,7 +808,7 @@ export function addJump(scrollEvent: UIEvent) {
jumps.timeoutid = setTimeout(() => {
let list = jumps.list
// if the page hasn't moved, stop
if (list[jumps.cur].x == pageX && list[jumps.cur].y == pageY) return
if (list[jumps.cur].x === pageX && list[jumps.cur].y === pageY) return
// Store the new jump
// Could removing all jumps from list[cur] to list[list.length] be
// a better/more intuitive behavior?
@ -833,7 +829,7 @@ document.addEventListener("load", () => curJumps().then(() => jumpprev(0)))
/** Blur (unfocus) the active element */
//#content
export function unfocus() {
;(document.activeElement as HTMLInputElement).blur()
(document.activeElement as HTMLInputElement).blur()
contentState.mode = "normal"
}
@ -856,7 +852,7 @@ export async function scrollpx(a: number, b: number) {
*/
//#content
export function scrollto(a: number | string, b: number | "x" | "y" = "y") {
if (typeof a == "string" && a.match(/c$/i)) {
if (typeof a === "string" && a.match(/c$/i)) {
a = (Number(a.replace(/c$/, "")) * 100) / (2 * Math.PI)
}
a = Number(a)
@ -865,16 +861,16 @@ export function scrollto(a: number | string, b: number | "x" | "y" = "y") {
if (b === "y") {
let top = elem.getClientRects()[0].top
window.scrollTo(window.scrollX, (percentage * elem.scrollHeight) / 100)
if (top == elem.getClientRects()[0].top && (percentage == 0 || percentage == 100)) {
if (top === elem.getClientRects()[0].top && (percentage === 0 || percentage === 100)) {
// scrollTo failed, if the user wants to go to the top/bottom of
// the page try scrolling.recursiveScroll instead
scrolling.recursiveScroll(window.scrollX, 1073741824 * (percentage == 0 ? -1 : 1), document.documentElement)
scrolling.recursiveScroll(window.scrollX, 1073741824 * (percentage === 0 ? -1 : 1), document.documentElement)
}
} else if (b === "x") {
let left = elem.getClientRects()[0].left
window.scrollTo((percentage * elem.scrollWidth) / 100, window.scrollY)
if (left == elem.getClientRects()[0].left && (percentage == 0 || percentage == 100)) {
scrolling.recursiveScroll(1073741824 * (percentage == 0 ? -1 : 1), window.scrollX, document.documentElement)
if (left === elem.getClientRects()[0].left && (percentage === 0 || percentage === 100)) {
scrolling.recursiveScroll(1073741824 * (percentage === 0 ? -1 : 1), window.scrollX, document.documentElement)
}
} else {
window.scrollTo(a, Number(b)) // a,b numbers
@ -1008,7 +1004,7 @@ export async function reloadall(hard = false) {
export async function reloadallbut(hard = false) {
let tabs = await browser.tabs.query({ currentWindow: true })
let currId = await activeTabId()
tabs = tabs.filter(tab => tab.id != currId)
tabs = tabs.filter(tab => tab.id !== currId)
let reloadprops = { bypassCache: hard }
tabs.forEach(tab => browser.tabs.reload(tab.id, reloadprops))
}
@ -1072,7 +1068,7 @@ export async function open(...urlarr: string[]) {
*/
//#background
export async function bmarks(opt: string, ...urlarr: string[]) {
if (opt == "-t") return tabopen(...urlarr)
if (opt === "-t") return tabopen(...urlarr)
else return open(opt, ...urlarr)
}
@ -1129,7 +1125,7 @@ export async function url2args() {
/** @hidden */
//#content_helper
let sourceElement = undefined
let sourceElement
/** @hidden */
//#content_helper
function removeSource() {
@ -1218,7 +1214,7 @@ export async function help(...helpItems: string[]) {
while (aliases[helpItem]) {
resolved.push(helpItem)
helpItem = aliases[helpItem].split(" ")
helpItem = helpItem[0] == "composite" ? helpItem[1] : helpItem[0]
helpItem = helpItem[0] === "composite" ? helpItem[1] : helpItem[0]
// Prevent infinite loops
if (resolved.includes(helpItem)) break
}
@ -1257,7 +1253,7 @@ export async function help(...helpItems: string[]) {
subSettings = subSettings[settingName]
}
}
if (settingHelpAnchor != "") {
if (settingHelpAnchor !== "") {
return browser.extension.getURL("static/docs/classes/_src_lib_config_.default_config.html") + "#" + settingHelpAnchor.slice(0, -1)
}
return ""
@ -1276,14 +1272,14 @@ export async function help(...helpItems: string[]) {
let url = ""
// If the user did specify what they wanted, specifically look for it
if (flag != "") {
if (flag !== "") {
url = flags[flag](settings, subject)
}
// Otherwise or if it couldn't be found, try all possible items
if (url == "") {
if (url === "") {
url = ["-b", "-s", "-a", "-e"].reduce((acc, curFlag) => {
if (acc != "") return acc
if (acc !== "") return acc
return flags[curFlag](settings, subject)
}, "")
}
@ -1515,7 +1511,7 @@ export function urlparent(count = 1) {
//#content
export function urlmodify(mode: "-t" | "-r" | "-q" | "-Q" | "-g", ...args: string[]) {
let oldUrl = new URL(window.location.href)
let newUrl = undefined
let newUrl
switch (mode) {
case "-t":
@ -2021,7 +2017,7 @@ export async function fullscreen() {
const currwin = await browser.windows.getCurrent()
const wid = currwin.id
// This might have odd behaviour on non-tiling window managers, but no-one uses those, right?
const state = currwin.state == "fullscreen" ? "normal" : "fullscreen"
const state = currwin.state === "fullscreen" ? "normal" : "fullscreen"
browser.windows.update(wid, { state })
}
@ -2130,7 +2126,7 @@ export async function undo(item = "recent"): Promise<number> {
}
} else if (!isNaN(parseInt(item, 10))) {
const sessionId = item
const session = sessions.find(s => (s.tab || s.window).sessionId == sessionId)
const session = sessions.find(s => (s.tab || s.window).sessionId === sessionId)
if (session) {
browser.sessions.restore(sessionId)
return (session.tab || session.window).id
@ -2226,7 +2222,7 @@ export async function mute(...muteArgs: string[]): Promise<void> {
let all = false
let argParse = (args: string[]) => {
if (args == null) {
if (args === null) {
return
}
if (args[0] === "all") {
@ -2321,7 +2317,7 @@ export async function winopen(...args: string[]) {
*/
//#background
export async function winclose(...ids: string[]) {
if (ids.length == 0) {
if (ids.length === 0) {
ids.push(`${(await browser.windows.getCurrent()).id}`)
}
return Promise.all(ids.map(id => browser.windows.remove(parseInt(id, 10))))
@ -2609,7 +2605,7 @@ export async function fillcmdline_tmp(ms: number, ...strarr: string[]) {
Messaging.messageOwnTab("commandline_frame", "fillcmdline", [strarr.join(" "), false, false])
return new Promise(resolve =>
setTimeout(async () => {
if ((await Messaging.messageOwnTab("commandline_frame", "getContent", [])) == str) {
if ((await Messaging.messageOwnTab("commandline_frame", "getContent", [])) === str) {
CommandLineContent.hide_and_blur()
resolve(Messaging.messageOwnTab("commandline_frame", "clear", [true]))
}
@ -2713,8 +2709,8 @@ async function setclip(str) {
*/
//#background_helper
async function getclip(fromm?: "clipboard" | "selection") {
if (fromm == undefined) fromm = await config.getAsync("putfrom")
if (fromm == "clipboard") {
if (fromm === undefined) fromm = await config.getAsync("putfrom")
if (fromm === "clipboard") {
return messageActiveTab("commandline_frame", "getClipboard")
} else {
return Native.clipboard("get", "")
@ -2723,17 +2719,17 @@ async function getclip(fromm?: "clipboard" | "selection") {
/** Use the system clipboard.
If `excmd == "open"`, call [[open]] with the contents of the clipboard. Similarly for [[tabopen]].
If `excmd === "open"`, call [[open]] with the contents of the clipboard. Similarly for [[tabopen]].
If `excmd == "yank"`, copy the current URL, or if given, the value of toYank, into the system clipboard.
If `excmd === "yank"`, copy the current URL, or if given, the value of toYank, into the system clipboard.
If `excmd == "yankcanon"`, copy the canonical URL of the current page if it exists, otherwise copy the current URL.
If `excmd === "yankcanon"`, copy the canonical URL of the current page if it exists, otherwise copy the current URL.
If `excmd == "yankshort"`, copy the shortlink version of the current URL, and fall back to the canonical then actual URL. Known to work on https://yankshort.neocities.org/.
If `excmd === "yankshort"`, copy the shortlink version of the current URL, and fall back to the canonical then actual URL. Known to work on https://yankshort.neocities.org/.
If `excmd == "yanktitle"`, copy the title of the open page.
If `excmd === "yanktitle"`, copy the title of the open page.
If `excmd == "yankmd"`, copy the title and url of the open page formatted in Markdown for easy use on sites such as reddit.
If `excmd === "yankmd"`, copy the title and url of the open page formatted in Markdown for easy use on sites such as reddit.
If you're on Linux and the native messenger is installed, Tridactyl will call an external binary (either xclip or xsel) to read or write to your X selection buffer. If you want another program to be used, set "externalclipboardcmd" to its name and make sure it has the same interface as xsel/xclip ("-i"/"-o" and reading from stdin).
@ -2750,7 +2746,7 @@ export async function clipboard(excmd: "open" | "yank" | "yankshort" | "yankcano
switch (excmd) {
case "yankshort":
urls = await geturlsforlinks("rel", "shortlink")
if (urls.length == 0) {
if (urls.length === 0) {
urls = await geturlsforlinks("rev", "canonical")
}
if (urls.length > 0) {
@ -2768,7 +2764,7 @@ export async function clipboard(excmd: "open" | "yank" | "yankshort" | "yankcano
}
// Trying yank if yankcanon failed...
case "yank":
content = content == "" ? (await activeTab()).url : content
content = content === "" ? (await activeTab()).url : content
await yank(content)
fillcmdline_tmp(3000, "# " + content + " copied to clipboard.")
break
@ -2903,7 +2899,7 @@ interface bind_args {
/** @hidden */
//#background_helper
function parse_bind_args(...args: string[]): bind_args {
if (args.length == 0) throw new Error("Invalid bind/unbind arguments.")
if (args.length === 0) throw new Error("Invalid bind/unbind arguments.")
let result = {} as bind_args
result.mode = "normal"
@ -2957,7 +2953,6 @@ function parse_bind_args(...args: string[]): bind_args {
[[fillcmdline]] to put a string in the cmdline and focus the cmdline
(otherwise the string is executed immediately).
You can bind to other modes with `bind --mode={insert|ignore|normal|input} ...`, e.g, `bind --mode=insert emacs qall` (NB: unlike vim, all preceeding characters will not be input).
See also:
@ -2969,7 +2964,7 @@ function parse_bind_args(...args: string[]): bind_args {
export function bind(...args: string[]) {
let args_obj = parse_bind_args(...args)
let p = Promise.resolve()
if (args_obj.excmd != "") {
if (args_obj.excmd !== "") {
for (let i = 0; i < args_obj.key.length; i++) {
// Check if any initial subsequence of the key exists and will shadow the new binding
let key_sub = args_obj.key.slice(0, i)
@ -2999,7 +2994,7 @@ export function bind(...args: string[]) {
export function bindurl(pattern: string, mode: string, keys: string, ...excmd: string[]) {
let args_obj = parse_bind_args(mode, keys, ...excmd)
let p = Promise.resolve()
if (args_obj.excmd != "") {
if (args_obj.excmd !== "") {
p = config.setURL(pattern, args_obj.configName, args_obj.key, args_obj.excmd)
} else if (args_obj.key.length) {
// Display the existing bind
@ -3041,7 +3036,7 @@ function validateSetArgs(key: string, values: string[]) {
if (md !== undefined) {
const strval = values.join(" ")
// Note: the conversion will throw if strval can't be converted to the right type
if (md.type.kind == "object" && target.length > 1) {
if (md.type.kind === "object" && target.length > 1) {
value = (md as any).type.convertMember(target.slice(1), strval)
} else {
value = md.type.convert(strval)
@ -3080,7 +3075,7 @@ function validateSetArgs(key: string, values: string[]) {
*/
//#content
export function seturl(pattern: string, key: string, ...values: string[]) {
if (values.length == 0 && key) {
if (values.length === 0 && key) {
values = [key]
key = pattern
pattern = window.location.href
@ -3111,7 +3106,7 @@ export function set(key: string, ...values: string[]) {
return get(key)
}
if (key == "noiframeon") {
if (key === "noiframeon") {
let noiframes = config.get("noiframeon")
// unset previous settings
if (noiframes) noiframes.forEach(url => seturl(url, "noiframe", "false"))
@ -3209,7 +3204,7 @@ export function blacklistadd(url: string) {
//#background
export async function unbind(...args: string[]) {
let args_obj = parse_bind_args(...args)
if (args_obj.excmd != "") throw new Error("unbind syntax: `unbind key`")
if (args_obj.excmd !== "") throw new Error("unbind syntax: `unbind key`")
return config.set(args_obj.configName, args_obj.key, "")
}
@ -3300,7 +3295,7 @@ export async function sanitise(...args: string[]) {
if (flagpos < args.length - 1) {
let match = args[flagpos + 1].match("^([0-9])+(m|h|d|w)$")
// If the arg of the flag matches Pentadactyl's sanitisetimespan format
if (match !== null && match.length == 3) {
if (match !== null && match.length === 3) {
// Compute the timespan in milliseconds and get a Date object
let millis = parseInt(match[1], 10) * 1000
switch (match[2]) {
@ -3345,7 +3340,7 @@ export async function sanitise(...args: string[]) {
"serverBoundCertificates": false,
*/
}
if (args.find(x => x == "all") !== undefined) {
if (args.find(x => x === "all") !== undefined) {
for (let attr in dts) dts[attr] = true
} else {
// We bother checking if dts[x] is false because
@ -3383,7 +3378,7 @@ export async function quickmark(key: string, ...addressarr: string[]) {
}
if (addressarr.length <= 1) {
let address = addressarr.length == 0 ? (await activeTab()).url : addressarr[0]
let address = addressarr.length === 0 ? (await activeTab()).url : addressarr[0]
// Have to await these or they race!
await bind("gn" + key, "tabopen", address)
await bind("go" + key, "open", address)
@ -3544,7 +3539,7 @@ import * as hinting from "@src/content/hinting"
export async function hint(option?: string, selectors?: string, ...rest: string[]): Promise<any> {
if (!option) option = ""
if (option == "-br") option = "-qb"
if (option === "-br") option = "-qb"
// extract flags
// Note: we need to process 'pipe' separately because it could be interpreted as -p -i -e otherwise
@ -3722,11 +3717,11 @@ export async function hint(option?: string, selectors?: string, ...rest: string[
// s: don't ask the user where to save the file
// a: ask the user where to save the file
let saveAs = true
if (option[1].toLowerCase() == "s") saveAs = false
if (option[1].toLowerCase() === "s") saveAs = false
// Lowercase: anchors
// Uppercase: images
let attr = "href"
if (option[1].toLowerCase() == option[1]) {
if (option[1].toLowerCase() === option[1]) {
attr = "href"
elems = hinting.saveableElements()
} else {
@ -3917,7 +3912,7 @@ export async function ttsvoices() {
export async function ttscontrol(action: string) {
// only pause seems to be working, so only provide access to that
// to avoid exposing users to things that won't work
if (action != "stop") {
if (action !== "stop") {
throw new Error("Unknown text-to-speech action: " + action)
}
@ -3985,7 +3980,7 @@ export async function perfhistogram(...filters: string[]) {
let filterconfigs = buildFilterConfigs(filters)
filterconfigs.push({ kind: "eventType", eventType: "measure" })
const entries = window.tri.statsLogger.getEntries(...filterconfigs)
if (entries.length == 0) {
if (entries.length === 0) {
fillcmdline_tmp(3000, "perfhistogram: No samples found.")
return
}
@ -4018,10 +4013,10 @@ export async function bmark(url?: string, ...titlearr: string[]) {
// if titlearr is given and we have duplicates, we probably want to give an error here.
const dupbmarks = await browser.bookmarks.search({ url })
dupbmarks.forEach(bookmark => browser.bookmarks.remove(bookmark.id))
if (dupbmarks.length != 0) return
if (dupbmarks.length !== 0) return
const path = title.substring(0, title.lastIndexOf("/") + 1)
// TODO: if title is blank, get it from the page.
if (path != "") {
if (path !== "") {
const tree = (await browser.bookmarks.getTree())[0] // Why would getTree return a tree? Obviously it returns an array of unit length.
// I hate recursion.
const treeClimber = (tree, treestr) => {
@ -4032,7 +4027,7 @@ export async function bmark(url?: string, ...titlearr: string[]) {
}
const validpaths = flatten(treeClimber(tree, "")).filter(x => "path" in x)
title = title.substring(title.lastIndexOf("/") + 1)
let pathobj = validpaths.find(p => p.path == path)
let pathobj = validpaths.find(p => p.path === path)
// If strict look doesn't find it, be a bit gentler
if (pathobj === undefined) pathobj = validpaths.find(p => p.path.includes(path))
if (pathobj !== undefined) {
@ -4162,8 +4157,8 @@ export async function updatecheck(polite = false) {
*/
//#background_helper
browser.runtime.onInstalled.addListener(details => {
if (details.reason == "install") tutor("newtab")
else if ((details as any).temporary !== true && details.reason == "update") updatenative(false)
if (details.reason === "install") tutor("newtab")
else if ((details as any).temporary !== true && details.reason === "update") updatenative(false)
// could add elif "update" and show a changelog. Hide it behind a setting to make it less annoying?
})

View file

@ -10,7 +10,7 @@ function initTridactylSettingElem(
let bindingNode = elem.getElementsByClassName(`Tridactyl${kind}`)[0]
if (bindingNode) {
Array.from(bindingNode.children)
.filter(e => e.tagName == "SPAN")
.filter(e => e.tagName === "SPAN")
.forEach(e => e.parentNode.removeChild(e))
} else {
// Otherwise, create it
@ -29,7 +29,7 @@ function getCommandElements() {
".tsd-panel.tsd-member.tsd-kind-function.tsd-parent-kind-external-module",
),
).reduce((all, elem) => {
let fnName = Array.from(elem.children).find(e => e.tagName == "H3")
let fnName = Array.from(elem.children).find(e => e.tagName === "H3")
if (fnName) all[fnName.textContent] = elem
return all
}, {})
@ -84,7 +84,7 @@ async function addSetting(settingName: string) {
Object.values(settingElems)
.filter(
(e: HTMLElement) =>
!Array.from(e.children).find(c => c.tagName == "SPAN"),
!Array.from(e.children).find(c => c.tagName === "SPAN"),
)
.forEach((e: HTMLElement) => e.parentNode.removeChild(e))
}
@ -93,10 +93,10 @@ async function onExcmdPageLoad() {
browser.storage.onChanged.addListener((changes, areaname) => {
if ("userconfig" in changes) {
// JSON.stringify for comparisons like it's 2012
;["nmaps", "imaps", "ignoremaps", "inputmaps", "exaliases"].forEach(
["nmaps", "imaps", "ignoremaps", "inputmaps", "exaliases"].forEach(
kind => {
if (
JSON.stringify(changes.userconfig.newValue[kind]) !=
JSON.stringify(changes.userconfig.newValue[kind]) !==
JSON.stringify(changes.userconfig.oldValue[kind])
)
addSetting(kind)
@ -129,14 +129,14 @@ function addSettingInputs() {
let onKeyUp = async ev => {
let input = ev.target
if (ev.key == "Enter") {
;(window as any).tri.messaging.message(
if (ev.key === "Enter") {
(window as any).tri.messaging.message(
"controller_background",
"acceptExCmd",
["set " + input.name + " " + input.value],
)
} else {
if (input.value == (await config.getAsync(input.name.split(".")))) {
if (input.value === (await config.getAsync(input.name.split(".")))) {
input.className = inputClassName
} else {
input.className = inputClassNameModified
@ -198,12 +198,12 @@ function addResetConfigButton() {
let p = prompt(
`Please write '${sentence}' without quotes in the following input field if you really want to reset your Tridactyl config.`,
)
if (p == sentence) {
;(window as any).tri.messaging
if (p === sentence) {
(window as any).tri.messaging
.message("controller_background", "acceptExCmd", [sentence])
.then(_ => alert("Config reset!"))
} else {
alert(`Config not reset because '${p}' != '${sentence}'`)
alert(`Config not reset because '${p}' !== '${sentence}'`)
}
})
document.querySelector("div.container.container-main").appendChild(button)

View file

@ -908,7 +908,7 @@ export function mergeDeep(o1, o2) {
Object.assign(r, o1, o2)
if (o2 === undefined) return r
Object.keys(o1)
.filter(key => typeof o1[key] == "object" && typeof o2[key] == "object")
.filter(key => typeof o1[key] === "object" && typeof o2[key] === "object")
.forEach(key => Object.assign(r[key], mergeDeep(o1[key], o2[key])))
return r
}
@ -926,7 +926,7 @@ export function getURL(url: string, target: string[]) {
.filter(
k =>
url.match(k) &&
getDeepProperty(USERCONFIG.subconfigs[k], target) !=
getDeepProperty(USERCONFIG.subconfigs[k], target) !==
undefined,
)
// Sort them from lowest to highest priority, default to a priority of 10
@ -1047,11 +1047,11 @@ export function unset(...target) {
@hidden
*/
export async function save(storage: "local" | "sync" = get("storageloc")) {
// let storageobj = storage == "local" ? browser.storage.local : browser.storage.sync
// let storageobj = storage === "local" ? browser.storage.local : browser.storage.sync
// storageobj.set({CONFIGNAME: USERCONFIG})
let settingsobj = o({})
settingsobj[CONFIGNAME] = USERCONFIG
return storage == "local"
return storage === "local"
? browser.storage.local.set(settingsobj)
: browser.storage.sync.set(settingsobj)
}
@ -1126,7 +1126,7 @@ export async function update() {
set("configversion", "1.2")
},
"1.2": () => {
;["ignoremaps", "inputmaps", "imaps", "nmaps"]
["ignoremaps", "inputmaps", "imaps", "nmaps"]
.map(mapname => [
mapname,
getDeepProperty(USERCONFIG, [mapname]),
@ -1158,7 +1158,7 @@ export async function update() {
set("configversion", "1.3")
},
"1.3": () => {
;[
[
"priority",
"hintdelay",
"scrollduration",
@ -1171,7 +1171,7 @@ export async function update() {
set("configversion", "1.4")
},
"1.4": () => {
;(getDeepProperty(USERCONFIG, ["noiframeon"]) || []).forEach(
(getDeepProperty(USERCONFIG, ["noiframeon"]) || []).forEach(
site => {
setURL(site, "noiframe", "true")
},
@ -1185,11 +1185,11 @@ export async function update() {
"1.6": () => {
let updateSetting = mapObj => {
if (!mapObj) return mapObj
if (mapObj[" "] != undefined) {
if (mapObj[" "] !== undefined) {
mapObj["<Space>"] = mapObj[" "]
delete mapObj[" "]
}
;[
[
"<A- >",
"<C- >",
"<M- >",
@ -1201,7 +1201,7 @@ export async function update() {
"<CS- >",
"<MS- >",
].forEach(binding => {
if (mapObj[binding] != undefined) {
if (mapObj[binding] !== undefined) {
let key = binding.replace(" ", "Space")
mapObj[key] = mapObj[binding]
delete mapObj[binding]
@ -1209,7 +1209,7 @@ export async function update() {
})
return mapObj
}
;["nmaps", "exmaps", "imaps", "inputmaps", "ignoremaps"].forEach(
["nmaps", "exmaps", "imaps", "inputmaps", "ignoremaps"].forEach(
settingName => updateAll([settingName], updateSetting),
)
set("configversion", "1.7")
@ -1287,7 +1287,7 @@ browser.storage.onChanged.addListener(async (changes, areaname) => {
let unsetKeys = Object.keys(USERCONFIG).filter(
k =>
changes[CONFIGNAME].newValue[k] === undefined &&
JSON.stringify(USERCONFIG[k]) !=
JSON.stringify(USERCONFIG[k]) !==
JSON.stringify(defaultConf[k]),
)
@ -1298,7 +1298,7 @@ browser.storage.onChanged.addListener(async (changes, areaname) => {
USERCONFIG[k] !== undefined
? USERCONFIG[k]
: defaultConf[k],
) != JSON.stringify(changes[CONFIGNAME].newValue[k]),
) !== JSON.stringify(changes[CONFIGNAME].newValue[k]),
)
let old = USERCONFIG
@ -1325,7 +1325,7 @@ browser.storage.onChanged.addListener(async (changes, areaname) => {
USERCONFIG = o({})
Object.keys(old)
.filter(key => old[key] != defaultConf[key])
.filter(key => old[key] !== defaultConf[key])
.forEach(key => {
let arr = changeListeners.get(key)
if (arr) {

View file

@ -15,10 +15,10 @@ export function findCssRules(
const filtSheet = [...sheet.stylesheet.rules.entries()].filter(x => {
const rule = x[1]
return (
rule.type == "rule" &&
rule.type === "rule" &&
// Make sure that there are as many selectors in the current rule
// as there are in the rule we're looking for
rule["selectors"].length == selectors.length &&
rule["selectors"].length === selectors.length &&
// Also make sure that each of the selectors of the current rule
// are present in the rule we're looking for
!rule["selectors"].find(selector => !selectors.includes(selector))

View file

@ -121,7 +121,7 @@ export function elementsWithText() {
return getElemsBySelector("*", [
isVisible,
hint => {
return hint.textContent != ""
return hint.textContent !== ""
},
])
}
@ -303,7 +303,7 @@ export function getSelector(e: HTMLElement) {
// Compute the position of the element
let index =
Array.from(e.parentElement.children)
.filter(child => child.tagName == e.tagName)
.filter(child => child.tagName === e.tagName)
.indexOf(e) + 1
return (
uniqueSelector(e.parentElement) +
@ -510,7 +510,7 @@ function onPageFocus(elem: HTMLElement, args: any[]): boolean {
if (isTextEditable(elem)) {
LAST_USED_INPUT = elem
}
return config.get("allowautofocus") == "true"
return config.get("allowautofocus") === "true"
}
async function setInput(el) {

View file

@ -37,7 +37,7 @@ type editor_function = (
**/
function applyToElem(e, fn) {
let result
if (e instanceof HTMLInputElement && e.type != "text") {
if (e instanceof HTMLInputElement && e.type !== "text") {
let t = e.type
e.type = "text"
result = fn(e)
@ -68,7 +68,7 @@ function getContentEditableValues(e: any): [string, number, number] {
let selection = e.ownerDocument.getSelection()
// The selection might actually not be in e so we need to make sure it is
let n = selection.anchorNode
while (n && n != e) n = n.parentNode
while (n && n !== e) n = n.parentNode
// The selection isn't for e, so we can't do anything
if (!n) return [null, null, null]
// selection might span multiple elements, might not start with the first element in e or end with the last element in e so the easiest way to compute caret position from beginning of e is to first compute distance from caret to end of e, then move beginning of selection to beginning of e and then use distance from end of selection to compute distance from beginning of selection
@ -177,7 +177,7 @@ function needs_text(fn: editor_function, arg?: any): editor_function {
return fn(
text,
selectionStart,
typeof selectionEnd == "number" ? selectionEnd : selectionStart,
typeof selectionEnd === "number" ? selectionEnd : selectionStart,
arg,
)
}
@ -284,7 +284,7 @@ export function wordAfterPos(text: string, position: number) {
**/
export const delete_char = wrap_input(
needs_text((text, selectionStart, selectionEnd) => {
if (selectionStart != selectionEnd) {
if (selectionStart !== selectionEnd) {
// If the user selected text, then we need to delete that instead of a single char
text =
text.substring(0, selectionStart) + text.substring(selectionEnd)
@ -302,7 +302,7 @@ export const delete_char = wrap_input(
**/
export const delete_backward_char = wrap_input(
needs_text((text, selectionStart, selectionEnd) => {
if (selectionStart != selectionEnd) {
if (selectionStart !== selectionEnd) {
text =
text.substring(0, selectionStart) + text.substring(selectionEnd)
} else {
@ -319,7 +319,7 @@ export const delete_backward_char = wrap_input(
* Behaves like readline's [tab_insert](http://web.mit.edu/gnu/doc/html/rlman_1.html#SEC14), i.e. inserts a tab character to the left of the caret.
**/
export const tab_insert = wrap_input((text, selectionStart, selectionEnd) => {
if (selectionStart != selectionEnd) {
if (selectionStart !== selectionEnd) {
text =
text.substring(0, selectionStart) +
"\t" +
@ -341,7 +341,7 @@ export const transpose_chars = wrap_input(
(text, selectionStart, selectionEnd) => {
if (text.length < 2) return [null, null, null]
// When at the beginning of the text, transpose the first and second characters
if (selectionStart == 0) selectionStart = 1
if (selectionStart === 0) selectionStart = 1
// When at the end of the text, transpose the last and second-to-last characters
if (selectionStart >= text.length) selectionStart = text.length - 1
@ -364,7 +364,7 @@ function applyWord(
selectionEnd,
fn: (string) => string,
): [string, number, number] {
if (text.length == 0) return [null, null, null]
if (text.length === 0) return [null, null, null]
// If the caret is at the end of the text, move it just before the last character
if (selectionStart >= text.length) {
selectionStart = text.length - 1
@ -460,9 +460,9 @@ export const capitalize_word = wrap_input(
export const kill_line = wrap_input(
needs_text((text, selectionStart, selectionEnd) => {
let newLine = text.substring(selectionStart).search("\n")
if (newLine != -1) {
if (newLine !== -1) {
// If the caret is right before the newline, kill the newline
if (newLine == 0) newLine = 1
if (newLine === 0) newLine = 1
text =
text.substring(0, selectionStart) +
text.substring(selectionStart + newLine)
@ -479,7 +479,7 @@ export const kill_line = wrap_input(
export const backward_kill_line = wrap_input(
needs_text((text, selectionStart, selectionEnd) => {
// If the caret is at the beginning of a line, join the lines
if (selectionStart > 0 && text[selectionStart - 1] == "\n") {
if (selectionStart > 0 && text[selectionStart - 1] === "\n") {
return [
text.substring(0, selectionStart - 1) +
text.substring(selectionStart),
@ -491,7 +491,7 @@ export const backward_kill_line = wrap_input(
// Find the closest newline
for (
newLine = selectionStart;
newLine > 0 && text[newLine - 1] != "\n";
newLine > 0 && text[newLine - 1] !== "\n";
--newLine
) {}
// Remove everything between the newline and the caret
@ -513,13 +513,13 @@ export const kill_whole_line = wrap_input(
// Find the newline before the caret
for (
firstNewLine = selectionStart;
firstNewLine > 0 && text[firstNewLine - 1] != "\n";
firstNewLine > 0 && text[firstNewLine - 1] !== "\n";
--firstNewLine
) {}
// Find the newline after the caret
for (
secondNewLine = selectionStart;
secondNewLine < text.length && text[secondNewLine - 1] != "\n";
secondNewLine < text.length && text[secondNewLine - 1] !== "\n";
++secondNewLine
) {}
// Remove everything between the newline and the caret
@ -572,8 +572,8 @@ export const backward_kill_word = wrap_input(
export const beginning_of_line = wrap_input(
needs_text((text, selectionStart, selectionEnd) => {
while (
text[selectionStart - 1] != undefined &&
text[selectionStart - 1] != "\n"
text[selectionStart - 1] !== undefined &&
text[selectionStart - 1] !== "\n"
)
selectionStart -= 1
return [null, selectionStart, null]
@ -586,8 +586,8 @@ export const beginning_of_line = wrap_input(
export const end_of_line = wrap_input(
needs_text((text, selectionStart, selectionEnd) => {
while (
text[selectionStart] != undefined &&
text[selectionStart] != "\n"
text[selectionStart] !== undefined &&
text[selectionStart] !== "\n"
)
selectionStart += 1
return [null, selectionStart, null]
@ -627,7 +627,7 @@ export const forward_word = wrap_input(
**/
export const backward_word = wrap_input(
(text, selectionStart, selectionEnd) => {
if (selectionStart == 0) return [null, null, null]
if (selectionStart === 0) return [null, null, null]
let boundaries = getWordBoundaries(text, selectionStart, true)
if (selectionStart >= boundaries[0] && selectionStart < boundaries[1])
boundaries = getWordBoundaries(text, boundaries[0] - 1, true)

View file

@ -82,7 +82,7 @@ export class MinimalKey {
}
let key = this.key
if (key == " ") {
if (key === " ") {
key = "Space"
needsBrackets = true
}
@ -287,7 +287,7 @@ export function mapstrToKeyseq(mapstr: string): MinimalKey[] {
// Reduce mapstr by one character or one bracket expression per iteration
while (mapstr.length) {
if (mapstr[0] === "<") {
;[key, mapstr] = bracketexprToKey(mapstr)
[key, mapstr] = bracketexprToKey(mapstr)
keyseq.push(key)
} else {
keyseq.push(new MinimalKey(mapstr[0]))

View file

@ -46,11 +46,11 @@ export class Logger {
} else if (
browser.runtime.getURL(
"_generated_background_page.html",
) == window.location.href
) === window.location.href
)
return "background"
}
if (getContext() == "content")
if (getContext() === "content")
return browser.runtime.sendMessage({
type: "controller_background",
command: "acceptExCmd",

View file

@ -84,7 +84,7 @@ export async function messageTab(tabId, type: TabMessageType, command, args?) {
return browserBg.tabs.sendMessage(tabId, message)
}
let _ownTabId = undefined
let _ownTabId
export async function messageOwnTab(type: TabMessageType, command, args?) {
if (_ownTabId === undefined) {
_ownTabId = await ownTabId()
@ -123,7 +123,7 @@ export function addListener(type: MessageType, callback: listener) {
}
}
if (getContext() == "background") {
if (getContext() === "background") {
// Warning: lib/webext.ts:ownTab() relies on this listener being added in order to work
addListener("owntab_background", (message, sender, sendResponse) => {
let x = Object.assign(Object.create(null), sender.tab)

View file

@ -60,7 +60,7 @@ async function sendNativeMsg(
export async function getrcpath(): Promise<string> {
const res = await sendNativeMsg("getconfigpath", {})
if (res.code != 0) throw new Error("getrcpath error: " + res.code)
if (res.code !== 0) throw new Error("getrcpath error: " + res.code)
return res.content
}
@ -224,7 +224,7 @@ export async function nativegate(
export async function inpath(cmd) {
const pathcmd =
(await browserBg.runtime.getPlatformInfo()).os == "win"
(await browserBg.runtime.getPlatformInfo()).os === "win"
? "where "
: "which "
return (await run(pathcmd + cmd.split(" ")[0])).code === 0
@ -245,10 +245,10 @@ export async function firstinpath(cmdarray) {
export async function editor(file: string, content?: string) {
if (content !== undefined) await write(file, content)
const editorcmd =
config.get("editorcmd") == "auto"
config.get("editorcmd") === "auto"
? await getBestEditor()
: config.get("editorcmd")
if (editorcmd.indexOf("%f") != -1) {
if (editorcmd.indexOf("%f") !== -1) {
await run(editorcmd.replace(/%f/, file))
} else {
await run(editorcmd + " " + file)
@ -336,25 +336,25 @@ export async function clipboard(
str: string,
): Promise<string> {
let clipcmd = await config.get("externalclipboardcmd")
if (clipcmd == "auto") clipcmd = await firstinpath(["xsel", "xclip"])
if (clipcmd === "auto") clipcmd = await firstinpath(["xsel", "xclip"])
if (clipcmd === undefined) {
throw new Error("Couldn't find an external clipboard executable")
}
if (action == "get") {
if (action === "get") {
let result = await run(clipcmd + " -o")
if (result.code != 0) {
if (result.code !== 0) {
throw new Error(
`External command failed with code ${result.code}: ${clipcmd}`,
)
}
return result.content
} else if (action == "set") {
} else if (action === "set") {
let required_version = "0.1.7"
if (await nativegate(required_version, false)) {
let result = await run(`${clipcmd} -i`, str)
if (result.code != 0)
if (result.code !== 0)
throw new Error(
`External command failed with code ${
result.code
@ -370,7 +370,7 @@ export async function clipboard(
// Find a delimiter that isn't in str
let heredoc = "TRIDACTYL"
while (str.search(heredoc) != -1)
while (str.search(heredoc) !== -1)
heredoc += Math.round(Math.random() * 10)
// Use delimiter to insert str into clipcmd's stdin
@ -417,11 +417,11 @@ export function parseProfilesIni(content: string, basePath: string) {
for (let profileName of Object.keys(result)) {
let profile = result[profileName]
// profile.IsRelative can be 0, 1 or undefined
if (profile.IsRelative == 1) {
if (profile.IsRelative === 1) {
profile.relativePath = profile.Path
profile.absolutePath = basePath + profile.relativePath
} else if (profile.IsRelative == 0) {
if (profile.Path.substring(0, basePath.length) != basePath) {
} else if (profile.IsRelative === 0) {
if (profile.Path.substring(0, basePath.length) !== basePath) {
throw new Error(
`Error parsing profiles ini: basePath "${basePath}" doesn't match profile path ${
profile.Path
@ -452,17 +452,17 @@ export async function getProfile() {
const ffDir = await getFirefoxDir()
const iniPath = ffDir + "profiles.ini"
const iniContent = await read(iniPath)
if (iniContent.code != 0 || iniContent.content.length == 0) {
if (iniContent.code !== 0 || iniContent.content.length === 0) {
throw new Error(`native.ts:getProfile() : Couldn't read "${iniPath}"`)
}
const iniObject = parseProfilesIni(iniContent.content, ffDir)
const curProfileDir = config.get("profiledir")
// First, try to see if the 'profiledir' setting matches a profile in profile.ini
if (curProfileDir != "auto") {
if (curProfileDir !== "auto") {
for (let profileName of Object.keys(iniObject)) {
let profile = iniObject[profileName]
if (profile.absolutePath == curProfileDir) {
if (profile.absolutePath === curProfileDir) {
return profile
}
}
@ -478,7 +478,7 @@ export async function getProfile() {
const profilePath = cmdline[profile + 1]
for (let profileName of Object.keys(iniObject)) {
let profile = iniObject[profileName]
if (profile.absolutePath == profilePath) {
if (profile.absolutePath === profilePath) {
return profile
}
}
@ -489,12 +489,12 @@ export async function getProfile() {
// Try to find a profile name in firefox's arguments
let p = cmdline.indexOf("-p")
if (p == -1) p = cmdline.indexOf("-P")
if (p === -1) p = cmdline.indexOf("-P")
if (p >= 0 && p < cmdline.length - 1) {
const pName = cmdline[p + 1]
for (let profileName of Object.keys(iniObject)) {
let profile = iniObject[profileName]
if (profile.Name == pName) {
if (profile.Name === pName) {
return profile
}
}
@ -510,18 +510,18 @@ export async function getProfile() {
if ((await browserBg.runtime.getPlatformInfo()).os === "mac")
hacky_profile_finder = `find "${ffDir}" -maxdepth 2 -name .parentlock`
let profilecmd = await run(hacky_profile_finder)
if (profilecmd.code == 0 && profilecmd.content.length != 0) {
if (profilecmd.code === 0 && profilecmd.content.length !== 0) {
// Remove trailing newline
profilecmd.content = profilecmd.content.trim()
// If there's only one profile in use, use that to find the right profile
if (profilecmd.content.split("\n").length == 1) {
if (profilecmd.content.split("\n").length === 1) {
const path = profilecmd.content
.split("/")
.slice(0, -1)
.join("/")
for (let profileName of Object.keys(iniObject)) {
let profile = iniObject[profileName]
if (profile.absolutePath == path) {
if (profile.absolutePath === path) {
return profile
}
}
@ -534,7 +534,7 @@ export async function getProfile() {
// Multiple profiles used but no -p or --profile, this means that we're using the default profile
for (let profileName of Object.keys(iniObject)) {
let profile = iniObject[profileName]
if (profile.Default == 1) {
if (profile.Default === 1) {
return profile
}
}
@ -550,7 +550,7 @@ export function getProfileName() {
export async function getProfileDir() {
let profiledir = config.get("profiledir")
if (profiledir != "auto") return Promise.resolve(profiledir)
if (profiledir !== "auto") return Promise.resolve(profiledir)
return getProfile().then(p => p.absolutePath)
}
@ -570,7 +570,7 @@ export async function parsePrefs(prefFileContent: string) {
const key = matches[2]
let value = matches[3]
// value = " means that it should be an empty string
if (value == '"') value = ""
if (value === '"') value = ""
prefs[key] = value
return prefs
}, {})
@ -584,7 +584,7 @@ export async function parsePrefs(prefFileContent: string) {
*/
export async function loadPrefs(filename): Promise<{ [key: string]: string }> {
const result = await read(filename)
if (result.code != 0) return {}
if (result.code !== 0) return {}
return parsePrefs(result.content)
}
@ -596,7 +596,7 @@ let cached_prefs = null
* Performance is slow so we need to cache the results.
*/
export async function getPrefs(): Promise<{ [key: string]: string }> {
if (cached_prefs != null) return cached_prefs
if (cached_prefs !== null) return cached_prefs
const profile = (await getProfileDir()) + "/"
const prefFiles = [
// Debian has these

View file

@ -4,7 +4,7 @@ import * as config from "@src/lib/config"
import * as UrlUtil from "@src/lib/url_util"
export function inContentScript() {
return getContext() == "content"
return getContext() === "content"
}
/** WebExt code can be run from three contexts:
@ -17,7 +17,7 @@ export function getContext() {
if (!("tabs" in browser)) {
return "content"
} else if (
browser.runtime.getURL("_generated_background_page.html") ==
browser.runtime.getURL("_generated_background_page.html") ===
window.location.href
) {
return "background"
@ -149,7 +149,7 @@ export async function openInNewWindow(createData = {}) {
export async function openInTab(tab, opts = {}, strarr: string[]) {
let address = strarr.join(" ")
if (address == "") {
if (address === "") {
address = config.get("newtab")
}
@ -157,7 +157,7 @@ export async function openInTab(tab, opts = {}, strarr: string[]) {
let firstWord = address
if (index > -1) firstWord = address.substr(0, index)
if (firstWord == "") {
if (firstWord === "") {
// No query, no newtab set, the user is asking for Tridactyl's newtab page
return browserBg.tabs.update(
tab.id,
@ -193,7 +193,7 @@ export async function openInTab(tab, opts = {}, strarr: string[]) {
}
const searchEngines = await browserBg.search.get()
let engine = searchEngines.find(engine => engine.alias == firstWord)
let engine = searchEngines.find(engine => engine.alias === firstWord)
// Maybe firstWord is the name of a firefox search engine?
if (engine !== undefined) {
return browserBg.search.search({
@ -220,7 +220,7 @@ export async function openInTab(tab, opts = {}, strarr: string[]) {
// if firstWord is "search", remove it from the query.
// This allows users to search for a URL or a word they defined as searchurl
let queryString = address
if (firstWord == "search") {
if (firstWord === "search") {
queryString = rest
}
@ -238,7 +238,7 @@ export async function openInTab(tab, opts = {}, strarr: string[]) {
)
}
engine = searchEngines.find(engine => engine.alias == enginename)
engine = searchEngines.find(engine => engine.alias === enginename)
if (engine !== undefined) {
return browserBg.search.search({
tabId: tab.id,

View file

@ -12,7 +12,7 @@ function getChangelogDiv() {
function updateChangelogStatus() {
const changelogDiv = getChangelogDiv()
const changelogContent = changelogDiv.textContent
if (localStorage.changelogContent == changelogContent) {
if (localStorage.changelogContent === changelogContent) {
const changelogButton = document.querySelector('input[id^="spoiler"]')
if (!changelogButton) {
console.error("Couldn't find changelog button!")

View file

@ -8,7 +8,7 @@ class GobbleState {
public endCommand = ""
}
let modeState: GobbleState = undefined
let modeState: GobbleState
/** Init gobble mode. After parsing the defined number of input keys, execute
`endCmd` with attached parsed input. `Escape` cancels the mode and returns to

View file

@ -1,5 +1,8 @@
{
"extends": ["tslint:recommended", "tslint-sonarts"],
"linterOptions": {
"exclude": [ "**/.*.generated.ts" ]
},
"rules": {
"align": false,
"arrow-parens": false,
@ -23,11 +26,7 @@
"no-identical-functions": false,
"no-shadowed-variable": false,
"no-string-throw": false,
"no-trailing-whitespace": false,
"no-unnecessary-initializer": false,
"no-unsafe-finally": false,
"no-var-keyword": false,
"no-variable-usage-before-declaration": false,
"object-literal-key-quotes": false,
"object-literal-sort-keys": false,
"only-arrow-functions": false,
@ -36,7 +35,6 @@
"semicolon": false,
"trailing-comma": false,
"triple-equals": false,
"variable-name": false,
"whitespace": false
"variable-name": false
}
}