@alexsun-top/opencode-chat-room 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server/chat.html CHANGED
@@ -1,10 +1,10 @@
1
1
  <!doctype html>
2
- <html lang="zh-CN">
2
+ <html lang="en">
3
3
  <head>
4
4
  <meta charset="utf-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
6
6
  <meta name="color-scheme" content="light dark">
7
- <title>闲叙 · 轻量聊天室</title>
7
+ <title data-i18n="documentTitle">Casual Chat · Lightweight Chatroom</title>
8
8
  <style>
9
9
  * { box-sizing: border-box; }
10
10
  [hidden] { display: none !important; }
@@ -101,6 +101,10 @@
101
101
  border-radius: 18px;
102
102
  box-shadow: var(--shadow);
103
103
  }
104
+ .locale-control { display: flex; align-items: center; justify-content: flex-end; gap: 8px; margin-bottom: 20px; color: var(--ink-2); font-size: 12.5px; }
105
+ .locale-control label { font-weight: 600; }
106
+ .locale-select { appearance: auto; font: inherit; font-size: 12.5px; color: var(--ink); background: var(--surface); border: 1px solid var(--line); border-radius: 8px; padding: 5px 9px; cursor: pointer; }
107
+ .chat-head-actions .locale-control { margin: 0; }
104
108
  .wordmark {
105
109
  margin: 0;
106
110
  font-family: var(--font-serif);
@@ -152,7 +156,7 @@
152
156
  .btn.ghost:not(:disabled):hover { color: var(--ink); border-color: var(--ink-3); }
153
157
  .btn.small { padding: 8px 14px; font-size: 13.5px; }
154
158
  .btn:focus-visible, .chip:focus-visible, .room-row:focus-visible, .input:focus-visible,
155
- .jump:focus-visible, .copy-id:focus-visible {
159
+ .jump:focus-visible, .copy-id:focus-visible, .locale-select:focus-visible {
156
160
  outline: 2px solid var(--accent);
157
161
  outline-offset: 2px;
158
162
  }
@@ -256,7 +260,7 @@
256
260
  .copy-id.copied .mono { display: none; }
257
261
  .copy-id.copied .copy-ok { display: inline; color: var(--accent); }
258
262
 
259
- .chat-head-actions { display: flex; align-items: center; gap: 8px; }
263
+ .chat-head-actions { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 8px; }
260
264
  .chip {
261
265
  appearance: none;
262
266
  font: inherit;
@@ -588,49 +592,56 @@
588
592
  <!-- ── 加入 / 创建 ── -->
589
593
  <section id="joinView" class="view">
590
594
  <div class="join-card">
591
- <p class="wordmark">闲叙</p>
592
- <p class="tagline">一个轻量的聊天房间。输入房间 ID 加入,或直接新建一个。</p>
595
+ <div class="locale-control">
596
+ <label for="localeSelectJoin" data-i18n="languageLabel">Language</label>
597
+ <select id="localeSelectJoin" class="locale-select" aria-label="Language" data-i18n-aria-label="languageLabel">
598
+ <option value="en">English</option>
599
+ <option value="zh-CN">中文</option>
600
+ </select>
601
+ </div>
602
+ <p class="wordmark" data-i18n="brand">Casual Chat</p>
603
+ <p class="tagline" data-i18n="tagline">A lightweight chat room. Enter a room ID to join, or create a new one.</p>
593
604
 
594
605
  <form id="joinForm" novalidate>
595
606
  <label class="field">
596
- <span class="field-label">房间 ID</span>
597
- <input id="inRoomId" class="input" placeholder="粘贴或输入房间 ID" autocomplete="off" spellcheck="false">
607
+ <span class="field-label" data-i18n="roomIdLabel">Room ID</span>
608
+ <input id="inRoomId" class="input" placeholder="Paste or enter a room ID" data-i18n-placeholder="roomIdPlaceholder" autocomplete="off" spellcheck="false">
598
609
  </label>
599
610
  <label class="field">
600
- <span class="field-label">你的昵称</span>
601
- <input id="inName" class="input" placeholder="怎么称呼你" autocomplete="nickname" maxlength="24">
611
+ <span class="field-label" data-i18n="nameLabel">Your name</span>
612
+ <input id="inName" class="input" placeholder="What should we call you?" data-i18n-placeholder="namePlaceholder" autocomplete="nickname" maxlength="24">
602
613
  </label>
603
- <button class="btn primary" type="submit" id="btnJoin">加入房间</button>
614
+ <button class="btn primary" type="submit" id="btnJoin" data-i18n="joinRoom">Join room</button>
604
615
  </form>
605
616
 
606
- <div class="or"><span>或</span></div>
617
+ <div class="or"><span data-i18n="or">or</span></div>
607
618
 
608
619
  <form id="createForm" novalidate>
609
620
  <label class="field">
610
- <span class="field-label">新房间名称</span>
611
- <input id="inRoomName" class="input" placeholder="例如:周末电影夜" maxlength="40">
621
+ <span class="field-label" data-i18n="newRoomNameLabel">New room name</span>
622
+ <input id="inRoomName" class="input" placeholder="e.g. Weekend movie night" data-i18n-placeholder="newRoomNamePlaceholder" maxlength="40">
612
623
  </label>
613
- <button class="btn ghost" type="submit" id="btnCreate">创建新房间</button>
624
+ <button class="btn ghost" type="submit" id="btnCreate" data-i18n="createRoom">Create room</button>
614
625
  </form>
615
626
 
616
627
  <div id="joinError" class="alert" role="alert" hidden></div>
617
628
 
618
629
  <details id="tokenBox" class="token-box">
619
- <summary>访问令牌(可选)</summary>
630
+ <summary data-i18n="tokenOptional">Access token (optional)</summary>
620
631
  <div class="token-body">
621
632
  <label class="field">
622
- <span class="field-label">Bearer Token</span>
623
- <input id="inToken" class="input" type="password" placeholder="服务器要求时填写" autocomplete="off" spellcheck="false">
633
+ <span class="field-label" data-i18n="bearerToken">Bearer Token</span>
634
+ <input id="inToken" class="input" type="password" placeholder="Enter if the server requires it" data-i18n-placeholder="tokenPlaceholder" autocomplete="off" spellcheck="false">
624
635
  </label>
625
- <button class="btn ghost small" type="button" data-token-save="inToken">保存</button>
626
- <p class="hint">若服务器设置了访问令牌(401),所有请求都会带上它。</p>
636
+ <button class="btn ghost small" type="button" data-token-save="inToken" data-i18n="save">Save</button>
637
+ <p class="hint" data-i18n="tokenHint">If the server requires an access token (401), all requests will include it.</p>
627
638
  </div>
628
639
  </details>
629
640
 
630
641
  <section class="room-list">
631
- <h2>已有房间</h2>
642
+ <h2 data-i18n="existingRooms">Existing rooms</h2>
632
643
  <ul id="roomList"></ul>
633
- <p id="roomListEmpty" class="hint" hidden>还没有房间,创建一个吧。</p>
644
+ <p id="roomListEmpty" class="hint" data-i18n="noRooms" hidden>No rooms yet. Create one.</p>
634
645
  </section>
635
646
  </div>
636
647
  </section>
@@ -641,57 +652,64 @@
641
652
  <div class="chat-head-main">
642
653
  <h1 id="roomName"></h1>
643
654
  <p class="room-meta">
644
- <button type="button" id="btnCopyId" class="copy-id" aria-label="复制房间 ID" title="点击复制完整房间 ID">
645
- <span class="mono" id="roomIdShort"></span><span class="copy-ok">已复制</span>
655
+ <button type="button" id="btnCopyId" class="copy-id" aria-label="Copy room ID" data-i18n-aria-label="copyRoomId" title="Click to copy the full room ID" data-i18n-title="copyRoomIdTitle">
656
+ <span class="mono" id="roomIdShort"></span><span class="copy-ok" data-i18n="copied">Copied</span>
646
657
  </button>
647
658
  </p>
648
659
  </div>
649
660
  <div class="chat-head-actions">
661
+ <div class="locale-control">
662
+ <label for="localeSelectChat" data-i18n="languageLabel">Language</label>
663
+ <select id="localeSelectChat" class="locale-select" aria-label="Language" data-i18n-aria-label="languageLabel">
664
+ <option value="en">English</option>
665
+ <option value="zh-CN">中文</option>
666
+ </select>
667
+ </div>
650
668
  <div class="anchor">
651
- <button class="chip" type="button" id="btnMembers" aria-haspopup="true" aria-expanded="false">成员</button>
669
+ <button class="chip" type="button" id="btnMembers" aria-haspopup="true" aria-expanded="false" data-i18n="members">Members</button>
652
670
  <div class="panel" id="memberPanel" hidden>
653
- <h3>成员</h3>
671
+ <h3 data-i18n="members">Members</h3>
654
672
  <ul id="memberList"></ul>
655
- <p id="memberEmpty" class="hint" hidden>暂无成员</p>
673
+ <p id="memberEmpty" class="hint" data-i18n="noMembers" hidden>No members yet.</p>
656
674
  </div>
657
675
  </div>
658
676
  <div class="anchor">
659
- <button class="chip" type="button" id="btnSettings" aria-haspopup="true" aria-expanded="false">设置</button>
677
+ <button class="chip" type="button" id="btnSettings" aria-haspopup="true" aria-expanded="false" data-i18n="settings">Settings</button>
660
678
  <div class="panel" id="chatSettings" hidden>
661
- <h3>设置</h3>
679
+ <h3 data-i18n="settings">Settings</h3>
662
680
  <label class="field">
663
- <span class="field-label">访问令牌(可选)</span>
664
- <input id="inTokenChat" class="input" type="password" placeholder="服务器要求时填写" autocomplete="off" spellcheck="false">
681
+ <span class="field-label" data-i18n="tokenOptional">Access token (optional)</span>
682
+ <input id="inTokenChat" class="input" type="password" placeholder="Enter if the server requires it" data-i18n-placeholder="tokenPlaceholder" autocomplete="off" spellcheck="false">
665
683
  </label>
666
- <button class="btn ghost small" type="button" data-token-save="inTokenChat">保存</button>
667
- <p id="tokenHint" class="hint" hidden>服务器要求访问令牌(401)。</p>
684
+ <button class="btn ghost small" type="button" data-token-save="inTokenChat" data-i18n="save">Save</button>
685
+ <p id="tokenHint" class="hint" data-i18n="tokenRequired" hidden>The server requires an access token (401).</p>
668
686
  </div>
669
687
  </div>
670
- <button class="chip danger" type="button" id="btnLeave">离开</button>
688
+ <button class="chip danger" type="button" id="btnLeave" data-i18n="leave">Leave</button>
671
689
  </div>
672
690
  </header>
673
691
 
674
692
  <div id="connBar" class="conn-bar" hidden aria-live="polite">
675
693
  <span class="pulse"></span>
676
- <span>连接中断,正在重试…</span>
694
+ <span data-i18n="reconnecting">Connection lost. Retrying…</span>
677
695
  </div>
678
696
 
679
697
  <div id="msgScroll" class="msg-scroll">
680
698
  <div id="thread" class="thread">
681
- <ul id="msgList" aria-label="消息列表"></ul>
682
- <p id="msgEmpty" class="chat-empty">还没有消息,说点什么吧。</p>
699
+ <ul id="msgList" aria-label="Message list" data-i18n-aria-label="messageList"></ul>
700
+ <p id="msgEmpty" class="chat-empty" data-i18n="noMessages">No messages yet. Say something.</p>
683
701
  </div>
684
- <button type="button" id="btnJump" class="jump" aria-label="回到最新消息" hidden>
702
+ <button type="button" id="btnJump" class="jump" aria-label="Back to latest messages" data-i18n-aria-label="latestMessages" hidden>
685
703
  <span aria-hidden="true">↓</span><span class="badge" id="jumpBadge" hidden></span>
686
704
  </button>
687
705
  </div>
688
706
 
689
707
  <footer class="composer">
690
708
  <p id="sendError" class="send-error" role="alert" hidden></p>
691
- <div id="mentionPicker" class="mention-picker" role="listbox" aria-label="选择要提及的成员" hidden></div>
709
+ <div id="mentionPicker" class="mention-picker" role="listbox" aria-label="Choose a member to mention" data-i18n-aria-label="mentionMembers" hidden></div>
692
710
  <div class="composer-row">
693
- <textarea id="msgInput" class="input" rows="1" placeholder="输入消息,Enter 发送,Shift+Enter 换行" autocomplete="off" aria-autocomplete="list" aria-controls="mentionPicker" aria-expanded="false" disabled></textarea>
694
- <button class="btn primary" type="button" id="btnSend" disabled>发送</button>
711
+ <textarea id="msgInput" class="input" rows="1" placeholder="Type a message, Enter to send, Shift+Enter for a new line" data-i18n-placeholder="messagePlaceholder" autocomplete="off" aria-autocomplete="list" aria-controls="mentionPicker" aria-expanded="false" disabled></textarea>
712
+ <button class="btn primary" type="button" id="btnSend" data-i18n="send" disabled>Send</button>
695
713
  </div>
696
714
  </footer>
697
715
  </section>
@@ -713,6 +731,19 @@
713
731
  try { if (v == null) localStorage.removeItem(k); else localStorage.setItem(k, v); }
714
732
  catch { if (v == null) delete memStore[k]; else memStore[k] = v; }
715
733
  }
734
+ function newSessionID() {
735
+ const webCrypto = globalThis.crypto;
736
+ if (typeof webCrypto?.randomUUID === "function") return webCrypto.randomUUID();
737
+ const bytes = new Uint8Array(16);
738
+ if (typeof webCrypto?.getRandomValues !== "function") {
739
+ throw new Error("Secure session ID generation is unavailable");
740
+ }
741
+ webCrypto.getRandomValues(bytes);
742
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
743
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
744
+ const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
745
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
746
+ }
716
747
  const LS = {
717
748
  get sessionID() {
718
749
  // ponytail: sessionID 必须 tab 级独立(sessionStorage)——localStorage
@@ -721,7 +752,7 @@
721
752
  let v = null;
722
753
  try { v = sessionStorage.getItem("chat.sessionID"); } catch { /* ignore */ }
723
754
  if (!v) {
724
- v = crypto.randomUUID();
755
+ v = newSessionID();
725
756
  try { sessionStorage.setItem("chat.sessionID", v); } catch { /* ignore */ }
726
757
  }
727
758
  return v;
@@ -732,8 +763,190 @@
732
763
  set name(v) { lsSet("chat.name", v || null); },
733
764
  get token() { return lsGet("chat.token") || ""; },
734
765
  set token(v) { lsSet("chat.token", v || null); },
766
+ get locale() { return lsGet("chat.locale") || "en"; },
767
+ set locale(v) { lsSet("chat.locale", v || null); },
735
768
  };
736
769
 
770
+ const I18N = {
771
+ en: {
772
+ brand: "Casual Chat",
773
+ documentTitle: "Casual Chat · Lightweight Chatroom",
774
+ roomTitle: "{name} · Casual Chat",
775
+ tagline: "A lightweight chat room. Enter a room ID to join, or create a new one.",
776
+ languageLabel: "Language",
777
+ roomIdLabel: "Room ID",
778
+ roomIdPlaceholder: "Paste or enter a room ID",
779
+ nameLabel: "Your name",
780
+ namePlaceholder: "What should we call you?",
781
+ joinRoom: "Join room",
782
+ or: "or",
783
+ newRoomNameLabel: "New room name",
784
+ newRoomNamePlaceholder: "e.g. Weekend movie night",
785
+ createRoom: "Create room",
786
+ tokenOptional: "Access token (optional)",
787
+ bearerToken: "Bearer Token",
788
+ tokenPlaceholder: "Enter if the server requires it",
789
+ save: "Save",
790
+ tokenHint: "If the server requires an access token (401), all requests will include it.",
791
+ existingRooms: "Existing rooms",
792
+ noRooms: "No rooms yet. Create one.",
793
+ copyRoomId: "Copy room ID",
794
+ copyRoomIdTitle: "Click to copy the full room ID: {id}",
795
+ copied: "Copied",
796
+ members: "Members",
797
+ membersCount: ({ count }) => `Members (${count})`,
798
+ noMembers: "No members yet.",
799
+ settings: "Settings",
800
+ tokenRequired: "The server requires an access token (401).",
801
+ leave: "Leave",
802
+ reconnecting: "Connection lost. Retrying…",
803
+ messageList: "Message list",
804
+ noMessages: "No messages yet. Say something.",
805
+ latestMessages: "Back to latest messages",
806
+ mentionMembers: "Choose a member to mention",
807
+ messagePlaceholder: "Type a message, Enter to send, Shift+Enter for a new line",
808
+ send: "Send",
809
+ roomMeta: ({ members, messages }) => `${members} ${members === 1 ? "member" : "members"} · ${messages} ${messages === 1 ? "message" : "messages"}`,
810
+ joinArrow: "Join →",
811
+ joinDirectTitle: "Click to join directly",
812
+ mentionEmpty: "No matching members",
813
+ mentionHint: "↑↓ Select · Enter to confirm · Esc to close",
814
+ today: "Today",
815
+ yesterday: "Yesterday",
816
+ earlierMessages: "Earlier messages omitted",
817
+ you: "You",
818
+ systemJoined: "{name} joined the room",
819
+ systemLeft: "{name} left the room",
820
+ saved: "Saved",
821
+ copyFailed: "Copy failed; please copy the room ID manually: {id}",
822
+ networkError: "Network connection failed",
823
+ requestFailed: "Request failed (HTTP {status})",
824
+ roomIdRequired: "Enter a room ID",
825
+ nameRequired: "Enter your name",
826
+ authRetry: "The server requires an access token. Enter it and try again.",
827
+ networkRetry: "Unable to connect to the server. Check your network and try again.",
828
+ joinFailed: "Could not join: {message}",
829
+ roomNameRequired: "Enter a room name",
830
+ createFailed: "Could not create the room: {message}",
831
+ roomNotFound: "The room no longer exists or was deleted",
832
+ sendAuth: "Send failed: an access token is required",
833
+ sendNetwork: "Send failed: the network connection was lost. Your message was kept; try again later",
834
+ sendFailed: "Send failed: {message}",
835
+ roomListError: "Unable to load the room list. You can enter a room ID directly.",
836
+ guest: "Guest",
837
+ },
838
+ "zh-CN": {
839
+ brand: "闲叙",
840
+ documentTitle: "闲叙 · 轻量聊天室",
841
+ roomTitle: "{name} · 闲叙",
842
+ tagline: "一个轻量的聊天房间。输入房间 ID 加入,或直接新建一个。",
843
+ languageLabel: "语言",
844
+ roomIdLabel: "房间 ID",
845
+ roomIdPlaceholder: "粘贴或输入房间 ID",
846
+ nameLabel: "你的昵称",
847
+ namePlaceholder: "怎么称呼你",
848
+ joinRoom: "加入房间",
849
+ or: "或",
850
+ newRoomNameLabel: "新房间名称",
851
+ newRoomNamePlaceholder: "例如:周末电影夜",
852
+ createRoom: "创建新房间",
853
+ tokenOptional: "访问令牌(可选)",
854
+ bearerToken: "Bearer Token",
855
+ tokenPlaceholder: "服务器要求时填写",
856
+ save: "保存",
857
+ tokenHint: "若服务器设置了访问令牌(401),所有请求都会带上它。",
858
+ existingRooms: "已有房间",
859
+ noRooms: "还没有房间,创建一个吧。",
860
+ copyRoomId: "复制房间 ID",
861
+ copyRoomIdTitle: "点击复制完整房间 ID:{id}",
862
+ copied: "已复制",
863
+ members: "成员",
864
+ membersCount: ({ count }) => `成员 ${count}`,
865
+ noMembers: "暂无成员",
866
+ settings: "设置",
867
+ tokenRequired: "服务器要求访问令牌(401)。",
868
+ leave: "离开",
869
+ reconnecting: "连接中断,正在重试…",
870
+ messageList: "消息列表",
871
+ noMessages: "还没有消息,说点什么吧。",
872
+ latestMessages: "回到最新消息",
873
+ mentionMembers: "选择要提及的成员",
874
+ messagePlaceholder: "输入消息,Enter 发送,Shift+Enter 换行",
875
+ send: "发送",
876
+ roomMeta: ({ members, messages }) => `${members} 人 · ${messages} 条消息`,
877
+ joinArrow: "加入 →",
878
+ joinDirectTitle: "点击直接加入",
879
+ mentionEmpty: "没有匹配的成员",
880
+ mentionHint: "↑↓ 选择 · Enter 确认 · Esc 关闭",
881
+ today: "今天",
882
+ yesterday: "昨天",
883
+ earlierMessages: "更早的消息已省略",
884
+ you: "我",
885
+ systemJoined: "{name} 加入了房间",
886
+ systemLeft: "{name} 离开了房间",
887
+ saved: "已保存",
888
+ copyFailed: "复制失败,请手动复制房间 ID:{id}",
889
+ networkError: "网络连接失败",
890
+ requestFailed: "请求失败(HTTP {status})",
891
+ roomIdRequired: "请输入房间 ID",
892
+ nameRequired: "请输入你的昵称",
893
+ authRetry: "服务器要求访问令牌,请填写后重试",
894
+ networkRetry: "无法连接服务器,请检查网络后重试",
895
+ joinFailed: "加入失败:{message}",
896
+ roomNameRequired: "请输入房间名称",
897
+ createFailed: "创建失败:{message}",
898
+ roomNotFound: "房间不存在或已被删除",
899
+ sendAuth: "发送失败:需要访问令牌",
900
+ sendNetwork: "发送失败:网络连接中断,消息已保留,可稍后重试",
901
+ sendFailed: "发送失败:{message}",
902
+ roomListError: "无法加载房间列表,可直接输入房间 ID 加入。",
903
+ guest: "访客",
904
+ },
905
+ };
906
+
907
+ function normalizeLocale(value) { return value === "zh-CN" ? "zh-CN" : "en"; }
908
+ let locale = normalizeLocale(LS.locale);
909
+ const intlLocale = () => locale === "zh-CN" ? "zh-CN" : "en-US";
910
+ function t(key, vars = {}) {
911
+ const value = I18N[locale][key] ?? I18N.en[key] ?? key;
912
+ const text = typeof value === "function" ? value(vars) : value;
913
+ return String(text).replace(/\{(\w+)\}/g, (_, name) => vars[name] ?? "");
914
+ }
915
+
916
+ function setI18nText(el, key, vars = {}) {
917
+ el.dataset.i18n = key;
918
+ el._i18nVars = vars;
919
+ el.textContent = t(key, vars);
920
+ }
921
+
922
+ function applyLocale() {
923
+ document.documentElement.lang = locale;
924
+ document.querySelectorAll("[data-i18n]").forEach((el) => {
925
+ el.textContent = el._flashKey ? t(el._flashKey) : t(el.dataset.i18n, el._i18nVars || {});
926
+ });
927
+ for (const attr of ["aria-label", "title", "placeholder"]) {
928
+ document.querySelectorAll(`[data-i18n-${attr}]`).forEach((el) => {
929
+ el.setAttribute(attr, t(el.getAttribute(`data-i18n-${attr}`), el._i18nVars || {}));
930
+ });
931
+ }
932
+ document.querySelectorAll(".locale-select").forEach((select) => { select.value = locale; });
933
+ MENTION_HINT.textContent = t("mentionHint");
934
+ if (mention.active) updateMentionList(mention.query);
935
+ if (state.room) {
936
+ renderHead();
937
+ renderMembers();
938
+ rerenderMessages();
939
+ } else {
940
+ updateTitle();
941
+ }
942
+ }
943
+
944
+ function setLocale(next) {
945
+ locale = normalizeLocale(next);
946
+ LS.locale = locale;
947
+ applyLocale();
948
+ }
949
+
737
950
  /* ---------- 请求 ---------- */
738
951
  async function api(path, opts = {}) {
739
952
  const headers = {};
@@ -743,13 +956,13 @@
743
956
  try {
744
957
  res = await fetch(path, { ...opts, headers });
745
958
  } catch {
746
- const e = new Error("网络连接失败");
959
+ const e = new Error(t("networkError"));
747
960
  e.network = true;
748
961
  throw e;
749
962
  }
750
963
  const data = await res.json().catch(() => ({}));
751
964
  if (!res.ok) {
752
- const e = new Error(data.error || `请求失败(HTTP ${res.status})`);
965
+ const e = new Error(data.error || t("requestFailed", { status: res.status }));
753
966
  e.status = res.status;
754
967
  throw e;
755
968
  }
@@ -766,13 +979,15 @@
766
979
  /* ---------- 工具 ---------- */
767
980
  function fmtTime(ts) {
768
981
  const d = new Date(ts);
769
- const hm = d.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" });
982
+ const hm = d.toLocaleTimeString(intlLocale(), { hour: "2-digit", minute: "2-digit" });
770
983
  const sameDay = d.toDateString() === new Date().toDateString();
771
- return sameDay ? `今天 ${hm}` : `${d.getMonth() + 1}月${d.getDate()}日 ${hm}`;
984
+ return sameDay ? `${t("today")} ${hm}` : new Intl.DateTimeFormat(intlLocale(), {
985
+ month: "short", day: "numeric", hour: "2-digit", minute: "2-digit",
986
+ }).format(d);
772
987
  }
773
988
 
774
989
  function timeHM(ts) {
775
- return new Date(ts).toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" });
990
+ return new Date(ts).toLocaleTimeString(intlLocale(), { hour: "2-digit", minute: "2-digit" });
776
991
  }
777
992
 
778
993
  function dayText(ts) {
@@ -781,21 +996,28 @@
781
996
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
782
997
  const that = new Date(d.getFullYear(), d.getMonth(), d.getDate());
783
998
  const diff = Math.round((today - that) / 86400000);
784
- if (diff === 0) return "今天";
785
- if (diff === 1) return "昨天";
786
- return `${d.getMonth() + 1}月${d.getDate()}日`;
999
+ if (diff === 0) return t("today");
1000
+ if (diff === 1) return t("yesterday");
1001
+ return new Intl.DateTimeFormat(intlLocale(), { month: "short", day: "numeric" }).format(d);
787
1002
  }
788
1003
 
789
1004
  function fmtSys(text) {
790
- return String(text)
791
- .replace(/^(.*?)\s+joined the room$/, "$1 加入了房间")
792
- .replace(/^(.*?)\s+left the room$/, "$1 离开了房间");
1005
+ const value = String(text);
1006
+ const joined = /^(.*?)\s+joined the room$/.exec(value);
1007
+ if (joined) return t("systemJoined", { name: joined[1] });
1008
+ const left = /^(.*?)\s+left the room$/.exec(value);
1009
+ if (left) return t("systemLeft", { name: left[1] });
1010
+ return value;
793
1011
  }
794
1012
 
795
- function flash(btn, msg) {
796
- const old = btn.textContent;
797
- btn.textContent = msg;
798
- setTimeout(() => { btn.textContent = old; }, 1200);
1013
+ function flash(btn, key) {
1014
+ btn._flashKey = key;
1015
+ btn.textContent = t(key);
1016
+ setTimeout(() => {
1017
+ if (btn._flashKey !== key) return;
1018
+ delete btn._flashKey;
1019
+ btn.textContent = t(btn.dataset.i18n, btn._i18nVars || {});
1020
+ }, 1200);
799
1021
  }
800
1022
 
801
1023
  /* ---------- 发送框 ---------- */
@@ -826,7 +1048,7 @@
826
1048
  updateTitle();
827
1049
  }
828
1050
  function updateTitle() {
829
- const base = state.room ? `${state.room.name} · 闲叙` : "闲叙 · 轻量聊天室";
1051
+ const base = state.room ? t("roomTitle", { name: state.room.name }) : t("documentTitle");
830
1052
  document.title = state.unread > 0 ? `(${state.unread}) ${base}` : base;
831
1053
  }
832
1054
 
@@ -839,7 +1061,7 @@
839
1061
  if (list.firstElementChild && !list.firstElementChild.classList.contains("gap")) {
840
1062
  const gap = document.createElement("li");
841
1063
  gap.className = "gap";
842
- gap.textContent = "更早的消息已省略";
1064
+ setI18nText(gap, "earlierMessages");
843
1065
  list.insertBefore(gap, list.firstChild);
844
1066
  }
845
1067
  }
@@ -864,7 +1086,10 @@
864
1086
  ta.style.opacity = "0";
865
1087
  document.body.appendChild(ta);
866
1088
  ta.select();
867
- try { document.execCommand("copy"); done(); } catch { /* 忽略 */ }
1089
+ let copied = false;
1090
+ try { copied = document.execCommand("copy"); } catch { /* ignore */ }
1091
+ if (copied) done();
1092
+ else showSendError("copyFailed", { id: text });
868
1093
  ta.remove();
869
1094
  }
870
1095
 
@@ -882,9 +1107,9 @@
882
1107
  }
883
1108
 
884
1109
  /* ---------- 加入 / 创建 ---------- */
885
- function showJoinError(msg) {
1110
+ function showJoinError(key, vars = {}) {
886
1111
  const el = $("#joinError");
887
- el.textContent = msg;
1112
+ setI18nText(el, key, vars);
888
1113
  el.hidden = false;
889
1114
  }
890
1115
  function hideJoinError() { $("#joinError").hidden = true; }
@@ -896,8 +1121,8 @@
896
1121
  function joinRoom() {
897
1122
  const roomId = $("#inRoomId").value.trim();
898
1123
  const name = $("#inName").value.trim();
899
- if (!roomId) return showJoinError("请输入房间 ID");
900
- if (!name) return showJoinError("请输入你的昵称");
1124
+ if (!roomId) return showJoinError("roomIdRequired");
1125
+ if (!name) return showJoinError("nameRequired");
901
1126
  doJoin(roomId, name);
902
1127
  }
903
1128
 
@@ -911,9 +1136,9 @@
911
1136
  });
912
1137
  enterRoom(room, name);
913
1138
  } catch (e) {
914
- if (e.status === 401) { openTokenBox(); showJoinError("服务器要求访问令牌,请填写后重试"); }
915
- else if (e.network) showJoinError("无法连接服务器,请检查网络后重试");
916
- else showJoinError(`加入失败:${e.message}`);
1139
+ if (e.status === 401) { openTokenBox(); showJoinError("authRetry"); }
1140
+ else if (e.network) showJoinError("networkRetry");
1141
+ else showJoinError("joinFailed", { message: e.message });
917
1142
  } finally {
918
1143
  setJoinBusy(false);
919
1144
  }
@@ -921,8 +1146,8 @@
921
1146
 
922
1147
  async function createRoom() {
923
1148
  const roomName = $("#inRoomName").value.trim();
924
- const displayName = $("#inName").value.trim() || "访客";
925
- if (!roomName) return showJoinError("请输入房间名称");
1149
+ const displayName = $("#inName").value.trim() || t("guest");
1150
+ if (!roomName) return showJoinError("roomNameRequired");
926
1151
  setJoinBusy(true);
927
1152
  hideJoinError();
928
1153
  try {
@@ -932,9 +1157,9 @@
932
1157
  });
933
1158
  enterRoom(room, displayName);
