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.

15.3 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// The control window's look, in the renderer of each app (after its UI kit):
//   UI.look(state.look): the accent colour into --accent (and --accent-soft, from it in the CSS), and
//     Glass or Simple as html.glass (shared/ui-glass.css; shared/look-early.js set it before the first paint).
//   UI.styleRow / UI.themeRow / UI.accentRow: General › Appearance's pickers.
//   UI.sections(cards): a long page in sections, a sticky list of the card titles beside it. A click
//     scrolls to that card, and the list follows where the page is as it scrolls (one page still).
'use strict';

(function () {
  const t = (s) => (window.I18n ? window.I18n.t(s) : s);
  let applied = '';

  UI.look = (look) => {
    if (look && look.style) document.documentElement.classList.toggle('glass', look.style !== 'simple');
    const c = look && look.color;
    if (!c || c === applied) return;
    applied = c;
    document.documentElement.style.setProperty('--accent', c);
  };

  // Glass (the default: the iPad app's look) or Simple (flat, as before).
  UI.styleRow = (onChange) => {
    const seg = UI.segmented([{ value: 'glass', label: t('look.glass') }, { value: 'simple', label: t('look.simple') }], onChange);
    const row = UI.row(t('Style'), t('Glass: soft colours from the accent behind translucent cards'), [seg.el]);
    row.render = (v) => seg.set(v === 'simple' ? 'simple' : 'glass');
    return row;
  };

  UI.themeRow = (onChange) => {
    const seg = UI.segmented([
      { value: 'system', label: t('System') }, { value: 'light', label: t('look.light') }, { value: 'dark', label: t('look.dark') },
    ], onChange);
    const row = UI.row(t('Theme'), t('System follows this computer’s light or dark setting'), [seg.el]);
    row.render = (v) => seg.set(v || 'system');
    return row;
  };

  // Swatches: "System" (the system's accent colour) first, then the fixed colours.
  UI.accentRow = (onChange) => {
    const box = UI.el('div', { class: 'swatches', attrs: { role: 'radiogroup', 'aria-label': t('Accent colour') } });
    const row = UI.row(t('Accent colour'), t('System uses this computer’s accent colour'), [box]);
    let built = '';
    const buttons = [];
    const make = (value, color, label) => {
      const b = UI.el('button', { class: 'swatch' + (value ? '' : ' sys'), attrs: { title: label, 'aria-label': label, role: 'radio' } });
      b.style.setProperty('--sw', color);
      b.onclick = () => onChange(value);
      b.value = value;
      buttons.push(b);
      box.append(b);
    };
    row.render = (look) => {
      if (!look) return;
      const key = look.os + (look.accents || []).join();
      if (key !== built) {
        built = key;
        box.textContent = '';
        buttons.length = 0;
        make('', look.os, t('System'));
        for (const c of look.accents || []) make(c, c, c);
      }
      for (const b of buttons) {
        const on = b.value === (look.accent || '');
        b.classList.toggle('on', on);
        b.setAttribute('aria-checked', on ? 'true' : 'false');
      }
    };
    return row;
  };

  // Paired computers nearby, under the phones at the top of the sidebar (as the phone app shows
  // them): its kind, its name and the link. Click: connect it; the connected one opens Overview.
  // list: [{id, name, os, connected, sub, go()}]; open(): show Overview; active: the connected one is lit (blue) on every page.
  let pcKey = '';
  UI.renderPcs = (box, list, { open, active }) => {
    const key = JSON.stringify([list.map((d) => [d.id, d.name, d.os, d.connected, d.sub]), active]);
    if (!box || key === pcKey) return;
    pcKey = key;
    box.replaceChildren(...list.map((d) => {
      const b = UI.el('button', { class: 'phone-tile pc-tile' + (d.connected ? ' connected' : ''), title: d.connected ? d.name : t('Connect to {name}', { name: d.name }) }, [
        UI.el('span', { class: 'pc-wall' }, [UI.osIcon(UI.osOf ? UI.osOf(d) : d.os)]),
        UI.el('span', { class: 'phone-text' }, [UI.el('span', { class: 'phone-name', text: d.name, attrs: { 'data-literal': '' } }),
          UI.el('span', { class: 'phone-sub', text: d.sub, attrs: { 'data-literal': '' } })]),
        d.connected ? UI.el('span', { class: 'dot good' }) : null,
      ]);
      b.classList.toggle('active', !!(d.connected && active));
      b.onclick = () => (d.connected ? open() : d.go());
      return b;
    }));
  };

  // A block that isn't a card (File Sharing's two direction cards) as a titled section for UI.sections.
  UI.titled = (title, block) => UI.el('div', { class: 'card-wrap' }, [UI.el('div', { class: 'card-title' }, [UI.el('span', { text: title })]), block]);

  // A direction of a feature (UI.dir / UI.pair on the Mac, UI.dirCards on Windows and Linux): its rows,
  // then any options of its main switch folded under one full-width Options row. Names in it read
  // "this device" and "the other device"; in Multi-device "other devices" (UI.sidePeer).
  // Every row shows; only `options` (settings of the main switch itself, given by the page) fold under Options.
  UI.dirSection = (rows, { options = [] } = {}) => {
    const rest = options.filter(Boolean);
    const sec = UI.el('div', { class: 'dir-sec' }, rows.filter(Boolean));
    if (!rest.length) return sec;
    const more = UI.el('div', { class: 'dir-more', hidden: true }, rest);
    const chev = UI.el('span', { class: 'dir-chev', text: '›' });
    const btn = UI.el('button', { class: 'dir-opts', attrs: { 'aria-expanded': 'false' } }, [UI.el('span', { text: I18n.t('Options') }), chev]);
    btn.onclick = () => {
      more.hidden = !more.hidden;
      btn.setAttribute('aria-expanded', String(!more.hidden));
      btn.classList.toggle('open', !more.hidden);
    };
    // Nothing to show under it (every row hidden for now): no Options row either.
    const sync = () => { btn.hidden = rest.every((r) => r.hidden); };
    for (const r of rest) new MutationObserver(sync).observe(r, { attributes: true, attributeFilter: ['hidden'] });
    sync();
    sec.append(btn, more);
    return sec;
  };
  // Both directions in one card, one under the other.
  UI.dirOne = (a, b) => UI.el('div', { class: 'card dir-one' }, [a, b].filter(Boolean));
  // Names on every page but Connection: words, never a device's name.
  UI.namedHere = (e) => !!e.closest('#page-connection, [data-literal]');
  UI.sidePeer = (p) => {
    const mesh = !!document.querySelector('.app-name .mesh-pill:not(.portable-pill)');
    const cap = (x) => (x ? x.charAt(0).toUpperCase() + x.slice(1) : x);
    const me = I18n.t('this device');
    const other = mesh ? I18n.t('other devices') : I18n.t('the other device'); // never a device's name (Connection keeps names)
    return { ...p, me, Me: cap(me), name: other, Name: cap(other), the: other, them: other, device: other, there: other, plural: mesh };
  };
  // A filled template with sidePeer's words: "other devices’s" reads "other devices’" (the plural takes no s).
  UI.sideText = (text, sp) => {
    if (!sp || !sp.plural) return text;
    const esc = (x) => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    return String(text).replace(new RegExp('(' + esc(sp.name) + '|' + esc(sp.Name) + ')([’\'])s\\b', 'g'), '$1$2');
  };

  // A page in tabs (File Sharing; Camera & Controller): a bar of tabs at the top, only the chosen tab's cards
  // below, room under them. The bar is the only way to switch. A tab can have its own switch in the bar
  // (Camera, Controller: each on or off by itself under the page's switch); its cards dim while it's off.
  // A tab whose cards are all hidden has no button. The chosen tab is remembered here (localStorage).
  //   const t = UI.tabbed(pageId, [{ id, title, cards: [card | null], toggle?: { get(s), set(v) } }]); t.update(s)
  UI.tabbed = (page, groups) => {
    const key = `td.tab.${page}`;
    let at = '';
    try { at = localStorage.getItem(key) || ''; } catch (_) { /* no storage: the first tab */ }
    const bar = UI.el('div', { class: 'tab-bar', attrs: { role: 'tablist' } });
    const panes = UI.el('div', { class: 'tab-panes' });
    // The tab shown's own switch at the right edge of the bar's row, labelled with its name.
    const side = UI.el('div', { class: 'tab-side' });
    const wrap = UI.el('div', { class: 'tabbed' }, [UI.el('div', { class: 'tab-row' }, [bar, side]), panes]);
    const tabs = groups.map((g) => {
      const cards = g.cards.filter(Boolean);
      const box = UI.el('div', { class: 'tab-pane', attrs: { role: 'tabpanel' } }, cards);
      const b = UI.el('button', { class: 'tab-btn', text: g.title, attrs: { role: 'tab' } });
      b.onclick = () => show(g.id);
      let sw = null, tog = null;
      const item = UI.el('span', { class: 'tab-item' }, [b]);
      if (g.toggle) {
        sw = UI.switch((v) => g.toggle.set(v), { label: g.title });
        tog = UI.el('label', { class: 'tab-toggle' }, [UI.el('span', { text: g.title }), sw.el]);
        side.append(tog);
      }
      bar.append(item);
      panes.append(box);
      return { id: g.id, b, box, cards, sw, tog, toggle: g.toggle };
    });
    const visible = (tb) => !tb.cards.length || tb.cards.some((c) => !c.hidden);
    function show(id) {
      const pick = tabs.find((tb) => tb.id === id && visible(tb)) || tabs.find(visible) || tabs[0];
      at = pick.id;
      try { localStorage.setItem(key, at); } catch (_) { /* not kept */ }
      for (const tb of tabs) {
        tb.b.parentElement.hidden = !visible(tb);
        tb.b.parentElement.classList.toggle('active', tb === pick);
        tb.b.classList.toggle('active', tb === pick);
        tb.b.setAttribute('aria-selected', String(tb === pick));
        tb.box.hidden = tb !== pick;
        if (tb.tog) tb.tog.hidden = tb !== pick;
      }
    }
    for (const tb of tabs) for (const c of tb.cards) new MutationObserver(() => show(at)).observe(c, { attributes: true, attributeFilter: ['hidden'] });
    show(at);
    wrap.show = show;
    wrap.spy = () => {};
    wrap.update = (s) => {
      for (const tb of tabs) {
        if (!tb.toggle) continue;
        const on = !!tb.toggle.get(s);
        tb.sw.set(on);
        if (tb.toggle.disabled) tb.sw.disable(!!tb.toggle.disabled(s));
        tb.box.classList.toggle('tab-off', !on);
      }
    };
    return wrap;
  };

  // General's scrolling list, by groups: each group a heading over its cards, the list beside them
  // following the scroll. A group with nothing shown has no heading and no link.
  //   UI.groupedSections([{ id, title, cards }])
  UI.groupedSections = (groups) => UI.sections(groups.map((g) => {
    const cards = g.cards.filter(Boolean);
    // A card titled like its group ("Paired" under "Paired") shows the group's heading only; its
    // buttons, if any, stay where they were.
    for (const c of cards) {
      const head = [...c.children].find((x) => x.classList && x.classList.contains('card-title'));
      const text = head && head.firstElementChild;
      if (!text || text.classList.contains('actions') || text.textContent.trim() !== String(g.title).trim()) continue;
      if (head.querySelector('.actions')) text.remove();
      else head.remove();
    }
    const box = UI.el('div', { class: 'sec-group', attrs: { 'data-sec': g.id || '' } }, [UI.el('div', { class: 'card-title sec-group-title' }, [UI.el('span', { text: g.title })]), ...cards]);
    const sync = () => { box.hidden = !cards.some((c) => !c.hidden); };
    for (const c of cards) new MutationObserver(sync).observe(c, { attributes: true, attributeFilter: ['hidden'] });
    sync();
    return box;
  }));

  // A sidebar page built the first time it's needed (shown, searched, pointed at by the tour), not
  // with the window: only its sidebar button exists until then. Its parts (page, body, master,
  // render…) are read through getters that build it. UI.buildPages() builds every one (search).
  const lazy = [];
  UI.lazyView = (def, build, extra) => {
    let built = null;
    const make = () => {
      if (built) return built;
      built = build(def);
      if (UI.pageBuilt) UI.pageBuilt(v); // the names the window filled in before it was built
      return built;
    };
    const v = { def, ...extra, build: make, get built() { return !!built; } };
    for (const k of ['page', 'body', 'master', 'render', 'headText', 'limitNote', 'wifiNote', 'art']) {
      Object.defineProperty(v, k, { get: () => make()[k], enumerable: true });
    }
    lazy.push(v);
    return v;
  };
  UI.buildPages = () => { for (const v of lazy) v.build(); };
  // A page's element by its id, built if it wasn't yet (the tour points at pages).
  UI.pageEl = (id) => { const v = lazy.find((x) => x.def.id === id); return v ? v.page : document.getElementById('page-' + id); };

  // Open a page at one of its groups (UI.groupedSections' id): Connection › Wireless debugging.
  UI.goSection = (page, sec) => {
    UI.go(page);
    setTimeout(() => {
      const host = UI.pageEl(page);
      const box = host && host.querySelector(`[data-sec="${sec}"]`);
      if (box && !box.hidden) box.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 60);
  };

  UI.sections = (cards) => {
    // A card a page has only sometimes comes as null (General's relay card where ui-relay.js isn't
    // loaded: the Mac's Multi-device window, whose General then didn't build at all).
    cards = cards.filter(Boolean);
    const list = UI.el('div', { class: 'sec-nav', attrs: { role: 'navigation' } });
    const col = UI.el('div', { class: 'sec-body' }, cards);
    const wrap = UI.el('div', { class: 'sections' }, [list, col]);
    const box = () => document.getElementById('content');
    // Where the cards show from: under the page's title, which stays at the top while they scroll.
    const under = (s) => {
      const head = wrap.closest('.page') && wrap.closest('.page').querySelector('.page-head');
      const top = s.getBoundingClientRect().top;
      return head && getComputedStyle(head).position === 'sticky' ? Math.max(top, head.getBoundingClientRect().bottom) : top;
    };
    const links = cards.map((c) => {
      const title = c.querySelector('.card-title span');
      const b = UI.el('button', { class: 'sec-link', text: title ? title.textContent : '' });
      b.onclick = () => {
        const s = box();
        if (s) s.scrollTo({ top: s.scrollTop + c.getBoundingClientRect().top - under(s) - 14, behavior: 'smooth' });
      };
      list.append(b);
      // A card that's hidden (General's Portable in an installed app) has no link either, and gets it when shown.
      b.hidden = c.hidden;
      new MutationObserver(() => { b.hidden = c.hidden; later(); }).observe(c, { attributes: true, attributeFilter: ['hidden'] });
      return b;
    });
    let queued = false;
    const spy = () => {
      queued = false;
      const s = box();
      if (!s || !wrap.offsetParent) return;
      const top = under(s) + 40;
      let at = 0;
      cards.forEach((c, i) => { if (!c.hidden && c.getBoundingClientRect().top <= top) at = i; });
      if (s.scrollTop + s.clientHeight >= s.scrollHeight - 2) at = cards.map((c) => !c.hidden).lastIndexOf(true); // the bottom: the last one shown, however short
      links.forEach((b, i) => b.classList.toggle('active', i === at));
    };
    const later = () => { if (!queued) { queued = true; requestAnimationFrame(spy); } };
    requestAnimationFrame(() => {
      const s = box();
      if (s) s.addEventListener('scroll', later, { passive: true });
      window.addEventListener('resize', later);
      spy();
    });
    wrap.spy = later;
    return wrap;
  };
})();