Skip to content

Instantly share code, notes, and snippets.

@k12u
Created December 26, 2024 05:02
Show Gist options
  • Save k12u/af4423244f0156f8a7b61770dca1329b to your computer and use it in GitHub Desktop.
Save k12u/af4423244f0156f8a7b61770dca1329b to your computer and use it in GitHub Desktop.
ブラウザタブで動かすエディタ
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>オフラインエディタ</title>
<style>
/* テキストエリアがリサイズ可能であることを示す */
textarea {
resize: vertical;
width: 100%;
}
</style>
</head>
<body>
<button id="newEditorButton">New</button>
<textarea id="editor" rows="20" placeholder="ここにテキストを入力..."></textarea>
<script>
const editor = document.getElementById('editor');
const newEditorButton = document.getElementById('newEditorButton');
// ランダムな文字列を生成する関数
function generateUniqueId() {
return Math.random().toString(36).substr(2, 9);
}
// URLからユニークIDを取得する関数
function getUniqueIdFromUrl() {
const urlParams = new URLSearchParams(window.location.search);
let uniqueId = urlParams.get('id');
if (!uniqueId) {
uniqueId = generateUniqueId();
urlParams.set('id', uniqueId);
window.history.replaceState({}, '', `${window.location.pathname}?${urlParams.toString()}`);
}
return uniqueId;
}
// IDの一覧を取得する関数
function getAllEditorIds() {
const keys = Object.keys(localStorage);
return keys.filter(key => key.startsWith('editor-'));
}
const uniqueId = getUniqueIdFromUrl();
const storageKey = `editor-${uniqueId}`;
// ブラウザのタイトルを更新する関数
function updateTitle(text) {
document.title = text.slice(0, 40) || 'オフラインエディタ';
}
// テキストエリアの内容が変更されたときに保存を実行
editor.addEventListener('input', () => {
const text = editor.value;
localStorage.setItem(storageKey, text);
updateTitle(text);
});
// ページロード時にローカルストレージからデータを読み込む
window.addEventListener('load', () => {
const savedText = localStorage.getItem(storageKey);
if (savedText) {
editor.value = savedText;
updateTitle(savedText);
}
// 保存されているIDの一覧を取得してコンソールに表示
const editorIds = getAllEditorIds();
console.log('保存されているエディタのID一覧:', editorIds);
});
// Newボタンがクリックされたときに新しいタブでエディタを開く
newEditorButton.addEventListener('click', () => {
const newTabUrl = `${window.location.origin}${window.location.pathname}`;
window.open(newTabUrl, '_blank');
});
</script>
</body>
</html>
ブラウザタブ上で動作するオフラインエディタを生成してください。仕様は以下です。
各タブはユニークIDをURLの一部として持っている。
ファイルの保存はIDをキーとしてlocalStorageに保存する。
ユニークIDが存在しない場合はランダムな文字列を生成してユニークIDとする。
ブラウザタイトルを文字列の先頭40文字から生成する。
テキストエリアがリサイズ可能で、縦方向に自由にリサイズできる。
Newボタンを作成し、クリックするとIDが空の新しいタブでエディタを開く。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment