Skip to content

All your computers and your phone/iPhone, working as one desk. Screens, apps, files, clipboard, calls, texts, notifications, mouse and keyboard, shared between Mac, Windows, Linux , Android, Web and ios / ipados . Free and open source. No account, no cloud, and no shared network needed.

2.4 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Keyboard › Modifier keys: how the keys this computer *receives* land, key by key (left and right
// Ctrl, Command/Windows, Option/Alt and Shift), e.g. a Mac's left Option as this PC's left Ctrl
// while its right Option stays Alt. Applied here just before injection; nothing changes on the wire.
// settings.keys.modMap = {on, keys: {from: to}}; off (the default) or a key not in it: exactly as
// before, Swap Ctrl and Command included. A mapped key isn't swapped as well.
// The mapping a key went down with is the one it comes up with, so changing the table while a key
// is held never leaves one stuck down (Mapper).
'use strict';

const MODS = ['ControlLeft', 'ControlRight', 'MetaLeft', 'MetaRight', 'AltLeft', 'AltRight', 'ShiftLeft', 'ShiftRight'];
const isMod = (c) => MODS.includes(c);

// A modMap from the page or a settings file, checked. Keys mapped to themselves are left out.
function clean(v) {
  const o = v && typeof v === 'object' ? v : {};
  const keys = {};
  const src = o.keys && typeof o.keys === 'object' ? o.keys : {};
  for (const from of MODS) {
    const to = src[from];
    if (isMod(to) && to !== from) keys[from] = to;
  }
  return { on: o.on === true, keys };
}

// What a received key becomes, without the memory of what was pressed (for tests and the page).
// swap(code): Swap Ctrl and Command's mapping when it applies, else the code itself.
function target(map, code, swap = (c) => c) {
  if (map && map.on && map.keys && Object.prototype.hasOwnProperty.call(map.keys, code)) return map.keys[code];
  return swap(code);
}

class Mapper {
  constructor(getMap) {
    this.getMap = getMap; // () => settings.keys.modMap
    this.down = new Map(); // received code -> the code it went down as
  }

  // down: a key down (true) or up (false). Returns the code to inject.
  map(down, code, swap) {
    if (down) {
      if (this.down.has(code)) return this.down.get(code); // a repeat while held: as it first went down
      const out = target(this.getMap(), code, swap);
      this.down.set(code, out);
      return out;
    }
    const was = this.down.get(code);
    this.down.delete(code);
    return was !== undefined ? was : target(this.getMap(), code, swap);
  }

  // The session ended or this computer stopped being driven: nothing is held any more.
  reset() {
    this.down.clear();
  }
}

module.exports = { MODS, clean, target, Mapper };