934
1159
  } catch (e) {
935
- if (e.status === 401) { openTokenBox(); showJoinError("服务器要求访问令牌,请填写后重试"); }
936
- else if (e.network) showJoinError("无法连接服务器,请检查网络后重试");
937
- else showJoinError(`创建失败:${e.message}`);
1160
+ if (e.status === 401) { openTokenBox(); showJoinError("authRetry"); }
1161
+ else if (e.network) showJoinError("networkRetry");
1162
+ else showJoinError("createFailed", { message: e.message });
938
1163
  } finally {
939
1164
  setJoinBusy(false);
940
1165
  }
@@ -964,7 +1189,9 @@
964
1189
  function renderHead() {
965
1190
  $("#roomName").textContent = state.room.name;
966
1191
  $("#roomIdShort").textContent = state.room.id.slice(0, 8);
967
- $("#btnCopyId").title = `复制完整房间 ID:${state.room.id}`;
1192
+ const copy = $("#btnCopyId");
1193
+ copy.setAttribute("aria-label", t("copyRoomId"));
1194
+ copy.title = t("copyRoomIdTitle", { id: state.room.id });
968
1195
  updateTitle();
969
1196
  }
970
1197
 
@@ -986,7 +1213,7 @@
986
1213
  meta.className = "msg-meta";
