engawa-chat 0.3.0

A peer-to-peer chat lobby for editors and browsers
<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="referrer" content="no-referrer">
  <meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; base-uri 'none'; form-action 'none'">
  <title>engawa — 縁側</title>
  <link rel="icon" href="/assets/icon.svg" type="image/svg+xml" sizes="any">
  <style>
    :root { color-scheme: light dark; --paper: #f8f6ef; --panel: #fffdf7; --ink: #292f27; --muted: #515f54; --line: #cbd0c4; --accent: #315d46; --wash: #e6eee2; --on-accent: #fff; --danger: #993b35; font: 100%/1.6 system-ui, sans-serif; }
    @media (prefers-color-scheme: dark) { :root { --paper: #1b211d; --panel: #242d26; --ink: #e5eee5; --muted: #b2c0b2; --line: #506052; --accent: #abd4b5; --wash: #334537; --on-accent: #172a20; --danger: #ffa79c; } }
    * { box-sizing: border-box; } [hidden] { display: none !important; }
    body { margin: 0; background: var(--paper); color: var(--ink); } header, main, footer { max-width: 72rem; margin: auto; padding: 1.2rem clamp(1rem, 4vw, 3rem); }
    header { display: flex; align-items: center; gap: .8rem; border-bottom: 1px solid var(--line); } header span, small, .muted, footer { color: var(--muted); } #status { margin-left: auto; font-size: .86rem; overflow-wrap: anywhere; min-width: 0; }
    main { display: grid; grid-template-columns: minmax(14rem, 1fr) minmax(0, 2fr); gap: 1.25rem; align-items: start; } h1, h2, h3, p { margin: 0 0 .7rem; } h1 { font-size: 1.6rem; } h2 { font-size: 1.15rem; } h3 { font-size: 1rem; } .kicker { color: var(--accent); font: 700 .75rem/1.4 monospace; letter-spacing: .14em; margin-bottom: .5rem; }
    .panel { border: 1px solid var(--line); border-radius: 1rem; background: var(--panel); padding: 1.2rem; min-width: 0; } .rooms, .messages { padding: 0; margin: 0; list-style: none; }
    button, select, input, textarea { font: inherit; color: inherit; border: 1px solid var(--line); border-radius: .5rem; background: var(--panel); } button { cursor: pointer; padding: .4rem .85rem; } button:hover, button[aria-current="true"] { background: var(--wash); } :focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; } .primary { background: var(--accent); color: var(--on-accent); } .primary:hover { background: var(--accent); filter: brightness(.92); }
    .rooms button { display: grid; width: 100%; text-align: start; margin-top: .45rem; overflow-wrap: anywhere; } .rooms strong { font-size: 1rem; } label { display: block; margin-top: .6rem; font-size: .9rem; } input, select, textarea { display: block; width: 100%; padding: .5rem; margin: .2rem 0 .65rem; } textarea { resize: vertical; } details { margin-top: 1.2rem; border-top: 1px solid var(--line); padding-top: .7rem; } summary { cursor: pointer; }
    .welcome { padding-block: 3rem; } .room-head, .send-row { display: flex; align-items: center; justify-content: space-between; gap: 1rem; } .room-head > div { min-width: 0; overflow-wrap: anywhere; } .room-head > button { flex: none; } .messages { max-height: 48vh; overflow: auto; padding: 0 .35rem .35rem 0; } .messages li { border-top: 1px solid var(--line); padding: .65rem 0; } .messages p { white-space: pre-wrap; overflow-wrap: anywhere; margin: .15rem 0 0; } .retract { margin-left: .6rem; font-size: .8rem; padding: 0 .45rem; } #error { color: var(--danger); overflow-wrap: anywhere; } footer { font-size: .85rem; }
    @media (max-width: 42rem) { main { grid-template-columns: 1fr; } header { flex-wrap: wrap; } .messages { max-height: 45vh; } }
  </style>
</head>
<body>
  <header><img src="/assets/logo.svg" width="165" height="44" alt="Engawa"><span>縁側</span><span id="status" role="status">接続中…</span></header>
  <main>
    <aside class="panel" aria-label="ロビー">
      <p class="kicker" lang="en">LOBBY</p><h2>公開の部屋</h2>
      <p class="muted">履歴の設定を見て、入る部屋を選んでください。</p>
      <ul id="rooms" class="rooms"></ul><p id="no-rooms" class="muted">部屋を探しています。</p>
      <details><summary>部屋を作る</summary>
        <form id="create" autocomplete="off"><label for="name">部屋の名前</label><input id="name" required spellcheck="false">
          <label for="policy">履歴(作成後は変更できません)</label>
          <select id="policy"><option value="off">その場だけ · 履歴なし</option><option value="on">あとから読める · 直近7日・最大200件</option></select>
          <button class="primary" type="submit">作成して入室</button>
        </form>
      </details>
      <details id="lobby-invite-details"><summary>ロビーに招待する</summary>
        <p>この PC で engawa を起動したまま、スマートフォンにリンクを送ってください。相手は自分で部屋を選べます。この PC で同じ部屋に入る必要はありません。</p>
        <p id="lobby-invite-unavailable" class="muted">接続先を確認中です。ロビーの招待リンクはまだ使えません。</p>
        <div id="lobby-invite-controls" hidden>
          <label for="lobby-invite-url">ロビーへのリンク</label><input id="lobby-invite-url" type="text" inputmode="url" readonly dir="ltr" spellcheck="false">
          <button type="button" id="lobby-invite-copy">コピー</button>
          <button type="button" id="lobby-invite-share" hidden>共有…</button>
        </div>
        <p id="lobby-invite-feedback" role="status"></p>
      </details>
    </aside>
    <div>
      <p id="error" role="alert" hidden></p>
      <section id="welcome" class="panel welcome"><p class="kicker" lang="en">ENGAWA / LOBBY</p><h1>作業の合間に、縁側へ。</h1><p>部屋を選ぶと、そこに居合わせた人と話せます。</p><p class="muted">誰もいないときは、あなたが最初のひとりです。</p></section>
      <section id="chat" class="panel" hidden aria-labelledby="title">
        <div class="room-head"><div><p class="kicker" lang="en">ENGAWA / ROOM</p><h1 id="title"></h1></div><button id="leave" type="button">退室</button></div>
        <p id="description" class="muted"></p>
        <details><summary>この部屋に招待する</summary>
          <p>この PC で部屋を開いたまま、相手のスマートフォンにリンクを送ってください。相手はブラウザーから参加できます。</p>
          <p id="invite-unavailable" class="muted">接続先を確認中です。招待リンクはまだ使えません。</p>
          <div id="invite-controls" hidden>
            <label for="invite-link">参加者用のリンク</label><input id="invite-link" type="text" inputmode="url" readonly dir="ltr" spellcheck="false">
            <button type="button" id="invite-copy">コピー</button>
            <button type="button" id="invite-share" hidden>共有…</button>
          </div>
          <p id="invite-feedback" role="status"></p>
        </details>
        <h2>この端末に届いた発言</h2>
        <ol id="messages" class="messages" aria-label="発言一覧" tabindex="0"></ol><p id="no-messages" class="muted">まだ発言は届いていません。</p>
        <form id="compose" autocomplete="off"><label for="draft">発言を書く</label><textarea id="draft" rows="3" required spellcheck="false"></textarea>
          <div class="send-row"><small>Ctrl / ⌘ + Enter でも送信</small><button class="primary" type="submit">送信</button></div>
        </form>
      </section>
    </div>
  </main>
  <footer>部屋は公開です。その場だけの部屋や取り消した発言でも、相手のコピーやスクリーンショットまでは消せません。</footer>
  <script>
    'use strict';
    let token = new URLSearchParams(location.hash.slice(1)).get('token');
    try {
      if (token) sessionStorage.setItem('engawa.token', token);
      else token = sessionStorage.getItem('engawa.token');
    } catch { /* The fragment still works when browser storage is disabled. */ }
    history.replaceState(null, '', location.pathname + location.search);
    const $ = id => document.getElementById(id);
    const policy = saved => saved ? 'あとから読める · 直近7日・最大200件' : 'その場だけ · 履歴なし';
    const label = (node, value) => { if (node.textContent !== value) node.textContent = value; };
    let room = null, reading = false, writing = false, version = 0, synced = false;
    function error(message) { label($('error'), message); $('error').hidden = !message; }
    function inviteUrl(state, i, fields) {
      if (!i || i.v !== 1 || typeof i.peer !== 'string' || !/^[a-f0-9]{64}$/.test(i.peer)) return '';
      try {
        const relay = new URL(i.relay);
        if (relay.protocol !== 'https:' || relay.username || relay.password || relay.search || relay.hash) return '';
        const url = new URL(state.invite_base ?? 'https://yukimemi.github.io/engawa/');
        const local = url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
        if ((!local && url.protocol !== 'https:') || url.username || url.password || url.search || url.hash) return '';
        url.hash = new URLSearchParams({v: '1', ...fields, peer: i.peer, relay: i.relay});
        return url.href;
      } catch { return ''; }
    }
    function roomInviteUrl(state, current) {
      const i = state.invite;
      if (!current || !i || i.room !== current.id || i.name !== current.name ||
          i.history !== current.history || typeof i.history !== 'boolean' || !/^[a-f0-9]{64}$/.test(i.room)) return '';
      return inviteUrl(state, i, {room: i.room, name: i.name, history: i.history ? '1' : '0'});
    }
    function inviteControls(prefix, inputId, title) {
      const input = $(inputId), feedback = $(prefix + '-feedback'), share = $(prefix + '-share');
      $(prefix + '-copy').onclick = async () => {
        const link = input.value;
        if (!link) return;
        try { await navigator.clipboard.writeText(link); }
        catch {
          if (input.value !== link) return;
          input.focus(); input.select(); input.setSelectionRange(0, link.length);
          let copied = false;
          try { copied = document.execCommand('copy'); } catch {}
          if (!copied) { label(feedback, 'リンクを選択しました。長押しまたは Ctrl / ⌘ + C でコピーしてください。'); return; }
        }
        if (input.value === link) label(feedback, '招待リンクをコピーしました。');
      };
      share.hidden = typeof navigator.share !== 'function';
      share.onclick = async () => {
        const link = input.value;
        if (!link) return;
        try { await navigator.share({title: title() + ' — engawa', url: link}); }
        catch (e) { if (e.name !== 'AbortError' && input.value === link) label(feedback, '共有できませんでした。「コピー」を使ってください。'); }
      };
      return link => {
        if (input.value !== link) { input.value = link; label(feedback, ''); }
        $(prefix + '-unavailable').hidden = !!link;
        $(prefix + '-controls').hidden = !link;
      };
    }
    const setInvite = inviteControls('invite', 'invite-link', () => $('title').textContent);
    const setLobbyInvite = inviteControls('lobby-invite', 'lobby-invite-url', () => '公開ロビー');
    async function api(op, body) {
      const options = { method: body ? 'POST' : 'GET', headers: { Authorization: 'Bearer ' + token }, cache: 'no-store', credentials: 'omit', redirect: 'error', referrerPolicy: 'no-referrer' };
      if (!body) options.signal = AbortSignal.timeout(6000);
      if (body) { options.headers['Content-Type'] = 'application/json'; options.body = JSON.stringify(body); }
      const response = await fetch('/api/' + op, options);
      if (!response.ok) throw new Error(await response.text() || 'HTTP ' + response.status);
      if (!body) return response.json();
    }
    // Keep existing controls in the DOM when polling, including the focused button.
    function reconcile(list, records, create, update) {
      const nodes = new Map(Array.from(list.children, n => [n.dataset.id, n]));
      const ids = new Set(records.map(record => record.id));
      for (const [id, node] of nodes) if (!ids.has(id)) node.remove();
      let next = list.firstElementChild;
      for (const record of records) {
        const node = nodes.get(record.id) || create(record.id);
        node.dataset.id = record.id;
        update(node, record);
        if (next !== node) {
          const focused = node.contains(document.activeElement) ? document.activeElement : null;
          list.insertBefore(node, next);
          if (focused && document.activeElement !== focused) focused.focus({preventScroll: true});
        }
        next = node.nextElementSibling;
      }
    }
    function roomRow(id) {
      const li = document.createElement('li'), button = document.createElement('button');
      button.type = 'button'; button.append(document.createElement('strong'), document.createElement('small'));
      button.onclick = () => { if (room !== id) act('join', {id}); };
      li.append(button); return li;
    }
    function messageRow(id) {
      const li = document.createElement('li'), owner = document.createElement('small'), button = document.createElement('button');
      button.type = 'button'; button.className = 'retract'; button.textContent = '取り消す'; button.onclick = () => act('retract', {id});
      const text = document.createElement('p'); text.dir = 'auto'; li.append(owner, button, text); return li;
    }
    function render(state) {
      const changed = room !== state.room;
      if (changed) $('draft').value = '';
      room = state.room;
      label($('status'), state.status);
      reconcile($('rooms'), state.rooms, roomRow, (li, r) => {
        const b = li.firstElementChild;
        label(b.children[0], '#' + r.name); label(b.children[1], policy(r.history) + (r.active ? ' · 最近活動あり' : ''));
        b.setAttribute('aria-current', String(room === r.id));
      });
      $('no-rooms').hidden = !!state.rooms.length; label($('no-rooms'), 'まだ部屋は見つかっていません。新しく作ることもできます。');
      const current = state.rooms.find(r => r.id === room);
      $('welcome').hidden = room !== null; $('chat').hidden = room === null;
      setInvite(roomInviteUrl(state, current));
      setLobbyInvite(state.lobby_invite?.kind === 'lobby' ? inviteUrl(state, state.lobby_invite, {kind: 'lobby'}) : '');
      label($('title'), current ? '#' + current.name : '現在の部屋');
      label($('description'), current ? policy(current.history) + (current.history ? '。履歴を持つ参加者と接続すると同期します。' : '。入室中の発言のみ表示します。') : '');
      const list = $('messages'), atEnd = list.scrollHeight - list.scrollTop - list.clientHeight < 6;
      reconcile(list, state.messages, messageRow, (li, m) => {
        label(li.children[0], m.mine ? '自分' : (m.author || '匿名')); li.children[1].hidden = !m.mine; label(li.children[2], m.text);
      });
      $('no-messages').hidden = !!state.messages.length;
      if (changed || atEnd) list.scrollTop = list.scrollHeight;
    }
    async function refresh() {
      if (!token || reading || writing) return;
      const start = version; reading = true;
      try { const state = await api('state'); if (start === version) { render(state); synced = true; } }
      catch { if (start === version) { synced = false; setInvite(''); setLobbyInvite(''); label($('status'), '接続できません。engawa が起動中か確認してください。'); } }
      finally { reading = false; if (start !== version && !writing) refresh(); }
    }
    async function act(op, body, accepted) {
      if (!token || writing || !synced) return;
      if (['join', 'leave', 'rooms'].includes(op)) setInvite('');
      writing = true; synced = false; version++; error('');
      try { await api(op, body); if (accepted) accepted(); }
      catch (e) { error(e.message); }
      finally { writing = false; refresh(); }
    }
    $('create').onsubmit = e => { e.preventDefault(); const name = $('name').value.trim(); if (name) act('rooms', {name, history: $('policy').value === 'on'}, () => { $('create').reset(); $('create').closest('details').open = false; }); };
    $('leave').onclick = () => act('leave', {});
    $('compose').onsubmit = e => { e.preventDefault(); const text = $('draft').value; if (room && text.trim()) act('send', {text}, () => { if ($('draft').value === text) $('draft').value = ''; }); };
    document.addEventListener('visibilitychange', () => {
      if (!document.hidden && token) { synced = false; version++; setInvite(''); setLobbyInvite(''); refresh(); }
    });
    $('draft').onkeydown = e => { if (!e.isComposing && e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); $('compose').requestSubmit(); } };
    if (token) { refresh(); setInterval(refresh, 1500); }
    else { label($('status'), '認証情報がありません'); error('ターミナルから engawa web で開き直してください。'); }
  </script>
</body>
</html>