TASTE ANALYZER

PWA v5.3

好みDNA分析 & 推しギャラリーDB

favoriteWorkPhotos: { 'wrk-1::0': true, 'wrk-3::2': true }, museState: getDefaultMuseState(), lastBackupAt: null }; } /** Clean blank-slate database for starting personal collection from 0 */ function getEmptyState() { return { version: SCHEMA_VERSION, actresses: [], works: [], scoutCandidates: [], galleryPhotos: [], favoriteWorkPhotos: {}, museState: getDefaultMuseState(), lastBackupAt: null }; } /** Default state structure for Muse Inbox & Feed synchronization */ function getDefaultMuseState() { return { feedUrl: './muse_feed.json', lastFetchedAt: null, feedUpdatedAt: null, feedSummary: '', dismissedIds: [], dismissedScoutNames: [], pendingScouts: [], pendingWorks: [], pendingUpdates: [] }; } /* ========================================================================== Global App State, Gallery State, Navigation Stack & Lightbox State ========================================================================== */ let state = getDefaultState(); let activeTab = 'dna'; let activeTrendCat = 'costumeTags'; let activeMuseTab = 'inbox'; // PWA & Persistent Storage Protection Status let storageProtection = { isStandalone: false, persisted: false, supported: false }; // Gallery Tab State let galleryState = { mode: 'albums', // 'albums' | 'all' selectedActressId: null, // string | null (when inside an Actress Album) source: 'all', // 'all' | 'standalone' | 'work-cut' favoritesOnly: false, shuffled: false, shuffleOrder: [] // array of unified item IDs for stable shuffle }; // View Stack for crisp Back navigation between Actress/Work Detail & Edit screens let viewStack = []; // Chart.js instances let dnaRadarChart = null; let detailRadarChart = null; // Filters let actressFilters = { search: '', sort: 'match', tags: new Set() }; let workFilters = { search: '', status: 'all', actressId: '', sort: 'rating' }; // Lightbox State (Supports Finger-Tracking Swipe, Pinch Zoom, Pan & Immersion Mode) favoriteWorkPhotos: (raw?.favoriteWorkPhotos && typeof raw.favoriteWorkPhotos === 'object') ? raw.favoriteWorkPhotos : {}, museState: normalizeMuseState(raw?.museState), lastBackupAt: typeof raw?.lastBackupAt === 'number' ? raw.lastBackupAt : null }; return normalized; } function normalizeMuseState(raw) { const def = getDefaultMuseState(); if (!raw || typeof raw !== 'object') return def; return { feedUrl: typeof raw.feedUrl === 'string' && raw.feedUrl.trim() ? raw.feedUrl.trim() : def.feedUrl, lastFetchedAt: typeof raw.lastFetchedAt === 'number' ? raw.lastFetchedAt : null, feedUpdatedAt: raw.feedUpdatedAt || null, feedSummary: typeof raw.feedSummary === 'string' ? raw.feedSummary : '', dismissedIds: Array.isArray(raw.dismissedIds) ? raw.dismissedIds : [], dismissedScoutNames: Array.isArray(raw.dismissedScoutNames) ? raw.dismissedScoutNames : [], pendingScouts: Array.isArray(raw.pendingScouts) ? raw.pendingScouts : [], pendingWorks: Array.isArray(raw.pendingWorks) ? raw.pendingWorks : [], pendingUpdates: Array.isArray(raw.pendingUpdates) ? raw.pendingUpdates : [] }; } async function loadStateFromIDB() { // ... existing code ... const mainPayload = { version: SCHEMA_VERSION, actresses: next.actresses, works: next.works, scoutCandidates: next.scoutCandidates, favoriteWorkPhotos: next.favoriteWorkPhotos || {}, museState: normalizeMuseState(next.museState), lastBackupAt: next.lastBackupAt || null }; // ... existing code ... stage.addEventListener('wheel', (e) => { const lbModal = document.getElementById('lightbox-modal'); if (lbModal.classList.contains('hidden')) return; e.preventDefault(); adjustLightboxZoom(e.deltaY < 0 ? 0.35 : -0.35); }, { passive: false }); } /* ========================================================================== IMAGE COMPRESSION HELPERS (SINGLE & GALLERY 2-SIZE PAIR) ========================================================================== */ function compressImageFile(file, maxDim = 800, quality = 0.78) { return new Promise((resolve, reject) => { if (!file || !file.type.startsWith('image/')) { reject(new Error('画像ファイルを選択してください')); return; } const reader = new FileReader(); reader.onerror = () => reject(new Error('ファイルの読み込みに失敗しました')); reader.onload = (ev) => { const img = new Image(); img.onerror = () => reject(new Error('画像のデコードに失敗しました')); img.onload = () => { try { const renderScaled = (limit, q) => { let w = img.width; let h = img.height; if (w > limit || h > limit) { if (w >= h) { h = Math.round((h * limit) / w); w = limit; } else { w = Math.round((w * limit) / h); h = limit; } } const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; const ctx = canvas.getContext('2d'); ctx.fillStyle = '#09090D'; ctx.fillRect(0, 0, w, h); ctx.drawImage(img, 0, 0, w, h); return canvas.toDataURL('image/jpeg', q); }; resolve(renderScaled(maxDim, quality)); } catch (e) { reject(e); } }; img.src = ev.target.result; }; reader.readAsDataURL(file); }); } /** Generates both a lightweight 360px grid thumbnail and a crisp 1400px full image */ function createGalleryImagePair(file) { return new Promise((resolve, reject) => { if (!file || !file.type.startsWith('image/')) { reject(new Error('画像ファイルを選択してください')); return; } const reader = new FileReader(); reader.onerror = () => reject(new Error('ファイルの読み込みに失敗しました')); reader.onload = (ev) => { const img = new Image(); img.onerror = () => reject(new Error('画像のデコードに失敗しました')); img.onload = () => { try { const encodeSize = (limit, q) => { let w = img.width; let h = img.height; if (w > limit || h > limit) { if (w >= h) { h = Math.round((h * limit) / w); w = limit; } else { w = Math.round((w * limit) / h); h = limit; } } const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; const ctx = canvas.getContext('2d'); ctx.fillStyle = '#09090D'; ctx.fillRect(0, 0, w, h); ctx.drawImage(img, 0, 0, w, h); return canvas.toDataURL('image/jpeg', q); }; resolve({ thumb: encodeSize(360, 0.72), full: encodeSize(1400, 0.86) }); } catch (e) { reject(e); } }; img.src = ev.target.result; }; reader.readAsDataURL(file); }); } /* ========================================================================== LIGHTBOX QUICK ACTIONS (FAVORITE, SET MAIN, JUMP TO WORK, DELETE) ========================================================================== */ function toggleLightboxFavorite() { // ... existing code ... } else if (cand) { const ms = state.museState || getDefaultMuseState(); const key = normalizeNameKey(cand.name); if (key && !ms.dismissedScoutNames.includes(key)) { ms.dismissedScoutNames.push(key); } state.museState = ms; showToast(`${cand.name} をスキップしました`, 'neutral'); } saveState(); isScoutAnimating = false; updateAllViews(); }, 240); } // ... existing code ... const bkInfo = formatBackupElapsed(state.lastBackupAt); lastBkEl.textContent = bkInfo.text; lastBkEl.className = `text-[11px] font-black ${bkInfo.isWarning ? 'text-amber-300' : 'text-emerald-300'}`; } /* ========================================================================== MUSE INTEGRATION ENGINE (AUTO-FETCH, JSON PASTE, SAFE MERGE & PROFILE EXPORT) ========================================================================== */ function normalizeNameKey(str) { return String(str || '').replace(/[\s ]+/g, '').trim().toLowerCase(); } function normalizeCodeKey(str) { return String(str || '').replace(/[\s\-_]+/g, '').trim().toUpperCase(); } function findActressByLooseName(name) { const target = normalizeNameKey(name); if (!target) return null; return state.actresses.find((a) => normalizeNameKey(a.name) === target) || null; } function countMusePendingItems() { const ms = state.museState || getDefaultMuseState(); return (ms.pendingScouts?.length || 0) + (ms.pendingWorks?.length || 0) + (ms.pendingUpdates?.length || 0); } function updateMuseBadge() { const total = countMusePendingItems(); const badge = document.getElementById('header-muse-badge'); if (badge) { badge.textContent = total > 99 ? '99+' : String(total); badge.classList.toggle('hidden', total === 0); } const tabCount = document.getElementById('muse-tab-count'); if (tabCount) { tabCount.textContent = total > 0 ? `(${total})` : ''; } } /** Builds lightweight taste_profile.json payload (no images / no personal memos) */ function buildTasteProfilePayload() { const dna = computeUserDNA(); const topBipolarSummary = BIPOLAR_AXES.map((ax) => { const val = Number(dna.idealBipolar[ax.key] || 0); const pct = Math.round(50 + (Math.abs(val) / 5) * 50); const lean = Math.abs(val) < 0.6 ? 'バランス型' : (val < 0 ? `${ax.left}寄り ${pct}%` : `${ax.right}寄り ${pct}%`); return { key: ax.key, left: ax.left, right: ax.right, score: val, label: lean }; }); const topWorkTags = { costume: computeWorkTagRanking('costumeTags').slice(0, 6).map((x) => x.tag), situation: computeWorkTagRanking('situationTags').slice(0, 6).map((x) => x.tag), play: computeWorkTagRanking('playTags').slice(0, 6).map((x) => x.tag) }; const registeredActresses = state.actresses.map((a) => ({ name: a.name, rating: a.rating || 0, isMvp: Boolean(a.isMvp), tags: a.tags || [], workCount: getWorksByActress(a.id).length })); const registeredWorkCodes = state.works .map((w) => w.code) .filter((c) => Boolean(c && c.trim())); return { schema: 'taste_profile_v1', updatedAt: new Date().toISOString(), stats: { actressCount: state.actresses.length, workCount: state.works.length, totalRepeats: getTotalRepeats() }, strikeZone: { idealBipolar: dna.idealBipolar, bipolarSummary: topBipolarSummary, avgRadar: dna.avgRadar, topActressTags: dna.topTags.slice(0, 10).map((t) => t.tag), topWorkTags }, registeredActresses, registeredWorkCodes, skippedScoutNames: (state.museState?.dismissedScoutNames || []).slice(0, 50) }; } /** Generates a ready-to-paste Japanese instruction prompt for Muse */ function buildMusePromptText() { const profileJson = JSON.stringify(buildTasteProfilePayload(), null, 2); return [ 'あなたは私の専用リサーチ担当(TASTE ANALYZER用アシスタント)です。', '以下の「現在の好みプロフィール(taste_profile.json)」をもとにWeb調査を行い、', '1) 好み座標に合う新規スカウト候補(未登録・未スキップのみ)', '2) 登録済み女優のおすすめ作品・新作(registeredWorkCodesと重複しないもの)', '3) 登録済み女優のプロフィール追記情報(追加タグ・特徴メモ)', 'をまとめて、以下の厳密なJSONフォーマット(muse_feed.json)で出力してください。', '', '【ルール】', '・bipolar の各値は -5〜+5 の整数(hierarchy: 格上-5⇔後輩+5 / face: キレイ-5⇔カワイイ+5 / vibe: 清楚-5⇔艶+5 / distance: クール-5⇔明るい+5 / body: 細身-5⇔グラマー+5 / voice: 高め-5⇔低め+5)', '・radar の各値は 1.0〜5.0 の数値(looks, style, voiceScore, expression, gap)', '・workProposals の id と actressUpdates の id は毎回ユニークな文字列にする(例: "prop-20261201-01")', '・GitHub運用時は最後に muse_feed.json を1回のコミットで更新する(直接チャット返答時はJSONのみ出力)', '', '【出力JSONフォーマット】', '{', ' "updatedAt": "2026-12-01T21:00:00+09:00",', ' "summary": "今回の調査まとめ(1〜2行)",', ' "newScouts": [', ' {', ' "name": "候補名",', ' "bipolar": { "hierarchy": -3, "face": -3, "vibe": -2, "distance": -2, "body": -2, "voice": 3 },', ' "radar": { "looks": 4.5, "style": 4.5, "voiceScore": 4.5, "expression": 4.0, "gap": 4.5 },', ' "tags": ["タグ1", "タグ2"],', ' "memo": "おすすめ理由",', ' "photoUrl": ""', ' }', ' ],', ' "workProposals": [', ' {', ' "id": "prop-YYYYMMDD-01",', ' "actressName": "登録済み女優名",', ' "code": "品番",', ' "title": "作品タイトル",', ' "costumeTags": ["衣装タグ"],', ' "situationTags": ["シチュエーションタグ"],', ' "playTags": ["プレイ・展開タグ"],', ' "memo": "見どころメモ",', ' "thumbnailUrl": ""', ' }', ' ],', ' "actressUpdates": [', ' {', ' "id": "upd-YYYYMMDD-01",', ' "actressName": "登録済み女優名",', ' "addTags": ["追加タグ候補"],', ' "appendMemo": "【Muse調査】追記メモ"', ' }', ' ]', '}', '', '【現在の好みプロフィール(taste_profile.json)】', profileJson ].join('\n'); } async function copyTextSafe(text, successMsg) { try { if (navigator.clipboard && navigator.clipboard.writeText) { await navigator.clipboard.writeText(text); showToast(successMsg, 'gold'); return true; } } catch (e) { // Fallback textarea copy below } try { const ta = document.createElement('textarea'); ta.value = text; ta.style.position = 'fixed'; ta.style.opacity = '0'; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta); showToast(successMsg, 'gold'); return true; } catch (err) { showToast('クリップボードへのコピーに失敗しました', 'error'); return false; } } function exportTasteProfileJson() { try { const payload = buildTasteProfilePayload(); const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = 'taste_profile.json'; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); showToast('💾 taste_profile.json を書き出しました', 'gold'); } catch (err) { console.error(err); showToast('書き出しに失敗しました', 'error'); } } /** Extracts and parses JSON even if wrapped in markdown code blocks or surrounding prose */ function parseJsonFromRawText(rawText) { let cleaned = String(rawText || '').trim(); if (!cleaned) throw new Error('JSONが空です'); // Strip leading/trailing markdown fences if present const fenceRegex = /^```(?:json)?\s*([\s\S]*?)\s*```$/i; const fenceMatch = cleaned.match(fenceRegex); if (fenceMatch) cleaned = fenceMatch[1].trim(); try { return JSON.parse(cleaned); } catch (e) { // Fallback: slice from first '{' to last '}' const start = cleaned.indexOf('{'); const end = cleaned.lastIndexOf('}'); if (start !== -1 && end > start) { return JSON.parse(cleaned.slice(start, end + 1)); } throw new Error('JSONの構文を解析できませんでした'); } } /** Deduplicates and ingests a muse_feed.json object into state.museState */ function ingestMuseFeed(feed, { sourceLabel = 'フィード', silent = false } = {}) { if (!feed || typeof feed !== 'object') { throw new Error('有効なMuseフィードJSONではありません'); } const ms = normalizeMuseState(state.museState); const existingActressKeys = new Set(state.actresses.map((a) => normalizeNameKey(a.name))); const existingScoutDeckKeys = new Set((state.scoutCandidates || []).map((c) => normalizeNameKey(c.name))); const dismissedScoutSet = new Set(ms.dismissedScoutNames || []); const dismissedIdSet = new Set(ms.dismissedIds || []); const existingWorkCodes = new Set(state.works.map((w) => normalizeCodeKey(w.code)).filter(Boolean)); const existingWorkTitles = new Set(state.works.map((w) => normalizeNameKey(w.title)).filter(Boolean)); // Keep track of previously pending items so manual paste merges instead of wiping unread items const pendingScoutMap = new Map((ms.pendingScouts || []).map((s) => [normalizeNameKey(s.name), s])); const pendingWorkMap = new Map((ms.pendingWorks || []).map((w) => [w.id, w])); const pendingUpdMap = new Map((ms.pendingUpdates || []).map((u) => [u.id, u])); let addedCount = 0; // 1. Ingest newScouts if (Array.isArray(feed.newScouts)) { feed.newScouts.forEach((sc, idx) => { const name = String(sc?.name || '').trim(); const key = normalizeNameKey(name); if (!key) return; if (existingActressKeys.has(key) || existingScoutDeckKeys.has(key) || dismissedScoutSet.has(key)) return; if (!pendingScoutMap.has(key)) addedCount++; pendingScoutMap.set(key, { id: sc.id || `mscout-${key}-${idx}`, name, theme: sc.theme || ['gold', 'crimson', 'violet', 'ember', 'sapphire'][idx % 5], photoUrl: typeof sc.photoUrl === 'string' ? sc.photoUrl.trim() : (typeof sc.photo === 'string' ? sc.photo.trim() : ''), bipolar: { hierarchy: Number(sc.bipolar?.hierarchy ?? 0), face: Number(sc.bipolar?.face ?? 0), vibe: Number(sc.bipolar?.vibe ?? 0), distance: Number(sc.bipolar?.distance ?? 0), body: Number(sc.bipolar?.body ?? 0), voice: Number(sc.bipolar?.voice ?? 0) }, radar: { looks: Number(sc.radar?.looks ?? 4.0), style: Number(sc.radar?.style ?? 4.0), voiceScore: Number(sc.radar?.voiceScore ?? 4.0), expression: Number(sc.radar?.expression ?? 4.0), gap: Number(sc.radar?.gap ?? 4.0) }, tags: Array.isArray(sc.tags) ? sc.tags.map((t) => String(t).replace(/^#/, '').trim()).filter(Boolean) : [], memo: String(sc.memo || '').trim() }); }); } // 2. Ingest workProposals if (Array.isArray(feed.workProposals)) { feed.workProposals.forEach((wp, idx) => { const title = String(wp?.title || '').trim(); const code = String(wp?.code || '').trim().toUpperCase(); if (!title && !code) return; const id = String(wp.id || `mwork-${normalizeCodeKey(code) || normalizeNameKey(title)}-${idx}`); if (dismissedIdSet.has(id)) return; if (code && existingWorkCodes.has(normalizeCodeKey(code))) return; if (!code && existingWorkTitles.has(normalizeNameKey(title))) return; if (!pendingWorkMap.has(id)) addedCount++; pendingWorkMap.set(id, { id, actressName: String(wp.actressName || '').trim(), code, title: title || code, costumeTags: Array.isArray(wp.costumeTags) ? wp.costumeTags.filter(Boolean) : [], situationTags: Array.isArray(wp.situationTags) ? wp.situationTags.filter(Boolean) : [], playTags: Array.isArray(wp.playTags) ? wp.playTags.filter(Boolean) : [], memo: String(wp.memo || '').trim(), thumbnailUrl: typeof wp.thumbnailUrl === 'string' ? wp.thumbnailUrl.trim() : '' }); }); } // 3. Ingest actressUpdates if (Array.isArray(feed.actressUpdates)) { feed.actressUpdates.forEach((upd, idx) => { const actressName = String(upd?.actressName || '').trim(); if (!actressName) return; const id = String(upd.id || `mupd-${normalizeNameKey(actressName)}-${idx}`); if (dismissedIdSet.has(id)) return; const addTags = Array.isArray(upd.addTags) ? upd.addTags.map((t) => String(t).replace(/^#/, '').trim()).filter(Boolean) : []; const appendMemo = String(upd.appendMemo || '').trim(); if (!addTags.length && !appendMemo) return; if (!pendingUpdMap.has(id)) addedCount++; pendingUpdMap.set(id, { id, actressName, addTags, appendMemo }); }); } ms.pendingScouts = Array.from(pendingScoutMap.values()); ms.pendingWorks = Array.from(pendingWorkMap.values()); ms.pendingUpdates = Array.from(pendingUpdMap.values()); ms.lastFetchedAt = Date.now(); if (feed.updatedAt) ms.feedUpdatedAt = feed.updatedAt; if (typeof feed.summary === 'string' && feed.summary.trim()) ms.feedSummary = feed.summary.trim(); state.museState = ms; saveState(); updateMuseBadge(); const totalPending = countMusePendingItems(); if (!silent) { if (addedCount > 0) { showToast(`📥 ${sourceLabel}から新着提案を${addedCount}件取り込みました`, 'gold'); } else if (totalPending > 0) { showToast(`未処理の提案が${totalPending}件あります(重複は除外済)`, 'neutral'); } else { showToast(`新しい提案はありませんでした(すべて処理済)`, 'neutral'); } } else if (addedCount > 0) { showToast(`📥 Museから新着提案が${addedCount}件届きました`, 'gold'); } return { addedCount, totalPending }; } /** Fetches ./muse_feed.json (or custom URL) with cache-busting */ async function fetchMuseFeed({ silent = false } = {}) { const ms = normalizeMuseState(state.museState); const baseUrl = ms.feedUrl || './muse_feed.json'; const sep = baseUrl.includes('?') ? '&' : '?'; const fetchUrl = `${baseUrl}${sep}t=${Date.now()}`; const statusEl = document.getElementById('muse-fetch-status'); if (!silent && statusEl) { statusEl.textContent = '取得中...'; statusEl.className = 'text-[10.5px] text-gold-light font-bold'; } try { const res = await fetch(fetchUrl, { cache: 'no-store' }); if (!res.ok) { if (res.status === 404) { if (!silent && statusEl) { statusEl.textContent = 'muse_feed.json がまだリポジトリに置かれていません(「JSON貼付」タブから直接取り込みも可能です)。'; statusEl.className = 'text-[10.5px] text-amber-300'; } if (!silent) showToast('muse_feed.json が見つかりません(404)', 'neutral'); return false; } throw new Error(`HTTP ${res.status}`); } const text = await res.text(); const parsed = parseJsonFromRawText(text); const result = ingestMuseFeed(parsed, { sourceLabel: 'muse_feed.json', silent }); if (statusEl) { statusEl.textContent = `✓ 最終同期: ${new Date().toLocaleTimeString('ja-JP')}(新着 ${result.addedCount}件 / 未処理 ${result.totalPending}件)`; statusEl.className = 'text-[10.5px] text-emerald-300 font-bold'; } renderMuseModal(); return true; } catch (err) { if (!silent) { if (statusEl) { statusEl.textContent = `取得できませんでした(${err.message || 'オフラインまたはファイル未配置'})`; statusEl.className = 'text-[10.5px] text-zinc-400'; } showToast('フィードを取得できませんでした(JSON貼付タブも使えます)', 'neutral'); } return false; } } function openMuseModal(initialTab = 'inbox') { activeMuseTab = initialTab; const modal = document.getElementById('muse-modal'); modal.classList.remove('hidden'); modal.classList.add('flex'); document.body.style.overflow = 'hidden'; switchMuseModalTab(initialTab); } function closeMuseModal() { const modal = document.getElementById('muse-modal'); modal.classList.add('hidden'); modal.classList.remove('flex'); document.body.style.overflow = ''; } function switchMuseModalTab(tabName) { activeMuseTab = tabName; ['inbox', 'paste', 'export'].forEach((t) => { document.getElementById(`muse-panel-${t}`).classList.toggle('hidden', t !== tabName); }); document.querySelectorAll('.muse-tab-btn').forEach((btn) => { const active = btn.dataset.museTab === tabName; btn.classList.toggle('bg-gold', active); btn.classList.toggle('text-obsidian', active); btn.classList.toggle('font-black', active); btn.classList.toggle('text-zinc-400', !active); }); renderMuseModal(); } function renderMuseModal() { const ms = normalizeMuseState(state.museState); state.museState = ms; updateMuseBadge(); // Sync Header Timestamp & Feed URL Input const syncLabel = document.getElementById('muse-last-sync-label'); if (syncLabel) { syncLabel.textContent = ms.lastFetchedAt ? `最終確認: ${new Date(ms.lastFetchedAt).toLocaleString('ja-JP', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' })}` : 'フィード未取得(JSON貼付もOK)'; } const urlInput = document.getElementById('muse-feed-url-input'); if (urlInput && document.activeElement !== urlInput) { urlInput.value = ms.feedUrl || './muse_feed.json'; } // Sync Feed Summary const summaryEl = document.getElementById('muse-feed-summary'); if (summaryEl) { summaryEl.innerHTML = ms.feedSummary ? `${esc(ms.feedSummary)}${ms.feedUpdatedAt ? `配信日時: ${esc(ms.feedUpdatedAt)}` : ''}` : `リポジトリの ${esc(ms.feedUrl)} から最新のスカウト・作品・プロフィール追記を取得します。`; } // Export Tab Stats Preview const statsEl = document.getElementById('muse-profile-preview-stats'); if (statsEl) { const codesCount = state.works.filter((w) => w.code && w.code.trim()).length; statsEl.innerHTML = `
登録女優
${state.actresses.length}名
既存品番
${codesCount}件
スキップ済
${ms.dismissedScoutNames.length}名
`; } // Inbox Items Rendering const listEl = document.getElementById('muse-inbox-list'); if (!listEl) return; const total = countMusePendingItems(); if (total === 0) { listEl.innerHTML = `
✨

