junkerstock
 AI解説ボタンのサンプル5 

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>履歴機能付き AIプロンプト</title>
<style>
body { font-family: sans-serif; padding: 1em; }
.container { display: flex; flex-direction: column; gap: 10px; max-width: 600px; }

/* 指示入力まわりのデザイン */
.prompt-area {
background-color: #eef;
padding: 10px;
border-radius: 8px;
border: 1px solid #ccc;
}
.prompt-input {
width: 100%;
padding: 8px;
font-size: 1em;
border: 2px solid #007bff;
border-radius: 4px;
box-sizing: border-box;
margin-bottom: 5px;
}
.history-controls {
display: flex;
gap: 10px;
align-items: center;
}
select.history-select {
flex-grow: 1; /* 横幅いっぱいに広げる */
padding: 5px;
}
.clear-btn {
font-size: 0.8em;
cursor: pointer;
color: #d9534f;
background: none;
border: 1px solid #d9534f;
border-radius: 3px;
padding: 2px 5px;
}

/* コード入力エリア */
textarea { width: 100%; height: 120px; padding: 8px; box-sizing: border-box;}

/* 送信ボタンエリア */
.controls { display: flex; gap: 10px; align-items: center; margin-top: 10px; }
select, button.send-btn { padding: 8px 12px; cursor: pointer; }
button.send-btn { background-color: #007bff; color: white; border: none; border-radius: 4px; }
button.send-btn:hover { background-color: #0056b3; }
</style>
</head>
<body>

<h1>AI解説(履歴機能付き)</h1>

<div class="container">

<div class="prompt-area">
<label style="font-weight:bold; font-size:0.9em;">AIへの指示:</label>

<input type="text" id="customPrompt" class="prompt-input"
value="以下のコードを初心者向けに日本語で解説してください:">

<div class="history-controls">
<select id="promptHistory" class="history-select" onchange="selectHistory()">
<option value="" disabled selected>履歴から選択...</option>
</select>
<button type="button" class="clear-btn" onclick="clearHistory()">履歴削除</button>
</div>
</div>

<textarea id="myEditor" placeholder="ここにコードを入力...">
// テストコード
console.log("History works!");
</textarea>

<div class="controls">
<select id="aiSelector">
<option value="perplexity">Perplexity (自動送信)</option>
<option value="gemini">Google Gemini</option>
<option value="chatgpt">ChatGPT</option>
<option value="claude">Claude</option>
</select>
<button class="send-btn" onclick="askAI()">🚀 AIに送信</button>
</div>
</div>

<script>
// ブラウザ保存用のキー名
const STORAGE_KEY = 'ai_prompt_history_v1';

// ページ読み込み時に履歴を復元
window.onload = function() {
loadHistory();
};

function askAI() {
const editor = document.getElementById('myEditor');
const customPromptInput = document.getElementById('customPrompt');

// 1. 指示を取得
const instruction = customPromptInput.value.trim();
if (!instruction) {
alert("AIへの指示を入力してください");
return;
}

// ★ここで履歴に保存する処理を実行
saveToHistory(instruction);

// 2. コード取得(選択範囲 or 全文)
let targetCode = "";
const selection = window.getSelection().toString();
targetCode = (selection.trim() !== "") ? selection : editor.value;

if (!targetCode.trim()) {
alert("コードが入力されていません。");
return;
}

// 3. プロンプト作成 & 送信
const finalPrompt = instruction + "\n\n" + targetCode;
const aiService = document.getElementById('aiSelector').value;
const encodedPrompt = encodeURIComponent(finalPrompt);

if (aiService === 'perplexity') {
window.open(`https://www.perplexity.ai/search?q=${encodedPrompt}`, '_blank');
} else {
let url = "";
switch (aiService) {
case "gemini": url = "https://gemini.google.com/app"; break;
case "chatgpt": url = "https://chatgpt.com/"; break;
case "claude": url = "https://claude.ai/new"; break;
}

if (navigator.clipboard) {
navigator.clipboard.writeText(finalPrompt).then(() => {
const msg = (selection.trim() !== "") ? "【選択部分】" : "【全文】";
if(confirm(msg + "と【指示】をコピーしました!\n貼り付け画面へ移動しますか?")) {
window.open(url, '_blank');
}
});
} else {
alert("コピー不可");
window.open(url, '_blank');
}
}
}

// --- ▼ 履歴管理用の関数群 ▼ ---

// 履歴をlocalStorageに保存してプルダウンを更新
function saveToHistory(text) {
let history = JSON.parse(localStorage.getItem(STORAGE_KEY)) || [];

// 既に同じものがあれば削除して先頭に持ってくる(並び替え)
history = history.filter(item => item !== text);
history.unshift(text); // 先頭に追加

// 最大20件までに制限(増えすぎ防止)
if (history.length > 20) history.pop();

localStorage.setItem(STORAGE_KEY, JSON.stringify(history));
loadHistory(); // プルダウン再描画
}

// 履歴を読み込んでプルダウンを作る
function loadHistory() {
const historySelect = document.getElementById('promptHistory');
const history = JSON.parse(localStorage.getItem(STORAGE_KEY)) || [];

// 一旦中身をリセット
historySelect.innerHTML = '<option value="" disabled selected>履歴から選択...</option>';

// デフォルトの選択肢をいくつか用意しておくと便利
const defaults = [
"このコードのバグを見つけて修正案を出してください:",
"このコードをPythonに書き換えてください:",
"もっと短く効率的な書き方にリファクタリングしてください:"
];

// 履歴とデフォルトを結合(重複排除)
const allItems = [...new Set([...history, ...defaults])];

allItems.forEach(text => {
const option = document.createElement('option');
option.value = text;
option.text = text.length > 30 ? text.substring(0, 30) + "..." : text; // 長すぎたら省略表示
historySelect.appendChild(option);
});
}

// プルダウンを選んだら入力欄に反映
function selectHistory() {
const historySelect = document.getElementById('promptHistory');
const customPromptInput = document.getElementById('customPrompt');

customPromptInput.value = historySelect.value;
}

// 履歴を全削除
function clearHistory() {
if(confirm("保存された履歴をすべて削除しますか?")) {
localStorage.removeItem(STORAGE_KEY);
loadHistory();
}
}
</script>

</body>
</html>


使用変数

aiService
allItems
askAI -------( Function )
charset
class
clearHistory -------( Function )
customPromptInput
defaults
editor
encodedPrompt
finalPrompt
history
historySelect
id
innerHTML
instruction
item
lang
loadHistory -------( Function )
msg
onchange
onclick
onload
option
placeholder
q
saveToHistory -------( Function )
selectHistory -------( Function )
selection
STORAGE_KEY
style
targetCode
text
type
url
value