987
1214
  const nm = document.createElement("span");
988
1215
  nm.className = "msg-name";
989
- nm.textContent = own ? "我" : m.senderId;
1216
+ nm.textContent = own ? t("you") : m.senderId;
990
1217
  const tm = document.createElement("span");
991
1218
  tm.className = "msg-time";
992
1219
  tm.textContent = timeHM(m.createdAt);
@@ -1086,9 +1313,26 @@
1086
1313
  return { skipped };
1087
1314
  }
1088
1315
 
1316
+ function rerenderMessages() {
1317
+ if (!state.room) return;
1318
+ const scroll = $("#thread");
1319
+ const oldHeight = scroll.scrollHeight;
1320
+ const oldTop = scroll.scrollTop;
1321
+ const atBottom = oldHeight - oldTop - scroll.clientHeight < 80;
1322
+ $("#msgList").textContent = "";
1323
+ state.rendered = 0;
1324
+ state.firstMsgId = null;
1325
+ failedRenderIds.clear();
1326
+ appendMessages(false);
1327
+ scroll.scrollTop = atBottom
1328
+ ? scroll.scrollHeight
1329
+ : Math.max(0, oldTop + scroll.scrollHeight - oldHeight);
1330
+ updateJump();
1331
+ }
1332
+
1089
1333
  function renderMembers() {
1090
1334
  const parts = state.room.participants || [];
1091
- $("#btnMembers").textContent = `成员 ${parts.length}`;
1335
+ setI18nText($("#btnMembers"), "membersCount", { count: parts.length });
1092
1336
  const list = $("#memberList");
1093
1337
  list.textContent = "";
1094
1338
  for (const p of parts) {
@@ -1143,7 +1387,7 @@
1143
1387
  if (!state.room || state.room.id !== roomId) return;
1144
1388
  if (!data.member) {
1145
1389
  leaveRoom(true);
1146
- showJoinError("房间不存在或已被删除");
1390
+ showJoinError("roomNotFound");
1147
1391
  return;
1148
1392
  }
1149
1393
  const items = Array.isArray(data.items) ? data.items : [];
@@ -1219,7 +1463,7 @@
1219
1463
  pollDelay = Math.min(pollDelay * 2, 30000); // 配置问题——退避
1220
1464
  } else if (e.status === 404) {
1221
1465
  leaveRoom(true);
1222
- showJoinError("房间不存在或已被删除");
1466
+ showJoinError("roomNotFound");
1223
1467
  return;
1224
1468
  } else {
1225
1469
  setOnline(false); // 网络/服务器重启等暂时性错误——固定 2s 快速重试
@@ -1306,13 +1550,14 @@
1306
1550
  input.value = text; // 失败时把消息还回来,提示重试
1307
1551
  autoGrow(input);
1308
1552
  updateSendState();
1309
- if (e.status === 401) { openChatSettings(); showSendError("发送失败:需要访问令牌"); }
1310
- else showSendError(e.network ? "发送失败:网络连接中断,消息已保留,可稍后重试" : `发送失败:${e.message}`);
1553
+ if (e.status === 401) { openChatSettings(); showSendError("sendAuth"); }
1554
+ else if (e.network) showSendError("sendNetwork");
1555
+ else showSendError("sendFailed", { message: e.message });
1311
1556
  });
