/* script.js
- スマホ優先で作り込んだマップロジック + Panzoom対応
- CSV: data/floor1.csv / data/floor2.csv を想定
- CSVヘッダ(日本語 or 英語): 名前,name / 説明,description / 画像,image / X座標,x / Y座標,y
*/
'use strict';
const IMAGE_PATH = { 1: 'images/1F.png', 2: 'images/floor2.png' };
const CSV_PATH = { 1: 'data/floor1.csv', 2: 'data/floor2.csv' };
// DOM
const img = document.getElementById('mapImage');
const map = document.getElementById('map');
const tabButtons = document.querySelectorAll('.tab-button');
const listToggle = document.getElementById('listToggle');
const listPanel = document.getElementById('listPanel');
const listContent = document.getElementById('listContent');
const closeListBtn = document.getElementById('closeList');
let currentFloor = 1;
let currentData = [];
let pinEls = [];
let tooltipEls = [];
let panzoomInstance = null;
/* ================= CSV パーサ ================= */
function parseCSV(text) {
const rows = [];
let cur = '', row = [], inQuotes = false;
for (let i=0;i<text.length;i++){
const ch = text[i];
if (ch === '"') {
if (inQuotes && text[i+1] === '"') { cur += '"'; i++; }
else { inQuotes = !inQuotes; }
continue;
}
if (ch === ',' && !inQuotes) { row.push(cur); cur=''; continue; }
if ((ch === '\n' || ch === '\r') && !inQuotes) {
if (ch === '\r' && text[i+1] === '\n') i++;
row.push(cur); rows.push(row); row=[]; cur=''; continue;
}
cur += ch;
}
if (cur !== '' || row.length>0) { row.push(cur); rows.push(row); }
return rows.map(r => r.map(cell => cell.replace(/^\uFEFF/, '').trim()));
}
function mapHeaders(headers) {
const map = {};
const norm = headers.map(h => (h||'').toLowerCase());
norm.forEach((h,i)=>{
if (['name','名前','title'].includes(h)) map.name = i;
else if (['description','説明','comment'].includes(h)) map.description = i;
else if (['image','画像','画像ファイル','img','imagefile'].includes(h)) map.image = i;
else if (['x','x座標','横','left'].includes(h)) map.x = i;
else if (['y','y座標','縦','top'].includes(h)) map.y = i;
});
const fallback = ['name','description','image','x','y'];
fallback.forEach((k,idx)=>{ if (map[k]===undefined && headers[idx] !== undefined) map[k]=idx; });
return map;
}
function csvToObjects(text) {
const rows = parseCSV(text).filter(r => r.length>0 && !(r.length===1 && r[0]===''));
if (rows.length===0) return [];
const headers = rows[0];
const map = mapHeaders(headers);
const data = [];
for (let i=1;i<rows.length;i++){
const r = rows[i];
if (!r.some(cell => cell && cell.trim() !== '')) continue;
const obj = {
name: (r[map.name]||'').trim(),
description: (r[map.description]||'').trim(),
image: (r[map.image]||'').trim(),
x: parseFloat(r[map.x]) || 0,
y: parseFloat(r[map.y]) || 0
};
data.push(obj);
}
return data;
}
async function loadCSV(url) {
try {
const res = await fetch(url, {cache:'no-cache'});
if (!res.ok) throw new Error('CSV読み込み失敗: ' + res.status);
const text = await res.text();
return csvToObjects(text);
} catch (err) {
console.error(err);
return [];
}
}
/* 画像ロード待ち */
function waitImageLoad(imgEl) {
return new Promise(resolve => {
if (imgEl.complete && imgEl.naturalWidth !== 0) return resolve();
const onLoad = () => { imgEl.removeEventListener('load', onLoad); resolve(); };
imgEl.addEventListener('load', onLoad);
});
}
/* ツールチップ位置調整(map 内の座標 -> ビューポートに合わせて補正) */
function adjustTooltipPosition(tooltip, desiredLeftPxMap, desiredTopPxMap) {
// mapRect = map 要素のビューポート座標
const mapRect = map.getBoundingClientRect();
const desiredLeftViewport = mapRect.left + desiredLeftPxMap;
const desiredTopViewport = mapRect.top + desiredTopPxMap;
// temporarily show (hidden) to measure size
tooltip.style.display = 'block';
tooltip.style.visibility = 'hidden';
tooltip.style.transform = 'translate(-50%, -120%)';
// measure tooltip in viewport coords
const tRect = tooltip.getBoundingClientRect();
const margin = 8;
// horizontal shift (viewport)
let shiftXViewport = 0;
if (tRect.left < margin) shiftXViewport = margin - tRect.left;
if (tRect.right > window.innerWidth - margin) shiftXViewport = (window.innerWidth - margin) - tRect.right;
// vertical flip if top would go above viewport margin
let flipped = false;
let newTopViewport = desiredTopViewport;
if (tRect.top < margin) {
flipped = true;
tooltip.style.transform = 'translate(-50%, 8px)'; // put below
// put new top slightly below pin (pin height ~44)
newTopViewport = desiredTopViewport + 44 + 10;
} else {
tooltip.style.transform = 'translate(-50%, -120%)';
}
// convert shiftXViewport to map-relative px (mapRect left offset)
const shiftXMap = shiftXViewport; // because left in px is same units
const newLeftMap = desiredLeftPxMap + shiftXMap;
const newTopMap = newTopViewport - mapRect.top;
// apply
tooltip.style.left = newLeftMap + 'px';
tooltip.style.top = newTopMap + 'px';
tooltip.style.visibility = 'visible';
}
/* 閉じる */
function closeAllTooltips() {
tooltipEls.forEach(t => { if (t) { t.style.display = 'none'; t.setAttribute('aria-hidden','true'); } });
}
/* ピン配置(data は csvToObjects の配列) */
function placePins(data) {
// remove existing
pinEls.forEach(p => p.remove());
tooltipEls.forEach(t => t.remove());
pinEls = []; tooltipEls = [];
// img の表示サイズ取得(縦長で height 基準)
const rect = img.getBoundingClientRect();
const width = rect.width;
const height = rect.height;
data.forEach((d, idx) => {
const xPx = d.x * width;
const yPx = d.y * height;
// Pin
const pin = document.createElement('div');
pin.className = 'pin';
pin.setAttribute('role','button');
pin.setAttribute('aria-label', d.name || `スポット ${idx+1}`);
pin.setAttribute('tabindex','0');
pin.dataset.index = String(idx);
pin.style.left = xPx + 'px';
pin.style.top = yPx + 'px';
const pinImg = document.createElement('img');
pinImg.src = 'images/pin.png';
pinImg.alt = '';
pin.appendChild(pinImg);
// stop propagation so Panzoom doesn't begin pan when tapping a pin
pin.addEventListener('pointerdown', e => e.stopPropagation());
pin.addEventListener('touchstart', e => e.stopPropagation(), {passive:true});
pin.addEventListener('keydown', (ev) => {
if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); pin.click(); }
});
// Tooltip (card)
const tooltip = document.createElement('div');
tooltip.className = 'tooltip';
tooltip.dataset.index = String(idx);
tooltip.setAttribute('aria-hidden','true');
const card = document.createElement('div');
card.className = 'tooltip-card';
const closeBtn = document.createElement('button');
closeBtn.className = 'close-btn';
closeBtn.type = 'button';
closeBtn.textContent = '✕';
closeBtn.setAttribute('aria-label','閉じる');
const header = document.createElement('div');
header.className = 'tooltip-header';
header.textContent = d.name || '(無題)';
const body = document.createElement('div');
body.className = 'tooltip-body';
const thumb = document.createElement('img');
thumb.className = 'tooltip-thumb';
thumb.src = d.image ? d.image : 'images/placeholder.png';
thumb.alt = d.name || '';
const p = document.createElement('p');
p.className = 'desc';
p.textContent = d.description || '';
body.appendChild(thumb);
body.appendChild(p);
card.appendChild(closeBtn);
card.appendChild(header);
card.appendChild(body);
tooltip.appendChild(card);
// initial hidden position (map-relative)
tooltip.style.left = xPx + 'px';
tooltip.style.top = yPx + 'px';
tooltip.style.display = 'none';
// events
pin.addEventListener('click', (e) => {
e.stopPropagation();
const isVisible = tooltip.style.display === 'block';
closeAllTooltips();
if (!isVisible) {
tooltip.style.display = 'block';
adjustTooltipPosition(tooltip, xPx, yPx);
tooltip.setAttribute('aria-hidden','false');
} else {
tooltip.style.display = 'none';
tooltip.setAttribute('aria-hidden','true');
}
});
closeBtn.addEventListener('click', (ev) => {
ev.stopPropagation();
tooltip.style.display = 'none';
tooltip.setAttribute('aria-hidden','true');
});
// prevent tooltip pointer events from panning map (stop propagation)
tooltip.addEventListener('pointerdown', ev => ev.stopPropagation());
tooltip.addEventListener('touchstart', ev => ev.stopPropagation(), {passive:true});
// append
map.appendChild(pin);
map.appendChild(tooltip);
pinEls.push(pin);
tooltipEls.push(tooltip);
});
renderListPanel(data);
}
/* 一覧パネルに描画 */
function renderListPanel(data) {
listContent.innerHTML = '';
data.forEach((d, idx) => {
const item = document.createElement('div');
item.className = 'shop-item';
item.dataset.index = String(idx);
const thumb = document.createElement('img');
thumb.className = 'shop-thumb';
thumb.src = d.image ? d.image : 'images/placeholder.png';
thumb.alt = d.name || '';
const meta = document.createElement('div');
meta.className = 'shop-meta';
const title = document.createElement('p');
title.className = 'shop-title';
title.textContent = d.name || `スポット ${idx+1}`;
const desc = document.createElement('p');
desc.className = 'shop-desc';
desc.textContent = d.description || '';
meta.appendChild(title);
meta.appendChild(desc);
item.appendChild(thumb);
item.appendChild(meta);
item.addEventListener('click', () => {
openTooltipByIndex(idx);
closeList();
});
listContent.appendChild(item);
});
}
/* 指定 index の tooltip を開く */
function openTooltipByIndex(index) {
if (!pinEls[index]) return;
// ensure visible on screen: scroll to map
const topY = Math.max(0, map.getBoundingClientRect().top + window.scrollY - 80);
window.scrollTo({ top: topY, behavior: 'smooth' });
// show tooltip
pinEls[index].click();
}
/* フロア読み込み */
async function loadFloor(floor) {
if (currentFloor === floor) return;
tabButtons.forEach(btn => {
const f = Number(btn.dataset.floor);
if (f === floor) { btn.classList.add('active'); btn.setAttribute('aria-selected','true'); }
else { btn.classList.remove('active'); btn.setAttribute('aria-selected','false'); }
});
currentFloor = floor;
img.src = IMAGE_PATH[floor];
await waitImageLoad(img);
const data = await loadCSV(CSV_PATH[floor]);
currentData = data;
placePins(data);
// reset zoom so new floor displays consistently
if (panzoomInstance && typeof panzoomInstance.reset === 'function') {
panzoomInstance.reset();
}
}
/* 一覧 open/close */
function openList() {
listPanel.classList.add('open');
listPanel.setAttribute('aria-hidden','false');
listToggle.setAttribute('aria-expanded','true');
setTimeout(() => listContent.focus(), 160);
}
function closeList() {
listPanel.classList.remove('open');
listPanel.setAttribute('aria-hidden','true');
listToggle.setAttribute('aria-expanded','false');
listToggle.focus();
}
/* 初期化 */
async function init() {
// Panzoom を map 要素に適用(map 内の img + pin を一緒に拡大縮小)
panzoomInstance = Panzoom(map, {
maxScale: 4,
minScale: 1,
step: 0.3,
contain: 'outside'
});
// wheel は親(map-wrapper)でキャプチャして zoomWithWheel を使う
const wrapper = map.parentElement;
wrapper.addEventListener('wheel', panzoomInstance.zoomWithWheel);
// タブ
tabButtons.forEach(btn => {
btn.addEventListener('click', () => {
const floor = Number(btn.dataset.floor);
if (!Number.isNaN(floor)) loadFloor(floor);
});
});
// グローバルタップでツールチップを閉じる
document.addEventListener('pointerdown', (ev) => {
const target = ev.target;
if (target.closest('.pin') || target.closest('.tooltip') || target.closest('.list-panel') || target.closest('.list-toggle')) return;
closeAllTooltips();
});
// 一覧操作
listToggle.addEventListener('click', openList);
closeListBtn.addEventListener('click', closeList);
// resize -> 再配置(デバウンス)
let resizeTimer = null;
window.addEventListener('resize', () => {
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => { if (currentData && currentData.length) placePins(currentData); }, 200);
});
// 最初に 1F を読み込み
img.src = IMAGE_PATH[1];
await waitImageLoad(img);
currentData = await loadCSV(CSV_PATH[1]);
placePins(currentData);
}
// 起動
document.addEventListener('DOMContentLoaded', init);