@alexsun-top/opencode-chat-room 0.7.6 → 0.7.8

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.
Files changed (78) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +5 -5
  3. package/README.zh-CN.md +5 -5
  4. package/dist/cli.js +815 -192
  5. package/package.json +3 -2
  6. package/plugin.ts +15 -3
  7. package/server/assets/base.css +0 -2
  8. package/server/assets/chat/announcements.js +5 -2
  9. package/server/assets/chat/clipboard.js +30 -0
  10. package/server/assets/chat/copy-action.js +48 -0
  11. package/server/assets/chat/diagram-viewer.js +253 -0
  12. package/server/assets/chat/doc-preview.js +160 -13
  13. package/server/assets/chat/editor.js +10 -7
  14. package/server/assets/chat/events.js +26 -5
  15. package/server/assets/chat/files.js +26 -5
  16. package/server/assets/chat/history-loader.js +3 -1
  17. package/server/assets/chat/index.js +11 -1
  18. package/server/assets/chat/join-requests.js +6 -3
  19. package/server/assets/chat/locales/de.js +20 -2
  20. package/server/assets/chat/locales/es.js +20 -2
  21. package/server/assets/chat/locales/fr.js +20 -2
  22. package/server/assets/chat/locales/it.js +20 -2
  23. package/server/assets/chat/locales/ja.js +20 -2
  24. package/server/assets/chat/locales/ko.js +20 -2
  25. package/server/assets/chat/markdown.js +75 -86
  26. package/server/assets/chat/messages.js +7 -3
  27. package/server/assets/chat/palette.js +40 -18
  28. package/server/assets/chat/pwa.js +2 -0
  29. package/server/assets/chat/questions.js +6 -0
  30. package/server/assets/chat/resource-format.js +74 -0
  31. package/server/assets/chat/rooms.js +9 -1
  32. package/server/assets/chat/shortcuts.js +14 -3
  33. package/server/assets/chat/side-pane.js +136 -0
  34. package/server/assets/chat/state.js +85 -8
  35. package/server/assets/chat/system-messages.js +3 -1
  36. package/server/assets/chat/task-form.js +197 -0
  37. package/server/assets/chat/task-row.js +170 -0
  38. package/server/assets/chat/tasks.js +521 -0
  39. package/server/assets/chat/viewport.js +5 -0
  40. package/server/assets/conversation.css +25 -1
  41. package/server/assets/diagram-viewer.css +141 -0
  42. package/server/assets/doc-preview.css +24 -5
  43. package/server/assets/responsive.css +108 -14
  44. package/server/assets/tasks.css +419 -0
  45. package/server/chat-server.ts +9 -4
  46. package/server/chat.html +120 -21
  47. package/server/member-routes.ts +3 -0
  48. package/server/resource-routes.ts +3 -1
  49. package/server/sw.js +247 -4
  50. package/server/task-routes.ts +53 -0
  51. package/skills/chatroom/SKILL.md +3 -1
  52. package/src/README.md +3 -3
  53. package/src/agent/chatroom-skill.ts +8 -2
  54. package/src/agent/task-tool.ts +155 -0
  55. package/src/center/center-client.ts +44 -0
  56. package/src/rooms/resources.ts +2 -2
  57. package/src/rooms/tasks.ts +246 -0
  58. package/src/runtime/v2-plugin.ts +11 -2
  59. package/src/runtime/watch.ts +38 -5
  60. package/src/state/sqlite-state.ts +93 -8
  61. package/src/state/store.ts +2 -2
  62. package/src/tui/app.mjs +14 -4
  63. package/src/tui/http.mjs +2 -2
  64. package/src/tui/info-app.mjs +24 -15
  65. package/src/tui/join-app.mjs +3 -3
  66. package/src/tui/main.mjs +4 -4
  67. package/src/tui/markdown.mjs +31 -5
  68. package/src/tui/mentions.mjs +218 -0
  69. package/src/tui/message-app.mjs +15 -11
  70. package/src/tui/palette-app.mjs +19 -9
  71. package/src/tui/reminder-app.mjs +14 -10
  72. package/src/tui/ui-content.mjs +12 -3
  73. package/src/tui/ui-mentions.mjs +44 -0
  74. package/src/tui/ui-suggest-view.mjs +63 -0
  75. package/src/tui/ui-suggest.mjs +197 -0
  76. package/src/tui/ui-theme.mjs +2 -1
  77. package/src/tui/ui-view.mjs +2 -0
  78. package/src/tui/ui.mjs +17 -9