1312
1557
  }
1313
- function showSendError(msg) {
1558
+ function showSendError(key, vars = {}) {
1314
1559
  const el = $("#sendError");
1315
- el.textContent = msg;
1560
+ setI18nText(el, key, vars);
1316
1561
  el.hidden = false;
1317
1562
  }
1318
1563
  function hideSendError() { $("#sendError").hidden = true; }
@@ -1347,7 +1592,7 @@
1347
1592
  async function refreshRoomList() {
1348
1593
  const list = $("#roomList");
1349
1594
  const empty = $("#roomListEmpty");
1350
- empty.textContent = "还没有房间,创建一个吧。";
1595
+ setI18nText(empty, "noRooms");
1351
1596
  try {
1352
1597
  const rooms = await api("/rooms");
1353
1598
  list.textContent = "";
@@ -1357,20 +1602,21 @@
1357
1602
  const btn = document.createElement("button");
1358
1603
  btn.type = "button";
1359
1604
  btn.className = "room-row";
1360
- btn.title = "点击直接加入";
1605
+ btn.dataset.i18nTitle = "joinDirectTitle";
1606
+ btn.title = t("joinDirectTitle");
1361
1607
  const nm = document.createElement("span");
1362
1608
  nm.className = "r-name";
1363
1609
  nm.textContent = r.name;
1364
1610
  const meta = document.createElement("span");
1365
1611
  meta.className = "r-meta";
1366
- meta.textContent = `${r.participants.length} 人 · ${r.messages.length} 条消息`;
1612
+ setI18nText(meta, "roomMeta", { members: r.participants.length, messages: r.messages.length });
1367
1613
  const go = document.createElement("span");
1368
1614
  go.className = "r-go";
1369
- go.textContent = "加入 →";
1615
+ setI18nText(go, "joinArrow");
1370
1616
  btn.append(nm, meta, go);
1371
1617
  btn.addEventListener("click", () => {
1372
1618
  $("#inRoomId").value = r.id;
1373
- doJoin(r.id, $("#inName").value.trim() || "访客"); // 一键加入,昵称未填则用“访客”
1619
+ doJoin(r.id, $("#inName").value.trim() || t("guest")); // Use the localized guest name when no nickname is entered.
1374
1620
  });
1375
1621
  li.appendChild(btn);
1376
1622
  list.appendChild(li);
@@ -1380,7 +1626,7 @@
1380
1626
  else {
1381
1627
  // 网络失败:加入/创建仍可用,列表给个说明
1382
1628
  empty.hidden = false;
1383
- empty.textContent = "无法加载房间列表,可直接输入房间 ID 加入。";
1629
+ setI18nText(empty, "roomListError");
1384
1630
  }
1385
1631
  }
1386
1632
  }
@@ -1420,7 +1666,7 @@
1420
1666
  const MENTION_RE = /<at>@([^<]+)<\/at>/g;
1421
1667
  const MENTION_HINT = document.createElement("p");
1422
1668
  MENTION_HINT.className = "mention-hint";
1423
- MENTION_HINT.textContent = "↑↓ 选择 · Enter 确认 · Esc 关闭";
1669
+ MENTION_HINT.textContent = t("mentionHint");
1424
1670
 
1425
1671
  // Markdown 最小子集渲染:粗体 / 斜体 / 行内代码 / 链接 / 围栏代码 / 列表 / 引用。
1426
1672
  // 全部用 DOM API + textContent 构建,不用 innerHTML;任何未闭合或畸形的标记
@@ -1657,7 +1903,7 @@
1657
1903
  if (!mention.items.length) {
1658
1904
  const empty = document.createElement("p");
1659
1905
  empty.className = "mention-empty";
1660
- empty.textContent = "没有匹配的成员";
1906
+ empty.textContent = t("mentionEmpty");
1661
1907
  picker.appendChild(empty);
1662
1908
  }
1663
1909
  picker.appendChild(MENTION_HINT);
@@ -1728,6 +1974,9 @@
1728
1974
 
1729
1975
  /* ---------- 事件 ---------- */
1730
1976
  function wireEvents() {
1977
+ document.querySelectorAll(".locale-select").forEach((select) => {
1978
+ select.addEventListener("change", () => setLocale(select.value));
1979
+ });
1731
1980
  $("#joinForm").addEventListener("submit", (e) => { e.preventDefault(); joinRoom(); });
1732
1981
  $("#createForm").addEventListener("submit", (e) => { e.preventDefault(); createRoom(); });
1733
1982
  $("#btnSend").addEventListener("click", send);
@@ -1804,7 +2053,9 @@
1804
2053
  input.value = LS.token;
1805
2054
  $("#inToken").value = LS.token;
1806
2055
  $("#inTokenChat").value = LS.token;
1807
- flash(save, "已保存");
2056
+ flash(save, "saved");
2057
+ void refreshRoomList();
2058
+ if (!state.room) void autoJoin();
1808
2059
  return;
1809
2060
  }
1810
2061
  if (mention.active && !e.target.closest("#mentionPicker")) closeMention();
@@ -1836,17 +2087,21 @@
1836
2087
  });
1837
2088
  enterRoom(room, name);
1838
2089
  } catch (e) {
1839
- LS.roomId = "";
1840
- LS.name = "";
1841
- if (e.status === 401) openTokenBox();
1842
- else if (e.status === 404) showJoinError("上次的房间已不存在");
1843
- else if (e.network) showJoinError("无法连接服务器,请检查网络后重试");
2090
+ if (e.status === 401) { openTokenBox(); showJoinError("authRetry"); }
2091
+ else if (e.status === 404) {
2092
+ LS.roomId = "";
2093
+ LS.name = "";
2094
+ showJoinError("roomNotFound");
2095
+ }
2096
+ else if (e.network) showJoinError("networkRetry");
2097
+ else showJoinError("joinFailed", { message: e.message });
1844
2098
  }
1845
2099
  }
1846
2100
 
1847
2101
  $("#inToken").value = LS.token;
1848
2102
  $("#inTokenChat").value = LS.token;
1849
2103
  wireEvents();
2104
+ applyLocale();
1850
2105
  refreshRoomList();
1851
2106
  autoJoin();
1852
2107
  $("#inRoomId").focus();