2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

HTML/JavaScriptの固定応答チャット:要素名・form・IMEの整合を確認する

2
Last updated at Posted at 2025-03-08

2026-10-12 訂正:HTML/JS/CSSのID・class不一致、form送信、IME、アクセス可能な名前を訂正しました。これは外部通信・保存・有人対応のない固定応答デモです。

旧CodePenと今回の訂正を区別する

旧埋込みは維持します。CodePen内のコードと以下の訂正版が一致するか、CodePenの実動作は今回確認できていません。以下の検証は新しいローカル3ファイルに対するものです。

See the Pen ラク子さんとチャット by Yushi Yamamoto (@yamamotoyushi) on CodePen.

要素名の契約をそろえる

旧HTMLはmessage-input/messages/message-formですが、JSはmessageInput/messageArea/sendButtonを取得してnullになっていました。CSSにもHTMLに存在しないselectorがありました。訂正版は同じID/classを使い、deferでHTML解析後に初期化します。

button clickとkeypressで別々に追加する構成を撤回し、formのsubmitへ統一します。preventDefaultでreload/GET URLへの内容送信を防ぎます。今回はserverへ送るformではありません。

index.html

<!doctype html>
<html lang="ja">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>ローカルチャットデモ</title><link rel="stylesheet" href="style.css"><script defer src="script.js"></script></head>
<body><main class="chat-container">
<header class="chat-header"><h1>ラク子さん:固定応答デモ</h1><p>通信・保存・有人対応はありません。再読み込みで消えます。</p></header>
<div id="messages" class="chat-messages" role="log" aria-label="デモの履歴" aria-live="polite" aria-relevant="additions"></div>
<form id="message-form" class="chat-input">
<label for="message-input">メッセージ</label><input id="message-input" maxlength="500" autocomplete="off">
<button type="submit">画面へ追加</button></form><p id="notice" role="status"></p>
</main></body></html>

オンラインという旧表示を固定応答デモへ変更し、input label・button text・履歴のlive領域を追加しました。アイコンfontに依存せず、初期autofocusも強制しません。画像や元のデザインが同じと保証する例ではありません。

style.css

* { box-sizing: border-box; }
body { margin: 0; padding: 1rem; font: 1rem/1.6 system-ui, sans-serif; background: #f5f5f5; }
.chat-container { max-width: 32rem; margin: auto; background: white; border: 1px solid #bbb; }
.chat-header, .chat-input, #notice { padding: 1rem; }
.chat-header { background: #24466f; color: white; }
.chat-header h1 { font-size: 1.25rem; }
.chat-messages { height: 45vh; min-height: 10rem; overflow-y: auto; padding: 1rem; }
.message { padding: .5rem; margin-bottom: .75rem; overflow-wrap: anywhere; }
.user-message { background: #e3f2fd; }
.bot-message { background: #f1f1f1; }
.chat-input { display: flex; flex-wrap: wrap; gap: .5rem; }
.chat-input label { width: 100%; }
#message-input { flex: 1; min-width: 0; font: inherit; padding: .5rem; }
button { font: inherit; padding: .5rem; }
:focus-visible { outline: 3px solid #174c91; outline-offset: 3px; }

HTMLのclass/IDへ合わせて表示します。可視focusを維持し、入力の最小幅と折返しを定義しました。狭い画面・mobile keyboard・読み上げ等は実利用環境で追加確認します。

script.js

const form = document.getElementById('message-form');
const input = document.getElementById('message-input');
const messages = document.getElementById('messages');
const notice = document.getElementById('notice');
if (!form || !input || !messages || !notice) throw new Error('デモの要素が不足しています');
let composing = false;
let count = 0;
input.addEventListener('compositionstart', () => { composing = true; });
input.addEventListener('compositionend', () => { composing = false; });
input.addEventListener('keydown', event => {
  if (event.key === 'Enter' && (composing || event.isComposing || event.keyCode === 229)) event.preventDefault();
});
function append(text, sender) {
  const item = document.createElement('div');
  item.classList.add('message', `${sender}-message`);
  item.textContent = `${sender === 'user' ? 'あなた' : '固定応答'}: ${text}`;
  messages.append(item);
  messages.scrollTop = messages.scrollHeight;
}
append('この画面内だけのデモです。', 'bot');
form.addEventListener('submit', event => {
  event.preventDefault();
  if (composing) return;
  const text = input.value.trim();
  if (!text || text.length > 500) { notice.textContent = '1〜500文字で入力してください。'; return; }
  if (count >= 20) { notice.textContent = 'デモの上限20件に達しました。'; return; }
  count++;
  append(text, 'user');
  append(text.includes('こんにちは') ? 'こんにちは!これは固定のデモ応答です。' : 'このデモは情報検索や外部送信を行いません。', 'bot');
  input.value = '';
  notice.textContent = '';
  input.focus();
});

KeyboardEvent.isComposingとcompositionの状態を使い、変換中のEnterを送信操作と混同しないようにします。submitで状態を再確認します。今回の検証は合成composition eventであり、全OSの実IMEで保証するものではありません。

旧textContentによる本文表示は適切なため維持します。入力をinnerHTMLへ変えず、HTML文字列を文字として表示します。これだけで将来のリンク・画像・server側処理も安全になるという意味ではありません。

500文字・20件はこのデモの上限です。遅延応答timerは必要ないので撤回し、同期で固定応答を表示します。実応答速度の測定やLLM生成ではありません。保存しないため再読み込みで履歴が消えます。

実施した確認と次の境界

Chromiumで13項目を確認しました。初期表示、click/Enterで各一件、空白拒否、HTML文字列がimgにならないこと、変換中のsubmit抑止、上限20件、入力clear、URL不変、HTTP通信なし、page errorなしです。外部CodePenや実スマホ・実IME・スクリーンリーダーは未検証です。

実チャットに進める時は受付APIと保存、認証・会話所有者、pending/accepted/failed/unknown、冪等性、再接続、監視、個人情報の保持/削除を設計します。WebSocket/Node.jsは選択肢であって全チャットに必須ではありません。HTTP、SSE、他runtimeやmanaged serviceも要件に沿って比較します。localStorageへ個人情報を無条件に保存する拡張は推奨しません。

今回修正した3ファイルのローカル動作は確認しましたが、実ユーザー間通信・外部API・LLM・永続保存を完成させた記事ではありません。

この記事を書いた人✏️@YushiYamamoto
ITPRODX.com代表 / AIアーキテクト
Next.js / TypeScript / n8nを活用した自律型アーキテクチャ設計を専門としています。
日々の自動化の検証結果や、ビジネス側の視点(ROI等)に関するより深い考察は、以下の公式サイトおよびnoteで発信しています。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?