@@ -43,7 +43,7 @@ export const fr = {
43
43
  reminderEdit: "Modifier", reminderEditHeading: "Modifier le rappel", reminderSave: "Enregistrer les modifications",
44
44
  reminderCreated: "Rappel créé.", reminderUpdated: "Rappel mis à jour.", reminderDeleted: "Rappel supprimé.",
45
45
  reminderInvalid: "Vérifiez la date, l’expression CRON à 5 champs, le fuseau IANA et le texte du rappel.", reminderLoadFailed: "Impossible de charger les rappels. Votre brouillon est toujours là.",
46
- diagramLoading: "Rendu du diagramme…", diagramRenderFailed: "Diagramme indisponible, affichage de sa source.", resourceLoading: "Chargement du fichier…", resourceFailed: "Impossible de charger ce fichier.", resourceDownload: "Télécharger", resourceMoreActions: "Plus d’actions pour {name}", resourcePreview: "Aperçu", resourceHide: "Masquer l’aperçu", docPreviewEyebrow: "Aperçu Markdown", docPreviewFailed: "Impossible de charger ce document.", docPreviewEmpty: "Ce document est vide.", zoomImage: "Ouvrir l’image", imagePreviewTitle: "Aperçu de l’image", imageZoomControls: "Zoom de l’image", zoomIn: "Zoom avant", zoomOut: "Zoom arrière", zoomReset: "Réinitialiser le zoom", installTitle: "Installer OC Chat", installBody: "Ajoutez-le à votre écran d’accueil pour discuter en plein écran.", installAction: "Installer", installHow: "Comment installer", installNotNow: "Plus tard", installIosGuide: "Touchez Partager, puis Ajouter à l’écran d’accueil.",
46
+ diagramLoading: "Rendu du diagramme…", diagramRenderFailed: "Diagramme indisponible, affichage de sa source.", resourceLoading: "Chargement du fichier…", resourceFailed: "Impossible de charger ce fichier.", resourceDownload: "Télécharger", resourceMoreActions: "Plus d’actions pour {name}", resourcePreview: "Aperçu", resourceHide: "Masquer l’aperçu", docPreviewEyebrow: "Aperçu Markdown", docPreviewFileEyebrow: "Aperçu du fichier", docPreviewFailed: "Impossible de charger ce document.", sidePaneResize: "Redimensionner le panneau latéral", docPreviewTooLarge: "Fichier trop volumineux pour l’aperçu (plus de 2 Mo). Téléchargez-le pour le consulter.", docPreviewEmpty: "Ce document est vide.", zoomImage: "Ouvrir l’image", imagePreviewTitle: "Aperçu de l’image", imageZoomControls: "Zoom de l’image", zoomIn: "Zoom avant", zoomOut: "Zoom arrière", zoomReset: "Réinitialiser le zoom", openDiagram: "Ouvrir le diagramme", diagramViewerTitle: "Diagramme", diagramZoomControls: "Zoom du diagramme", diagramFit: "Ajuster", installTitle: "Installer OC Chat", installBody: "Ajoutez-le à votre écran d’accueil pour discuter en plein écran.", installAction: "Installer", installHow: "Comment installer", installNotNow: "Plus tard", installIosGuide: "Touchez Partager, puis Ajouter à l’écran d’accueil.",
47
47
  pwaUpdateTitle: "Mise à jour disponible", pwaUpdateBody: "Une nouvelle version est prête. Rechargez maintenant ou mettez à jour à la prochaine ouverture de l’application.", pwaUpdateNow: "Mettre à jour", pwaUpdateLater: "Plus tard",
48
48
  announcementDelete: "Supprimer l’annonce",
49
49
  announcementNew: "Nouvelle annonce", announcementEmpty: "Aucune annonce pour l’instant.", announcementLoading: "Chargement des annonces…",
@@ -94,10 +94,28 @@ export const fr = {
94
94
  filesUnknownUploader: "Envoyeur inconnu", filesSummary: ({ count, size }) => `${count} fichier${count === 1 ? "" : "s"} · ${size}`,
95
95
  filesLoading: "Chargement des fichiers…", filesLoadFailed: "Impossible de charger les fichiers. Réessayez.", filesEmpty: "Ce salon n’a pas encore de fichiers.",
96
96
  filesEmptyFiltered: "Aucun fichier de cet envoyeur.", filesLoadMore: "Charger plus",
97
- filesHint: "Prévisualisez les images, l’audio, la vidéo et Markdown. Tous les fichiers peuvent être téléchargés.",
97
+ filesHint: "Prévisualisez les images, l’audio, la vidéo, Markdown, le texte, le code et les PDF. Tous les fichiers peuvent être téléchargés.",
98
98
  filesPreviewFailed: "Impossible de charger cet aperçu.", filesDownloadFailed: "Impossible de télécharger ce fichier.",
99
99
  filesPreviewLabel: ({ name }) => `Aperçu de ${name}`, filesDownloadLabel: ({ name }) => `Télécharger ${name}`,
100
100
  filesDeleteLabel: ({ name }) => `Supprimer ${name}`, filesRefresh: "Actualiser les fichiers",
101
+ tasksTitle: "Tâches", tasksEyebrow: "Tâches du salon", tasksRefresh: "Actualiser les tâches", tasksMenuLabel: "Actions des tâches",
102
+ tasksClearCompleted: "Effacer les tâches terminées", tasksClearConfirm: ({ count }) => `Effacer ${count} tâche${count === 1 ? "" : "s"} terminée${count === 1 ? "" : "s"} ? Cette action est irréversible.`,
103
+ tasksClearFailed: "Impossible d’effacer les tâches terminées. Réessayez.",
104
+ tasksLoading: "Chargement des tâches…", tasksLoadFailed: "Impossible de charger les tâches. Réessayez.", tasksEmpty: "Aucune tâche pour l’instant. Ajoutez la première.",
105
+ tasksEmptyFiltered: "Aucune tâche avec ce statut.", tasksCreate: "Ajouter une tâche", tasksTitleLabel: "Titre",
106
+ tasksTitlePlaceholder: "Que faut-il faire ?", tasksDescriptionLabel: "Description", tasksDescriptionPlaceholder: "Ajoutez des détails, des liens ou des critères",
107
+ tasksAssigneeLabel: "Responsable", tasksUnassigned: "Non attribuée", tasksFilterLabel: "Afficher", tasksFilterAll: "Tous les statuts",
108
+ tasksDueDateLabel: "Date limite", tasksDueOn: ({ date }) => `Échéance ${date}`, tasksOverdue: "En retard",
109
+ tasksParticipantsLabel: "Participants", tasksParticipantsMeta: ({ names }) => `Participants : ${names}`,
110
+ tasksConclusionLabel: "Conclusion", tasksConclusionPlaceholder: "Quel a été le résultat ?",
111
+ tasksStepsLabel: "Étapes", tasksAddStep: "Ajouter une étape", tasksRemoveStep: "Supprimer l’étape", tasksStepPlaceholder: "Décrivez une étape",
112
+ tasksStepDoneLabel: "Étape terminée", tasksStepsHint: "Jusqu’à 30 étapes. Cochez celles qui sont terminées.",
113
+ tasksStepsProgress: ({ done, total }) => `${done} étape${done === 1 ? "" : "s"} sur ${total} terminée${done === 1 ? "" : "s"}`,
114
+ tasksStatusTodo: "À faire", tasksStatusDoing: "En cours", tasksStatusDone: "Terminée",
115
+ tasksSummary: ({ count }) => `${count} tâche${count === 1 ? "" : "s"}`, tasksCreator: ({ name }) => `Créée par ${name}`, tasksUpdated: ({ time }) => `Mise à jour ${time}`,
116
+ tasksEditLabel: ({ title }) => `Modifier ${title}`, tasksDeleteLabel: ({ title }) => `Supprimer ${title}`, tasksStatusFor: ({ title }) => `Statut de ${title}`,
117
+ tasksInvalid: "Saisissez un titre de 1 à 200 caractères.", tasksCreateFailed: "Impossible d’ajouter la tâche. Réessayez.", tasksUpdateFailed: "Impossible de modifier la tâche. Réessayez.",
118
+ tasksDeleteFailed: "Impossible de supprimer la tâche. Réessayez.", tasksDeleteConfirm: ({ title }) => `Supprimer « ${title} » ? Cette action est irréversible.`,
101
119
  earlierMessages: "Messages précédents omis", messagesBetweenOmitted: "Les messages entre ce point de lecture et les derniers sont omis.", you: "Vous", saved: "Enregistré",
102
120
  savedMemory: "Enregistré pour cet onglet uniquement", copyFailed: ({ id }) => `Copie impossible. Copiez manuellement : ${id}`,
103
121
  copyMessage: "Copier", copiedMessage: "Copié", copyMessageFailed: "Copie impossible. Sélectionnez et copiez le message manuellement.", wrapCode: "Retour à la ligne",
@@ -43,7 +43,7 @@ export const it = {
43
43
  reminderEdit: "Modifica", reminderEditHeading: "Modifica promemoria", reminderSave: "Salva modifiche",
44
44
  reminderCreated: "Promemoria creato.", reminderUpdated: "Promemoria aggiornato.", reminderDeleted: "Promemoria eliminato.",
45
45
  reminderInvalid: "Controlla la data, l’espressione CRON a 5 campi, il fuso orario IANA e il testo del promemoria.", reminderLoadFailed: "Impossibile caricare i promemoria. La tua bozza è ancora qui.",
46
- diagramLoading: "Rendering del diagramma…", diagramRenderFailed: "Diagramma non disponibile; viene mostrato il codice sorgente.", resourceLoading: "Caricamento del file…", resourceFailed: "Impossibile caricare questo file.", resourceDownload: "Scarica", resourceMoreActions: "Altre azioni per {name}", resourcePreview: "Anteprima", resourceHide: "Nascondi anteprima", docPreviewEyebrow: "Anteprima Markdown", docPreviewFailed: "Impossibile caricare questo documento.", docPreviewEmpty: "Questo documento è vuoto.", zoomImage: "Apri immagine", imagePreviewTitle: "Anteprima immagine", imageZoomControls: "Zoom immagine", zoomIn: "Ingrandisci", zoomOut: "Riduci", zoomReset: "Reimposta zoom", installTitle: "Installa OC Chat", installBody: "Aggiungilo alla schermata Home per una chat a schermo intero.", installAction: "Installa", installHow: "Come installare", installNotNow: "Non ora", installIosGuide: "Tocca Condividi, poi Aggiungi alla schermata Home.",
46
+ diagramLoading: "Rendering del diagramma…", diagramRenderFailed: "Diagramma non disponibile; viene mostrato il codice sorgente.", resourceLoading: "Caricamento del file…", resourceFailed: "Impossibile caricare questo file.", resourceDownload: "Scarica", resourceMoreActions: "Altre azioni per {name}", resourcePreview: "Anteprima", resourceHide: "Nascondi anteprima", docPreviewEyebrow: "Anteprima Markdown", docPreviewFileEyebrow: "Anteprima file", docPreviewFailed: "Impossibile caricare questo documento.", sidePaneResize: "Ridimensiona il pannello laterale", docPreviewTooLarge: "File troppo grande per l’anteprima (oltre 2 MB). Scaricalo per visualizzarlo.", docPreviewEmpty: "Questo documento è vuoto.", zoomImage: "Apri immagine", imagePreviewTitle: "Anteprima immagine", imageZoomControls: "Zoom immagine", zoomIn: "Ingrandisci", zoomOut: "Riduci", zoomReset: "Reimposta zoom", openDiagram: "Apri diagramma", diagramViewerTitle: "Diagramma", diagramZoomControls: "Zoom diagramma", diagramFit: "Adatta", installTitle: "Installa OC Chat", installBody: "Aggiungilo alla schermata Home per una chat a schermo intero.", installAction: "Installa", installHow: "Come installare", installNotNow: "Non ora", installIosGuide: "Tocca Condividi, poi Aggiungi alla schermata Home.",
47
47
  pwaUpdateTitle: "Aggiornamento disponibile", pwaUpdateBody: "È pronta una nuova versione. Ricarica ora o aggiorna la prossima volta che apri l’app.", pwaUpdateNow: "Aggiorna ora", pwaUpdateLater: "Più tardi",
48
48
  announcementDelete: "Elimina annuncio",
49
49
  announcementNew: "Nuovo annuncio", announcementEmpty: "Nessun annuncio.", announcementLoading: "Caricamento degli annunci…",
@@ -94,10 +94,28 @@ export const it = {
94
94
  filesUnknownUploader: "Autore sconosciuto", filesSummary: ({ count, size }) => `${count} file · ${size}`,
95
95
  filesLoading: "Caricamento dei file…", filesLoadFailed: "Impossibile caricare i file. Riprova.", filesEmpty: "Questa stanza non ha ancora file.",
96
96
  filesEmptyFiltered: "Nessun file di questo autore.", filesLoadMore: "Carica altri",
97
- filesHint: "Puoi visualizzare immagini, audio, video e Markdown. Tutti i file si possono scaricare.",
97
+ filesHint: "Puoi visualizzare immagini, audio, video, Markdown, testo, codice e PDF. Tutti i file si possono scaricare.",
98
98
  filesPreviewFailed: "Impossibile caricare l’anteprima.", filesDownloadFailed: "Impossibile scaricare questo file.",
99
99
  filesPreviewLabel: ({ name }) => `Anteprima di ${name}`, filesDownloadLabel: ({ name }) => `Scarica ${name}`,
100
100
  filesDeleteLabel: ({ name }) => `Elimina ${name}`, filesRefresh: "Aggiorna i file",
101
+ tasksTitle: "Attività", tasksEyebrow: "Attività della stanza", tasksRefresh: "Aggiorna attività", tasksMenuLabel: "Azioni attività",
102
+ tasksClearCompleted: "Elimina attività completate", tasksClearConfirm: ({ count }) => `Eliminare ${count} attività completate? L’operazione non è reversibile.`,
103
+ tasksClearFailed: "Impossibile eliminare le attività completate. Riprova.",
104
+ tasksLoading: "Caricamento attività…", tasksLoadFailed: "Impossibile caricare le attività. Riprova.", tasksEmpty: "Nessuna attività. Aggiungi la prima.",
105
+ tasksEmptyFiltered: "Nessuna attività con questo stato.", tasksCreate: "Aggiungi attività", tasksTitleLabel: "Titolo",
106
+ tasksTitlePlaceholder: "Cosa c’è da fare?", tasksDescriptionLabel: "Descrizione", tasksDescriptionPlaceholder: "Aggiungi dettagli, link o criteri di completamento",
107
+ tasksAssigneeLabel: "Assegnatario", tasksUnassigned: "Non assegnata", tasksFilterLabel: "Mostra", tasksFilterAll: "Tutti gli stati",
108
+ tasksDueDateLabel: "Scadenza", tasksDueOn: ({ date }) => `Scade ${date}`, tasksOverdue: "In ritardo",
109
+ tasksParticipantsLabel: "Partecipanti", tasksParticipantsMeta: ({ names }) => `Partecipanti: ${names}`,
110
+ tasksConclusionLabel: "Conclusione", tasksConclusionPlaceholder: "Qual è stato il risultato?",
111
+ tasksStepsLabel: "Passaggi", tasksAddStep: "Aggiungi passaggio", tasksRemoveStep: "Rimuovi passaggio", tasksStepPlaceholder: "Descrivi un passaggio",
112
+ tasksStepDoneLabel: "Passaggio completato", tasksStepsHint: "Fino a 30 passaggi. Spunta quelli completati.",
113
+ tasksStepsProgress: ({ done, total }) => `${done} di ${total} passaggi completati`,
114
+ tasksStatusTodo: "Da fare", tasksStatusDoing: "In corso", tasksStatusDone: "Completata",
115
+ tasksSummary: ({ count }) => `${count} attività`, tasksCreator: ({ name }) => `Creata da ${name}`, tasksUpdated: ({ time }) => `Aggiornata ${time}`,
116
+ tasksEditLabel: ({ title }) => `Modifica ${title}`, tasksDeleteLabel: ({ title }) => `Elimina ${title}`, tasksStatusFor: ({ title }) => `Stato di ${title}`,
117
+ tasksInvalid: "Inserisci un titolo da 1 a 200 caratteri.", tasksCreateFailed: "Impossibile aggiungere l’attività. Riprova.", tasksUpdateFailed: "Impossibile aggiornare l’attività. Riprova.",
118
+ tasksDeleteFailed: "Impossibile eliminare l’attività. Riprova.", tasksDeleteConfirm: ({ title }) => `Eliminare «${title}»? L’operazione non può essere annullata.`,
101
119
  earlierMessages: "Messaggi precedenti omessi", messagesBetweenOmitted: "I messaggi tra questo punto di lettura e i più recenti sono omessi.", you: "Tu", saved: "Salvato",
102
120
  savedMemory: "Salvato solo per questa scheda", copyFailed: ({ id }) => `Copia non riuscita. Copia manualmente: ${id}`,
103
121
  copyMessage: "Copia", copiedMessage: "Copiato", copyMessageFailed: "Impossibile copiare. Seleziona e copia il messaggio manualmente.", wrapCode: "Adatta il codice",
@@ -44,7 +44,7 @@ export const ja = {
44
44
  reminderEdit: "編集", reminderEditHeading: "リマインダーを編集", reminderSave: "変更を保存",
45
45
  reminderCreated: "リマインダーを作成しました。", reminderUpdated: "リマインダーを更新しました。", reminderDeleted: "リマインダーを削除しました。",
46
46
  reminderInvalid: "日時、5 フィールドの CRON 式、IANA タイムゾーン、リマインダーのテキストを確認してください。", reminderLoadFailed: "リマインダーを読み込めませんでした。下書きは残っています。",
47
- diagramLoading: "図を描画中…", diagramRenderFailed: "図を表示できません。ソースを表示しています。", resourceLoading: "ファイルを読み込み中…", resourceFailed: "このファイルを読み込めませんでした。", resourceDownload: "ダウンロード", resourceMoreActions: "{name} のその他の操作", resourcePreview: "プレビュー", resourceHide: "プレビューを隠す", docPreviewEyebrow: "Markdown プレビュー", docPreviewFailed: "このドキュメントを読み込めませんでした。", docPreviewEmpty: "このドキュメントは空です。", zoomImage: "画像を開く", imagePreviewTitle: "画像プレビュー", imageZoomControls: "画像のズーム", zoomIn: "拡大", zoomOut: "縮小", zoomReset: "ズームをリセット", installTitle: "OC Chat をインストール", installBody: "ホーム画面に追加すると、全画面でチャットできます。", installAction: "インストール", installHow: "インストール方法", installNotNow: "後で", installIosGuide: "共有をタップし、「ホーム画面に追加」を選択します。",
47
+ diagramLoading: "図を描画中…", diagramRenderFailed: "図を表示できません。ソースを表示しています。", resourceLoading: "ファイルを読み込み中…", resourceFailed: "このファイルを読み込めませんでした。", resourceDownload: "ダウンロード", resourceMoreActions: "{name} のその他の操作", resourcePreview: "プレビュー", resourceHide: "プレビューを隠す", docPreviewEyebrow: "Markdown プレビュー", docPreviewFileEyebrow: "ファイルプレビュー", docPreviewFailed: "このドキュメントを読み込めませんでした。", sidePaneResize: "サイドパネルの幅を調整", docPreviewTooLarge: "ファイルが大きすぎるためプレビューできません(2 MB 超)。ダウンロードして確認してください。", docPreviewEmpty: "このドキュメントは空です。", zoomImage: "画像を開く", imagePreviewTitle: "画像プレビュー", imageZoomControls: "画像のズーム", zoomIn: "拡大", zoomOut: "縮小", zoomReset: "ズームをリセット", openDiagram: "図を開く", diagramViewerTitle: "図", diagramZoomControls: "図のズーム", diagramFit: "ウィンドウに合わせる", installTitle: "OC Chat をインストール", installBody: "ホーム画面に追加すると、全画面でチャットできます。", installAction: "インストール", installHow: "インストール方法", installNotNow: "後で", installIosGuide: "共有をタップし、「ホーム画面に追加」を選択します。",
48
48
  pwaUpdateTitle: "アップデートがあります", pwaUpdateBody: "新しいバージョンの準備ができました。今すぐ再読み込みするか、次回起動時に更新できます。", pwaUpdateNow: "今すぐ更新", pwaUpdateLater: "後で",
49
49
  announcementDelete: "お知らせを削除",
50
50
  announcementNew: "新しいお知らせ", announcementEmpty: "お知らせはまだありません。", announcementLoading: "お知らせを読み込み中…",
@@ -94,10 +94,28 @@ export const ja = {
94
94
  filesUnknownUploader: "不明なアップロード者", filesSummary: ({ count, size }) => `${count} 個のファイル · ${size}`,
95
95
  filesLoading: "ファイルを読み込み中…", filesLoadFailed: "ファイルを読み込めませんでした。もう一度お試しください。", filesEmpty: "このルームにはまだファイルがありません。",
96
96
  filesEmptyFiltered: "このアップロード者のファイルはありません。", filesLoadMore: "さらに読み込む",
97
- filesHint: "画像・音声・動画・Markdown をプレビューできます。すべてのファイルをダウンロードできます。",
97
+ filesHint: "画像・音声・動画・Markdown・テキスト・コード・PDF をプレビューできます。すべてのファイルをダウンロードできます。",
98
98
  filesPreviewFailed: "プレビューを読み込めませんでした。", filesDownloadFailed: "このファイルをダウンロードできませんでした。",
99
99
  filesPreviewLabel: ({ name }) => `${name} をプレビュー`, filesDownloadLabel: ({ name }) => `${name} をダウンロード`,
100
100
  filesDeleteLabel: ({ name }) => `${name} を削除`, filesRefresh: "ファイルを更新",
101
+ tasksTitle: "タスク", tasksEyebrow: "ルームのタスク", tasksRefresh: "タスクを更新", tasksMenuLabel: "タスクの操作",
102
+ tasksClearCompleted: "完了したタスクを削除", tasksClearConfirm: ({ count }) => `完了したタスクを ${count} 件削除しますか?元に戻せません。`,
103
+ tasksClearFailed: "完了したタスクを削除できませんでした。もう一度お試しください。",
104
+ tasksLoading: "タスクを読み込み中…", tasksLoadFailed: "タスクを読み込めませんでした。もう一度お試しください。", tasksEmpty: "タスクはまだありません。最初のタスクを追加しましょう。",
105
+ tasksEmptyFiltered: "このステータスのタスクはありません。", tasksCreate: "タスクを追加", tasksTitleLabel: "タイトル",
106
+ tasksTitlePlaceholder: "何をしますか?", tasksDescriptionLabel: "説明", tasksDescriptionPlaceholder: "詳細、リンク、完了条件を追加",
107
+ tasksAssigneeLabel: "担当者", tasksUnassigned: "未割り当て", tasksFilterLabel: "表示", tasksFilterAll: "すべてのステータス",
108
+ tasksDueDateLabel: "期限日", tasksDueOn: ({ date }) => `期限 ${date}`, tasksOverdue: "期限切れ",
109
+ tasksParticipantsLabel: "参加者", tasksParticipantsMeta: ({ names }) => `参加者:${names}`,
110
+ tasksConclusionLabel: "結論", tasksConclusionPlaceholder: "最終的な結果を入力",
111
+ tasksStepsLabel: "手順", tasksAddStep: "手順を追加", tasksRemoveStep: "手順を削除", tasksStepPlaceholder: "手順を入力",
112
+ tasksStepDoneLabel: "完了した手順", tasksStepsHint: "手順は最大 30 件です。完了したものにチェックを入れてください。",
113
+ tasksStepsProgress: ({ done, total }) => `全 ${total} 手順中 ${done} 件完了`,
114
+ tasksStatusTodo: "未着手", tasksStatusDoing: "進行中", tasksStatusDone: "完了",
115
+ tasksSummary: ({ count }) => `${count} 件のタスク`, tasksCreator: ({ name }) => `${name} が作成`, tasksUpdated: ({ time }) => `${time} に更新`,
116
+ tasksEditLabel: ({ title }) => `${title} を編集`, tasksDeleteLabel: ({ title }) => `${title} を削除`, tasksStatusFor: ({ title }) => `${title} のステータス`,
117
+ tasksInvalid: "タイトルは 1〜200 文字で入力してください。", tasksCreateFailed: "タスクを追加できませんでした。もう一度お試しください。", tasksUpdateFailed: "タスクを更新できませんでした。もう一度お試しください。",
118
+ tasksDeleteFailed: "タスクを削除できませんでした。もう一度お試しください。", tasksDeleteConfirm: ({ title }) => `「${title}」を削除しますか?元に戻せません。`,
101
119
  earlierMessages: "以前のメッセージは省略されています", messagesBetweenOmitted: "この閲覧位置と最新の間のメッセージは省略されています。", you: "あなた", saved: "保存済み",
102
120
  savedMemory: "このタブにのみ保存", copyFailed: ({ id }) => `コピーに失敗しました。手動でコピーしてください:${id}`,
103
121
  copyMessage: "コピー", copiedMessage: "コピーしました", copyMessageFailed: "コピーできませんでした。メッセージを選択して手動でコピーしてください。", wrapCode: "コードを折り返す",
@@ -44,7 +44,7 @@ export const ko = {
44
44
  reminderEdit: "편집", reminderEditHeading: "리마인더 편집", reminderSave: "변경 사항 저장",
45
45
  reminderCreated: "리마인더를 만들었습니다.", reminderUpdated: "리마인더를 수정했습니다.", reminderDeleted: "리마인더를 삭제했습니다.",
46
46
  reminderInvalid: "날짜, 5필드 CRON 식, IANA 시간대, 리마인더 텍스트를 확인하세요.", reminderLoadFailed: "리마인더를 불러오지 못했습니다. 작성 중인 내용은 그대로 있습니다.",
47
- diagramLoading: "다이어그램 그리는 중…", diagramRenderFailed: "다이어그램을 표시할 수 없습니다. 원본을 표시합니다.", resourceLoading: "파일 불러오는 중…", resourceFailed: "이 파일을 불러오지 못했습니다.", resourceDownload: "다운로드", resourceMoreActions: "{name}의 추가 작업", resourcePreview: "미리 보기", resourceHide: "미리 보기 숨기기", docPreviewEyebrow: "Markdown 미리 보기", docPreviewFailed: "이 문서를 불러오지 못했습니다.", docPreviewEmpty: "이 문서는 비어 있습니다.", zoomImage: "이미지 열기", imagePreviewTitle: "이미지 미리 보기", imageZoomControls: "이미지 확대/축소", zoomIn: "확대", zoomOut: "축소", zoomReset: "확대/축소 초기화", installTitle: "OC Chat 설치", installBody: "홈 화면에 추가하면 전체 화면으로 채팅할 수 있습니다.", installAction: "설치", installHow: "설치 방법", installNotNow: "나중에", installIosGuide: "공유를 탭한 다음 홈 화면에 추가를 선택하세요.",
47
+ diagramLoading: "다이어그램 그리는 중…", diagramRenderFailed: "다이어그램을 표시할 수 없습니다. 원본을 표시합니다.", resourceLoading: "파일 불러오는 중…", resourceFailed: "이 파일을 불러오지 못했습니다.", resourceDownload: "다운로드", resourceMoreActions: "{name}의 추가 작업", resourcePreview: "미리 보기", resourceHide: "미리 보기 숨기기", docPreviewEyebrow: "Markdown 미리 보기", docPreviewFileEyebrow: "파일 미리 보기", docPreviewFailed: "이 문서를 불러오지 못했습니다.", sidePaneResize: "사이드 패널 너비 조정", docPreviewTooLarge: "파일이 너무 커서 미리 볼 수 없습니다(2MB 초과). 다운로드해서 확인하세요.", docPreviewEmpty: "이 문서는 비어 있습니다.", zoomImage: "이미지 열기", imagePreviewTitle: "이미지 미리 보기", imageZoomControls: "이미지 확대/축소", zoomIn: "확대", zoomOut: "축소", zoomReset: "확대/축소 초기화", openDiagram: "다이어그램 열기", diagramViewerTitle: "다이어그램", diagramZoomControls: "다이어그램 확대/축소", diagramFit: "화면에 맞추기", installTitle: "OC Chat 설치", installBody: "홈 화면에 추가하면 전체 화면으로 채팅할 수 있습니다.", installAction: "설치", installHow: "설치 방법", installNotNow: "나중에", installIosGuide: "공유를 탭한 다음 홈 화면에 추가를 선택하세요.",
48
48
  pwaUpdateTitle: "업데이트 가능", pwaUpdateBody: "새 버전이 준비되었습니다. 지금 새로고침하거나 다음에 앱을 열 때 업데이트할 수 있습니다.", pwaUpdateNow: "지금 업데이트", pwaUpdateLater: "나중에",
49
49
  announcementDelete: "공지 삭제",
50
50
  announcementNew: "새 공지", announcementEmpty: "아직 공지가 없습니다.", announcementLoading: "공지 불러오는 중…",
@@ -94,10 +94,28 @@ export const ko = {
94
94
  filesUnknownUploader: "알 수 없는 업로더", filesSummary: ({ count, size }) => `${count}개 파일 · ${size}`,
95
95
  filesLoading: "파일을 불러오는 중…", filesLoadFailed: "파일을 불러오지 못했습니다. 다시 시도해 주세요.", filesEmpty: "이 방에는 아직 파일이 없습니다.",
96
96
  filesEmptyFiltered: "이 업로더의 파일이 없습니다.", filesLoadMore: "더 불러오기",
97
- filesHint: "이미지, 오디오, 동영상, Markdown을 미리 볼 수 있습니다. 모든 파일을 다운로드할 수 있습니다.",
97
+ filesHint: "이미지, 오디오, 동영상, Markdown, 텍스트, 코드, PDF를 미리 볼 수 있습니다. 모든 파일을 다운로드할 수 있습니다.",
98
98
  filesPreviewFailed: "미리보기를 불러오지 못했습니다.", filesDownloadFailed: "이 파일을 다운로드하지 못했습니다.",
99
99
  filesPreviewLabel: ({ name }) => `${name} 미리보기`, filesDownloadLabel: ({ name }) => `${name} 다운로드`,
100
100
  filesDeleteLabel: ({ name }) => `${name} 삭제`, filesRefresh: "파일 새로고침",
101
+ tasksTitle: "작업", tasksEyebrow: "방 작업", tasksRefresh: "작업 새로 고침", tasksMenuLabel: "작업 메뉴",
102
+ tasksClearCompleted: "완료한 작업 지우기", tasksClearConfirm: ({ count }) => `완료한 작업 ${count}개를 지울까요? 되돌릴 수 없습니다.`,
103
+ tasksClearFailed: "완료한 작업을 지우지 못했습니다. 다시 시도하세요.",
104
+ tasksLoading: "작업을 불러오는 중…", tasksLoadFailed: "작업을 불러오지 못했습니다. 다시 시도하세요.", tasksEmpty: "아직 작업이 없습니다. 첫 작업을 추가하세요.",
105
+ tasksEmptyFiltered: "이 상태의 작업이 없습니다.", tasksCreate: "작업 추가", tasksTitleLabel: "제목",
106
+ tasksTitlePlaceholder: "무엇을 해야 하나요?", tasksDescriptionLabel: "설명", tasksDescriptionPlaceholder: "세부 정보, 링크 또는 완료 기준 추가",
107
+ tasksAssigneeLabel: "담당자", tasksUnassigned: "미지정", tasksFilterLabel: "표시", tasksFilterAll: "모든 상태",
108
+ tasksDueDateLabel: "마감일", tasksDueOn: ({ date }) => `마감 ${date}`, tasksOverdue: "기한 지남",
109
+ tasksParticipantsLabel: "참여자", tasksParticipantsMeta: ({ names }) => `참여자: ${names}`,
110
+ tasksConclusionLabel: "결론", tasksConclusionPlaceholder: "최종 결과를 입력하세요",
111
+ tasksStepsLabel: "단계", tasksAddStep: "단계 추가", tasksRemoveStep: "단계 삭제", tasksStepPlaceholder: "단계 설명",
112
+ tasksStepDoneLabel: "완료한 단계", tasksStepsHint: "단계는 최대 30개입니다. 완료한 단계를 선택하세요.",
113
+ tasksStepsProgress: ({ done, total }) => `전체 ${total}단계 중 ${done}단계 완료`,
114
+ tasksStatusTodo: "할 일", tasksStatusDoing: "진행 중", tasksStatusDone: "완료",
115
+ tasksSummary: ({ count }) => `작업 ${count}개`, tasksCreator: ({ name }) => `${name} 생성`, tasksUpdated: ({ time }) => `${time} 업데이트`,
116
+ tasksEditLabel: ({ title }) => `${title} 편집`, tasksDeleteLabel: ({ title }) => `${title} 삭제`, tasksStatusFor: ({ title }) => `${title} 상태`,
117
+ tasksInvalid: "제목은 1–200자로 입력하세요.", tasksCreateFailed: "작업을 추가하지 못했습니다. 다시 시도하세요.", tasksUpdateFailed: "작업을 업데이트하지 못했습니다. 다시 시도하세요.",
118
+ tasksDeleteFailed: "작업을 삭제하지 못했습니다. 다시 시도하세요.", tasksDeleteConfirm: ({ title }) => `“${title}” 작업을 삭제할까요? 되돌릴 수 없습니다.`,
101
119
  earlierMessages: "이전 메시지는 생략됨", messagesBetweenOmitted: "이 읽기 지점과 최신 메시지 사이는 생략되었습니다.", you: "나", saved: "저장됨",
102
120
  savedMemory: "이 탭에만 저장됨", copyFailed: ({ id }) => `복사하지 못했습니다. 직접 복사하세요: ${id}`,
103
121
  copyMessage: "복사", copiedMessage: "복사됨", copyMessageFailed: "복사하지 못했습니다. 메시지를 선택해 직접 복사하세요.", wrapCode: "코드 줄 바꿈",
@@ -1,16 +1,44 @@
1
1
  import { createRandomId, LS } from "./state.js";
2
2
  import { isRoomAdmin } from "./admin-badge.js";
3
3
  import { iconNode } from "./icons.js";
4
+ import { isUnsafeDiagram, rememberDiagramSource, renderDiagram, showDiagramFallback } from "./diagram-viewer.js";
5
+ import { docPreviewFormat, TEXT_PREVIEW_LIMIT } from "./resource-format.js";
6
+ import { copyTextToClipboard } from "./clipboard.js";
7
+ import { createCopyButton, copyResourceText } from "./copy-action.js";
8
+
9
+ export { copyTextToClipboard };
4
10
 
5
11
  const mentionPattern = /<at>@([^<]+)<\/at>/g;
6
12
  const resourcePattern = /\[\[resource:([\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})\]\]/gi;
7
- let mermaidReady = false;
8
13
  const previewUrls = new Map();
14
+ const sanitizerTags = new Map();
9
15
  let previewObserver;
10
16
 
11
- export function isMarkdownResource(resource) {
12
- const mime = String(resource?.mimeType || "").split(";")[0].trim().toLowerCase();
13
- return mime === "text/markdown" || mime === "text/x-markdown" || /\.(?:md|markdown)$/i.test(String(resource?.name || ""));
17
+ // Raw HTML is not a formatting surface here: unknown tags must stay visible as
18
+ // text instead of disappearing inside the sanitizer. Known safe tags still pass
19
+ // through, and DOMPurify remains the final gate.
20
+ function preserveRawHtml(value) {
21
+ return String(value).replace(/<[^>]*>/g, (tag) => {
22
+ const name = /^<\/?([A-Za-z][\w:-]*)/.exec(tag)?.[1];
23
+ return name && sanitizerKeepsTag(name) ? tag : escapeHtmlText(tag);
24
+ });
25
+ }
26
+
27
+ const SANITIZER_TAG_CACHE_MAX = 256;
28
+ function sanitizerKeepsTag(name) {
29
+ const key = name.toLowerCase();
30
+ if (sanitizerTags.has(key)) return sanitizerTags.get(key);
31
+ // A message with endless distinct tag names must not probe DOMPurify forever;
32
+ // past the cap, unknown tags simply stay literal text.
33
+ if (sanitizerTags.size >= SANITIZER_TAG_CACHE_MAX) return false;
34
+ const probe = `<${key}></${key}>`;
35
+ const keeps = window.DOMPurify.sanitize(probe).toLowerCase().includes(`<${key}`);
36
+ sanitizerTags.set(key, keeps);
37
+ return keeps;
38
+ }
39
+
40
+ function escapeHtmlText(value) {
41
+ return String(value).replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[char]);
14
42
  }
15
43
 
16
44
  export function renderMarkdown(root, text, app) {
@@ -22,6 +50,7 @@ export function renderMarkdown(root, text, app) {
22
50
  return token;
23
51
  });
24
52
  const renderer = new window.marked.Renderer(), renderCode = renderer.code.bind(renderer);
53
+ renderer.html = ({ text }) => preserveRawHtml(text);
25
54
  renderer.code = (token) => {
26
55
  if ((token.lang || "").trim().toLowerCase().split(/\s+/)[0] !== "mermaid") return renderCode(token);
27
56
  const key = `CHATDIAGRAM${nonce}${diagrams.size}END`;
@@ -37,7 +66,11 @@ export function renderMarkdown(root, text, app) {
37
66
  for (const node of diagramNodes) {
38
67
  const source = diagrams.get(node.dataset.chatMermaid);
39
68
  node.removeAttribute("data-chat-mermaid"); node.className = "mermaid-diagram";
40
- if (source !== undefined) showDiagramFallback(node, source, app, !isUnsafeDiagram(source));
69
+ if (source !== undefined) {
70
+ const unsafe = isUnsafeDiagram(source);
71
+ showDiagramFallback(node, source, app, !unsafe);
72
+ if (!unsafe) activateDiagram(node, source, app);
73
+ }
41
74
  }
42
75
  fragment.querySelectorAll("a").forEach((link) => {
43
76
  link.target = "_blank";
@@ -137,54 +170,26 @@ async function copyCode(button, code, app) {
137
170
  }, 1600);
138
171
  }
139
172
 
140
- async function initializeMermaid() {
141
- if (mermaidReady) return;
142
- if (!window.mermaid) await new Promise((resolve, reject) => {
143
- const script = document.querySelector('script[src$="mermaid-11.12.2.min.js"]');
144
- if (!script) return reject(new Error("Mermaid bundle is missing"));
145
- script.addEventListener("load", resolve, { once: true });
146
- script.addEventListener("error", reject, { once: true });
147
- window.addEventListener("load", resolve, { once: true });
148
- });
149
- if (!window.mermaid) throw new Error("Mermaid bundle failed to load");
150
- window.mermaid.initialize({
151
- startOnLoad: false, securityLevel: "strict", htmlLabels: false,
152
- theme: matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "default",
153
- flowchart: { htmlLabels: false }, maxTextSize: 20000, maxEdges: 200, suppressErrorRendering: true,
154
- secure: ["secure", "securityLevel", "startOnLoad", "htmlLabels", "flowchart", "theme", "themeCSS", "themeVariables", "dompurifyConfig", "maxTextSize", "maxEdges", "suppressErrorRendering"],
173
+ // A rendered diagram is a button: click, Enter, or Space opens the readable overlay.
174
+ function activateDiagram(node, source, app) {
175
+ node.tabIndex = 0;
176
+ node.setAttribute("role", "button");
177
+ node.dataset.i18nAriaLabel = "openDiagram";
178
+ node.setAttribute("aria-label", app.t("openDiagram"));
179
+ rememberDiagramSource(node, source);
180
+ const open = (event) => {
181
+ const svg = node.querySelector("svg");
182
+ if (!svg || !app.openDiagram) return;
183
+ event.preventDefault();
184
+ event.stopPropagation();
185
+ app.openDiagram(svg, source);
186
+ };
187
+ // Focus belongs in the viewer; closing returns it here.
188
+ node.addEventListener("mousedown", (event) => { if (node.querySelector("svg")) event.preventDefault(); });
189
+ node.addEventListener("click", open);
190
+ node.addEventListener("keydown", (event) => {
191
+ if (event.key === "Enter" || event.key === " ") open(event);
155
192
  });
156
- mermaidReady = true;
157
- }
158
- async function renderDiagram(node, source, app) {
159
- if (source === undefined || isUnsafeDiagram(source)) return;
160
- try {
161
- await initializeMermaid();
162
- const { svg } = await window.mermaid.render(`oc-chat-${createRandomId()}`, source);
163
- if (!node.isConnected) return;
164
- const fragment = window.DOMPurify.sanitize(svg, {
165
- RETURN_DOM_FRAGMENT: true, USE_PROFILES: { svg: true, svgFilters: true },
166
- FORBID_TAGS: ["foreignObject", "a", "script"], FORBID_ATTR: ["href", "xlink:href", "onclick", "onload"],
167
- ALLOW_DATA_ATTR: false,
168
- });
169
- if (!fragment.querySelector("svg")) throw new Error("Diagram SVG was rejected");
170
- const update = () => node.replaceChildren(fragment);
171
- if (app.preserveReadingLayout) await app.preserveReadingLayout(update); else update();
172
- } catch {
173
- if (node.isConnected) showDiagramFallback(node, source, app, false);
174
- }
175
- }
176
- function isUnsafeDiagram(source = "") {
177
- return /%%\s*\{|^\s*---\s*(?:\r?\n)|\burl\s*\(|@import|@\s*\{[^}]*\b(?:img|image)\s*:/i.test(source);
178
- }
179
- function showDiagramFallback(node, source, app, loading) {
180
- node.textContent = "";
181
- const status = document.createElement("p"); status.className = "diagram-status";
182
- status.setAttribute("role", "status"); status.textContent = app.t(loading ? "diagramLoading" : "diagramRenderFailed");
183
- node.append(status);
184
- if (!loading) {
185
- const pre = document.createElement("pre"), code = document.createElement("code");
186
- code.textContent = source; pre.append(code); node.append(pre);
187
- }
188
193
  }
189
194
 
190
195
  function replaceResourceMarkers(fragment, app) {
@@ -226,14 +231,26 @@ async function loadResourceCard(card, roomId, app) {
226
231
  remove = resourceMenuItem("resourceDelete", () => deleteResource(card, roomId, id, resource, app, status, remove), app);
227
232
  actions.append(resourceSplit(app, resource, download, remove));
228
233
  } else actions.append(download);
229
- const markdown = isMarkdownResource(resource);
230
- if (previewKind(type) || markdown) {
231
- const preview = resourceButton("resourcePreview", resource.name, () => markdown
234
+ const docFormat = docPreviewFormat(resource);
235
+ if (docFormat && docFormat.kind !== "pdf") {
236
+ const copy = createCopyButton(app, "resource-copy");
237
+ copy.dataset.copyAction = "card";
238
+ copy.addEventListener("click", () => {
239
+ void copyResourceText(copy, app, async () => {
240
+ if (Number(resource.size) > TEXT_PREVIEW_LIMIT) return "";
241
+ const data = await app.apiBlob(`/rooms/${encodeURIComponent(roomId)}/resources/${encodeURIComponent(id)}/content`);
242
+ return data.text();
243
+ });
244
+ });
245
+ actions.append(copy);
246
+ }
247
+ if (previewKind(type) || docFormat) {
248
+ const preview = resourceButton("resourcePreview", resource.name, () => docFormat
232
249
  ? app.openDocPreview(roomId, resource, preview)
233
250
  : previewResource(card, roomId, id, resource, type, preview, app, status), app);
234
251
  actions.append(preview);
235
252
  // Media you sent yourself is shown inline; other people's media stays collapsed.
236
- if (!markdown && card.closest(".msg.own")) void previewResource(card, roomId, id, resource, type, preview, app, status);
253
+ if (!docFormat && card.closest(".msg.own")) void previewResource(card, roomId, id, resource, type, preview, app, status);
237
254
  }
238
255
  } catch (error) { if (card.isConnected) setResourceError(card, app, error?.status === 404 ? "resourceDeleted" : "resourceFailed"); }
239
256
  }
@@ -436,38 +453,10 @@ function replaceMentionTokens(fragment, mentions, app) {
436
453
  const chip = document.createElement("span");
437
454
  chip.className = "mention-chip";
438
455
  if (app.mentionNames().has(mention.name)) chip.classList.add("member");
439
- chip.textContent = `@${mention.name}`;
456
+ chip.dataset.mention = mention.name;
457
+ chip.textContent = `@${mention.name === "all" ? app.t("allMembers") : mention.name}`;
440
458
  replacement.appendChild(chip);
441
459
  }
442
460
  node.replaceWith(replacement);
443
461
  }
444
462
  }
445
-
446
- export async function copyTextToClipboard(text, mentionSource = false) {
447
- // The HTML marker lets a later paste rebuild mention chips; unmarked external text stays literal.
448
- const html = mentionSource ? `<div data-chatroom-mentions>${String(text).replace(/[&<>"]/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[char])}</div>` : "";
449
- try {
450
- if (html && navigator.clipboard?.write && typeof ClipboardItem !== "undefined") {
451
- await navigator.clipboard.write([new ClipboardItem({ "text/plain": new Blob([text], { type: "text/plain" }), "text/html": new Blob([html], { type: "text/html" }) })]);
452
- return true;
453
- }
454
- if (navigator.clipboard?.writeText) {
455
- await navigator.clipboard.writeText(text);
456
- return true;
457
- }
458
- } catch { /* Use the legacy clipboard command when permission is unavailable. */ }
459
- const field = document.createElement(html ? "div" : "textarea"), selection = getSelection(), active = document.activeElement;
460
- const ranges = selection ? Array.from({ length: selection.rangeCount }, (_, index) => selection.getRangeAt(index).cloneRange()) : [];
461
- if (html) { field.contentEditable = "true"; field.innerHTML = html; } else field.value = text;
462
- field.setAttribute("readonly", "");
463
- field.style.cssText = "position:fixed;left:-9999px;top:0";
464
- document.body.append(field);
465
- if (html && selection) { const range = document.createRange(); range.selectNodeContents(field); selection.removeAllRanges(); selection.addRange(range); }
466
- else if (!html) field.select();
467
- let copied = false;
468
- try { copied = document.execCommand("copy"); } catch { /* Clipboard access may be disabled. */ }
469
- field.remove();
470
- if (selection) { selection.removeAllRanges(); ranges.forEach((range) => selection.addRange(range)); }
471
- if (active instanceof HTMLElement) active.focus({ preventScroll: true });
472
- return copied;
473
- }
@@ -11,6 +11,7 @@ export function initMessages(app) {
11
11
  const $ = app.$;
12
12
  installEditor($("#msgInput"));
13
13
  $("#msgInput").isKnownMention = (name) => app.mentionExists(name);
14
+ $("#msgInput").mentionLabel = (name) => name === "all" ? app.t("allMembers") : name;
14
15
 
15
16
  app.autoGrow = (textarea) => {
16
17
  const thread = $("#thread"), atBottom = Boolean(app.state.room && Math.abs(thread.scrollHeight - thread.clientHeight - thread.scrollTop) < 1);
@@ -69,6 +70,8 @@ export function initMessages(app) {
69
70
  app.saveFailedMessages(roomId, (app.state.failedMessages.get(roomId) || []).filter((item) => item.id !== failedId));
70
71
  app.renderFailedMessages();
71
72
  };
73
+ // A retry reuses the first attempt's clientMessageID so a lost response
74
+ // cannot create a twin.
72
75
  app.retryFailedMessage = async (roomId, failedId) => {
73
76
  const item = app.state.failedMessages.get(roomId)?.find((message) => message.id === failedId);
74
77
  if (!item || app.state.retryingFailedIds.has(failedId)) return;
@@ -77,7 +80,7 @@ export function initMessages(app) {
77
80
  try {
78
81
  const questionTarget = item.replyTarget?.isQuestion, entry = app.state.rooms.get(roomId);
79
82
  const updated = questionTarget ? (await app.answerQuestionFromReply(roomId, item.replyToMessageID, item.text), entry?.room)
80
- : await app.api(`/rooms/${encodeURIComponent(roomId)}/messages`, { method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text: item.text, isQuestion: Boolean(item.isQuestion), ...(item.replyToMessageID ? { replyToMessageID: item.replyToMessageID } : {}) }) });
83
+ : await app.api(`/rooms/${encodeURIComponent(roomId)}/messages`, { method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text: item.text, isQuestion: Boolean(item.isQuestion), ...(item.clientMessageID ? { clientMessageID: item.clientMessageID } : {}), ...(item.replyToMessageID ? { replyToMessageID: item.replyToMessageID } : {}) }) });
81
84
  app.completeAttachmentsFromText?.(roomId, item.text);
82
85
  if (entry) {
83
86
  if (!questionTarget) entry.room = mergeRoom(entry.room, updated);
@@ -369,6 +372,7 @@ export function initMessages(app) {
369
372
  // keep the caret in the composer or the next keystrokes go nowhere.
370
373
  input.focus({ preventScroll: true });
371
374
  const text = message.text;
375
+ const clientMessageID = createRandomId();
372
376
  const thread = $("#thread"), followedBottom = thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80;
373
377
  const revision = app.state.draftRevision.get(room.id) || 0;
374
378
  app.state.sendingRooms ||= new Set(); app.state.sendingRooms.add(room.id);
@@ -393,7 +397,7 @@ export function initMessages(app) {
393
397
  let updated;
394
398
  if (replyTarget?.isQuestion) { await app.answerQuestionFromReply(room.id, replyTarget.id, text); updated = app.state.rooms.get(room.id)?.room || room; }
395
399
  else updated = await app.api(`/rooms/${encodeURIComponent(room.id)}/messages`, {
396
- method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text, ...(replyTarget ? { replyToMessageID: replyTarget.id } : {}) }),
400
+ method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text, clientMessageID, ...(replyTarget ? { replyToMessageID: replyTarget.id } : {}) }),
397
401
  });
398
402
  // A successful request proves the connection is usable, even if a stale
399
403
  // long-poll is still waiting to time out.
@@ -440,7 +444,7 @@ export function initMessages(app) {
440
444
  if (staleReply) app.saveDraft(room.id, text);
441
445
  else {
442
446
  const failures = app.state.failedMessages.get(room.id) || [];
443
- app.saveFailedMessages(room.id, [...failures, { id: createRandomId(), text, ...(replyTarget ? { replyToMessageID: replyTarget.id, replyTarget } : {}) }]);
447
+ app.saveFailedMessages(room.id, [...failures, { id: createRandomId(), text, clientMessageID, ...(replyTarget ? { replyToMessageID: replyTarget.id, replyTarget } : {}) }]);
444
448
  app.renderFailedMessages();
445
449
  }
446
450
  app.completeAttachments?.(room.id, message.ids);
@@ -1,6 +1,6 @@
1
1
  import { icon } from "./icons.js";
2
2
 
3
- // Alt+Space opens one keyboard-first surface: message search plus common room commands.
3
+ // Alt+Space or Ctrl+P opens one keyboard-first surface: message search plus common room commands.
4
4
 
5
5
  const SEARCH_DEBOUNCE_MS = 220;
6
6
 
@@ -15,22 +15,24 @@ export function initPalette(app) {
15
15
 
16
16
  // The eyebrow names the real key on this platform, matching the shortcut sheet.
17
17
  const combo = app.$("#paletteCombo");
18
- if (combo && /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent)) combo.textContent = "Option + Space";
18
+ const mac = /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent);
19
+ if (combo) combo.textContent = mac ? "Ctrl + P / Option + Space" : "Ctrl + P / Alt + Space";
19
20
 
20
21
  const commands = () => {
21
22
  const available = [
22
- { id: "refresh", label: t("refreshRooms"), icon: "arrow_sync", keywords: "reload rooms", run: () => void app.refreshRoomList?.() },
23
- { id: "create", label: t("createRoom"), icon: "add", keywords: "new room", focusComposer: false,
23
+ { id: "refresh", label: t("refreshRooms"), en: "Refresh rooms", icon: "arrow_sync", keywords: "reload rooms", run: () => void app.refreshRoomList?.() },
24
+ { id: "create", label: t("createRoom"), en: "New room", icon: "add", keywords: "new room", focusComposer: false,
24
25
  run: () => room() ? app.openCreateRoomDialog?.() : app.$("#inRoomName")?.focus({ preventScroll: true }) },
25
- { id: "settings", label: t("settings"), icon: "options", keywords: "preferences theme language", focusComposer: false, run: () => app.openSettings?.() },
26
+ { id: "settings", label: t("settings"), en: "Settings", icon: "options", keywords: "preferences theme language", focusComposer: false, run: () => app.openSettings?.() },
26
27
  ];
27
28
  if (room()) available.push(
28
- { id: "members", label: t("members"), icon: "people", keywords: "people roster", focusComposer: false, run: () => app.$("#btnMembers")?.click() },
29
- { id: "questions", label: t("questions"), icon: "question_circle", keywords: "answers", focusComposer: false, run: () => app.$("#btnQuestions")?.click() },
30
- { id: "announcements", label: t("announcements"), icon: "megaphone", keywords: "notice board", focusComposer: false, run: () => app.$("#btnAnnouncements")?.click() },
31
- { id: "reminders", label: t("reminders"), icon: "alert", keywords: "schedule alarm", focusComposer: false, run: () => app.$("#btnReminders")?.click() },
32
- { id: "leave", label: t("paletteLeaveRoom"), icon: "arrow_exit", keywords: "exit quit", focusComposer: false, run: () => app.leaveRoom?.(false) },
33
- { id: "latest", label: t("paletteJumpLatest"), icon: "arrow_down", keywords: "bottom newest", run: () => app.jumpToBottom?.() },
29
+ { id: "members", label: t("members"), en: "Members", icon: "people", keywords: "people roster", focusComposer: false, run: () => app.$("#btnMembers")?.click() },
30
+ { id: "questions", label: t("questions"), en: "Questions", icon: "question_circle", keywords: "answers", focusComposer: false, run: () => app.$("#btnQuestions")?.click() },
31
+ { id: "announcements", label: t("announcements"), en: "Announcements", icon: "megaphone", keywords: "notice board", focusComposer: false, run: () => app.$("#btnAnnouncements")?.click() },
32
+ ...(room().kind === "direct" ? [] : [{ id: "tasks", label: t("tasksTitle"), en: "Tasks", icon: "checkmark", keywords: "todo checklist work", focusComposer: false, run: () => app.openTasksDialog?.() }]),
33
+ { id: "reminders", label: t("reminders"), en: "Reminders", icon: "alert", keywords: "schedule alarm", focusComposer: false, run: () => app.$("#btnReminders")?.click() },
34
+ { id: "leave", label: t("paletteLeaveRoom"), en: "Leave room", icon: "arrow_exit", keywords: "exit quit", focusComposer: false, run: () => app.leaveRoom?.(false) },
35
+ { id: "latest", label: t("paletteJumpLatest"), en: "Jump to latest", icon: "arrow_down", keywords: "bottom newest", run: () => app.jumpToBottom?.() },
34
36
  );
35
37
  return available;
36
38
  };
@@ -131,12 +133,24 @@ export function initPalette(app) {
131
133
  syncSelection();
132
134
  };
133
135
 
136
+ // Empty input is search, not a command wall: commands appear only after "/".
137
+ const showIdle = () => {
138
+ clearTimeout(searchTimer);
139
+ sequence++;
140
+ dialog.dataset.mode = "search";
141
+ dialog.dataset.state = "ready";
142
+ modeLabel.textContent = t("paletteSearchMode");
143
+ list.setAttribute("aria-busy", "false");
144
+ render([], null);
145
+ status.textContent = t("palettePlaceholder");
146
+ };
147
+
134
148
  const showCommands = (fragment = "") => {
135
149
  clearTimeout(searchTimer);
136
150
  sequence++;
137
151
  const needle = fragment.trim().toLowerCase();
138
152
  const available = commands()
139
- .filter((command) => !needle || `${command.label} ${command.keywords || ""}`.toLowerCase().includes(needle))
153
+ .filter((command) => !needle || `${command.label} ${command.en || ""} ${command.keywords || ""} ${command.id}`.toLowerCase().includes(needle))
140
154
  .map((command) => ({ kind: "command", ...command }));
141
155
  dialog.dataset.mode = "commands";
142
156
  dialog.dataset.state = "ready";
@@ -230,7 +244,7 @@ export function initPalette(app) {
230
244
  clearTimeout(searchTimer);
231
245
  const token = ++sequence;
232
246
  const value = input.value;
233
- if (!value.trim()) { showCommands(""); return; }
247
+ if (!value.trim()) { showIdle(); return; }
234
248
  if (value.startsWith("/")) { showCommands(value.slice(1)); return; }
235
249
  const wasSearch = dialog.dataset.mode === "search";
236
250
  dialog.dataset.mode = "search";
@@ -240,6 +254,7 @@ export function initPalette(app) {
240
254
  // Keep the previous hits visible while typing. Clearing them on every
241
255
  // keystroke is what makes the result list flicker.
242
256
  if (!wasSearch || !items.length) render([], null);
257
+ else { selected = -1; syncSelection(); }
243
258
  status.textContent = t("paletteSearching");
244
259
  const text = value.trim();
245
260
  searchTimer = setTimeout(() => { void executeSearch(text, token); }, SEARCH_DEBOUNCE_MS);
@@ -291,7 +306,7 @@ export function initPalette(app) {
291
306
  scope = scope === "room" ? "all" : "room";
292
307
  syncScope();
293
308
  const value = input.value;
294
- if (!value.trim()) showCommands("");
309
+ if (!value.trim()) showIdle();
295
310
  else if (value.startsWith("/")) showCommands(value.slice(1));
296
311
  else scheduleSearch();
297
312
  };
@@ -309,13 +324,16 @@ export function initPalette(app) {
309
324
  input.value = "";
310
325
  scope = "room";
311
326
  syncScope();
312
- showCommands("");
327
+ showIdle();
313
328
  dialog.showModal();
314
329
  input.focus();
315
330
  };
316
331
  app.openPalette = openPalette;
317
332
 
318
333
  input.addEventListener("input", (event) => { if (!event.isComposing) scheduleSearch(); });
334
+ // IME commits (Chinese, Japanese, Korean) may fire no plain input event after
335
+ // composition ends, so filter the committed text here as well.
336
+ input.addEventListener("compositionend", () => scheduleSearch());
319
337
  scopeButton.addEventListener("click", () => { toggleScope(); input.focus(); });
320
338
  app.$("#btnClosePalette")?.addEventListener("click", () => closePalette());
321
339
  dialog.addEventListener("click", (event) => { if (event.target === dialog) closePalette(); });
@@ -381,8 +399,11 @@ export function initPalette(app) {
381
399
 
382
400
  document.addEventListener("keydown", (event) => {
383
401
  if (event.defaultPrevented || event.isComposing) return;
384
- if (!event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
385
- if (event.code !== "Space" && event.key !== " ") return;
402
+ const altSpace = event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey
403
+ && (event.code === "Space" || event.key === " ");
404
+ const ctrlP = event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey
405
+ && (event.code === "KeyP" || event.key.toLowerCase() === "p");
406
+ if (!altSpace && !ctrlP) return;
386
407
  event.preventDefault();
387
408
  event.stopPropagation();
388
409
  openPalette();
@@ -394,7 +415,8 @@ export function initPalette(app) {
394
415
  syncScope();
395
416
  if (!dialog.open) return;
396
417
  const value = input.value;
397
- if (!value.trim() || value.startsWith("/")) showCommands(value.startsWith("/") ? value.slice(1) : "");
418
+ if (!value.trim()) showIdle();
419
+ else if (value.startsWith("/")) showCommands(value.slice(1));
398
420
  else scheduleSearch();
399
421
  };
400
422
  }
@@ -52,6 +52,8 @@ export function initPwa(app) {
52
52
  // next open; otherwise this page keeps running without interruption.
53
53
  later.addEventListener("click", hide);
54
54
  navigator.serviceWorker.addEventListener("controllerchange", () => {
55
+ // A new worker lost the in-memory identity; the cache partition must follow this page.
56
+ void app.postMediaIdentity?.();
55
57
  if (reloading && !reloaded) {
56
58
  reloaded = true;
57
59
  location.reload();