セクションの D&D を「全体 draggable」から「ドラッグハンドル方式」に変えた話 — petapeta #193
結論(先に)
- 子要素に
cursor: textがある要素を全体draggable="true"にすると、ブラウザは drag より text selection を優先する。user-select: noneを足しても直らないことが多い - 解決は「全体 draggable をやめて、専用のドラッグハンドル要素を作る」
- 並び替え API は既存の
setSectionOrderを流用、別コレクション移動は新規moveSection(batch update)を追加 - 派生で「section-header の margin と collection-group の margin-bottom を grid gap に一本化」したら CSS が単純になった
やりたかったこと(#193)
petapeta のセクション機能 Phase 2:
- セクションを D&D で並び替え
- セクションをサイドバーの別コレクションへドロップで丸ごと移動(配下カードも一緒に)
データ構造:
list.sections: [{ id, title, order }] // list 1 件 = 1 doc、sections は array
card.listId // 親 list の id
card.sectionId // 所属 section id (null/undefined = 未分類)
試して失敗した方針 — section-header 全体 draggable
最初は section-header (<div class="section-header">) 全体に draggable="true" を付ける方針で実装した。
setupSectionDrag() {
document.querySelectorAll('.section-header').forEach(header => {
header.setAttribute('draggable', 'true');
header.addEventListener('dragstart', (e) => this.handleSectionDragStart(e, header));
// ...
});
}
ローカルで動作確認したら、ドラッグが起動しなかった。代わりに section-header 内のテキストが反転(text selection)してしまう。
理由: section-header 内の .section-title には cursor: text が指定されていた(inline 編集 UI のため)。
.collection-cards > .section-header .section-title {
cursor: text; /* ← ここがブラウザに「テキスト編集できる」と伝える */
}
cursor: text が付いた子要素の上で mousedown すると、ブラウザは drag 起動より text selection を優先する。user-select: none を section-header に足しても、子要素の cursor 設定が drag の起動を阻害する挙動は変わらなかった。
解決: ドラッグハンドル方式
専用のハンドル要素を section-header の中に追加し、それだけ を draggable="true" にする。
HTML
<div class="section-header" data-section-id="..." data-list-index="...">
<span class="section-drag-handle" data-tooltip="ドラッグで並び替え / サイドバーへドロップで別コレクションへ移動">
<i class="ph ph-dots-six-vertical"></i>
</span>
<button class="btn-section-collapse">...</button>
<span class="section-title">セクション名</span>
<!-- ... -->
</div>
CSS
.collection-cards > .section-header .section-drag-handle {
cursor: grab;
opacity: 0.5;
user-select: none;
-webkit-user-select: none;
touch-action: none; /* タッチで縦スクロールに奪われない */
}
.collection-cards > .section-header:hover .section-drag-handle {
opacity: 1;
}
.collection-cards > .section-header .section-drag-handle[draggable="true"]:active {
cursor: grabbing;
}
JS
setupSectionDrag() {
document.querySelectorAll('.section-header').forEach(header => {
const handle = header.querySelector('.section-drag-handle');
if (handle) {
handle.setAttribute('draggable', 'true');
handle.addEventListener('dragstart', (e) => this.handleSectionDragStart(e, header));
handle.addEventListener('dragend', (e) => this.handleSectionDragEnd(e, header));
// ハンドル click が section-header の折りたたみ click に伝播しないよう抑止
handle.addEventListener('click', (e) => e.stopPropagation());
}
// section-header 自体は drop ターゲット
header.addEventListener('dragover', (e) => this.handleSectionDragOver(e, header));
header.addEventListener('dragleave', (e) => this.handleSectionDragLeave(e, header));
header.addEventListener('drop', (e) => this.handleSectionDrop(e, header));
});
}
ポイント:
- ハンドルだけが drag 起点、section-header 全体は drop ターゲットとしてのみ機能
- ハンドルの click は
stopPropagationで section-header の折りたたみクリックに伝播させない(ハンドルクリックで折りたたまれると混乱する) touch-action: noneでモバイルのスクロールに奪われない
これで section-header の他の機能(タイトルクリックで inline 編集、バー全体クリックで折りたたみ、編集ボタンで rename)はすべて元のまま動く。役割が混ざらない。
カード D&D / コレクション D&D との競合
既存のカード D&D は .collection-cards の dragover で e.target.closest('.section-header') を見て「カードを section に振り分ける」ハイライト(section-drop-target)を出す処理がある。section drag 中もこれが発火すると見た目が混乱する。
container.addEventListener('dragover', (e) => {
if (this.draggedSection) return; // セクション D&D 中はカード drop 経路を停止
this.handleCardDragOver(e, container);
container.classList.add('drag-over');
});
this.draggedSection をグローバル状態として持って、各 dragover ハンドラの先頭でガードする。section drag 中はカード drop の処理経路を完全に飛ばす。
モバイル(touch)対応
petapeta は touch ドラッグを自前実装している(HTML drag は touchstart に対応していないため)。section にも同じパターンを適用。
setupSectionTouchDrag() {
document.querySelectorAll('.section-header').forEach(header => {
const handle = header.querySelector('.section-drag-handle');
if (!handle) return;
handle.addEventListener('touchstart', (e) => this.handleSectionTouchStart(e, header), { passive: false });
handle.addEventListener('touchmove', (e) => this.handleSectionTouchMove(e), { passive: false });
handle.addEventListener('touchend', (e) => this.handleSectionTouchEnd(e));
});
}
handleSectionTouchStart(e, header) {
const touch = e.touches[0];
// ハンドル起点なので長押し閾値は短め (200ms)
this.longPressTimer = setTimeout(() => {
navigator.vibrate && navigator.vibrate(50);
// クローン要素を body に append + touchDragState セット
// ...
}, 200);
}
ハンドル起点なら誤タップの心配が少ないので、カード D&D の 500ms より短い 200ms に。
並び替え API(既存流用)
並び替えは Phase 1 時点で FirestoreStore.setSectionOrder(listId, sectionIds) を実装済みだった。これに helper を被せる:
async _reorderSection(listIndex, dragId, dropId, before) {
if (!dragId || !dropId || dragId === dropId) return;
const list = this.data.lists[listIndex];
if (!list || !Array.isArray(list.sections)) return;
const sortedIds = list.sections.slice()
.sort((a, b) => (a.order || 0) - (b.order || 0))
.map(s => s.id);
const fromIdx = sortedIds.indexOf(dragId);
sortedIds.splice(fromIdx, 1);
let toIdx = sortedIds.indexOf(dropId);
if (!before) toIdx += 1;
sortedIds.splice(toIdx, 0, dragId);
await FirestoreStore.setSectionOrder(list.id, sortedIds);
// 即時反映
const sectionMap = new Map(list.sections.map(s => [s.id, s]));
const newSections = sortedIds.map((id, idx) => ({ ...sectionMap.get(id), order: idx }));
DataStore.applyListChange({ type: 'modified', doc: { ...list, sections: newSections } });
}
PC の handleSectionDrop と Touch の handleSectionTouchEnd から同じ helper を呼ぶ。
別コレクション移動 API(新規)
moveSection(srcListId, sectionId, dstListId) を Firestore 側に新規追加。配下カードも一緒に batch update で原子的に移動する:
async moveSection(srcListId, sectionId, dstListId) {
if (srcListId === dstListId) return;
const userRef = this._userRef();
const srcRef = userRef.collection('lists').doc(srcListId);
const dstRef = userRef.collection('lists').doc(dstListId);
const [srcSnap, dstSnap] = await Promise.all([srcRef.get(), dstRef.get()]);
const srcSections = srcSnap.data().sections || [];
const dstSections = dstSnap.data().sections || [];
const target = srcSections.find(s => s.id === sectionId);
// 移動先 sections に末尾追加 (id 維持)
const newDstSections = [...dstSections, { ...target, order: dstSections.length }];
// 移動元 sections は該当除去 + order 振り直し
const newSrcSections = srcSections
.filter(s => s.id !== sectionId)
.map((s, idx) => ({ ...s, order: idx }));
// 配下カードを取得
const cardsSnap = await userRef.collection('cards')
.where('listId', '==', srcListId)
.where('sectionId', '==', sectionId)
.get();
const batch = db.batch();
batch.update(srcRef, { sections: newSrcSections, /* timestamps */ });
batch.update(dstRef, { sections: newDstSections, /* timestamps */ });
cardsSnap.forEach(doc => {
batch.update(doc.ref, { listId: dstListId, /* timestamps */ });
});
await batch.commit();
return { movedCardCount: cardsSnap.size };
}
ポイント:
- 移動元の section から target を除いて order を 0 から振り直す
- 移動先の section に末尾追加(id は維持、order は既存長)
- 配下カードは
listIdだけ更新(sectionIdは維持、移動後も同じセクションに属する) - 全部 batch.commit で原子化、書き込み失敗時に整合性が崩れない
派生: spacing を grid gap に一本化
実装後、ドラッグ中の line 位置を調整していたら「section-header の margin と grid gap が二重に余白を作っている」ことに気づいた。
/* Before */
.collection-cards > .section-header { margin: 8px 0 4px; }
.collection-group { margin-bottom: 10px; }
/* After: grid gap に責務一本化 */
.collection-cards > .section-header { margin: 0; }
.collection-group { /* margin-bottom 削除 */ }
.collection-cards には gap: 15px、.cards-container には gap: 20px が既に指定されていて、要素間の余白は grid gap で十分。margin の追加は二重管理だった。
派生 issue を別 PR にせず同じ commit にまとめた(dogfooding 中の派生発見は記憶ホットなうちに当てる方針)。
どこに drop させるか — UX 上の分岐
別コレクションへの移動をどこで受けるかは2案あった:
| 案 | drop ターゲット | Pros | Cons |
|---|---|---|---|
| A | 別コレクションの section-header | カードエリア内で完結 | 同一コレクション内 drop = 並び替え、別コレクション内 drop = 移動、の分岐が紛らわしい |
| B | サイドバーの collection-item | 並び替えと移動が UI 的に分離(場所が違う) | サイドバーまで指を運ぶ必要あり |
採用は B。同じ操作で異なる結果になる UX を避けたかった。tooltip にも「サイドバーへドロップで別コレクションへ移動」と明記。
教訓
- 全体 draggable は子要素の cursor 設定で阻害される。テキスト編集 UI を含む要素は、専用ドラッグハンドルを別 element で持つ
user-select: noneは万能ではない。cursor: textの子要素を持つ要素では、テキスト選択を抑制しても drag 起動の優先度は上がらないケースがある- 余白の責務は grid gap に一本化。margin と grid gap の両方で余白を持たせると DevTools で見たときに「どっちが効いてるか」分かりにくい。grid を使うなら gap だけに任せる
- dogfooding 中の派生発見は同 commit でスコープ拡大 OK。記憶がホットなうちに当てた方が、後から思い出して別 PR にするより速い
関連
- Issue: #193(リポは非公開)
- 親: #31(セクション機能 Phase 1・リポは非公開)
- 派生未着手: #192(ハイライト強化、dogfood 後判断)
- commit: 6207815 + fd542e6
追記: dogfood 派生で #199 + #200 + 追加モーダル漏れも同日中に補完
#193 完了後、編集モーダルを開いてみたら派生課題が 3 連続で見つかった。同日中に補完した。
#199 フォーム内 Dropdown のスタイル統一
セクション選択 Dropdown のスタイルが、元々タグフィルター用のデザイン(border-radius: 9999px の丸形 + padding: 0.4rem 0.875rem)を引き継いでいた。.form-group input は border-radius: 6px + padding: 10px 12px + font-size: 0.95rem なので、横に並んだときに見た目がバラバラ。
/* フォーム内で使う場合は input/textarea と同じ角丸・サイズ・幅に揃える */
.form-group .dropdown {
display: block;
width: 100%;
}
.form-group .dropdown .dropdown-trigger {
border-radius: 6px;
padding: 10px 12px;
font-size: 0.95rem;
}
ポイント:
- 元の
.dropdownはdisplay: inline-blockでコンテンツ幅になっていた(テキストの長さに合わせて Dropdown 全体が縮む) - フォーム内では input と同じ全幅で揃えたいので、
.form-group .dropdownだけdisplay: block+width: 100%で上書き - フォーム外(タグフィルター / admin / くしゃくしゃ並び替え)は元の丸形・コンテンツ幅のまま維持
#200 コレクション変更時にセクション Dropdown を再構築
カード編集モーダルでコレクションを変更しても、セクション Dropdown が古いコレクションの選択肢のままだった。
// initCollectionSelect 内、コレクションアイテムの click ハンドラに追加
item.addEventListener('click', () => {
// ...既存処理(hidden value 更新、selected 切替)
// コレクション変更時はセクション Dropdown を新コレクションの sections で再構築 (#200)
this._initCardSectionDropdown(parseInt(value), '');
});
Dropdown.create は既存インスタンスを自動 destroy する仕様(dropdown.js 内部の _instances Map で管理)なので、明示的な Dropdown.destroy() 呼び出しは不要。再 create するだけで OK。
追加モーダルの section 選択 UI 漏れ補完
#198 でカード編集モーダルにだけ section 選択を追加していて、追加モーダルへの反映を忘れていた。dogfood で発見、同 commit で補完。
// showAddLinkModal の content
const content = `
<div class="add-mode-toggle">...</div>
${this.renderCollectionSelect(listIndex)}
${this._renderCardSectionSelectHtml(listIndex, '')} // ← 追加
// ...
`;
// Modal.open の onSubmit
const sectionEl = document.getElementById('link-section');
const sectionId = sectionEl ? (Dropdown.getValue(sectionEl) || '') : '';
// ...
if (sectionId) cardData.sectionId = sectionId;
加えて、storage.js の _addCardNewSchema も sectionId フィールドを保存するよう拡張:
if (card.description) newCard.description = card.description;
if (card.image) newCard.image = card.image;
if (card.imageUrl) newCard.imageUrl = card.imageUrl;
if (card.sectionId) newCard.sectionId = card.sectionId; // ← 追加
教訓 (補完)
- 新規追加した UI は「追加 / 編集 両方のモーダル」で揃える。片方だけ実装するパターンに気をつける(特に既存の編集モーダル経由で追加された機能は、追加モーダルに反映漏れしがち)
- dogfood は同 commit で派生まで巻き取る方が速い。記憶がホットなうちに当てる
- Dropdown 等の汎用部品はデフォルトの
displayプロパティに気をつける。inline-blockはコンテンツ幅、フォーム内では block + width:100% で上書きが必要
追加 commit
- 88abd5b: #199 + #200 + 追加モーダル漏れ補完
- 5668d0e: #199 補正 (.form-group .dropdown を全幅に)
- Issue #199 / #200 close 済
- SW v405 → v408
追記 2: #201 ギャラクシー色改善 + 全テーマ色相統一
セクション周り完了後、ギャラクシーテーマのカード色が「沼っぽい中間色」で銀河感がない、と dogfood で発見。修正のついでに全テーマで color1〜6 = 色相の対応関係を統一する派生対応も実施。
元の問題
ギャラクシー ([data-theme="dark"]) の sticky-color は彩度低めの中間色:
--sticky-color1: #5a4070; /* 紫 */
--sticky-color2: #6a3048; /* マゼンタ赤 */
--sticky-color3: #2c4068; /* 青 */
--sticky-color4: #305848; /* シアン緑 */
--sticky-color5: #5a4838; /* 温かみオレンジ茶 */
--sticky-color6: #443060; /* バイオレット */
dark 背景 + 低彩度色で「銀河」というより「沼」。
派生発見: テーマ間で色番号と色相の対応がバラバラ
色を直そうとして全テーマ確認したら:
| color | ほんわか | ゆめかわ | ミント | ギャラクシー(元) |
|---|---|---|---|---|
| 1 | 黄 | 黄淡 | 黄緑 | 紫 |
| 2 | ピンク | ピンク淡 | 緑 | マゼンタ赤 |
| 3 | 青 | 青淡 | 緑淡 | 青 |
| 4 | 緑 | 緑淡 | 緑濃 | シアン緑 |
| 5 | 紫 | 紫淡 | 黄緑 | オレンジ茶 |
| 6 | オレンジ | オレンジ淡 | 黄 | バイオレット |
- ミントは全 6 色が緑系で、色番号と色相が独立
- ギャラクシーは順番がバラバラ (color1=紫、color5=オレンジ茶 等)
UX 問題: 「あの URL は color3 = いつも青で覚えてる」がテーマを切り替えると保たれない。
対応: 全テーマで color1〜6 = (黄/ピンク/青/緑/紫/オレンジ) に統一
ほんわか (基準、変更なし):
--sticky-color1: #fff9c4; /* 黄 */
--sticky-color2: #ffcdd2; /* ピンク */
--sticky-color3: #bbdefb; /* 青 */
--sticky-color4: #c8e6c9; /* 緑 */
--sticky-color5: #e1bee7; /* 紫 */
--sticky-color6: #ffe0b2; /* オレンジ */
ゆめかわ (元から色相一致、変更なし): 上記の淡め版
ミント (作り直し): 寒色寄り淡色で多色化
--sticky-color1: #f0f5c8; /* 黄 (ライム) */
--sticky-color2: #f0d8d8; /* ピンク (ローズ) */
--sticky-color3: #c8e8e8; /* 青 (シアン) */
--sticky-color4: #b8e8c8; /* 緑 (ミント本命) */
--sticky-color5: #d8d0e8; /* 紫 (ラベンダー) */
--sticky-color6: #f0d8b8; /* オレンジ (くすみ) */
ギャラクシー (作り直し + 落ち着き調整 3 段階):
- 段階 1: ネオン彩度 up → ユーザー「まぶしい」
- 段階 2: 15% 落ち着き → ユーザー「もう一段」
- 段階 3 (確定): 深宇宙の落ち着いたネオン
--sticky-color1: #8e7a2a; /* 黄 (深ゴールド) */
--sticky-color2: #8c2c4a; /* ピンク (深ローズ) */
--sticky-color3: #233f8e; /* 青 (深コバルト) */
--sticky-color4: #1a6e58; /* 緑 (深エメラルド) */
--sticky-color5: #5a2f82; /* 紫 (深バイオレット) */
--sticky-color6: #8a5028; /* オレンジ (深アンバー) */
文字視認性対策
ギャラクシー色を彩度上げた段階で、カード内の文字(薄紫白の --text-primary: #e8e0f0)が背景色とコントラスト不足になった。対策:
[data-theme="dark"] .card .card-title {
color: #ffffff;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.45);
}
[data-theme="dark"] .card .card-description,
[data-theme="dark"] .card .card-url {
color: #f0f0f0;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
}
[data-theme="dark"] .card .card-dates {
color: #f5f5f5;
opacity: 1;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
}
[data-theme="dark"] .card-memo .card-favicon-icon {
color: #ffffff;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}
text-shadow で文字に輪郭を入れて、6 色すべての背景色に対してコントラスト確保。
LP プレビュー色も同期
index.html の .preview-note は style="background: #..." で hard-code されていた (CSS 変数参照なし、preview なので意図的)。本体色を変えるときは LP も同時に更新する運用に注意:
<!-- ミント -->
<div class="preview-note" style="background: #b8e8c8"></div>
<div class="preview-note" style="background: #f0d8d8"></div>
<div class="preview-note" style="background: #c8e8e8"></div>
<!-- ギャラクシー -->
<div class="preview-note" style="background: #5a2f82"></div>
<div class="preview-note" style="background: #8c2c4a"></div>
<div class="preview-note" style="background: #233f8e"></div>
教訓 (色設計)
- 色番号と色相の対応関係をテーマ間で統一する。ユーザーがカードに付けた色 (color1〜6) はテーマ切替後も同じ意味であってほしい
- 彩度を上げると文字色のコントラストが破綻する。背景色を変える時はテキスト色との対比を再検証。
text-shadowで輪郭を入れる対症療法も有効 - 色の nuance は dogfood で段階的に詰める。最初から「これ」と決めず、3 段階くらい振って収束させる方が速い (今回ネオン → 15%落ち着き → さらに 15% 深め、で確定)
- LP の preview は CSS 変数を参照していない場合がある。テーマ色を変えるときは LP の inline style も同時に更新する
追加 commit
- 2a6e0c5: 全テーマ色相統一 + ギャラクシー文字視認性強化
- Issue #201 close 済
- SW v411 → v419
追記 3: v1.6 提出前で見つけた 3 つの罠
セクション周りと色直しで一段落した後、Chrome ウェブストア提出に向けて拡張 v1.6 を準備していたら、3 つの罠に当たった。
罠 1: PowerShell Compress-Archive の path separator がバックスラッシュ
Windows 上で Compress-Archive を使うと、zip 内のエントリ名にバックスラッシュ \ が含まれることがある。
Compress-Archive -Path "chrome-extension\*" -DestinationPath "petapeta-extension-v1.6.0.zip"
unzip -l で中を見ると分かる:
Length Date Time Name
78131 2026-03-05 01:15 fonts\phosphor.css ← \ になっている
488716 2026-03-05 01:15 fonts\Phosphor.woff
Chrome ウェブストア (Linux 系で解凍) ではサブディレクトリを認識せず、fonts\phosphor.css という名前のフラットなファイルとして扱われる可能性が高い。manifest.json が fonts/phosphor.css を参照していてもファイルが見つからず、審査で弾かれる or インストール時に壊れる。
解決: Python zipfile で作り直す
Python の zipfile モジュールは常に / を使う。明示的に os.sep を / に置換する。
import zipfile, os
src = 'C:/path/to/petapeta/chrome-extension'
out = 'C:/path/to/petapeta/dist/petapeta-extension-v1.6.0.zip'
exclude_files = {'PRIVACY.md'}
exclude_dirs = {'.git', '__pycache__', 'node_modules'}
with zipfile.ZipFile(out, 'w', zipfile.ZIP_DEFLATED) as zf:
for root, dirs, files in os.walk(src):
dirs[:] = [d for d in dirs if d not in exclude_dirs]
for f in files:
if f in exclude_files or f.startswith('.'):
continue
full = os.path.join(root, f)
rel = os.path.relpath(full, src).replace(os.sep, '/')
zf.write(full, rel)
unzip -l で確認:
Length Date Time Name
78131 2026-03-05 01:15 fonts/phosphor.css ← / になった
488716 2026-03-05 01:15 fonts/Phosphor.woff
他の選択肢
| 方法 | 評価 |
|---|---|
PowerShell Compress-Archive | × Windows のパス区切りが入る既知バグ |
7-Zip CLI | ○ 確実だが追加インストール必要 |
Git Bash の zip | × Git for Windows には zip コマンドが含まれていないことがある (本人環境では zip: command not found) |
Python zipfile | ◎ 標準ライブラリ、/ 強制置換で確実 |
WSL の zip | ○ WSL があれば確実だが、未インストールならハードル高い |
Windows で配布用 zip を作るときの第一候補は Python zipfile で確定。
罠 2: Cloud Functions のタグ集約に未使用タグが含まれていない
petapeta は タグ管理ページでタグを作成だけしてカードに付けていない「未使用タグ」を許容している。Web 側の getAllTags() は以下の union を返す:
card.tags(カードに付いている)settings.tagColorsのキー (タグ管理で作成、未使用でも存在)
ところが Chrome 拡張 popup 用に listExtensionData callable が返すタグは、cards.tags の distinct 集約のみだった:
// Before: 未使用タグが含まれない
const tagsSnap = await userRef.collection('cards').select('tags').get();
const tagSet = new Set();
tagsSnap.docs.forEach((d) => {
const cardTags = d.data().tags;
if (Array.isArray(cardTags)) {
cardTags.forEach((t) => {
if (typeof t === 'string' && t.trim()) tagSet.add(t.trim());
});
}
});
const tags = [...tagSet].sort();
test や 画像生成 のように「タグ管理で作っただけ、まだカードに付けていない」タグが拡張 popup のサジェストに出てこない。
解決: settings.tagColors のキーも union
// After: settings.tagColors のキーも union
const settingsDoc = await userRef.collection('meta').doc('settings').get();
const settings = settingsDoc.exists ? settingsDoc.data() : {};
const theme = settings.theme || null;
const tagColors = settings.tagColors || {};
const tagsSnap = await userRef.collection('cards').select('tags').get();
const tagSet = new Set();
tagsSnap.docs.forEach((d) => {
const cardTags = d.data().tags;
if (Array.isArray(cardTags)) {
cardTags.forEach((t) => {
if (typeof t === 'string' && t.trim()) tagSet.add(t.trim());
});
}
});
// settings.tagColors のキーも union (タグ管理ページで作って未使用のタグ)
Object.keys(tagColors).forEach((t) => {
if (typeof t === 'string' && t.trim()) tagSet.add(t.trim());
});
const tags = [...tagSet].sort();
settings は元々 theme 取得のために読んでいたので、追加の Firestore read は発生しない。
教訓
Web 側に「マスター + 使用実績」両方を持つデータがあるとき、API 経由で取り出す側 (拡張・モバイル等) が片方しか集約していないと整合が崩れる。Web の getAllTags() 系メソッドと API の集約ロジックは並べて見て同じにする。
罠 3: setupTagInput() の初期化順序
拡張 popup の DOMContentLoaded 内で、タグ入力 UI (TagChipInput) の初期化が loadPetapetaData() より後に呼ばれていた:
// Before
document.addEventListener('DOMContentLoaded', async () => {
initTheme();
setupAuthListeners();
await waitForAuth();
await loadPetapetaData(); // ← この中で populateCollections → loadExistingTags() が呼ばれる
await loadPageInfo();
setupEventListeners();
setupCustomDropdown();
setupTagInput(); // ← tagChipInput はここで初めて作られる
});
loadExistingTags() には次のガードがある:
function loadExistingTags() {
if (!petapetaData || !tagChipInput) return; // tagChipInput が null なら何もしない
const existingTags = petapetaData.tags || [];
tagChipInput.setExistingTags(existingTags);
}
つまり:
loadPetapetaData()内でloadExistingTags()が走る →tagChipInput === nullで早期 return- その後
setupTagInput()が呼ばれてtagChipInputが初期化される - でも
setExistingTags()は誰も呼ばない → サジェスト永遠に空
解決: setupTagInput() を先に呼ぶ
// After
document.addEventListener('DOMContentLoaded', async () => {
initTheme();
setupAuthListeners();
await waitForAuth();
setupTagInput(); // ← 一番先に
await loadPetapetaData(); // populateCollections → loadExistingTags() で setExistingTags が動く
await loadPageInfo();
setupEventListeners();
setupCustomDropdown();
});
「UI 構築 → データ流し込み」の順序が自然。setupTagInput() は DOM 操作だけで Firestore 通信を伴わないので、loadPetapetaData() の await より前に置いて問題ない。
教訓
非同期初期化が混じる DOMContentLoaded ハンドラは、「UI 骨格を全部作ってから、データ取得 → UI に流す」順序を意識する。「データ取得 → その中でガード付きで UI を埋める」順序にすると、UI 初期化が後回しになった瞬間に sub-component が空のままになる。
全体まとめ
| 罠 | 影響範囲 | 検出 | 解決時間 |
|---|---|---|---|
| PowerShell zip path separator | Chrome ウェブストア提出 (Linux 系解凍) | unzip -l で zip 内エントリ名を確認 | Python zipfile で作り直し |
| Cloud Functions タグ集約に未使用分が漏れる | 拡張 popup のタグサジェスト | Web / 拡張で並べて比較 | 集約ロジックに tagColors キー union 追加 |
setupTagInput() 初期化順序 | 拡張 popup のタグサジェスト | popup を開いて目視 | DOMContentLoaded 内の関数呼出順序を入れ替え |
3 件とも本番リリース手前で発見できたが、本来は実装時の試験で気付くべきものだった。Web と並走する API (Cloud Functions callable) は、Web 側のロジック変更時に並べて diff レビューする習慣が必要。
追加 commit
- 49aa3b7: 拡張 popup タグサジェスト表示の修正 (v1.6 提出前) (#189)
- Issue #189 動作確認 OK、close 候補
- v1.6 zip:
dist/petapeta-extension-v1.6.0.zip(18 ファイル / 7.6 MB / PRIVACY.md 除外)
この記事は、開発の記録をもとに Claude Code が下書きし、私が確認して公開しています。