Skip to content

Commit

Permalink
add a command named dispatchEvent
Browse files Browse the repository at this point in the history
  • Loading branch information
gdh1995 committed Aug 18, 2021
1 parent 4916f3b commit 65e9cae
Show file tree
Hide file tree
Showing 11 changed files with 53 additions and 19 deletions.
14 changes: 7 additions & 7 deletions background/help_dialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,22 +284,23 @@ const commandGroups_: {
]: readonly NoaliasInCNames<kCName>[]
} & SafeObject = {
__proto__: null as never,
pageNavigation: ["scrollDown", "scrollUp", "scrollLeft", "scrollRight", "scrollToTop"
pageNavigation: [
"LinkHints.activate", "LinkHints.activateOpenInNewTab"
, "LinkHints.activateOpenInNewForegroundTab", "LinkHints.activateWithQueue"
, "scrollDown", "scrollUp", "scrollLeft", "scrollRight", "scrollToTop"
, "scrollToBottom", "scrollToLeft", "scrollToRight", "scrollPageDown", "scrollPageUp"
, "scrollPxDown", "scrollPxUp", "scrollPxLeft", "scrollPxRight"
, "scrollFullPageDown", "scrollFullPageUp", "scrollSelect"
, "reload", "reloadTab", "reloadGivenTab"
, "zoom", "zoomIn", "zoomOut", "zoomReset", "toggleViewSource"
, "copyCurrentUrl", "copyCurrentTitle", "switchFocus", "simulateBackspace"
, "copyCurrentUrl", "copyCurrentTitle", "switchFocus", "focusInput"
, "LinkHints.activateCopyLinkUrl", "LinkHints.activateCopyLinkText"
, "openCopiedUrlInCurrentTab", "openCopiedUrlInNewTab", "goUp", "goToRoot"
, "focusInput", "LinkHints.activate", "LinkHints.activateOpenInNewTab"
, "LinkHints.activateOpenInNewForegroundTab", "LinkHints.activateWithQueue"
, "LinkHints.activateDownloadImage", "LinkHints.activateOpenImage"
, "LinkHints.activateDownloadLink", "LinkHints.activateOpenIncognito"
, "LinkHints.activateHover", "LinkHints.activateLeave", "LinkHints.unhoverLast"
, "LinkHints.activateSearchLinkText", "LinkHints.activateEdit"
, "LinkHints.activateSelect", "LinkHints.click"
, "LinkHints.activateSelect", "LinkHints.click", "simulateBackspace", "dispatchEvent"
, "goPrevious", "goNext", "nextFrame", "mainFrame", "parentFrame"
, "enterInsertMode", "enterVisualMode", "enterVisualLineMode"
, "Marks.activateCreate", "Marks.activate"
Expand Down Expand Up @@ -328,11 +329,10 @@ const commandGroups_: {
}

const advancedCommands_: { readonly [k in NoaliasInCNames<kCName>]?: 1 | 0; } & SafeObject = { __proto__: null as never,
toggleViewSource: 1, clearFindHistory: 1
toggleViewSource: 1, clearFindHistory: 1, dispatchEvent: 1
, scrollToLeft: 1, scrollToRight: 1, moveTabToNextWindow: 1
, moveTabToNewWindow: 1, moveTabToIncognito: 1, reloadGivenTab: 1
, focusOrLaunch: 1
, goUp: 1, goToRoot: 1, focusInput: 1, "LinkHints.activateWithQueue": 1
, enableContentSettingTemp: 1, toggleContentSetting: 1, toggleStyle: 1, clearContentSettings: 1
, "LinkHints.activateDownloadImage": 1, reopenTab: 1
, "LinkHints.activateOpenImage": 1, removeRightTab: 1
Expand Down
1 change: 1 addition & 0 deletions background/key_mappings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,7 @@ export const availableCommands_: Dict<CommandsNS.Description> & SafeObject =
id_mask: "$id", url_mask: ""
}],
discardTab: [ kBgCmd.discardTab, 1, /* 20 in all_commands.ts */ 0 ],
dispatchEvent: [kFgCmd.dispatchEventCmd, 0, /** only 1 / -1, in fact */ 0],
duplicateTab: [ kBgCmd.duplicateTab, 1, 20 as 0 ],
editText: [ kFgCmd.editText, 0, 0 ],
enableCSTemp: [ kBgCmd.toggleCS, 1, 0, { incognito: true } ],
Expand Down
3 changes: 2 additions & 1 deletion background/typed_commands.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ interface BgCmdOptions {
keepWindow: "at-least-one" | "always"
} & Req.FallbackOptions
[kBgCmd.removeTabsR]: {
filter: "url" | "hash" | "host" | "url+title" | "hash+title" | "host+title"
filter: "url" | "hash" | "url=..." | "host" | "host=..." | "title" | "title*" | "group" | "url+hash" | "host&title"
other: boolean; mayConfirm: true; noPinned: boolean
} & Req.FallbackOptions
[kBgCmd.reopenTab]: Pick<OpenUrlOptions, "group"> & Req.FallbackOptions
Expand Down Expand Up @@ -355,6 +355,7 @@ interface CmdNameIds {
createTab: kBgCmd.createTab
debugBackground: kBgCmd.openUrl
discardTab: kBgCmd.discardTab
dispatchEvent: kFgCmd.dispatchEventCmd
duplicateTab: kBgCmd.duplicateTab
editText: kFgCmd.editText
enableCSTemp: kBgCmd.toggleCS
Expand Down
28 changes: 26 additions & 2 deletions content/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
import {
isHTML_, htmlTag_, createElement_, querySelectorAll_unsafe_, SafeEl_not_ff_, docEl_unsafe_, MDW, CLK,
querySelector_unsafe_, DAC, removeEl_s, appendNode_s, setClassName_s, INP, contains_s, toggleClass_s, modifySel,
focus_, testMatch, docHasFocus_
focus_, testMatch, docHasFocus_, deepActiveEl_unsafe_
} from "../lib/dom_utils"
import {
pushHandler_, removeHandler_, getMappedKey, prevent_, isEscape_, keybody_, DEL, BSP, ENTER, handler_stack,
Expand All @@ -23,7 +23,7 @@ import {
hideHelp, set_hideHelp, set_helpBox, checkHidden,
} from "./dom_ui"
import { hudHide, hudShow, hudTip, hud_text } from "./hud"
import { onKeyup2, set_onKeyup2, passKeys, set_nextKeys, set_passKeys, keyFSM } from "./key_handler"
import { onKeyup2, set_onKeyup2, passKeys, set_nextKeys, set_passKeys, keyFSM, onEscDown } from "./key_handler"
import { InputHintItem, activate as linkActivate, clear as linkClear, kSafeAllSelector } from "./link_hints"
import { activate as markActivate } from "./marks"
import { FindAction, activate as findActivate, deactivate as findDeactivate, execCommand } from "./mode_find"
Expand Down Expand Up @@ -388,6 +388,30 @@ set_contentCommands_([
}
(el || id) && runFallbackKey(options, 0)
},
/* kFgCmd.dispatchEventCmd: */ (options: CmdOptions[kFgCmd.dispatchEventCmd], count: number): void => {
const type = options.type, rawClass = options.class
const evClass = (rawClass && (rawClass[0].toUpperCase() + rawClass.slice(1)) || "Keyboard") + "Event"
let event: Event | "" | undefined, delay = options.delay
if (options.esc) {
keydownEvents_[kKeyCode.None] = 0
onEscDown(0, kKeyCode.None, count > 1)
keydownEvents_[kKeyCode.None] = 0
runFallbackKey(options, 0, "", delay)
} else {
try {
event = type && new (window as any)[evClass](count < 0 ? type.replace("down", "up") : type, options)
} catch {}
if (event) {
const activeEl = deref_(currentScrolling)
|| (OnFirefox ? deepActiveEl_unsafe_() : SafeEl_not_ff_!(deepActiveEl_unsafe_()))
// earlier, in case listeners are too slow
runFallbackKey(options, activeEl && activeEl !== doc.body ? 0 : 2, "", delay)
activeEl && activeEl.dispatchEvent(event)
} else {
hudTip(kTip.raw, 0, `Can not create ${evClass}#${type}`)
}
}
},
/* kFgCmd.showHelpDialog: */ ((options: Exclude<CmdOptions[kFgCmd.showHelpDialog], {h?: null}>): any => {
// Note: not suppress key on the top, because help dialog may need a while to render,
// and then a keyup may occur before or after it
Expand Down
4 changes: 2 additions & 2 deletions content/insert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,10 @@ export const setupSuppress = (onExit?: (this: void) => void): void => {
}

/** should only be called during keydown events */
export const focusUpper = (key: kKeyCode, force: boolean, event: ToPrevent): void | 1 => {
export const focusUpper = (key: kKeyCode, force: boolean, event: ToPrevent | 0): void | 1 => {
const parEl = frameElement_() && !fullscreenEl_unsafe_();
if (!parEl && (!force || isTop)) { return; }
prevent_(event); // safer
event && prevent_(event); // safer
if (parEl) {
keydownEvents_[key] = 1;
const parApi = getParentVApi()
Expand Down
5 changes: 2 additions & 3 deletions content/key_handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ export const onKeydown = (event: KeyboardEventToPrevent): void => {
tempStr = getMappedKey(eventWrapper, currentKeys ? kModeId.Next : kModeId.Normal)
action = checkKey(eventWrapper, tempStr, tempStr);
if (action > HandlerResult.MaxNotEsc) {
action = action > HandlerResult.PlainEsc ? /*#__NOINLINE__*/ onEscDown(event, key)
action = action > HandlerResult.PlainEsc ? /*#__NOINLINE__*/ onEscDown(event, key, event.repeat)
: HandlerResult.Nothing;
}
if (action === HandlerResult.Nothing
Expand Down Expand Up @@ -250,10 +250,9 @@ export const onKeydown = (event: KeyboardEventToPrevent): void => {
}

/** @param key should be valid */
const onEscDown = (event: KeyboardEventToPrevent, key: kKeyCode
export const onEscDown = (event: KeyboardEventToPrevent | 0, key: kKeyCode, repeat: boolean
): HandlerResult.Default | HandlerResult.PassKey | HandlerResult.Prevent => {
let action: HandlerResult.Default | HandlerResult.PassKey | HandlerResult.Prevent = HandlerResult.Prevent
let repeat = event.repeat
let activeEl = repeat || !isTop ? deepActiveEl_unsafe_() : null
/** if `notBody` then `activeEl` is not null */
if (!repeat && removeSelection()) {
Expand Down
6 changes: 3 additions & 3 deletions content/port.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,22 +96,22 @@ export const runtimeConnect = (function (this: void): void {
})

export const runFallbackKey = ((options: Req.FallbackOptions
, anotherTip: kTip | 0 | false | 2, tipArgs?: string | Array<string | number>): void => {
, anotherTip: kTip | 0 | false | 2, tipArgs?: string | Array<string | number>, wait?: number): void => {
const fallback = !anotherTip ? options.$then : options.$else, context = options.$f
if (fallback && isTY(fallback)) {
if (!(Build.NDEBUG || Build.Minify)) {
console.log("Vimium C: run another command %o for type & tip = %o", fallback, anotherTip)
}
suppressTail_(GlobalConsts.TimeOfSuppressingUnexpectedKeydownEvents)
post_({
H: kFgReq.nextKey, k: fallback, f: { c: context, r: options.$retry, u: anotherTip }
H: kFgReq.nextKey, k: fallback, f: { c: context, r: options.$retry, u: anotherTip, w: wait }
})
} else {
const tip = anotherTip && anotherTip !== 2 ? anotherTip : context ? context.t : 0
tip && hudTip(tip, 0, tipArgs)
}
}) as {
/** if `anotherTip` is `0` / `false`, then use `.$then`; otherwise use `.$else` */
(options: Req.FallbackOptions, anotherTip: 0 | 2 | false, tipArgs?: TimerType.fake): void
(options: Req.FallbackOptions, anotherTip: 0 | 2 | false, tipArgs?: "" | TimerType.fake, wait?: number): void
(options: Req.FallbackOptions, anotherTip: kTip, tipArgs?: string | Array<string | number>): void
}
1 change: 1 addition & 0 deletions i18n/en/help_dialog.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
"createTab": "Create new tabs",
"debugBackground": "Debug the background page",
"discardTab": "Discard some other tabs",
"dispatchEvent": "Simulate dipatching arbitrary DOM event",
"duplicateTab": "Duplicate current tab for N times",
"editText": "Send editing action to browser",
"enableContentSettingTemp": "Enable the site's ContentSetting in incognito window",
Expand Down
1 change: 1 addition & 0 deletions i18n/fr/help_dialog.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
"createTab": "Créer de nouveaux onglets",
"debugBackground": "Débugger le fond de la page",
"discardTab": "Défausser d'autres onglets",
"dispatchEvent": "Simuler l'envoi d'un événement DOM arbitraire",
"duplicateTab": "Dupliquer l'onglet courant N fois",
"editText": "Envoyer l'action d'édition au navigateur",
"enableContentSettingTemp": "Activer les feuilles de style du site en fenêtre incognito",
Expand Down
1 change: 1 addition & 0 deletions i18n/zh/help_dialog.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
"createTab": "打开新的标签页",
"debugBackground": "打开 Vimium C 扩展程序的管理页",
"discardTab": "暂时丢弃某个网页以节约资源",
"dispatchEvent": "模拟触发任意 DOM 事件",
"duplicateTab": "复制当前标签页",
"editText": "向浏览器发送文字编辑指令",
"enableContentSettingTemp": "在无痕窗口中赋予网站对一项功能的使用权限",
Expand Down
8 changes: 7 additions & 1 deletion typings/messages.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ declare const enum kBgCmd {

declare const enum kFgCmd {
framesGoBack, findMode, linkHints, marks, scroll, visualMode, vomnibar, insertMode, toggle,
passNextKey, goNext, autoOpen, focusInput, editText, scrollSelect, toggleStyle, showHelpDialog,
passNextKey, goNext, autoOpen, focusInput, editText, scrollSelect, toggleStyle, dispatchEventCmd, showHelpDialog,
END, ENDS = "END",
}

Expand Down Expand Up @@ -439,6 +439,12 @@ interface CmdOptions {
id?: undefined
css?: undefined
}) & { disabled?: boolean } & Req.FallbackOptions
[kFgCmd.dispatchEventCmd]: {
class?: string
type: string // if count < 0, then replace "down" with "up"
delay?: number
esc?: true // if true, then call onEscDown({ repeat: count > 1 })
} & Req.FallbackOptions
}

declare const enum kMarkAction {
Expand Down

0 comments on commit 65e9cae

Please sign in to comment.