未処理の提案はありません

「Museへ渡す」タブからプロンプトをコピーしてMuseに調査を依頼し、muse_feed.json を更新するか「JSON貼付」タブから取り込んでください。

`; return; } const dna = computeUserDNA(); const blocks = []; // Section 1: Work Proposals if (ms.pendingWorks.length) { blocks.push(`

🎬 新作・おすすめ作品提案 (${ms.pendingWorks.length}件)

${ms.pendingWorks.length > 1 ? ` ` : ''}
${ms.pendingWorks.map((wp) => { const matchedActress = findActressByLooseName(wp.actressName); const tagHtml = [ ...(wp.costumeTags || []).map((t) => `${esc(t)}`), ...(wp.situationTags || []).map((t) => `${esc(t)}`), ...(wp.playTags || []).map((t) => `${esc(t)}`) ].join(''); return `
${esc(wp.code || 'NO-CODE')} ${matchedActress ? `✓ ${esc(matchedActress.name)} に自動紐付け` : (wp.actressName ? `出演: ${esc(wp.actressName)}(未登録)` : '出演女優未指定')}
${esc(wp.title)}
${tagHtml ? `
${tagHtml}
` : ''} ${wp.memo ? `

${esc(wp.memo)}

` : ''}
`; }).join('')}
`); } // Section 2: Actress Profile Updates (Safe Non-Destructive Append) if (ms.pendingUpdates.length) { blocks.push(`

