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.

11.4 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Who gets a feature from this computer and whose it takes, in Multi-device (Clipboard, Notifications,
// File Sharing): the lists of the Share-folder picker as cards, from the whole mesh's state.matrix
// (shared/mesh-edges.js) and changed with setConsent (shared/consent.js), plus the page's gear and a
// device-grouped Recent.
//
//   const L = UI.shareLists({ feature, flat(s) → {out, in}, setFlat(dir, on), send, receive, sendAll, receiveAll })
//     L.cards   [All devices, Send to, Receive from]; hidden one-to-one (the page's own direction cards show)
//     L.render(s)
//   All devices (on by default, as Multi-device always was): one pool, every device follows the two
//   switches, devices added later too. Off: each device ticked on its own.
//
//   UI.pageGear(body, onClick) → {set(on)}       a gear at the top of the page, beside its switch
//   UI.byDevice(items, deviceOf(item) → name) → [{name, items}]   Recent grouped by device, newest group first
'use strict';

(function () {
  const t = (k, v) => I18n.t(k, v);
  const OSNAME = { mac: 'Mac', win: 'Windows', linux: 'Linux', android: 'Android', ios: 'iPhone', ipados: 'iPad' };

  function checkbox(checked, onChange, label, disabled) {
    const c = UI.el('input', { type: 'checkbox', attrs: { 'aria-label': label } });
    c.checked = !!checked;
    c.disabled = !!disabled;
    c.onchange = () => onChange(c.checked);
    return c;
  }

  UI.shareLists = (o) => {
    const KEY = 'td.alldevices.' + o.feature;
    let all = true;
    try { all = localStorage.getItem(KEY) !== '0'; } catch (_) { /* default on */ }
    let last = null;
    let lastKey = '';

    const allBox = UI.el('div', { class: 'sl-list' });
    const sendBox = UI.el('div', { class: 'sl-list' });
    const recvBox = UI.el('div', { class: 'sl-list' });
    const allCard = UI.card(t('All devices'), [allBox], { cls: 'keep-on' });
    const sendCard = UI.card(o.send || t('Send to'), [sendBox], { cls: 'keep-on' });
    const recvCard = UI.card(o.receive || t('Receive from'), [recvBox], { cls: 'keep-on' });
    const cards = [allCard, sendCard, recvCard];
    for (const c of cards) c.hidden = true;

    const setAll = (v) => {
      all = v;
      try { localStorage.setItem(KEY, v ? '1' : '0'); } catch (_) { /* this window only */ }
      if (v && last) { // back to one pool: every device follows the two switches again
        const f = o.flat(last) || {};
        for (const d of devices(last)) {
          if (d.out !== !!f.out) UI.api.setConsent(d.id, o.feature, 'out', !!f.out);
          if (d.in !== !!f.in) UI.api.setConsent(d.id, o.feature, 'in', !!f.in);
        }
      }
      lastKey = '';
      if (last) render(last);
    };

    // Every other device of the mesh with this computer's two switches for it (row: we send; column: we take).
    function devices(s) {
      const m = s.matrix;
      if (!m || !m.devices || !(m.features || []).includes(o.feature)) return [];
      const self = m.devices.find((d) => d.self);
      if (!self) return [];
      const cells = m.cells[o.feature] || [];
      const cell = (from, to) => cells.find((c) => c.from === from && c.to === to) || {};
      const peers = new Map((s.peers || []).map((p) => [p.id, p]));
      return m.devices.filter((d) => !d.self).map((d) => {
        const p = peers.get(d.id) || {};
        const out = cell(self.id, d.id);
        const inn = cell(d.id, self.id);
        return {
          id: d.id, name: d.name, os: d.os, connected: !!p.connected || p.state === 'via',
          // ours: what this computer said for that pair (the cell's own side), theirs: whether it's on there too
          out: out.ours === true, in: inn.ours === true,
          theirsOut: !!out.on, theirsIn: !!inn.on,
        };
      });
    }
    function list(box, devs, dir, everyLabel) {
      const f = (last && o.flat(last)) || {};
      const rows = [];
      if (all) {
        const every = checkbox(!!f[dir], (v) => {
          o.setFlat(dir, v);
          for (const d of devs) if (d[dir] !== v) UI.api.setConsent(d.id, o.feature, dir, v);
        }, everyLabel);
        rows.push(UI.el('label', { class: 'sf-all' }, [every, UI.el('span', {}, [UI.el('b', { text: everyLabel }), UI.el('small', { text: t('Includes devices added later') })])]));
      }
      for (const d of devs) {
        const on = d[dir];
        const state = !d.connected ? t('Not connected') : on && !(dir === 'out' ? d.theirsOut : d.theirsIn) ? t('Off on {device}', { device: d.name }) : (OSNAME[d.os] || '');
        const row = UI.el('label', { class: 'sf-dev' + (all ? ' off' : '') }, [
          checkbox(on, (v) => UI.api.setConsent(d.id, o.feature, dir, v), d.name, all),
          UI.el('span', { class: 'sf-dev-name', text: d.name }),
          UI.el('span', { class: 'sf-dev-os', text: state }),
        ]);
        rows.push(row);
      }
      if (!devs.length) rows.push(UI.el('div', { class: 'sl-empty', text: t('No other device yet') }));
      box.replaceChildren(...rows);
    }

    function render(s) {
      last = s;
      const devs = devices(s);
      const mesh = !!(s.matrix && s.matrix.devices && s.matrix.devices.length > 1);
      for (const c of cards) c.hidden = !mesh;
      if (!mesh) return;
      const key = JSON.stringify([devs, o.flat(s), all]);
      if (key === lastKey) return;
      lastKey = key;
      const sw = UI.switch((v) => setAll(v), { label: t('All devices') });
      sw.set(all);
      allBox.replaceChildren(UI.row(t('All devices'), all ? t('On: one pool, every device follows the two switches below') : t('Off: tick each device below'), [sw]));
      list(sendBox, devs, 'out', o.sendAll || t('Send to every device'));
      list(recvBox, devs, 'in', o.receiveAll || t('Receive from every device'));
    }

    return { cards, render };
  };

  // A gear at the top of the page (beside its switch) that opens its Settings.
  const GEAR = 'M10 7.2a2.8 2.8 0 1 0 0 5.6 2.8 2.8 0 0 0 0-5.6z M8.6 2.5h2.8l.4 2 1.6.9 1.9-.7 1.4 2.4-1.5 1.4v1.9l1.5 1.3-1.4 2.5-1.9-.7-1.6.9-.4 2h-2.8l-.4-2-1.6-.9-1.9.7-1.4-2.5 1.5-1.3V8.5L2.4 7.1l1.4-2.4 1.9.7 1.6-.9z';
  UI.pageGear = (body, onClick) => {
    const b = UI.el('button', { class: 'page-gear', attrs: { 'aria-label': t('Settings'), title: t('Settings') } });
    const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    svg.setAttribute('viewBox', '0 0 20 20');
    const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
    path.setAttribute('d', GEAR);
    svg.append(path);
    b.append(svg);
    b.onclick = onClick;
    const place = () => {
      const head = body.closest('.page') && body.closest('.page').querySelector('.page-head');
      if (!head) return false;
      head.append(b);
      return true;
    };
    if (!place()) setTimeout(place, 0); // a page whose head comes after its build
    return { el: b, set: (on) => b.classList.toggle('on', !!on) };
  };

  // A big gear (no text) that opens a page's settings: at the end of the page's top card.
  UI.gearButton = (onClick) => {
    const b = UI.el('button', { class: 'gear-btn', attrs: { 'aria-label': t('Settings'), title: t('Settings') } });
    const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    svg.setAttribute('viewBox', '0 0 20 20');
    const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
    path.setAttribute('d', GEAR);
    svg.append(path);
    b.append(svg);
    b.onclick = onClick;
    return b;
  };
  // A page in two views: its own (top card with the gear at its end, then the rest) and its settings (Back, then
  // the setting cards, one column). top: the rows of the top card; main: what follows; settings: cards.
  //   const v = UI.gearView(body, { top: [rows], main: [cards], settings: [cards] }); v.show(on)
  UI.gearView = (body, o) => {
    const gear = UI.gearButton(() => show(true));
    // o.topCard: a card of the page's own that takes the gear (the Phone page's hero) instead of a new one.
    const top = o.topCard || UI.el('div', { class: 'card gear-top dir-sec' }, [UI.el('div', { class: 'gear-rows' }, (o.top || []).filter(Boolean))]);
    top.classList.add('gear-host');
    top.append(gear);
    const main = UI.el('div', { class: 'gear-main' }, [top, ...o.main.filter(Boolean)]);
    const back = UI.button(t('Back'), () => show(false), 'small');
    const settings = UI.el('div', { class: 'gear-settings', hidden: true }, [UI.el('div', { class: 'feed-back' }, [back]), ...o.settings.filter(Boolean)]);
    function show(on) { settings.hidden = !on; main.hidden = on; }
    body.append(main, settings);
    return { show, top, main, settings };
  };
    // Recent items grouped by the device each came from, the groups in the order of their newest item.
  UI.byDevice = (items, deviceOf) => {
    const groups = new Map();
    for (const it of items) {
      const k = deviceOf(it) || t('This computer');
      if (!groups.has(k)) groups.set(k, []);
      groups.get(k).push(it);
    }
    return [...groups].map(([name, list]) => ({ name, items: list }));
  };
  // A list's rows (nodes, one per item) with a heading before each device's (Multi-device only).
  UI.inGroups = (items, nodes, deviceOf, on) => {
    if (!on) return nodes;
    const order = [];
    const by = new Map();
    items.forEach((it, i) => {
      const k = deviceOf(it) || t('This computer');
      if (!by.has(k)) { by.set(k, []); order.push(k); }
      by.get(k).push(nodes[i]);
    });
    return order.flatMap((k) => [UI.groupHead(k), ...by.get(k)]);
  };
  // Recent notifications (state.notifs.history), the newest first; grouped by the device each came from
  // in Multi-device. opts.open(item, s) → a button for it, or null.
  UI.notifRecent = (opts = {}) => {
    const box = UI.el('div', { class: 'history' });
    const clear = UI.api.clearNotifHistory ? UI.button(t('Clear'), () => UI.api.clearNotifHistory(), 'small') : null;
    const card = UI.card(t('Recent'), [box], clear ? { actions: [clear], cls: 'keep-on' } : { cls: 'keep-on' });
    let lastKey = '';
    return {
      el: card,
      update(s) {
        const n = s.notifs || {};
        const hist = n.history || [];
        const icons = n.historyIcons || {};
        const mesh = !!(s.matrix && s.matrix.devices && s.matrix.devices.length > 1);
        if (clear) clear.disabled = !hist.length;
        const key = JSON.stringify([hist.map((x) => [x.id, x.at, x.on]), Object.keys(icons), mesh]) + Math.floor(Date.now() / 15000);
        if (key === lastKey) return;
        lastKey = key;
        if (!hist.length) {
          box.replaceChildren(UI.row(t('No notifications yet'), t('Notifications from the other devices show up here')));
          return;
        }
        const nodes = hist.slice(0, 100).map((x) => {
          const top = [x.appName || x.app, x.title].filter(Boolean).join(', ');
          const sub = [x.subtitle, x.body].filter(Boolean).join(' — ') || t('Notification');
          const r = UI.row(top, `${sub}, ${UI.ago ? UI.ago(x.at) : new Date(x.at).toLocaleString()}`, [opts.open ? opts.open(x, s) : null], { literal: true });
          if (icons[x.app]) {
            const img = UI.el('img', { class: 'notif-ico', src: icons[x.app], alt: '' });
            r.querySelector('.text').prepend(img);
            r.classList.add('with-ico');
          }
          return r;
        });
        box.replaceChildren(...UI.inGroups(hist.slice(0, 100), nodes, (x) => x.on, mesh));
      },
    };
  };
  UI.groupHead = (name) => UI.el('div', { class: 'dev-group-head', text: name, attrs: { 'data-literal': '' } });
})();