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 fi
# .bracketexpr.generated.ts is needed for metadata generation # .bracketexpr.generated.ts is needed for metadata generation
"$(npm bin)/nearleyc" src/grammars/bracketexpr.ne \ "$(npm bin)/nearleyc" src/grammars/bracketexpr.ne > \
> src/grammars/.bracketexpr.generated.ts src/grammars/.bracketexpr.generated.ts
# It's important to generate the metadata before the documentation because # It's important to generate the metadata before the documentation because
# missing imports might break documentation generation on clean builds # missing imports might break documentation generation on clean builds

View file

@ -20,7 +20,7 @@ import state from "@src/state"
import * as webext from "@src/lib/webext" import * as webext from "@src/lib/webext"
import { AutoContain } from "@src/lib/autocontainers" import { AutoContain } from "@src/lib/autocontainers"
/* tslint:disable:import-spacing */ /* tslint:disable:import-spacing */
;(window as any).tri = Object.assign(Object.create(null), { ; (window as any).tri = Object.assign(Object.create(null), {
messaging, messaging,
excmds, excmds,
convert, convert,
@ -41,7 +41,7 @@ import { AutoContain } from "@src/lib/autocontainers"
// {{{ tri.contentLocation // {{{ tri.contentLocation
// When loading the background, use the active tab to know what the current content url is // 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 => { 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 // After that, on every tab change, update the current url
let contentLocationCount = 0 let contentLocationCount = 0
@ -51,8 +51,8 @@ browser.tabs.onActivated.addListener(ev => {
browser.tabs.get(ev.tabId).then(t => { 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 // 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 // This is needed because otherWise the following chain of execution might happen: onActivated1 => onActivated2 => tabs.get2 => tabs.get1
if (contentLocationCount == myId) { if (contentLocationCount === myId) {
;(window as any).tri.contentLocation = new URL(t.url) (window as any).tri.contentLocation = new URL(t.url)
} }
}) })
}) })
@ -91,7 +91,7 @@ browser.runtime.onStartup.addListener(_ => {
config.getAsync("autocmds", "TriStart").then(aucmds => { config.getAsync("autocmds", "TriStart").then(aucmds => {
let hosts = Object.keys(aucmds) let hosts = Object.keys(aucmds)
// If there's only one rule and it's "all", no need to check the hostname // 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]]) BackgroundController.acceptExCmd(aucmds[hosts[0]])
} else { } else {
native.run("hostname").then(hostname => { native.run("hostname").then(hostname => {

View file

@ -5,7 +5,7 @@ const logger = new Logger("rc")
export async function source(filename = "auto") { export async function source(filename = "auto") {
let rctext = "" let rctext = ""
if (filename == "auto") { if (filename === "auto") {
rctext = await Native.getrc() rctext = await Native.getrc()
} else { } else {
rctext = (await Native.read(filename)).content 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 // We want to return a promise that will resolve once the file has been moved somewhere else
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let onDownloadComplete = async downloadDelta => { let onDownloadComplete = async downloadDelta => {
if (downloadDelta.id != downloadId) { if (downloadDelta.id !== downloadId) {
return 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 // 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 // This seems acceptable for now as taking all states into account seems quite difficult
if ( if (
downloadDelta.state && downloadDelta.state &&
downloadDelta.state.current != "in_progress" downloadDelta.state.current !== "in_progress"
) { ) {
browser.downloads.onChanged.removeListener(onDownloadComplete) browser.downloads.onChanged.removeListener(onDownloadComplete)
let downloadItem = (await browser.downloads.search({ let downloadItem = (await browser.downloads.search({
id: downloadId, id: downloadId,
}))[0] }))[0]
if (downloadDelta.state.current == "complete") { if (downloadDelta.state.current === "complete") {
let operation = await Native.move( let operation = await Native.move(
downloadItem.filename, downloadItem.filename,
saveAs, saveAs,
) )
if (operation.code != 0) { if (operation.code !== 0) {
reject( reject(
new Error( new Error(
`'${ `'${

View file

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

View file

@ -49,7 +49,7 @@ import * as tri_editor from "@src/lib/editor"
const logger = new Logger("cmdline") const logger = new Logger("cmdline")
/** @hidden **/ /** @hidden **/
let activeCompletions: Completions.CompletionSource[] = undefined let activeCompletions: Completions.CompletionSource[]
/** @hidden **/ /** @hidden **/
let completionsDiv = window.document.getElementById("completions") let completionsDiv = window.document.getElementById("completions")
/** @hidden **/ /** @hidden **/
@ -185,7 +185,7 @@ export function complete() {
let fragment = clInput.value let fragment = clInput.value
let matches = state.cmdHistory.filter(key => key.startsWith(fragment)) let matches = state.cmdHistory.filter(key => key.startsWith(fragment))
let mostrecent = matches[matches.length - 1] let mostrecent = matches[matches.length - 1]
if (mostrecent != undefined) clInput.value = mostrecent if (mostrecent !== undefined) clInput.value = mostrecent
return refresh_completions(clInput.value) return refresh_completions(clInput.value)
} }
@ -275,7 +275,7 @@ clInput.addEventListener("input", () => {
// Make sure the previous computation has ended // Make sure the previous computation has ended
await onInputPromise await onInputPromise
// If we're not the current completion computation anymore, stop // If we're not the current completion computation anymore, stop
if (exstr != clInput.value) return if (exstr !== clInput.value) return
onInputPromise = refresh_completions(exstr) onInputPromise = refresh_completions(exstr)
}, 100) }, 100)
@ -344,7 +344,7 @@ function history(n) {
let matches = state.cmdHistory.filter(key => let matches = state.cmdHistory.filter(key =>
key.startsWith(HISTORY_SEARCH_STRING), key.startsWith(HISTORY_SEARCH_STRING),
) )
if (cmdline_history_position == 0) { if (cmdline_history_position === 0) {
cmdline_history_current = clInput.value cmdline_history_current = clInput.value
} }
let clamped_ind = matches.length + n - cmdline_history_position let clamped_ind = matches.length + n - cmdline_history_position
@ -352,11 +352,11 @@ function history(n) {
const pot_history = matches[clamped_ind] const pot_history = matches[clamped_ind]
clInput.value = 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 // if there was no clampage, update history position
// there's a more sensible way of doing this but that would require more programmer time // 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 cmdline_history_position = cmdline_history_position - n
} }
@ -482,6 +482,6 @@ Messaging.addListener("commandline_frame", Messaging.attributeCaller(SELF))
// object since there's apparently a bug that causes performance // object since there's apparently a bug that causes performance
// observers to be GC'd even if they're still the target of a // observers to be GC'd even if they're still the target of a
// callback. // callback.
;(window as any).tri = Object.assign(window.tri || {}, { ; (window as any).tri = Object.assign(window.tri || {}, {
perfObserver: perf.listenForCounters(), perfObserver: perf.listenForCounters(),
}) })

View file

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

View file

@ -29,7 +29,7 @@ export class FileSystemCompletionSource extends Completions.CompletionSourceFuse
} }
public async filter(exstr: string) { public async filter(exstr: string) {
if (!exstr || exstr.indexOf(" ") == -1) { if (!exstr || exstr.indexOf(" ") === -1) {
this.state = "hidden" this.state = "hidden"
return 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 // If there's already a promise being executed, wait for it to finish
await this.prevCompletion 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 // 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 // If we are the last completion
this.prevCompletion = this.updateOptions(exstr) this.prevCompletion = this.updateOptions(exstr)
await this.prevCompletion 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) this.options = Object.keys(metaRules)
.concat(Object.keys(potentialRules)) .concat(Object.keys(potentialRules))
.filter(s => s.startsWith(ruleName)) .filter(s => s.startsWith(ruleName))

View file

@ -59,7 +59,7 @@ export class HistoryCompletionSource extends Completions.CompletionSourceFuse {
// Ignoring command-specific arguments // 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 // 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")) { if (query.startsWith("-c")) {
let args = query.split(" ") let args = query.split(" ")
options = args.slice(0, 2).join(" ") options = args.slice(0, 2).join(" ")
@ -70,7 +70,7 @@ export class HistoryCompletionSource extends Completions.CompletionSourceFuse {
options = args.slice(0, 1).join(" ") options = args.slice(0, 1).join(" ")
query = args.slice(1).join(" ") query = args.slice(1).join(" ")
} }
} else if (prefix == "winopen " && query.startsWith("-private")) { } else if (prefix === "winopen " && query.startsWith("-private")) {
options = "-private" options = "-private"
query = query.substring(options.length) query = query.substring(options.length)
} }
@ -102,7 +102,7 @@ export class HistoryCompletionSource extends Completions.CompletionSourceFuse {
private async scoreOptions(query: string, n: number) { private async scoreOptions(query: string, n: number) {
const newtab = (browser.runtime.getManifest()).chrome_url_overrides.newtab const newtab = (browser.runtime.getManifest()).chrome_url_overrides.newtab
const newtaburl = browser.extension.getURL(newtab) const newtaburl = browser.extension.getURL(newtab)
if (!query || config.get("historyresults") == 0) { if (!query || config.get("historyresults") === 0) {
return (await browserBg.topSites.get()) return (await browserBg.topSites.get())
.filter(page => page.url !== newtaburl) .filter(page => page.url !== newtaburl)
.slice(0, n) .slice(0, n)

View file

@ -53,7 +53,7 @@ export class SettingsCompletionSource extends Completions.CompletionSourceFuse {
// Ignoring command-specific arguments // 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 // 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 // copy pasting code is fun and good
if (prefix == "seturl " || prefix == "unseturl ") { if (prefix === "seturl " || prefix === "unseturl ") {
let args = query.split(" ") let args = query.split(" ")
options = args.slice(0, 1).join(" ") options = args.slice(0, 1).join(" ")
query = args.slice(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 // 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 = !( this.shouldSetStateFromScore = !(
prefix == "tabmove " && query.match("^[+-][0-9]+$") prefix === "tabmove " && query.match("^[+-][0-9]+$")
) )
/* console.log('updateOptions', this.optionContainer) */ /* console.log('updateOptions', this.optionContainer) */

View file

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

View file

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

View file

@ -4,7 +4,7 @@
if ((window as any).tridactyl_content_lock !== undefined) { if ((window as any).tridactyl_content_lock !== undefined) {
throw Error("Trying to load Tridactyl, but it's already loaded.") 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 // 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 // assigned to a name. If you want an import just for its side effects, make
@ -74,7 +74,7 @@ import * as keyseq from "@src/lib/keyseq"
import * as native from "@src/lib/native" import * as native from "@src/lib/native"
import * as styling from "@src/content/styling" import * as styling from "@src/content/styling"
/* tslint:disable:import-spacing */ /* tslint:disable:import-spacing */
;(window as any).tri = Object.assign(Object.create(null), { ; (window as any).tri = Object.assign(Object.create(null), {
browserBg: webext.browserBg, browserBg: webext.browserBg,
commandline_content, commandline_content,
convert, convert,
@ -116,7 +116,7 @@ if (
window.location.pathname === "/static/newtab.html" window.location.pathname === "/static/newtab.html"
) { ) {
config.getAsync("newtab").then(newtab => { config.getAsync("newtab").then(newtab => {
if (newtab == "about:blank") { if (newtab === "about:blank") {
} else if (newtab) { } else if (newtab) {
excmds.open_quiet(newtab) excmds.open_quiet(newtab)
} else { } else {
@ -211,7 +211,7 @@ config.getAsync("modeindicator").then(mode => {
let mode = newValue let mode = newValue
let suffix = "" let suffix = ""
let result = "" let result = ""
if (property != "mode") { if (property !== "mode") {
if (property === "suffix") { if (property === "suffix") {
mode = oldMode mode = oldMode
suffix = newValue suffix = newValue
@ -243,7 +243,7 @@ config.getAsync("modeindicator").then(mode => {
result = mode result = mode
} }
let modeindicatorshowkeys = Config.get("modeindicatorshowkeys") let modeindicatorshowkeys = Config.get("modeindicatorshowkeys")
if (modeindicatorshowkeys === "true" && suffix != "") { if (modeindicatorshowkeys === "true" && suffix !== "") {
result = mode + " " + suffix result = mode + " " + suffix
} }
logger.debug( logger.debug(
@ -263,12 +263,12 @@ config.getAsync("modeindicator").then(mode => {
// Site specific fix for / on GitHub.com // Site specific fix for / on GitHub.com
config.getAsync("leavegithubalone").then(v => { config.getAsync("leavegithubalone").then(v => {
if (v == "true") return if (v === "true") return
try { try {
// On quick loading pages, the document is already loaded // 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) { 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.cancelBubble = true
e.stopImmediatePropagation() e.stopImmediatePropagation()
} }
@ -277,9 +277,9 @@ config.getAsync("leavegithubalone").then(v => {
} catch (e) { } catch (e) {
// But on slower pages we wait for the document to load // But on slower pages we wait for the document to load
window.addEventListener("DOMContentLoaded", () => { window.addEventListener("DOMContentLoaded", () => {
// if (document.location.host == "github.com") { // if (document.location.host === "github.com") {
document.body.addEventListener("keydown", function(e) { 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.cancelBubble = true
e.stopImmediatePropagation() e.stopImmediatePropagation()
} }
@ -293,6 +293,6 @@ config.getAsync("leavegithubalone").then(v => {
// background for collection. Attach the observer to the window object // background for collection. Attach the observer to the window object
// since there's apparently a bug that causes performance observers to // since there's apparently a bug that causes performance observers to
// be GC'd even if they're still the target of a callback. // be GC'd even if they're still the target of a callback.
;(window as any).tri = Object.assign(window.tri, { ; (window as any).tri = Object.assign(window.tri, {
perfObserver: perf.listenForCounters(), perfObserver: perf.listenForCounters(),
}) })

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

View file

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

View file

@ -20,8 +20,8 @@ export class Match {
function isCommandLineNode(n) { function isCommandLineNode(n) {
let url = n.ownerDocument.location.href let url = n.ownerDocument.location.href
return ( return (
url.protocol == "moz-extension:" && url.protocol === "moz-extension:" &&
url.pathname == "/static/commandline.html" url.pathname === "/static/commandline.html"
) )
} }
@ -51,7 +51,7 @@ let lastMatches = []
export function getMatches(findings, contextLength = 10): Match[] { export function getMatches(findings, contextLength = 10): Match[] {
let result = [] let result = []
if (findings.length == 0) return result if (findings.length === 0) return result
// Checks if a node belongs to the command line // Checks if a node belongs to the command line
let nodes = getNodes() let nodes = getNodes()
@ -130,13 +130,13 @@ export async function find(query, count = -1, reverse = false) {
let findId = findCount let findId = findCount
let findcase = await config.getAsync("findcase") let findcase = await config.getAsync("findcase")
let caseSensitive = let caseSensitive =
findcase == "sensitive" || findcase === "sensitive" ||
(findcase == "smart" && query.search(/[A-Z]/) >= 0) (findcase === "smart" && query.search(/[A-Z]/) >= 0)
let tabId = await activeTabId() let tabId = await activeTabId()
// No point in searching for something that won't be used anyway // No point in searching for something that won't be used anyway
await prevFind await prevFind
if (findId != findCount) return [] if (findId !== findCount) return []
prevFind = browserBg.find.find(query, { prevFind = browserBg.find.find(query, {
tabId, tabId,
@ -167,7 +167,7 @@ export async function find(query, count = -1, reverse = false) {
let pivot = findings.indexOf(findings.find(finder)) let pivot = findings.indexOf(findings.find(finder))
findings = findings.slice(pivot).concat(findings.slice(0, pivot)) 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 return findings
} }
@ -209,7 +209,7 @@ export function findVisibleNode(allMatches, i, direction) {
while (!match.firstNode.ownerDocument.contains(match.firstNode)) { while (!match.firstNode.ownerDocument.contains(match.firstNode)) {
n += direction n += direction
match = lastMatches[n] match = lastMatches[n]
if (n == i) return null if (n === i) return null
} }
match.firstNode.parentNode.scrollIntoView() match.firstNode.parentNode.scrollIntoView()
} while (!DOM.isVisible(match.firstNode.parentNode)) } while (!DOM.isVisible(match.firstNode.parentNode))
@ -223,7 +223,7 @@ function focusMatch(match: Match) {
if (elem) { 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 // 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 let newElem = elem
while (newElem && newElem.tagName != "A") newElem = newElem.parentNode while (newElem && newElem.tagName !== "A") newElem = newElem.parentNode
if (newElem) newElem.focus() if (newElem) newElem.focus()
else elem.focus() else elem.focus()
} }
@ -237,7 +237,7 @@ export async function jumpToMatch(pattern, reverse, startingFrom) {
let match let match
// When we already computed all the matches, don't recompute them // 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] match = lastMatches[startingFrom]
if (!match) { if (!match) {
@ -271,7 +271,7 @@ export function jumpToNextMatch(n: number) {
if (lastMatches.length < 1) { if (lastMatches.length < 1) {
// Let's try to find new matches // Let's try to find new matches
return jumpToMatch(state.lastSearch, n == -1, 0) return jumpToMatch(state.lastSearch, n === -1, 0)
} }
browserBg.find.highlightResults() browserBg.find.highlightResults()
@ -281,7 +281,7 @@ export function jumpToNextMatch(n: number) {
n <= 0 ? -1 : 1, 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` 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) { 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 */ /** For each hintable element, add a hint */
export function hintPage( export function hintPage(
@ -178,7 +178,7 @@ function defaultHintFilter() {
} }
function defaultHintChars() { function defaultHintChars() {
if (config.get("hintnames") == "numeric") { if (config.get("hintnames") === "numeric") {
return "1234567890" return "1234567890"
} }
return config.get("hintchars") return config.get("hintchars")
@ -210,7 +210,7 @@ function* hintnames_simple(
So it removes them. This function is not yet clever enough to realise that if n > h ** 2 it should remove So it removes them. This function is not yet clever enough to realise that if n > h ** 2 it should remove
h + (n - h**2 - h) / h ** 2 h + (n - h**2 - h) / h ** 2
and so on, but we hardly ever see that many hints, so whatever. and so on, but we hardly ever see that many hints, so whatever.
*/ */
function* hintnames_short( function* hintnames_short(
n: number, n: number,
@ -278,7 +278,7 @@ class Hint {
let offsetLeft = 0 let offsetLeft = 0
if (target.ownerDocument !== document) { if (target.ownerDocument !== document) {
let iframe = DOM.getAllDocumentFrames().find( let iframe = DOM.getAllDocumentFrames().find(
frame => frame.contentDocument == target.ownerDocument, frame => frame.contentDocument === target.ownerDocument,
) )
let rect = iframe.getClientRects()[0] let rect = iframe.getClientRects()[0]
offsetTop += rect.top offsetTop += rect.top
@ -288,7 +288,7 @@ class Hint {
const rect = target.getClientRects()[0] const rect = target.getClientRects()[0]
this.flag.textContent = name this.flag.textContent = name
this.flag.className = "TridactylHint" this.flag.className = "TridactylHint"
if (config.get("hintuppercase") == "true") { if (config.get("hintuppercase") === "true") {
this.flag.classList.add("TridactylHintUppercase") this.flag.classList.add("TridactylHintUppercase")
} }
this.flag.classList.add("TridactylHint" + target.tagName) this.flag.classList.add("TridactylHint" + target.tagName)
@ -361,7 +361,7 @@ function buildHintsVimperator(els: Element[], onSelect: HintSelectedCallback) {
function elementFilterableText(el: Element): string { function elementFilterableText(el: Element): string {
const nodename = el.nodeName.toLowerCase() const nodename = el.nodeName.toLowerCase()
let text: string let text: string
if (nodename == "input") { if (nodename === "input") {
text = (el as HTMLInputElement).value text = (el as HTMLInputElement).value
} else if (0 < el.textContent.length) { } else if (0 < el.textContent.length) {
text = el.textContent text = el.textContent
@ -392,7 +392,7 @@ function filterHintsSimple(fstr) {
active.push(h) active.push(h)
} }
} }
if (active.length == 1) { if (active.length === 1) {
selectFocusedHint() selectFocusedHint()
} }
} }
@ -476,7 +476,7 @@ function filterHintsVimperator(fstr, reflow = false) {
} }
// Select focused hint if it's the only match // Select focused hint if it's the only match
if (active.length == 1) { if (active.length === 1) {
selectFocusedHint(true) selectFocusedHint(true)
} }
} }

View file

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

View file

@ -1,7 +1,4 @@
/* tslint:disable:array-type */
/* tslint:disable:comment-format */ /* 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 // '//#' is a start point for a simple text-replacement-type macro. See excmds_macros.py
/** # Tridactyl help page /** # Tridactyl help page
@ -56,7 +53,6 @@
All three channels are mirrored together, so it doesn't matter which one you use. All three channels are mirrored together, so it doesn't matter which one you use.
[1]: https://github.com/tridactyl/tridactyl/issues [1]: https://github.com/tridactyl/tridactyl/issues
[2]: https://github.com/tridactyl/tridactyl#readme [2]: https://github.com/tridactyl/tridactyl#readme
[3]: https://github.com/tridactyl/tridactyl/blob/master/doc/troubleshooting.md [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. * This function is used by rssexec and rssexec completions.
*/ */
//#content //#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>() let seen = new Set<string>()
return Array.from(document.querySelectorAll("a, link[rel='alternate']")) 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) => { .reduce((acc, e: any) => {
let type = "" let type = ""
// Start by detecting type because url doesn't necessarily contain the words "rss" or "atom" // 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 //#content
export async function rssexec(url: string, type?: string, ...title: string[]) { export async function rssexec(url: string, type?: string, ...title: string[]) {
if (!url || url == "") { if (!url || url === "") {
let links = await getRssLinks() let links = await getRssLinks()
switch (links.length) { switch (links.length) {
case 0: case 0:
@ -205,7 +201,7 @@ export async function fillinput(selector: string, ...content: string[]) {
let inputToFill = document.querySelector(selector) let inputToFill = document.querySelector(selector)
if (!inputToFill) inputToFill = DOM.getLastUsedInput() if (!inputToFill) inputToFill = DOM.getLastUsedInput()
if ("value" in inputToFill) { if ("value" in inputToFill) {
;(inputToFill as HTMLInputElement).value = content.join(" ") (inputToFill as HTMLInputElement).value = content.join(" ")
} else { } else {
inputToFill.textContent = content.join(" ") inputToFill.textContent = content.join(" ")
} }
@ -379,7 +375,7 @@ export function cssparse(...css: string[]) {
//#background //#background
export async function loadtheme(themename: string) { export async function loadtheme(themename: string) {
if (!(await Native.nativegate("0.1.9"))) return 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 // remove the "tridactylrc" bit so that we're left with the directory
const path = const path =
(await Native.getrcpath()) (await Native.getrcpath())
@ -392,7 +388,7 @@ export async function loadtheme(themename: string) {
themename + themename +
".css" ".css"
const file = await Native.read(path) 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) return set("customthemes." + themename, file.content)
} }
@ -812,7 +808,7 @@ export function addJump(scrollEvent: UIEvent) {
jumps.timeoutid = setTimeout(() => { jumps.timeoutid = setTimeout(() => {
let list = jumps.list let list = jumps.list
// if the page hasn't moved, stop // 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 // Store the new jump
// Could removing all jumps from list[cur] to list[list.length] be // Could removing all jumps from list[cur] to list[list.length] be
// a better/more intuitive behavior? // a better/more intuitive behavior?
@ -833,7 +829,7 @@ document.addEventListener("load", () => curJumps().then(() => jumpprev(0)))
/** Blur (unfocus) the active element */ /** Blur (unfocus) the active element */
//#content //#content
export function unfocus() { export function unfocus() {
;(document.activeElement as HTMLInputElement).blur() (document.activeElement as HTMLInputElement).blur()
contentState.mode = "normal" contentState.mode = "normal"
} }
@ -856,7 +852,7 @@ export async function scrollpx(a: number, b: number) {
*/ */
//#content //#content
export function scrollto(a: number | string, b: number | "x" | "y" = "y") { 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.replace(/c$/, "")) * 100) / (2 * Math.PI)
} }
a = Number(a) a = Number(a)
@ -865,16 +861,16 @@ export function scrollto(a: number | string, b: number | "x" | "y" = "y") {
if (b === "y") { if (b === "y") {
let top = elem.getClientRects()[0].top let top = elem.getClientRects()[0].top
window.scrollTo(window.scrollX, (percentage * elem.scrollHeight) / 100) 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 // scrollTo failed, if the user wants to go to the top/bottom of
// the page try scrolling.recursiveScroll instead // 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") { } else if (b === "x") {
let left = elem.getClientRects()[0].left let left = elem.getClientRects()[0].left
window.scrollTo((percentage * elem.scrollWidth) / 100, window.scrollY) window.scrollTo((percentage * elem.scrollWidth) / 100, window.scrollY)
if (left == elem.getClientRects()[0].left && (percentage == 0 || percentage == 100)) { if (left === elem.getClientRects()[0].left && (percentage === 0 || percentage === 100)) {
scrolling.recursiveScroll(1073741824 * (percentage == 0 ? -1 : 1), window.scrollX, document.documentElement) scrolling.recursiveScroll(1073741824 * (percentage === 0 ? -1 : 1), window.scrollX, document.documentElement)
} }
} else { } else {
window.scrollTo(a, Number(b)) // a,b numbers window.scrollTo(a, Number(b)) // a,b numbers
@ -1008,7 +1004,7 @@ export async function reloadall(hard = false) {
export async function reloadallbut(hard = false) { export async function reloadallbut(hard = false) {
let tabs = await browser.tabs.query({ currentWindow: true }) let tabs = await browser.tabs.query({ currentWindow: true })
let currId = await activeTabId() let currId = await activeTabId()
tabs = tabs.filter(tab => tab.id != currId) tabs = tabs.filter(tab => tab.id !== currId)
let reloadprops = { bypassCache: hard } let reloadprops = { bypassCache: hard }
tabs.forEach(tab => browser.tabs.reload(tab.id, reloadprops)) tabs.forEach(tab => browser.tabs.reload(tab.id, reloadprops))
} }
@ -1050,7 +1046,7 @@ export async function open(...urlarr: string[]) {
p = Messaging.message("controller_background", "acceptExCmd", ["nativeopen " + url]) p = Messaging.message("controller_background", "acceptExCmd", ["nativeopen " + url])
} else if (url.match(/^javascript:/)) { } else if (url.match(/^javascript:/)) {
let bookmarklet = url.replace(/^javascript:/, "") let bookmarklet = url.replace(/^javascript:/, "")
;(document.body as any).append( ; (document.body as any).append(
html` html`
<script> <script>
${bookmarklet} ${bookmarklet}
@ -1072,7 +1068,7 @@ export async function open(...urlarr: string[]) {
*/ */
//#background //#background
export async function bmarks(opt: string, ...urlarr: string[]) { 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) else return open(opt, ...urlarr)
} }
@ -1129,7 +1125,7 @@ export async function url2args() {
/** @hidden */ /** @hidden */
//#content_helper //#content_helper
let sourceElement = undefined let sourceElement
/** @hidden */ /** @hidden */
//#content_helper //#content_helper
function removeSource() { function removeSource() {
@ -1218,7 +1214,7 @@ export async function help(...helpItems: string[]) {
while (aliases[helpItem]) { while (aliases[helpItem]) {
resolved.push(helpItem) resolved.push(helpItem)
helpItem = aliases[helpItem].split(" ") helpItem = aliases[helpItem].split(" ")
helpItem = helpItem[0] == "composite" ? helpItem[1] : helpItem[0] helpItem = helpItem[0] === "composite" ? helpItem[1] : helpItem[0]
// Prevent infinite loops // Prevent infinite loops
if (resolved.includes(helpItem)) break if (resolved.includes(helpItem)) break
} }
@ -1257,7 +1253,7 @@ export async function help(...helpItems: string[]) {
subSettings = subSettings[settingName] 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 browser.extension.getURL("static/docs/classes/_src_lib_config_.default_config.html") + "#" + settingHelpAnchor.slice(0, -1)
} }
return "" return ""
@ -1276,14 +1272,14 @@ export async function help(...helpItems: string[]) {
let url = "" let url = ""
// If the user did specify what they wanted, specifically look for it // If the user did specify what they wanted, specifically look for it
if (flag != "") { if (flag !== "") {
url = flags[flag](settings, subject) url = flags[flag](settings, subject)
} }
// Otherwise or if it couldn't be found, try all possible items // Otherwise or if it couldn't be found, try all possible items
if (url == "") { if (url === "") {
url = ["-b", "-s", "-a", "-e"].reduce((acc, curFlag) => { url = ["-b", "-s", "-a", "-e"].reduce((acc, curFlag) => {
if (acc != "") return acc if (acc !== "") return acc
return flags[curFlag](settings, subject) return flags[curFlag](settings, subject)
}, "") }, "")
} }
@ -1515,7 +1511,7 @@ export function urlparent(count = 1) {
//#content //#content
export function urlmodify(mode: "-t" | "-r" | "-q" | "-Q" | "-g", ...args: string[]) { export function urlmodify(mode: "-t" | "-r" | "-q" | "-Q" | "-g", ...args: string[]) {
let oldUrl = new URL(window.location.href) let oldUrl = new URL(window.location.href)
let newUrl = undefined let newUrl
switch (mode) { switch (mode) {
case "-t": case "-t":
@ -2021,7 +2017,7 @@ export async function fullscreen() {
const currwin = await browser.windows.getCurrent() const currwin = await browser.windows.getCurrent()
const wid = currwin.id const wid = currwin.id
// This might have odd behaviour on non-tiling window managers, but no-one uses those, right? // 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 }) browser.windows.update(wid, { state })
} }
@ -2130,7 +2126,7 @@ export async function undo(item = "recent"): Promise<number> {
} }
} else if (!isNaN(parseInt(item, 10))) { } else if (!isNaN(parseInt(item, 10))) {
const sessionId = item 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) { if (session) {
browser.sessions.restore(sessionId) browser.sessions.restore(sessionId)
return (session.tab || session.window).id return (session.tab || session.window).id
@ -2226,7 +2222,7 @@ export async function mute(...muteArgs: string[]): Promise<void> {
let all = false let all = false
let argParse = (args: string[]) => { let argParse = (args: string[]) => {
if (args == null) { if (args === null) {
return return
} }
if (args[0] === "all") { if (args[0] === "all") {
@ -2321,7 +2317,7 @@ export async function winopen(...args: string[]) {
*/ */
//#background //#background
export async function winclose(...ids: string[]) { export async function winclose(...ids: string[]) {
if (ids.length == 0) { if (ids.length === 0) {
ids.push(`${(await browser.windows.getCurrent()).id}`) ids.push(`${(await browser.windows.getCurrent()).id}`)
} }
return Promise.all(ids.map(id => browser.windows.remove(parseInt(id, 10)))) 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]) Messaging.messageOwnTab("commandline_frame", "fillcmdline", [strarr.join(" "), false, false])
return new Promise(resolve => return new Promise(resolve =>
setTimeout(async () => { setTimeout(async () => {
if ((await Messaging.messageOwnTab("commandline_frame", "getContent", [])) == str) { if ((await Messaging.messageOwnTab("commandline_frame", "getContent", [])) === str) {
CommandLineContent.hide_and_blur() CommandLineContent.hide_and_blur()
resolve(Messaging.messageOwnTab("commandline_frame", "clear", [true])) resolve(Messaging.messageOwnTab("commandline_frame", "clear", [true]))
} }
@ -2713,8 +2709,8 @@ async function setclip(str) {
*/ */
//#background_helper //#background_helper
async function getclip(fromm?: "clipboard" | "selection") { async function getclip(fromm?: "clipboard" | "selection") {
if (fromm == undefined) fromm = await config.getAsync("putfrom") if (fromm === undefined) fromm = await config.getAsync("putfrom")
if (fromm == "clipboard") { if (fromm === "clipboard") {
return messageActiveTab("commandline_frame", "getClipboard") return messageActiveTab("commandline_frame", "getClipboard")
} else { } else {
return Native.clipboard("get", "") return Native.clipboard("get", "")
@ -2723,17 +2719,17 @@ async function getclip(fromm?: "clipboard" | "selection") {
/** Use the system clipboard. /** 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). 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) { switch (excmd) {
case "yankshort": case "yankshort":
urls = await geturlsforlinks("rel", "shortlink") urls = await geturlsforlinks("rel", "shortlink")
if (urls.length == 0) { if (urls.length === 0) {
urls = await geturlsforlinks("rev", "canonical") urls = await geturlsforlinks("rev", "canonical")
} }
if (urls.length > 0) { if (urls.length > 0) {
@ -2768,7 +2764,7 @@ export async function clipboard(excmd: "open" | "yank" | "yankshort" | "yankcano
} }
// Trying yank if yankcanon failed... // Trying yank if yankcanon failed...
case "yank": case "yank":
content = content == "" ? (await activeTab()).url : content content = content === "" ? (await activeTab()).url : content
await yank(content) await yank(content)
fillcmdline_tmp(3000, "# " + content + " copied to clipboard.") fillcmdline_tmp(3000, "# " + content + " copied to clipboard.")
break break
@ -2903,7 +2899,7 @@ interface bind_args {
/** @hidden */ /** @hidden */
//#background_helper //#background_helper
function parse_bind_args(...args: string[]): bind_args { 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 let result = {} as bind_args
result.mode = "normal" 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 [[fillcmdline]] to put a string in the cmdline and focus the cmdline
(otherwise the string is executed immediately). (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). 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: See also:
@ -2969,7 +2964,7 @@ function parse_bind_args(...args: string[]): bind_args {
export function bind(...args: string[]) { export function bind(...args: string[]) {
let args_obj = parse_bind_args(...args) let args_obj = parse_bind_args(...args)
let p = Promise.resolve() let p = Promise.resolve()
if (args_obj.excmd != "") { if (args_obj.excmd !== "") {
for (let i = 0; i < args_obj.key.length; i++) { 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 // Check if any initial subsequence of the key exists and will shadow the new binding
let key_sub = args_obj.key.slice(0, i) 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[]) { export function bindurl(pattern: string, mode: string, keys: string, ...excmd: string[]) {
let args_obj = parse_bind_args(mode, keys, ...excmd) let args_obj = parse_bind_args(mode, keys, ...excmd)
let p = Promise.resolve() 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) p = config.setURL(pattern, args_obj.configName, args_obj.key, args_obj.excmd)
} else if (args_obj.key.length) { } else if (args_obj.key.length) {
// Display the existing bind // Display the existing bind
@ -3041,7 +3036,7 @@ function validateSetArgs(key: string, values: string[]) {
if (md !== undefined) { if (md !== undefined) {
const strval = values.join(" ") const strval = values.join(" ")
// Note: the conversion will throw if strval can't be converted to the right type // 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) value = (md as any).type.convertMember(target.slice(1), strval)
} else { } else {
value = md.type.convert(strval) value = md.type.convert(strval)
@ -3080,7 +3075,7 @@ function validateSetArgs(key: string, values: string[]) {
*/ */
//#content //#content
export function seturl(pattern: string, key: string, ...values: string[]) { export function seturl(pattern: string, key: string, ...values: string[]) {
if (values.length == 0 && key) { if (values.length === 0 && key) {
values = [key] values = [key]
key = pattern key = pattern
pattern = window.location.href pattern = window.location.href
@ -3111,7 +3106,7 @@ export function set(key: string, ...values: string[]) {
return get(key) return get(key)
} }
if (key == "noiframeon") { if (key === "noiframeon") {
let noiframes = config.get("noiframeon") let noiframes = config.get("noiframeon")
// unset previous settings // unset previous settings
if (noiframes) noiframes.forEach(url => seturl(url, "noiframe", "false")) if (noiframes) noiframes.forEach(url => seturl(url, "noiframe", "false"))
@ -3209,7 +3204,7 @@ export function blacklistadd(url: string) {
//#background //#background
export async function unbind(...args: string[]) { export async function unbind(...args: string[]) {
let args_obj = parse_bind_args(...args) 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, "") return config.set(args_obj.configName, args_obj.key, "")
} }
@ -3300,7 +3295,7 @@ export async function sanitise(...args: string[]) {
if (flagpos < args.length - 1) { if (flagpos < args.length - 1) {
let match = args[flagpos + 1].match("^([0-9])+(m|h|d|w)$") let match = args[flagpos + 1].match("^([0-9])+(m|h|d|w)$")
// If the arg of the flag matches Pentadactyl's sanitisetimespan format // 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 // Compute the timespan in milliseconds and get a Date object
let millis = parseInt(match[1], 10) * 1000 let millis = parseInt(match[1], 10) * 1000
switch (match[2]) { switch (match[2]) {
@ -3345,7 +3340,7 @@ export async function sanitise(...args: string[]) {
"serverBoundCertificates": false, "serverBoundCertificates": false,
*/ */
} }
if (args.find(x => x == "all") !== undefined) { if (args.find(x => x === "all") !== undefined) {
for (let attr in dts) dts[attr] = true for (let attr in dts) dts[attr] = true
} else { } else {
// We bother checking if dts[x] is false because // 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) { 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! // Have to await these or they race!
await bind("gn" + key, "tabopen", address) await bind("gn" + key, "tabopen", address)
await bind("go" + key, "open", 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> { export async function hint(option?: string, selectors?: string, ...rest: string[]): Promise<any> {
if (!option) option = "" if (!option) option = ""
if (option == "-br") option = "-qb" if (option === "-br") option = "-qb"
// extract flags // extract flags
// Note: we need to process 'pipe' separately because it could be interpreted as -p -i -e otherwise // 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 // s: don't ask the user where to save the file
// a: ask the user where to save the file // a: ask the user where to save the file
let saveAs = true let saveAs = true
if (option[1].toLowerCase() == "s") saveAs = false if (option[1].toLowerCase() === "s") saveAs = false
// Lowercase: anchors // Lowercase: anchors
// Uppercase: images // Uppercase: images
let attr = "href" let attr = "href"
if (option[1].toLowerCase() == option[1]) { if (option[1].toLowerCase() === option[1]) {
attr = "href" attr = "href"
elems = hinting.saveableElements() elems = hinting.saveableElements()
} else { } else {
@ -3917,7 +3912,7 @@ export async function ttsvoices() {
export async function ttscontrol(action: string) { export async function ttscontrol(action: string) {
// only pause seems to be working, so only provide access to that // only pause seems to be working, so only provide access to that
// to avoid exposing users to things that won't work // 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) throw new Error("Unknown text-to-speech action: " + action)
} }
@ -3985,7 +3980,7 @@ export async function perfhistogram(...filters: string[]) {
let filterconfigs = buildFilterConfigs(filters) let filterconfigs = buildFilterConfigs(filters)
filterconfigs.push({ kind: "eventType", eventType: "measure" }) filterconfigs.push({ kind: "eventType", eventType: "measure" })
const entries = window.tri.statsLogger.getEntries(...filterconfigs) const entries = window.tri.statsLogger.getEntries(...filterconfigs)
if (entries.length == 0) { if (entries.length === 0) {
fillcmdline_tmp(3000, "perfhistogram: No samples found.") fillcmdline_tmp(3000, "perfhistogram: No samples found.")
return 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. // if titlearr is given and we have duplicates, we probably want to give an error here.
const dupbmarks = await browser.bookmarks.search({ url }) const dupbmarks = await browser.bookmarks.search({ url })
dupbmarks.forEach(bookmark => browser.bookmarks.remove(bookmark.id)) 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) const path = title.substring(0, title.lastIndexOf("/") + 1)
// TODO: if title is blank, get it from the page. // 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. const tree = (await browser.bookmarks.getTree())[0] // Why would getTree return a tree? Obviously it returns an array of unit length.
// I hate recursion. // I hate recursion.
const treeClimber = (tree, treestr) => { 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) const validpaths = flatten(treeClimber(tree, "")).filter(x => "path" in x)
title = title.substring(title.lastIndexOf("/") + 1) 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 strict look doesn't find it, be a bit gentler
if (pathobj === undefined) pathobj = validpaths.find(p => p.path.includes(path)) if (pathobj === undefined) pathobj = validpaths.find(p => p.path.includes(path))
if (pathobj !== undefined) { if (pathobj !== undefined) {
@ -4162,8 +4157,8 @@ export async function updatecheck(polite = false) {
*/ */
//#background_helper //#background_helper
browser.runtime.onInstalled.addListener(details => { browser.runtime.onInstalled.addListener(details => {
if (details.reason == "install") tutor("newtab") if (details.reason === "install") tutor("newtab")
else if ((details as any).temporary !== true && details.reason == "update") updatenative(false) 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? // 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] let bindingNode = elem.getElementsByClassName(`Tridactyl${kind}`)[0]
if (bindingNode) { if (bindingNode) {
Array.from(bindingNode.children) Array.from(bindingNode.children)
.filter(e => e.tagName == "SPAN") .filter(e => e.tagName === "SPAN")
.forEach(e => e.parentNode.removeChild(e)) .forEach(e => e.parentNode.removeChild(e))
} else { } else {
// Otherwise, create it // Otherwise, create it
@ -29,7 +29,7 @@ function getCommandElements() {
".tsd-panel.tsd-member.tsd-kind-function.tsd-parent-kind-external-module", ".tsd-panel.tsd-member.tsd-kind-function.tsd-parent-kind-external-module",
), ),
).reduce((all, elem) => { ).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 if (fnName) all[fnName.textContent] = elem
return all return all
}, {}) }, {})
@ -84,7 +84,7 @@ async function addSetting(settingName: string) {
Object.values(settingElems) Object.values(settingElems)
.filter( .filter(
(e: HTMLElement) => (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)) .forEach((e: HTMLElement) => e.parentNode.removeChild(e))
} }
@ -93,10 +93,10 @@ async function onExcmdPageLoad() {
browser.storage.onChanged.addListener((changes, areaname) => { browser.storage.onChanged.addListener((changes, areaname) => {
if ("userconfig" in changes) { if ("userconfig" in changes) {
// JSON.stringify for comparisons like it's 2012 // JSON.stringify for comparisons like it's 2012
;["nmaps", "imaps", "ignoremaps", "inputmaps", "exaliases"].forEach( ["nmaps", "imaps", "ignoremaps", "inputmaps", "exaliases"].forEach(
kind => { kind => {
if ( if (
JSON.stringify(changes.userconfig.newValue[kind]) != JSON.stringify(changes.userconfig.newValue[kind]) !==
JSON.stringify(changes.userconfig.oldValue[kind]) JSON.stringify(changes.userconfig.oldValue[kind])
) )
addSetting(kind) addSetting(kind)
@ -129,14 +129,14 @@ function addSettingInputs() {
let onKeyUp = async ev => { let onKeyUp = async ev => {
let input = ev.target let input = ev.target
if (ev.key == "Enter") { if (ev.key === "Enter") {
;(window as any).tri.messaging.message( (window as any).tri.messaging.message(
"controller_background", "controller_background",
"acceptExCmd", "acceptExCmd",
["set " + input.name + " " + input.value], ["set " + input.name + " " + input.value],
) )
} else { } else {
if (input.value == (await config.getAsync(input.name.split(".")))) { if (input.value === (await config.getAsync(input.name.split(".")))) {
input.className = inputClassName input.className = inputClassName
} else { } else {
input.className = inputClassNameModified input.className = inputClassNameModified
@ -198,12 +198,12 @@ function addResetConfigButton() {
let p = prompt( let p = prompt(
`Please write '${sentence}' without quotes in the following input field if you really want to reset your Tridactyl config.`, `Please write '${sentence}' without quotes in the following input field if you really want to reset your Tridactyl config.`,
) )
if (p == sentence) { if (p === sentence) {
;(window as any).tri.messaging (window as any).tri.messaging
.message("controller_background", "acceptExCmd", [sentence]) .message("controller_background", "acceptExCmd", [sentence])
.then(_ => alert("Config reset!")) .then(_ => alert("Config reset!"))
} else { } else {
alert(`Config not reset because '${p}' != '${sentence}'`) alert(`Config not reset because '${p}' !== '${sentence}'`)
} }
}) })
document.querySelector("div.container.container-main").appendChild(button) document.querySelector("div.container.container-main").appendChild(button)

View file

@ -12,8 +12,8 @@
* Unescaped periods will match *anything*. `autocontain google.co.uk work` will match `google!co$uk`. Escape your periods or accept that you might get some false positives. * Unescaped periods will match *anything*. `autocontain google.co.uk work` will match `google!co$uk`. Escape your periods or accept that you might get some false positives.
* You can use regex in your domain pattern. `autocontain google\,(co\.uk|com) work` will match either `google.co.uk` or `google.com`. * You can use regex in your domain pattern. `autocontain google\,(co\.uk|com) work` will match either `google.co.uk` or `google.com`.
TODO: Should try and detect Multi Account Containers and/or Contain Facebook extensions from Mozilla. TODO: Should try and detect Multi Account Containers and/or Contain Facebook extensions from Mozilla.
A lot of the inspiration for this code was drawn from the Mozilla `contain facebook` Extension. A lot of the inspiration for this code was drawn from the Mozilla `contain facebook` Extension.
https://github.com/mozilla/contain-facebook/ https://github.com/mozilla/contain-facebook/
@ -31,7 +31,7 @@ import * as Logging from "@src/lib/logging"
const logger = new Logging.Logger("containers") const logger = new Logging.Logger("containers")
/** An interface for the additional object that's supplied in the BlockingResponse callback. /** An interface for the additional object that's supplied in the BlockingResponse callback.
Details here: Details here:
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/webRequest/onBeforeRequest#details https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/webRequest/onBeforeRequest#details

View file

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

View file

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

View file

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

View file

@ -37,7 +37,7 @@ type editor_function = (
**/ **/
function applyToElem(e, fn) { function applyToElem(e, fn) {
let result let result
if (e instanceof HTMLInputElement && e.type != "text") { if (e instanceof HTMLInputElement && e.type !== "text") {
let t = e.type let t = e.type
e.type = "text" e.type = "text"
result = fn(e) result = fn(e)
@ -68,7 +68,7 @@ function getContentEditableValues(e: any): [string, number, number] {
let selection = e.ownerDocument.getSelection() let selection = e.ownerDocument.getSelection()
// The selection might actually not be in e so we need to make sure it is // The selection might actually not be in e so we need to make sure it is
let n = selection.anchorNode 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 // The selection isn't for e, so we can't do anything
if (!n) return [null, null, null] 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 // 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( return fn(
text, text,
selectionStart, selectionStart,
typeof selectionEnd == "number" ? selectionEnd : selectionStart, typeof selectionEnd === "number" ? selectionEnd : selectionStart,
arg, arg,
) )
} }
@ -284,7 +284,7 @@ export function wordAfterPos(text: string, position: number) {
**/ **/
export const delete_char = wrap_input( export const delete_char = wrap_input(
needs_text((text, selectionStart, selectionEnd) => { 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 // If the user selected text, then we need to delete that instead of a single char
text = text =
text.substring(0, selectionStart) + text.substring(selectionEnd) text.substring(0, selectionStart) + text.substring(selectionEnd)
@ -302,7 +302,7 @@ export const delete_char = wrap_input(
**/ **/
export const delete_backward_char = wrap_input( export const delete_backward_char = wrap_input(
needs_text((text, selectionStart, selectionEnd) => { needs_text((text, selectionStart, selectionEnd) => {
if (selectionStart != selectionEnd) { if (selectionStart !== selectionEnd) {
text = text =
text.substring(0, selectionStart) + text.substring(selectionEnd) text.substring(0, selectionStart) + text.substring(selectionEnd)
} else { } 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. * 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) => { export const tab_insert = wrap_input((text, selectionStart, selectionEnd) => {
if (selectionStart != selectionEnd) { if (selectionStart !== selectionEnd) {
text = text =
text.substring(0, selectionStart) + text.substring(0, selectionStart) +
"\t" + "\t" +
@ -341,7 +341,7 @@ export const transpose_chars = wrap_input(
(text, selectionStart, selectionEnd) => { (text, selectionStart, selectionEnd) => {
if (text.length < 2) return [null, null, null] if (text.length < 2) return [null, null, null]
// When at the beginning of the text, transpose the first and second characters // 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 // When at the end of the text, transpose the last and second-to-last characters
if (selectionStart >= text.length) selectionStart = text.length - 1 if (selectionStart >= text.length) selectionStart = text.length - 1
@ -364,7 +364,7 @@ function applyWord(
selectionEnd, selectionEnd,
fn: (string) => string, fn: (string) => string,
): [string, number, number] { ): [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 the caret is at the end of the text, move it just before the last character
if (selectionStart >= text.length) { if (selectionStart >= text.length) {
selectionStart = text.length - 1 selectionStart = text.length - 1
@ -460,9 +460,9 @@ export const capitalize_word = wrap_input(
export const kill_line = wrap_input( export const kill_line = wrap_input(
needs_text((text, selectionStart, selectionEnd) => { needs_text((text, selectionStart, selectionEnd) => {
let newLine = text.substring(selectionStart).search("\n") 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 the caret is right before the newline, kill the newline
if (newLine == 0) newLine = 1 if (newLine === 0) newLine = 1
text = text =
text.substring(0, selectionStart) + text.substring(0, selectionStart) +
text.substring(selectionStart + newLine) text.substring(selectionStart + newLine)
@ -479,7 +479,7 @@ export const kill_line = wrap_input(
export const backward_kill_line = wrap_input( export const backward_kill_line = wrap_input(
needs_text((text, selectionStart, selectionEnd) => { needs_text((text, selectionStart, selectionEnd) => {
// If the caret is at the beginning of a line, join the lines // 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 [ return [
text.substring(0, selectionStart - 1) + text.substring(0, selectionStart - 1) +
text.substring(selectionStart), text.substring(selectionStart),
@ -491,7 +491,7 @@ export const backward_kill_line = wrap_input(
// Find the closest newline // Find the closest newline
for ( for (
newLine = selectionStart; newLine = selectionStart;
newLine > 0 && text[newLine - 1] != "\n"; newLine > 0 && text[newLine - 1] !== "\n";
--newLine --newLine
) {} ) {}
// Remove everything between the newline and the caret // 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 // Find the newline before the caret
for ( for (
firstNewLine = selectionStart; firstNewLine = selectionStart;
firstNewLine > 0 && text[firstNewLine - 1] != "\n"; firstNewLine > 0 && text[firstNewLine - 1] !== "\n";
--firstNewLine --firstNewLine
) {} ) {}
// Find the newline after the caret // Find the newline after the caret
for ( for (
secondNewLine = selectionStart; secondNewLine = selectionStart;
secondNewLine < text.length && text[secondNewLine - 1] != "\n"; secondNewLine < text.length && text[secondNewLine - 1] !== "\n";
++secondNewLine ++secondNewLine
) {} ) {}
// Remove everything between the newline and the caret // 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( export const beginning_of_line = wrap_input(
needs_text((text, selectionStart, selectionEnd) => { needs_text((text, selectionStart, selectionEnd) => {
while ( while (
text[selectionStart - 1] != undefined && text[selectionStart - 1] !== undefined &&
text[selectionStart - 1] != "\n" text[selectionStart - 1] !== "\n"
) )
selectionStart -= 1 selectionStart -= 1
return [null, selectionStart, null] return [null, selectionStart, null]
@ -586,8 +586,8 @@ export const beginning_of_line = wrap_input(
export const end_of_line = wrap_input( export const end_of_line = wrap_input(
needs_text((text, selectionStart, selectionEnd) => { needs_text((text, selectionStart, selectionEnd) => {
while ( while (
text[selectionStart] != undefined && text[selectionStart] !== undefined &&
text[selectionStart] != "\n" text[selectionStart] !== "\n"
) )
selectionStart += 1 selectionStart += 1
return [null, selectionStart, null] return [null, selectionStart, null]
@ -627,7 +627,7 @@ export const forward_word = wrap_input(
**/ **/
export const backward_word = wrap_input( export const backward_word = wrap_input(
(text, selectionStart, selectionEnd) => { (text, selectionStart, selectionEnd) => {
if (selectionStart == 0) return [null, null, null] if (selectionStart === 0) return [null, null, null]
let boundaries = getWordBoundaries(text, selectionStart, true) let boundaries = getWordBoundaries(text, selectionStart, true)
if (selectionStart >= boundaries[0] && selectionStart < boundaries[1]) if (selectionStart >= boundaries[0] && selectionStart < boundaries[1])
boundaries = getWordBoundaries(text, boundaries[0] - 1, true) boundaries = getWordBoundaries(text, boundaries[0] - 1, true)

View file

@ -34,7 +34,7 @@ export function find(iter, predicate) {
/** Zip some arrays together /** Zip some arrays together
If you need variable length args, you need izip for now. If you need variable length args, you need izip for now.
*/ */
export function zip(...arrays) { export function zip(...arrays) {
// Make an array of length values // Make an array of length values
@ -87,7 +87,7 @@ export function zeros(n) {
return new Array(n).fill(0) return new Array(n).fill(0)
} }
/** islice(iter, stop) = Give the first `stop` elements /** islice(iter, stop) = Give the first `stop` elements
islice(iter, start, stop) islice(iter, start, stop)
skip `start` elements, then give `stop - start` elements, skip `start` elements, then give `stop - start` elements,
unless `stop` is null, then emit indefinitely unless `stop` is null, then emit indefinitely

View file

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

View file

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

View file

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

View file

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

View file

@ -17,7 +17,7 @@ export function my_mod(dividend, divisor) {
} }
/** Always gives a positive result. /** Always gives a positive result.
Equivalent to knuth_mod when divisor is +ve Equivalent to knuth_mod when divisor is +ve
Equivalent to % when dividend is +ve Equivalent to % when dividend is +ve
*/ */

View file

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

View file

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

View file

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

View file

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