diff options
| author | Teddy Wing | 2019-05-01 18:22:53 +0200 | 
|---|---|---|
| committer | Teddy Wing | 2019-05-01 18:22:53 +0200 | 
| commit | e65c92e98a2c98e57814ac4bec148cbbf169616d (patch) | |
| tree | 615af84fb12474d554045c3331b1e86f5cb50ae0 /src/multi_key_command.ts | |
| parent | 75221eab7a3188a92d221b2d0be7a9d082fca31a (diff) | |
| download | muttagen-e65c92e98a2c98e57814ac4bec148cbbf169616d.tar.bz2 | |
sidebar.ts: Extract multi-key shortcut command code
Make the multi-key command generic so that it works with other commands,
not just `\m`.
Use the array equality method from Abhi
(https://stackoverflow.com/users/2968762/abhi) on Stack Overflow:
https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript/19746771#19746771
Diffstat (limited to 'src/multi_key_command.ts')
| -rw-r--r-- | src/multi_key_command.ts | 29 | 
1 files changed, 29 insertions, 0 deletions
| diff --git a/src/multi_key_command.ts b/src/multi_key_command.ts new file mode 100644 index 0000000..7e303fe --- /dev/null +++ b/src/multi_key_command.ts @@ -0,0 +1,29 @@ +import key_codes, { KeyCode } from './key_codes'; + +export default function( +	el: HTMLDocument | HTMLElement, +	command: KeyCode[], +	action: () => void +): void { +	var key_buffer: number[] = []; + +	el.addEventListener('keydown', function(e: KeyboardEvent) { +		command.forEach((key_code) => { +			if (e.keyCode === key_code) { +				key_buffer.push(key_code); +			} +		}); +	}); + +	el.addEventListener('keyup', function(e: KeyboardEvent) { +		if (key_buffer.length >= 2) { +			var command_executed = key_buffer.length === command.length +				&& key_buffer.every((value, index) => value === command[index]); + +			if (command_executed) { +				action(); +				key_buffer = []; +			} +		} +	}); +}; | 