📝 既存女優の情報補強 (${ms.pendingUpdates.length}件)

${ms.pendingUpdates.map((upd) => { const target = findActressByLooseName(upd.actressName); return `
${esc(upd.actressName)} ${target ? '登録済みに安全追記' : '女優DBに未登録'}
${upd.addTags.length ? `
${upd.addTags.map((t) => `+#${esc(t)}`).join('')}
` : ''} ${upd.appendMemo ? `

${esc(upd.appendMemo)}

` : ''}

※ あなたの★評価・スライダー・既存メモは上書きされません。

`; }).join('')}
`); } // Section 3: New Scout Candidates if (ms.pendingScouts.length) { blocks.push(`

✨ 新規スカウト候補 (${ms.pendingScouts.length}名)

${ms.pendingScouts.map((sc, idx) => { const matchPct = calculateMatchScore(sc, dna); return `
${esc(sc.name)}
推定一致 ${matchPct}%
${(sc.tags || []).length ? `
${sc.tags.map((t) => `#${esc(t)}`).join('')}
` : ''} ${sc.memo ? `

${esc(sc.memo)}

` : ''}
`; }).join('')}
`); } listEl.innerHTML = blocks.join(''); } function approveMuseWork(propId) { const ms = normalizeMuseState(state.museState); const idx = ms.pendingWorks.findIndex((w) => w.id === propId); if (idx === -1) return; const wp = ms.pendingWorks[idx]; const matchedActress = findActressByLooseName(wp.actressName); const newWork = { id: `wrk-${Date.now()}-${Math.random().toString(36).slice(2, 5)}`, code: wp.code || '', title: wp.title, actressId: matchedActress ? matchedActress.id : '', thumbnail: wp.thumbnailUrl || generateWorkArt(wp.code || 'MUSE', 'MUSE PICK', `${matchedActress ? matchedActress.name + ' / ' : ''}${wp.title.slice(0, 14)}`, 'crimson', 0), thumbnailPosition: normalizeCrop(null, 50), subPhotos: [], watched: false, rating: 4, repeatCount: 0, costumeTags: [...(wp.costumeTags || [])], situationTags: [...(wp.situationTags || [])], playTags: [...(wp.playTags || [])], memo: wp.memo || '', createdAt: Date.now() }; state.works.unshift(newWork); ms.pendingWorks.splice(idx, 1); if (!ms.dismissedIds.includes(propId)) ms.dismissedIds.push(propId); state.museState = ms; saveState(); updateAllViews(); renderMuseModal(); showToast(`🎬 「${wp.code || wp.title.slice(0, 14)}」を未視聴に追加しました`, 'gold'); } function approveAllMuseWorks() { const ms = normalizeMuseState(state.museState); if (!ms.pendingWorks.length) return; const count = ms.pendingWorks.length; const baseTs = Date.now(); ms.pendingWorks.forEach((wp, i) => { const matchedActress = findActressByLooseName(wp.actressName); state.works.unshift({ id: `wrk-${baseTs}-${i}-${Math.random().toString(36).slice(2, 5)}`, code: wp.code || '', title: wp.title, actressId: matchedActress ? matchedActress.id : '', thumbnail: wp.thumbnailUrl || generateWorkArt(wp.code || 'MUSE', 'MUSE PICK', `${matchedActress ? matchedActress.name + ' / ' : ''}${wp.title.slice(0, 14)}`, 'crimson', i % 4), thumbnailPosition: normalizeCrop(null, 50), subPhotos: [], watched: false, rating: 4, repeatCount: 0, costumeTags: [...(wp.costumeTags || [])], situationTags: [...(wp.situationTags || [])], playTags: [...(wp.playTags || [])], memo: wp.memo || '', createdAt: baseTs + i }); if (!ms.dismissedIds.includes(wp.id)) ms.dismissedIds.push(wp.id); }); ms.pendingWorks = []; state.museState = ms; saveState(); updateAllViews(); renderMuseModal(); showToast(`🎬 ${count}本の作品をまとめて未視聴に追加しました`, 'gold'); } function dismissMuseWork(propId) { const ms = normalizeMuseState(state.museState); ms.pendingWorks = ms.pendingWorks.filter((w) => w.id !== propId); if (!ms.dismissedIds.includes(propId)) ms.dismissedIds.push(propId); state.museState = ms; saveState(); renderMuseModal(); showToast('作品提案をスキップしました', 'neutral'); } function approveMuseActressUpdate(updId) { const ms = normalizeMuseState(state.museState); const idx = ms.pendingUpdates.findIndex((u) => u.id === updId); if (idx === -1) return; const upd = ms.pendingUpdates[idx]; const target = findActressByLooseName(upd.actressName); if (!target) { showToast('対象の女優が登録されていません', 'error'); return; } // Safe merge: append only new tags & append memo without overwriting existing data const existingTags = new Set(target.tags || []); (upd.addTags || []).forEach((t) => existingTags.add(t)); target.tags = Array.from(existingTags); if (upd.appendMemo) { target.memo = target.memo ? `${target.memo}\n\n${upd.appendMemo}` : upd.appendMemo; } ms.pendingUpdates.splice(idx, 1); if (!ms.dismissedIds.includes(updId)) ms.dismissedIds.push(updId); state.museState = ms; saveState(); updateAllViews(); renderMuseModal(); showToast(`✓ ${target.name} にタグ・メモを追記しました`, 'gold'); } function dismissMuseActressUpdate(updId) { const ms = normalizeMuseState(state.museState); ms.pendingUpdates = ms.pendingUpdates.filter((u) => u.id !== updId); if (!ms.dismissedIds.includes(updId)) ms.dismissedIds.push(updId); state.museState = ms; saveState(); renderMuseModal(); showToast('プロフィール追記をスキップしました', 'neutral'); } function approveMuseScoutToDb(index) { const ms = normalizeMuseState(state.museState); const sc = ms.pendingScouts[index]; if (!sc) return; const newActress = { id: `act-${Date.now()}`, name: sc.name, rating: 4, isMvp: state.actresses.length === 0, theme: sc.theme || 'gold', photo: sc.photoUrl || generatePortraitArt(sc.name, sc.theme || 'gold', 'MUSE'), photoPosition: normalizeCrop(null, 20), bipolar: { ...(sc.bipolar || {}) }, radar: { ...(sc.radar || { looks: 4, style: 4, voiceScore: 4, expression: 4, gap: 4 }) }, tags: [...(sc.tags || [])], memo: sc.memo || '', createdAt: Date.now() }; state.actresses.unshift(newActress); ms.pendingScouts.splice(index, 1); state.museState = ms; saveState(); updateAllViews(); renderMuseModal(); showToast(`★ ${sc.name} を女優DBに登録しました`, 'gold'); } function sendMuseScoutToDeck(index) { const ms = normalizeMuseState(state.museState); const sc = ms.pendingScouts[index]; if (!sc) return; state.scoutCandidates.unshift({ id: `sc-${Date.now()}`, name: sc.name, theme: sc.theme || 'crimson', photo: sc.photoUrl || generatePortraitArt(sc.name, sc.theme || 'crimson', 'MUSE'), bipolar: { ...(sc.bipolar || {}) }, radar: { ...(sc.radar || { looks: 4, style: 4, voiceScore: 4, expression: 4, gap: 4 }) }, tags: [...(sc.tags || [])], memo: sc.memo || '' }); ms.pendingScouts.splice(index, 1); state.museState = ms; saveState(); updateAllViews(); renderMuseModal(); showToast(`🃏 ${sc.name} をスカウトタブへ送りました`, 'gold'); } function dismissMuseScout(index) { const ms = normalizeMuseState(state.museState); const sc = ms.pendingScouts[index]; if (!sc) return; const key = normalizeNameKey(sc.name); if (key && !ms.dismissedScoutNames.includes(key)) { ms.dismissedScoutNames.push(key); } ms.pendingScouts.splice(index, 1); state.museState = ms; saveState(); renderMuseModal(); showToast(`${sc.name} をスキップしました`, 'neutral'); } function handleMuseManualPaste() { const input = document.getElementById('muse-paste-input'); const raw = input.value; try { const parsed = parseJsonFromRawText(raw); ingestMuseFeed(parsed, { sourceLabel: '貼り付けJSON', silent: false }); input.value = ''; switchMuseModalTab('inbox'); } catch (err) { showToast(err.message || 'JSONの解析に失敗しました', 'error'); } } function loadSampleMusePaste() { const firstActress = state.actresses[0]?.name || '桐生 玲奈'; const sample = { updatedAt: new Date().toISOString(), summary: `テスト配信:${firstActress}のおすすめ作品1本・プロフィール追記1件・新スカウト候補1名をピックアップしました。`, newScouts: [ { name: '黒木 蓮華', bipolar: { hierarchy: -4, face: -4, vibe: -1, distance: -3, body: -2, voice: 4 }, radar: { looks: 4.5, style: 4.5, voiceScore: 5.0, expression: 4.5, gap: 4.5 }, tags: ['低音ボイス', '知的オーラ', '黒髪ロング'], memo: '落ち着いた低めボイスとクールな立ち振る舞いが好み座標と高一致。' } ], workProposals: [ { id: `prop-sample-${Date.now()}`, actressName: firstActress, code: 'MUSE-001', title: '深夜のプライベートラウンジ — 静かな囁きと二人だけの時間', costumeTags: ['ドレス', 'スーツ'], situationTags: ['ホテル夜景', '秘密の関係'], playTags: ['囁き・耳元', 'スロー展開'], memo: 'Museテスト提案:高評価レビュー多数の人気作。' } ], actressUpdates: [ { id: `upd-sample-${Date.now()}`, actressName: firstActress, addTags: ['ドラマ重視', '大人の色気'], appendMemo: '【Muse調査】落ち着いた掛け合いと終盤のギャップ演出が特に高評価。' } ] }; document.getElementById('muse-paste-input').value = JSON.stringify(sample, null, 2); showToast('テスト用JSONを入力しました。「解析して取り込む」を押してください', 'gold'); } /* ========================================================================== BACKUP, INDEXEDDB STORAGE USAGE BAR & JSON IMPORT/EXPORT ========================================================================== */ // ... existing code ... const payload = { version: SCHEMA_VERSION, exportedAt: now.toISOString(), lastBackupAt: exportedTs, actresses: state.actresses, works: state.works, scoutCandidates: state.scoutCandidates, galleryPhotos: state.galleryPhotos || [], favoriteWorkPhotos: state.favoriteWorkPhotos || {}, museState: normalizeMuseState(state.museState) }; // ... existing code ... function updateAllViews() { renderDnaTab(); renderActressesTab(); renderWorksTab(); renderGalleryTab(); renderScoutTab(); updateBackupReminderDot(); updateMuseBadge(); } // ... existing code ... // Sheet Backdrop Close document.getElementById('sheet-overlay').addEventListener('click', (e) => { if (e.target.id === 'sheet-overlay') popView(); }); // Lightbox Controls, Gestures (Swipe/Pinch/Pan/Pull-Dismiss) & Keyboard document.getElementById('lb-back-btn').addEventListener('click', closeLightbox); document.getElementById('lb-prev-btn').addEventListener('click', () => stepLightbox(-1, true)); document.getElementById('lb-next-btn').addEventListener('click', () => stepLightbox(1, true)); document.getElementById('lb-zoom-out').addEventListener('click', () => adjustLightboxZoom(-0.5)); document.getElementById('lb-zoom-in').addEventListener('click', () => adjustLightboxZoom(0.5)); document.getElementById('lb-zoom-reset').addEventListener('click', () => resetLightboxZoom(true)); document.getElementById('lb-fav-btn').addEventListener('click', toggleLightboxFavorite); document.getElementById('lb-set-main-btn').addEventListener('click', setLightboxPhotoAsActressMain); document.getElementById('lb-open-work-btn').addEventListener('click', openLightboxSourceWork); document.getElementById('lb-delete-btn').addEventListener('click', deleteLightboxStandalonePhoto); initLightboxGestures(); window.addEventListener('keydown', (e) => { const lbModal = document.getElementById('lightbox-modal'); if (!lbModal.classList.contains('hidden')) { if (e.key === 'Escape') closeLightbox(); else if (e.key === 'ArrowLeft') stepLightbox(-1, true); else if (e.key === 'ArrowRight') stepLightbox(1, true); else if (e.key === '+' || e.key === '=') adjustLightboxZoom(0.4); else if (e.key === '-') adjustLightboxZoom(-0.4); else if (e.key === '0') resetLightboxZoom(true); } }); // Muse Inbox & Sync Modal Controls document.getElementById('btn-open-muse').addEventListener('click', () => openMuseModal('inbox')); document.getElementById('btn-close-muse').addEventListener('click', closeMuseModal); document.getElementById('muse-modal').addEventListener('click', (e) => { if (e.target.id === 'muse-modal') closeMuseModal(); }); document.querySelectorAll('.muse-tab-btn').forEach((btn) => { btn.addEventListener('click', () => switchMuseModalTab(btn.dataset.museTab)); }); document.getElementById('btn-muse-fetch').addEventListener('click', () => fetchMuseFeed({ silent: false })); document.getElementById('btn-muse-parse-paste').addEventListener('click', handleMuseManualPaste); document.getElementById('btn-muse-clear-paste').addEventListener('click', () => { document.getElementById('muse-paste-input').value = ''; }); document.getElementById('btn-muse-load-sample').addEventListener('click', loadSampleMusePaste); document.getElementById('btn-muse-export-profile').addEventListener('click', exportTasteProfileJson); document.getElementById('btn-muse-copy-profile').addEventListener('click', () => { copyTextSafe(JSON.stringify(buildTasteProfilePayload(), null, 2), '📋 taste_profile.json をコピーしました'); }); document.getElementById('btn-muse-copy-prompt').addEventListener('click', () => { copyTextSafe(buildMusePromptText(), '🤖 Muse用・調査指示プロンプトをコピーしました'); }); document.getElementById('btn-muse-save-url').addEventListener('click', () => { const val = document.getElementById('muse-feed-url-input').value.trim() || './muse_feed.json'; state.museState = normalizeMuseState(state.museState); state.museState.feedUrl = val; saveState(); renderMuseModal(); showToast('受信フィードURLを保存しました', 'gold'); }); document.getElementById('btn-muse-reset-history').addEventListener('click', () => { openConfirmModal( 'Muse処理履歴をリセット', 'スキップ済み・既読済みのIDとスカウト除外リストをクリアしますか?(同じ muse_feed.json を再度取り込み直せます)', () => { const ms = normalizeMuseState(state.museState); ms.dismissedIds = []; ms.dismissedScoutNames = []; state.museState = ms; saveState(); renderMuseModal(); showToast('Museの処理履歴をクリアしました', 'gold'); } ); }); // Backup Modal & JSON Import/Export Controls // ... existing code ... // Initial Render & Background Muse Feed Check updateAllViews(); fetchMuseFeed({ silent: true }); });