Vanilla JS PWA にコレクション内セクション機能を追加する — データ構造選定とDOMベースDnD判定
結論(先に)
ブックマーク管理 PWA「petapeta」にコレクション内セクション機能を実装した。データ構造は list.sections: [{id,title,order}] + card.sectionId 案を採用し、サブコレクション化案・cardIds 配列案は却下。
D&D 移動では「カード間にドロップした時、ドロップ先カードの sectionId をデータベースから取る」のではなく「DOM 上で直前の section-header 要素を遡って data-section-id を取る」方式に切り替え、視覚的な領域感と一致する判定を実現した。
課題
サブコレクション化済みの Firestore スキーマ(users/{uid}/lists/{listId} + users/{uid}/cards/{cardId})の上に、コレクション内のさらに細かいグループ分け(セクション)機能を追加したい。
ユースケース例:
- 「業務」コレクションを「A社 – ドキュメント」「A社 – AppSheet」「Googleドキュメント – 業務」の 3 セクションに分けたい
- 既存の 950 件カードを既存のサブコレ構造を壊さずに対応したい
データ構造の選定
3 案を比較した。
| 観点 | A: card.sectionId + list.sections[] | B: list.sections[].cardIds | C: lists/{listId}/sections/{sectionId} サブコレ化 |
|---|---|---|---|
| 構造 | section メタは list 内、card 側に listId と sectionId | cardIds 配列を section に持つ | section も独立 doc |
| カード移動 | 1 write (updateCard) | list 全体書換 | 1 write |
| section 追加/削除 | list 1 write | list 1 write | section doc 操作 |
| 既存サブコレと整合 | ◎ | × (二重管理) | △ (2 段ネスト) |
| 実装コスト | 中 | 中 | 大 |
案 A 採用の理由
petapeta の既存設計に card.listId で親参照する素朴な flat 構造がある(#103 サブコレ化の経緯)。sectionId を追加するだけで同じパターンに乗る。
案 B は list.sections.cardIds と card.listId の二重管理になり、同期ズレリスクが高い。petapeta は per-doc LWW で sync しているため、配列内の cardIds をマージするロジックは複雑化する。
案 C は section 自体を独立 doc にする案。柔軟性は最大だが、petapeta のユースケース(section は単なるメタデータ、独立検索しない、onSnapshot 個別不要)に対しては過剰設計。#108 バックアップで chunk 分割 vs サブコレ化を選んだ時と同じ判断軸 — 「Firestore らしさ」よりユースケースに合致するかを優先した。
FirestoreStore API
新規追加した 4 つの API:
// 追加: list.sections に push、order = 現在の section 数
async addSection(listId, title) {
const listRef = this._userRef().collection('lists').doc(listId);
const snap = await listRef.get();
const cur = snap.data().sections || [];
const newSection = {
id: this._newSectionId(), // sec_<random12>
title: title.trim() || '新しいセクション',
order: cur.length
};
await listRef.update({
sections: [...cur, newSection],
updatedAt: this._serverTs(),
updatedAtLocal: Date.now()
});
this._retainWriteId(listId);
return newSection.id;
}
// 削除: 配下 cards の sectionId を FieldValue.delete()、list.sections から除外
async deleteSection(listId, sectionId) {
const userRef = this._userRef();
const cardsSnap = await userRef.collection('cards')
.where('listId', '==', listId)
.where('sectionId', '==', sectionId)
.get();
const batch = db.batch();
cardsSnap.forEach(doc => {
batch.update(doc.ref, {
sectionId: firebase.firestore.FieldValue.delete(),
updatedAt: this._serverTs(),
updatedAtLocal: Date.now()
});
});
const listSnap = await listRef.get();
const sections = (listSnap.data().sections || [])
.filter(s => s.id !== sectionId)
.map((s, idx) => ({ ...s, order: idx }));
batch.update(listRef, { sections, updatedAt: this._serverTs(), updatedAtLocal: Date.now() });
await batch.commit();
}
ポイント:
list.sectionsは doc 内 array で持つので、追加・削除は list 1 doc の update で完結- 削除時は配下 cards を
where('listId', '==', X).where('sectionId', '==', Y)で抽出、FieldValue.delete()で sectionId フィールドを削除 - DataStore は
applyListChangeでthis.lists.set(id, doc)のスプレッド更新するため、sectionsは自動的に反映される(adapter 経由でlist.sectionsがgetLegacyShape()に乗る)
D&D ハイライト判定の落とし穴
実装最初のバージョンでこんなコードを書いた:
handleCardDragOver(e, container) {
...
const sectionTarget = e.target.closest('.section-header');
if (sectionTarget && container.contains(sectionTarget)) {
sectionTarget.classList.add('section-drop-target');
this.dropTarget = { type: 'section', sectionId: sectionTarget.dataset.sectionId, ... };
this.hideDropIndicator(); // ← これが罠
return;
}
...
}
hideDropIndicator() の中身:
hideDropIndicator() {
const ind = document.getElementById('card-drop-indicator');
if (ind) ind.classList.remove('show');
this.dropTarget = null; // ← セクション用 dropTarget まで消される
}
ヘルパ関数の名前は「インジケータを隠す」なのに、副作用で dropTarget まで null にしていた。section の dropTarget を設定した直後にこれを呼ぶと、消されてしまう。
修正:
if (sectionTarget && container.contains(sectionTarget)) {
...
// hideDropIndicator は呼ばず、インジケータの表示だけ消す
const ind = document.getElementById('card-drop-indicator');
if (ind) ind.classList.remove('show');
this.dropTarget = { type: 'section', ... };
return;
}
教訓: ヘルパ関数の副作用を読まずに呼ぶと、想定外の状態リセットを引き起こす。名前が「単一責任」っぽく見える関数でも、内部実装で複数の状態を触っていることがある。
DOM ベース sectionId 解決
D&D でカード間にドロップしたとき、ドロップ先カードと同じセクションに入れたい。
最初の実装は card.sectionId をデータから取る方式:
const tCard = this.data.lists[tListIdx]?.cards?.[tCardIdx];
inheritSectionId = tCard?.sectionId ?? null;
これだと「カードがあるエリア」にしかドロップ判定が効かない。「セクション内のカード末尾の空きスペース」にドロップしたとき、targetCard を見つけられない(カード間判定が成立しない)。
切り替えたのは DOM 上で直前の section-header を遡る 方式:
_resolveSectionAtDropTarget(targetCard, insertBefore) {
if (!targetCard) return null;
let cursor = insertBefore ? targetCard.previousElementSibling : targetCard;
while (cursor) {
if (cursor.classList?.contains('section-header')) {
return cursor.dataset.sectionId || null;
}
cursor = cursor.previousElementSibling;
}
return null; // 未分類エリア
}
_resolveSectionAtEnd(container) {
if (!container) return null;
const headers = container.querySelectorAll('.section-header');
if (headers.length === 0) return null;
return headers[headers.length - 1].dataset.sectionId || null;
}
レンダー時、collection-cards grid は section-header と card が flat に並ぶ:
<div class="collection-cards">
<div class="card">未分類カード1</div>
<div class="card">未分類カード2</div>
<div class="section-header" data-section-id="sec_A">セクションA</div>
<div class="card">secAカード1</div>
<div class="card">secAカード2</div>
<div class="section-header" data-section-id="sec_B">セクションB</div>
<div class="card">secBカード1</div>
</div>
ドロップ先カードから previousElementSibling で遡って最初に出会った section-header の data-section-id を取る。
この方式の利点:
- セクション内の どこにドロップしても、そのセクションに入る(空きスペースも、カード間も、末尾も)
card.sectionIdのデータ状態に依存しない(DOM が真実)- onSnapshot 遅延中も DOM ベースなので即時判定が可能
まとめ
| 学び | 適用シーン |
|---|---|
| Firestore らしさ vs ユースケース | 案 B/C を即座に却下できた、#108 chunk 分割と同じ判断軸 |
| ヘルパ関数の副作用 | 名前が単一責任に見えても内部実装を確認、複数の状態を触る場合あり |
| DOM ベース判定 vs データベース判定 | 視覚的な領域感と一致させたい時は DOM が真実、データの同期遅延に強い |
| プレースホルダーは全員に見える | 個人情報・業務情報を例示しない、汎用例にする |
| 用語整理は抽象比喩より実物指差し | ユーザーが既に画面で見ているものに名前を貼る方が早い |
関連
- petapeta Issue #31: コレクション内にセクション(仕切り)を追加
commit 8402494でデプロイ
この記事は、開発の記録をもとに Claude Code が下書きし、私が確認して公開しています。