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.

19.7 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Share screen › the sharing map (Multi-device, phase 3 of the 2026-11-28 plan): this computer's screens on
// the left, every device of the mesh on the right. Drag a screen onto a device (or select a screen, then
// the device) and that device's window opens with it: a real screen is mirrored, TwinDesk Virtual Display
// is TwinDesk's virtual display (one device at a time). Each device says what it gets; Stop sharing here, and
// Stop all in the bar below. Devices not connected are shown with Wake. Mac, Windows and Linux; each page
// maps its own state into the model below (docs/screen-mesh.md, the stream table).
//
//   const m = ShareMap.create({ assign(id, {mode: 'off'|'mirror'|'extend', displayId}), add?(size), remove?(slot),
//                               main?: {mode(v), mirror(id), size(v)} })
//   body.append(m.el)
//   m.render({ displays: [{id, name, w, h, primary}], virtual: {can, why} | null,
//              extras?: [{slot, name, w, h, displayId}], extrasWhy?: text for one not there yet, add?: {can, why},
//              targets: [{id, name, os, mode, displayId, status, place?, monitors?: [{id, x, y, w, h}]}], offline: [{id, name, os}], selected: id })
// extras: virtual displays added on this page (Mac, Multi-device): each is a screen like the others once
// it exists (displayId, '' while it doesn't), shared by mirroring it; add and remove need opts.add/remove.
// main: the main card, Mirror | Extend ({mode, mirror: display id, mirrors: [{value, label}], size, sizes,
// extend: {can, why}}): the half picked is what the card gives when dragged, and the picker under it is the
// screen Mirror shows or TwinDesk Extend's size. Extend is TwinDesk's own virtual display, always there to
// give (made while a device is on it). The other monitors and the added virtual displays follow as tiles.
// Only connected devices are shown.
// The selected device (the one in use: where the pointer is, Multi-device's selection) comes first, marked.
'use strict';

