Published
Edited
Mar 1, 2019
Importers
1 star
Insert cell
Insert cell
shortcuts = {
const reMap = { control: "ctrl", alt: "option", meta: "cmd" };
const clearSet = new Set(["control", "meta", "option"]);

const eventToKey = e => e.key.toLowerCase();
const keyName = k => {
return reMap[k] || k;
};

const parseCombos = combosHandlers => {
const out = new assoc.EquivMap();
const parseCombo = c => new Set(c.split("+"));
for (let combo in combosHandlers) {
out.set(parseCombo(combo), combosHandlers[combo]);
}
return out;
};

const handleShortcut = (combosHandlers, keyRenameMap = reMap) => {
const comboDispatch = parseCombos(combosHandlers);
const currentCombo = new Set();
const onkeydown = e => {
const k = eventToKey(e);
currentCombo.add(keyName(k));
const handler = comboDispatch.get(currentCombo);
if (handler) {
if (!handler(e)) {
e.preventDefault();
e.stopPropagation();
}
}
};
const onkeyup = e => {
const k = eventToKey(e);
currentCombo.delete(keyName(k));
// key ups don't register when modifier keys are pressed simulaneously
// since these _become_ different keys such as π (opt+p) so we clear all
clearSet.has(k) && currentCombo.clear();
};
return { onkeydown, onkeyup };
};

return handleShortcut;
}
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more