fesmap / pj
forked from Ray8/pj
Newer
Older
pj / fes.js
/* script.js
 - スマホ優先で作り込んだマップロジック + Panzoom対応
 - CSV: data/floor1.csv / data/floor2.csv を想定
*/

'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);
  });
}

/* ---------------- ツールチップの位置調整(viewport基準) ---------------- */
function adjustTooltipPosition(tooltip, desiredLeftPxMap, desiredTopPxMap) {
  const mapRect = map.getBoundingClientRect();
  const desiredLeftViewport = mapRect.left + desiredLeftPxMap;
  const desiredTopViewport  = mapRect.top  + desiredTopPxMap;

  tooltip.style.display = 'block';
  tooltip.style.visibility = 'hidden';
  tooltip.style.transform = 'translate(-50%, -120%)';

  const tRect = tooltip.getBoundingClientRect();
  const margin = 8;

  let shiftXViewport = 0;
  if (tRect.left < margin) shiftXViewport = margin - tRect.left;
  if (tRect.right > window.innerWidth - margin) shiftXViewport = (window.innerWidth - margin) - tRect.right;

  let newTopViewport = desiredTopViewport;
  if (tRect.top < margin) {
    tooltip.style.transform = 'translate(-50%, 8px)';
    newTopViewport = desiredTopViewport + 44 + 10;
  } else {
    tooltip.style.transform = 'translate(-50%, -120%)';
  }

  const shiftXMap = shiftXViewport;
  const newLeftMap = desiredLeftPxMap + shiftXMap;
  const newTopMap = newTopViewport - mapRect.top;

  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'); } });
}

/* ---------------- ピン配置 ---------------- */
function placePins(data) {
  pinEls.forEach(p => p.remove());
  tooltipEls.forEach(t => t.remove());
  pinEls = []; tooltipEls = [];

  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;

    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 pointer propagation to avoid accidental pan start
    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
    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);

    tooltip.style.left = xPx + 'px';
    tooltip.style.top  = yPx + 'px';
    tooltip.style.display = 'none';

    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');
    });

    tooltip.addEventListener('pointerdown', ev => ev.stopPropagation());
    tooltip.addEventListener('touchstart', ev => ev.stopPropagation(), {passive:true});

    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);
  });
}
function openTooltipByIndex(index) {
  if (!pinEls[index]) return;
  const topY = Math.max(0, map.getBoundingClientRect().top + window.scrollY - 80);
  window.scrollTo({ top: topY, behavior: 'smooth' });
  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);

  // リセット(左揃えを保つため transform を初期化)
  if (panzoomInstance && typeof panzoomInstance.reset === 'function') {
    panzoomInstance.reset();
    // さらに明示的に pan を 0,0 にする(左上を基準に)
    try { panzoomInstance.pan(0, 0); } catch (e) { /* ignore if not supported */ }
  }
}
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 要素に適用
  panzoomInstance = Panzoom(map, {
    maxScale: 4,
    minScale: 1,
    step: 0.3,
    contain: 'outside'
  });

  // wheel は wrapper 側で扱う
  const wrapper = map.parentElement;
  wrapper.addEventListener('wheel', panzoomInstance.zoomWithWheel, {passive:false});

  // タブ
  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);

  // 最初は左揃えを確実にする(reset + pan(0,0))
  if (panzoomInstance) {
    panzoomInstance.reset();
    try { panzoomInstance.pan(0,0); } catch (e) {}
  }
}

document.addEventListener('DOMContentLoaded', init);