(function () {
  const OSNAME = { mac: 'macOS', win: 'Windows', windows: 'Windows', linux: 'Linux', android: 'Android', ios: 'iOS', ipados: 'iPadOS' };
  const VIRTUAL = '\u0000virtual';

  function create(opts) {
    const t = (k, v) => I18n.t(k, v);
    const el = UI.el('div', { class: 'sm' });
    const side = UI.el('div', { class: 'sm-side' });
    const grid = UI.el('div', { class: 'sm-grid' });
    const count = UI.el('span', { class: 'sm-count' });
    const main = UI.el('div', { class: 'sm-main' }, [UI.el('div', { class: 'sm-head' }, [UI.el('h3', { text: t('Devices') }), count]), grid]);
    const bar = UI.el('div', { class: 'sm-bar' });
    el.append(UI.el('div', { class: 'sm-body' }, [side, main]), bar);
    let m = null, key = '', picked = null, dragging = null;

    const screenName = (id) => {
      if (id === VIRTUAL) return t('TwinDesk Extend');
      const x = (m.extras || []).find((e) => e.displayId && e.displayId === id);
      if (x) return x.name;
      const d = (m.displays || []).find((x) => x.id === id);
      return d ? UI.monitorLabel(d.name) : t('Screen');
    };
    // What a target gets, as a screen key: a display id, VIRTUAL, or ''.
    const gets = (x) => (x.mode === 'mirror' ? String(x.displayId || '') : x.mode === 'extend' ? VIRTUAL : '');
    const give = (id, screen, place = '') => {
      if (screen === VIRTUAL) opts.assign(id, { mode: 'extend', place });
      else opts.assign(id, { mode: 'mirror', displayId: screen, place });
      picked = null;
    };

    // o: {off, why, virtual}: a tile that can't be shared now (and why), drawn as a virtual display.
    function tile(screenArg, label, sub, to, o = {}) {
      const screen = typeof screenArg === 'function' ? screenArg() : screenArg;
      const off = o.off !== undefined ? o.off : screen === VIRTUAL && !(m.virtual && m.virtual.can);
      const why = o.why !== undefined ? o.why : (m.virtual && m.virtual.why) || '';
      const b = UI.el('button', { class: 'sm-tile' + (screen === VIRTUAL || o.virtual ? ' virtual' : '') + (to.length ? ' on' : '') + (picked === screen ? ' picked' : ''), attrs: { draggable: off ? 'false' : 'true', 'data-literal': '', 'aria-pressed': String(picked === screen) }, disabled: off }, [
        UI.el('span', { class: 'sm-screen' }, [UI.el('b', { text: label })]),
        UI.el('small', { text: off ? why : to.length ? t('Shared to {devices}', { devices: to.join(', ') }) : sub }),
      ]);
      b.addEventListener('dragstart', (e) => { dragging = typeof screenArg === 'function' ? screenArg() : screen; e.dataTransfer.setData('text/plain', 'td-screen'); e.dataTransfer.effectAllowed = 'copy'; el.classList.add('dragging'); });
      b.addEventListener('dragend', () => { dragging = null; el.classList.remove('dragging'); grid.querySelectorAll('.over').forEach((x) => x.classList.remove('over')); });
      b.onclick = () => { const k = typeof screenArg === 'function' ? screenArg() : screen; picked = picked === k ? null : k; draw(); };
      return b;
    }

    // What a device gets from this computer: stream 0 (gets(x)) and the extra ones (x.more, shared/screen-ch.js).
    const streamsOf = (x) => [...(gets(x) ? [{ ch: 0, screen: gets(x), place: x.place || '' }] : []),
      ...(x.more || []).map((e) => ({ ch: e.ch, screen: String(e.monitor), place: e.place || '' }))];

    // A device: its monitors drawn as they're arranged (the layout's monitor map), each one a drop target.
    // A screen dropped on a monitor fills it there (screen.state place); more than one on a monitor share it.
    // A second screen of this computer to the same device is a stream of its own when that device takes
    // them (x.multi); otherwise it replaces the first. A device whose monitors aren't known is one box.
    function card(x) {
      const list = streamsOf(x);
      const phone = /^(android|ios|ipados)$/.test(x.os || '');
      const mons = Array.isArray(x.monitors) && x.monitors.length ? x.monitors : [phone ? { id: '', x: 0, y: 0, w: 9, h: 19 } : { id: '', x: 0, y: 0, w: 16, h: 10 }];
      const where = (st) => (mons.some((d) => d.id === st.place) ? st.place : mons[0].id); // the monitor it shows on
      const box = UI.el('div', { class: 'sm-mons' });
      const minX = Math.min(...mons.map((d) => d.x)), minY = Math.min(...mons.map((d) => d.y));
      const W = Math.max(...mons.map((d) => d.x + d.w)) - minX, H = Math.max(...mons.map((d) => d.y + d.h)) - minY;
      box.style.aspectRatio = `${Math.max(W, 1)} / ${Math.max(H, 1)}`;
      box.style.width = `min(100%, ${Math.round((mons.length > 1 ? 170 : 130) * W / H)}px)`; // as wide as fits, at most 170 px tall (one monitor 130)
      // Where a screen dropped on monitor d goes: its own stream moves there; a new one is added or replaces.
      const put = (screen, d) => {
        if (!screen) return;
        const has = list.find((st) => st.screen === screen);
        if (has && where(has) === d.id) return;
        if (has && has.ch) return opts.assign(x.id, { ch: has.ch, mode: 'mirror', displayId: screen, place: d.id });
        if (has || !list.length || !x.multi || screen === VIRTUAL) return give(x.id, screen, d.id);
        opts.assign(x.id, { add: true, mode: 'mirror', displayId: screen, place: d.id });
        picked = null;
      };
      const boxes = [];
      const fill = () => {
        const s = dragging || picked;
        for (const [d, b] of boxes) {
          b.textContent = '';
          const here = list.filter((st) => where(st) === d.id);
          b.classList.toggle('has', !!here.length);
          const n = mons.length > 1 ? String(mons.indexOf(d) + 1) : '';
          const moving = s && !here.some((st) => st.screen === s);
          if (moving) b.append(UI.el('b', { text: list.length && !x.multi && !list.some((st) => st.screen === s) ? t('Replaces {screen}', { screen: screenName(list[0].screen) }) : here.length ? t('Add here') : t('Drop here') }));
          else if (here.length) {
            for (const st of here.slice(0, 3)) b.append(UI.el('b', { text: screenName(st.screen) }));
            if (here.length > 3) b.append(UI.el('span', { text: t('{count} more', { count: here.length - 3 }) }));
            else if (here.length === 1) b.append(UI.el('span', { text: x.status === 'starting' ? t('Starting…') : n ? t('Fills monitor {number}', { number: n }) : t('Window open on {name}', { name: x.name }) }));
            else b.append(UI.el('span', { text: t('Side by side') }));
          } else if (n) b.append(UI.el('small', { class: 'sm-mon-n', text: n }));
        }
      };
      for (const d of mons) {
        const b = UI.el('div', { class: 'sm-mon', attrs: { role: 'button', tabindex: '0', 'data-literal': '', title: d.name || '' } });
        b.style.cssText = `left:${(d.x - minX) / W * 100}%;top:${(d.y - minY) / H * 100}%;width:${d.w / W * 100}%;height:${d.h / H * 100}%`;
        if (d.w / W < 0.3 || d.h / H < 0.45) b.classList.add('small');
        b.addEventListener('dragover', (e) => { if (!dragging) return; e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; b.classList.add('over'); });
        b.addEventListener('dragleave', () => b.classList.remove('over'));
        b.addEventListener('drop', (e) => { e.preventDefault(); b.classList.remove('over'); put(dragging, d); dragging = null; });
        b.onclick = () => put(picked, d);
        b.onkeydown = (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); put(picked, d); } };
        boxes.push([d, b]);
        box.append(b);
      }
      fill();
      const stopAll = () => { for (const st of list.filter((y) => y.ch)) opts.assign(x.id, { ch: st.ch, mode: 'off' }); opts.assign(x.id, { mode: 'off' }); };
      const current = x.id === m.selected;
      const c = UI.el('div', { class: 'sm-card' + (mons.length > 2 ? ' many' : '') + (list.length ? ' sharing' : '') + (picked ? ' target' : '') + (current ? ' current' : ''), attrs: { 'data-literal': '' } }, [
        UI.el('div', { class: 'sm-card-head' }, [
          UI.el('b', { text: x.name }),
          ...(current ? [UI.el('span', { class: 'sm-badge', text: t('In use') })] : []),
          UI.el('span', { class: 'sm-os on', text: mons.length > 1 ? t('{count} monitors', { count: mons.length }) : OSNAME[x.os] || t('Connected') }),
        ]),
        box,
        ...(x.error ? [UI.el('div', { class: 'sm-err', text: t(x.error) })] : []),
        // More than one screen here: each can stop on its own.
        ...(list.length > 1 ? [UI.el('div', { class: 'sm-streams' }, list.map((st) => {
          const chip = UI.el('span', { class: 'sm-chip', attrs: { 'data-literal': '' } }, [screenName(st.screen) + ' ']);
          const x2 = UI.el('button', { class: 'sm-chip-x', text: '×', attrs: { 'aria-label': t('Stop sharing {screen} here', { screen: screenName(st.screen) }) } });
          x2.onclick = () => (st.ch ? opts.assign(x.id, { ch: st.ch, mode: 'off' }) : stopAll());
          chip.append(x2);
          return chip;
        }))] : []),
        ...(list.length ? [UI.button(list.length > 1 ? t('Stop all here') : t('Stop sharing here'), stopAll, 'small danger')] : []),
      ]);
      c.refill = fill;
      return c;
    }

    // Add virtual display: one more screen at 1920 × 1080; its size is changed under Virtual displays.
    function addRow() {
      const add = UI.button(t('Add virtual display'), () => opts.add({ width: 1920, height: 1080 }), 'small');
      add.disabled = !m.add.can;
      add.setAttribute('data-literal', '');
      return m.add.can ? add : UI.el('div', {}, [add, UI.el('small', { class: 'sm-tip', text: m.add.why || '' })]);
    }

    // The main card's model: given by the page, or Mirror of the main screen with Extend when it can.
    let localMode = 'mirror';
    function mainOf() {
      const primary = (m.displays || []).find((d) => d.primary) || (m.displays || [])[0];
      const x = m.main || {};
      const extend = x.extend || (m.virtual ? m.virtual : { can: false, why: '' });
      const mirrors = x.mirrors || (m.displays || []).map((d) => ({ value: d.id, label: UI.monitorLabel(d.name) + (d.primary ? t(' (main)') : '') }));
      const mirror = x.mirror && mirrors.some((o) => String(o.value) === String(x.mirror)) ? String(x.mirror) : primary ? String(primary.id) : '';
      const mode = (x.mode || localMode) === 'extend' && extend.can !== false ? 'extend' : 'mirror';
      return { mode, mirror, mirrors, extend, size: x.size, sizes: x.sizes || [] };
    }
    // Mirror | Extend in one wide card: a half is picked with a click, the card drags what's picked.
    function mainCard(mn, sharedTo) {
      const screenOf = () => (mn.mode === 'extend' ? VIRTUAL : mn.mirror);
      const setMode = (v) => { if (v === mn.mode) return; localMode = v; if (opts.main && opts.main.mode) opts.main.mode(v); if (!(m.main && m.main.mode)) draw(); };
      const half = (v, title, sub, off, shared) => {
        const h = UI.el('span', { class: 'sm-half' + (mn.mode === v ? ' sel' : '') + (off ? ' off' : ''), attrs: { role: 'radio', tabindex: '0', 'aria-checked': String(mn.mode === v), title: off || '' } }, [
          UI.el('small', { class: 'sm-half-k', text: v === 'extend' ? t('Extend') : t('Mirror') }),
          UI.el('b', { text: title }),
          UI.el('small', { class: shared ? 'on' : '', text: sub }),
        ]);
        // A click shares this half with the device in use (Multi-device's selection; the only one if there's one),
        // or stops it there when it's already on; it stays picked, so a click on another device's monitor adds it there.
        const go = (e) => {
          e.stopPropagation();
          if (off) return;
          setMode(v);
          const screen = v === 'extend' ? VIRTUAL : mn.mirror;
          const targets = m.targets || [];
          const sel = targets.find((x) => x.id === m.selected) || (targets.length === 1 ? targets[0] : null);
          if (!sel) { picked = picked === screen ? null : screen; draw(); return; }
          const has = streamsOf(sel).find((st) => st.screen === screen);
          if (has) { opts.assign(sel.id, has.ch ? { ch: has.ch, mode: 'off' } : { mode: 'off' }); picked = null; }
          else { give(sel.id, screen); picked = screen; }
          draw();
        };
        h.onclick = go;
        h.onkeydown = (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(e); } };
        return h;
      };
      const mName = (mn.mirrors.find((o) => String(o.value) === mn.mirror) || {}).label || t('Screen');
      const toM = sharedTo(mn.mirror), toE = sharedTo(VIRTUAL);
      const card = tile(screenOf, '', '', [], { main: true });
      card.textContent = '';
      card.classList.add('sm-maincard');
      if (toM.length || toE.length) card.classList.add('on');
      card.append(UI.el('span', { class: 'sm-halves' }, [
        half('mirror', mName, toM.length ? t('Shared to {devices}', { devices: toM.join(', ') }) : t('This screen as it is'), '', toM.length > 0),
        half('extend', t('TwinDesk Extend'), toE.length ? t('Shared to {devices}', { devices: toE.join(', ') }) : t('A new screen beside these'), mn.extend.can === false ? (mn.extend.why || t('Not available')) : '', toE.length > 0),
      ]));
      // Under it: which screen Mirror shows, or Extend's size.
      let pick = null;
      if (mn.mode === 'mirror' && mn.mirrors.length > 1) {
        pick = UI.select(mn.mirrors, (v) => opts.main && opts.main.mirror && opts.main.mirror(v));
        pick.set(mn.mirror);
      } else if (mn.mode === 'extend' && mn.sizes.length) {
        pick = UI.select(mn.sizes, (v) => opts.main && opts.main.size && opts.main.size(v));
        pick.set(mn.size);
      }
      const row = pick ? UI.el('label', { class: 'sm-mainpick' }, [UI.el('span', { text: mn.mode === 'extend' ? t('Size') : t('Mirror') }), pick.el || pick]) : null;
      return UI.el('div', { class: 'sm-mainwrap' }, [card, ...(row ? [row] : [])]);
    }

    function draw() {
      const targets = (m.targets || []).slice().sort((a, b) => (b.id === m.selected) - (a.id === m.selected));
      const sharedTo = (screen) => targets.filter((x) => streamsOf(x).some((st) => st.screen === screen)).map((x) => x.name);
      side.textContent = '';
      side.append(UI.el('div', { class: 'sm-side-title', text: t('Screens on this computer') }), UI.el('div', { class: 'sm-tip', text: t('Click Mirror or Extend to share it with the device in use, then click another device’s monitor to add it there. You can also drag a screen onto a monitor.') }));
      const tiles = UI.el('div', { class: 'sm-tiles' });
      const main = mainOf();
      const primary = (m.displays || []).find((d) => d.primary) || (m.displays || [])[0];
      tiles.append(mainCard(main, sharedTo));
      for (const d of m.displays || []) if (d !== primary) tiles.append(tile(d.id, UI.monitorLabel(d.name), `${d.w} × ${d.h}`, sharedTo(d.id)));
      for (const x of m.extras || []) {
        const tl = tile(x.displayId || `\u0000extra${x.slot}`, x.name, `${x.w} × ${x.h}`, x.displayId ? sharedTo(x.displayId) : [],
          { virtual: true, off: !x.displayId, why: m.extrasWhy || t('Appears while this Mac’s screen is shared') });
        if (!opts.remove) { tiles.append(tl); continue; }
        const rm = UI.el('button', { class: 'sm-tile-x', text: '×', attrs: { 'aria-label': t('Remove {name}', { name: x.name }), title: t('Remove') } });
        rm.onclick = (e) => { e.stopPropagation(); opts.remove(x.slot); };
        tiles.append(UI.el('div', { class: 'sm-tile-wrap' }, [tl, rm]));
      }
      side.append(tiles);
      if (opts.add && m.add) side.append(addRow());

      grid.textContent = '';
      const phones = targets.filter((x) => /^(android|ios|ipados)$/.test(x.os || '')).length;
      count.textContent = targets.length ? t('{connected} connected', { connected: targets.length }) + (phones ? ', ' + t(phones === 1 ? '1 phone' : '{count} phones', { count: phones }) : '') : '';
      for (const x of targets) grid.append(card(x));
      if (!targets.length) grid.append(UI.el('div', { class: 'sm-empty', text: t('No devices connected') }));

      bar.textContent = '';
      const live = targets.filter((x) => streamsOf(x).length);
      bar.append(UI.el('b', { text: t('Sharing now') }));
      if (!live.length) bar.append(UI.el('span', { class: 'sm-none', text: t('Nothing') }));
      for (const x of live) for (const st of streamsOf(x)) bar.append(UI.el('span', { class: 'sm-chip', attrs: { 'data-literal': '' }, text: `${screenName(st.screen)} → ${x.name}` }));
      bar.append(UI.el('span', { class: 'sm-grow' }));
      if (live.length) bar.append(UI.button(t('Stop all'), () => { for (const x of live) { for (const st of streamsOf(x)) if (st.ch) opts.assign(x.id, { ch: st.ch, mode: 'off' }); opts.assign(x.id, { mode: 'off' }); } }, 'small danger'));
    }

    // While dragging, every card says where the screen would go.
    el.addEventListener('dragstart', () => setTimeout(() => grid.querySelectorAll('.sm-card').forEach((c) => c.refill && c.refill()), 0));
    el.addEventListener('dragend', () => grid.querySelectorAll('.sm-card').forEach((c) => c.refill && c.refill()));
    document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && picked) { picked = null; draw(); } });

    return {
      el,
      render(model) {
        const k = JSON.stringify(model || null);
        if (k === key || dragging) return;
        key = k;
        m = model || {};
        el.hidden = !model;
        if (model) draw();
      },
    };
  }

  // A device's monitors from the shared layout's monitor map (state.layout.map.monitors: {dev, id, x, y, w, h}),
  // ids being that device's own display ids (what screen.state place names).
  function monitorsOf(s, dev) {
    const all = s && s.layout && s.layout.map && Array.isArray(s.layout.map.monitors) ? s.layout.map.monitors : [];
    return all.filter((d) => d.dev === dev && d.w > 0 && d.h > 0).slice(0, 8).map((d) => ({ id: String(d.id), x: d.x, y: d.y, w: d.w, h: d.h }));
  }

  window.ShareMap = { create, monitorsOf };
})();