打开/关闭菜单
26
6679
46
1.2万
OGAS数据中枢
打开/关闭外观设置菜单
打开/关闭个人菜单
未登录
未登录用户的IP地址会在进行任意编辑后公开展示。

Widget:GameSwitcher:修订间差异

来自OGAS数据中枢
弃权者留言 | 贡献
无编辑摘要
弃权者留言 | 贡献
无编辑摘要
标签手工回退
 
(未显示同一用户的24个中间版本)
第1行: 第1行:
<script type="text/javascript">
<noinclude>
document.addEventListener('DOMContentLoaded', function () {
少女前线系列多游戏首页切换Widget。调用方式:<code><nowiki>{{#widget:GameSwitcher}}</nowiki></code>
   var switcher = document.querySelector('.game-switcher');
</noinclude><includeonly><script>
  if (!switcher) return;
( function () {
   'use strict';


   var heroWrap = document.getElementById('gs-hero-wrap');
   var heroImages = {
  var heroImg = heroWrap ? heroWrap.querySelector('img') : null;
    'gf':  'index_gf_hero.jpg',
  var loaded = {};
    'gf2''index_gf2_hero.jpg',
   var prefetching = {};
    'gfnc': 'index_gfnc_hero.jpg',
  var storageKey = 'gs-cache-';
    'gfb': 'index_gfb_hero.jpg'
   };


   // ============ 初始化 ============
   function getApiBase() {
  var firstBtn = switcher.querySelector('.gs-tab-btn');
    var canonical = document.querySelector( 'link[rel="canonical"]' );
  if (firstBtn) {
    if ( canonical ) {
    firstBtn.classList.add('gs-active');
      var m = canonical.href.match( /^(https?:\/\/[^\/]+(?:\/[^\/]+)*?)\/wiki\// );
    firstBtn.setAttribute('aria-selected', 'true');
      if ( m ) { return m[ 1 ] + '/api.php'; }
    if (heroImg && !heroImg.getAttribute('src')) {
      heroImg.src = firstBtn.dataset.hero;
     }
     }
    return window.location.origin + '/api.php';
   }
   }
  restoreHash();


   // ============ 点击 ============
   function getWikiImageUrl( filename, callback ) {
  switcher.addEventListener('click', function (e) {
    fetch( getApiBase() + '?action=query&titles=File:' + encodeURIComponent( filename ) +
    var btn = e.target.closest('.gs-tab-btn');
          '&prop=imageinfo&iiprop=url&format=json&origin=*' )
    if (btn) activate(btn);
      .then( function ( r ) { return r.json(); } )
  });
      .then( function ( data ) {
        var pages = data.query.pages;
        var page = pages[ Object.keys( pages )[ 0 ] ];
        if ( page.imageinfo && page.imageinfo[ 0 ] ) {
          callback( page.imageinfo[ 0 ].url );
        }
      } )
      .catch( function ( e ) { console.warn( 'GameSwitcher: 图片加载失败', filename, e ); } );
  }


   // ============ 键盘 ============
   function applyFadeColor() {
  switcher.addEventListener('keydown', function (e) {
     var style = getComputedStyle( document.documentElement );
     var btn = e.target.closest('.gs-tab-btn');
    var bg = style.getPropertyValue( '--color-surface-0' ).trim()
    if (!btn) return;
          || style.getPropertyValue( '--background-color-base' ).trim()
    if (e.key === 'Enter' || e.key === ' ') {
          || '#1d1e20';
      e.preventDefault();
    var el = document.getElementById( 'gf-hero-fade-bottom' );
       activate(btn);
    if ( el ) {
       el.style.background = 'linear-gradient(to bottom, transparent 0%, ' + bg + ' 100%)';
     }
     }
    if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
   }
      e.preventDefault();
      var btns = Array.from(switcher.querySelectorAll('.gs-tab-btn'));
      var idx = btns.indexOf(btn);
      var next = e.key === 'ArrowRight' ? idx + 1 : idx - 1;
      if (next >= 0 && next < btns.length) btns[next].focus();
    }
   });


  // ============ 悬停预加载 ============
function moveIndicator( tab ) {
  switcher.addEventListener('mouseenter', function (e) {
  var indicator = document.getElementById( 'gf-tab-indicator' );
    var btn = e.target.closest('.gs-tab-btn');
  if ( !indicator ) { return; }
    if (!btn) return;
  indicator.style.width     = tab.offsetWidth + 'px';
     var panelId = btn.dataset.panel;
  indicator.style.transform = 'translateX(' + tab.offsetLeft + 'px)';
    var pageName = btn.dataset.page;
}
    if (pageName && !loaded[panelId] && !prefetching[panelId]) {
      prefetch(panelId, pageName);
    }
  }, true);


   // ============ URL hash ============
   var currentGame = 'gf';
   window.addEventListener('hashchange', restoreHash);
  var switching  = false;
   var pending    = null;


  // ============ 激活面板 ============
   function doSwitch( game, tabEl ) {
   function activate(btn) {
     var slides = document.querySelectorAll( '#gf-homepage .gf-hero-slide' );
     if (btn.classList.contains('gs-active')) return;
    var panels = document.querySelectorAll( '#gf-homepage .gf-content-panel' );
    var tabs  = document.querySelectorAll( '#gf-homepage .gf-tab' );


     var panelId = btn.dataset.panel;
     var outSlide = document.getElementById( 'hero-' + currentGame );
     var heroSrc = btn.dataset.hero;
     var inSlide  = document.getElementById( 'hero-' + game );
    var pageName = btn.dataset.page;


     switchHero(heroSrc);
     if ( inSlide ) {
      inSlide.style.zIndex = '1';
      inSlide.classList.add( 'active' );
    }
    if ( outSlide ) {
      outSlide.style.zIndex = '0';
      outSlide.classList.remove( 'active' );
    }


     switcher.querySelectorAll('.gs-tab-btn').forEach(function (b) {
     tabs.forEach( function ( t ) {
       b.classList.remove('gs-active');
       var on = t.getAttribute( 'data-game' ) === game;
       b.setAttribute('aria-selected', 'false');
      t.classList.toggle( 'active', on );
     });
       t.setAttribute( 'aria-selected', on ? 'true' : 'false' );
     btn.classList.add('gs-active');
     } );
    btn.setAttribute('aria-selected', 'true');
     if ( tabEl ) { moveIndicator( tabEl ); }


     switcher.querySelectorAll('.gs-content-panel').forEach(function (p) {
     panels.forEach( function ( p ) {
       p.classList.remove('gs-active');
       p.classList.toggle( 'active', p.id === 'content-' + game );
     });
     } );


     var panel = document.getElementById(panelId);
     currentGame = game;
     if (!panel) {
     switching  = true;
      panel = document.createElement('div');
      panel.id = panelId;
      panel.className = 'gs-content-panel gs-active';
      switcher.querySelector('.gs-content').appendChild(panel);
      loadContent(panel, panelId, pageName);
    } else {
      panel.classList.add('gs-active');
    }


     setHash(panelId);
     setTimeout( function () {
     schedulePrefetchOthers();
      slides.forEach( function ( s ) { s.style.zIndex = ''; } );
      switching = false;
      if ( pending && pending.game !== currentGame ) {
        var p = pending;
        pending = null;
        doSwitch( p.game, p.tabEl );
      } else {
        pending = null;
      }
     }, 520 );
   }
   }


   // ============ 头图切换 ============
   function switchGame( game, tabEl ) {
function switchHero(url) {
    if ( game === currentGame ) { return; }
  if (!heroWrap || !heroImg || !url) return;
    if ( switching ) {
  if (heroImg.src === url) return;
      pending = { game: game, tabEl: tabEl };
      var tabs = document.querySelectorAll( '#gf-homepage .gf-tab' );
      tabs.forEach( function ( t ) {
        var on = t.getAttribute( 'data-game' ) === game;
        t.classList.toggle( 'active', on );
        t.setAttribute( 'aria-selected', on ? 'true' : 'false' );
      } );
      if ( tabEl ) { moveIndicator( tabEl ); }
      return;
    }
    doSwitch( game, tabEl );
  }


   var next = new Image();
   function init() {
  next.className = 'gs-hero-next';
    var tabs = document.querySelectorAll( '#gf-homepage .gf-tab' );
    if ( !tabs.length ) { return; }


  next.onload = function () {
    Object.keys( heroImages ).forEach( function ( game ) {
    heroWrap.appendChild(next);
      getWikiImageUrl( heroImages[ game ], function ( url ) {
    // 强制浏览器完成一次布局,确保 transition 能触发
        var bg  = document.getElementById( 'hero-' + game + '-bg' );
    next.offsetWidth;
        var fg  = document.getElementById( 'hero-' + game + '-fg' );
    next.classList.add('gs-hero-next--in');
        var val = 'url("' + url + '")';
        if ( bg ) { bg.style.backgroundImage = val; }
        if ( fg ) { fg.style.backgroundImage = val; }
      } );
    } );


     setTimeout(function () {
     applyFadeColor();
      heroImg.src = url;
      if (heroWrap.contains(next)) heroWrap.removeChild(next);
    }, 420); // 略大于 transition 的 400ms
  };


  next.onerror = function () {
     var firstActive = document.querySelector( '#gf-homepage .gf-tab.active' );
    if (heroWrap.contains(next)) heroWrap.removeChild(next);
     if ( firstActive ) {
  };
       setTimeout( function () { moveIndicator( firstActive ); }, 50 );
 
     }
  next.src = url;
}
 
  // ============ 内容加载 ============
  function loadContent(panel, panelId, pageName) {
     if (loaded[panelId]) { panel.innerHTML = loaded[panelId]; return; }
 
    try {
      var stored = localStorage.getItem(storageKey + panelId);
      if (stored) { loaded[panelId] = stored; panel.innerHTML = stored; return; }
    } catch (e) {}
 
    if (!pageName) return;
    panel.innerHTML = '<div class="gs-loading">加载中...</div>';
 
    fetchPage(pageName).then(function (html) {
      loaded[panelId] = html;
      try { localStorage.setItem(storageKey + panelId, html); } catch (e) {}
      panel.innerHTML = html;
     }).catch(function () {
       panel.innerHTML = '<div class="gs-loading">加载失败,<a href="javascript:location.reload()">刷新</a>重试</div>';
    });
  }
 
  // ============ 预加载 ============
  function prefetch(panelId, pageName) {
    prefetching[panelId] = true;
    try {
      var stored = localStorage.getItem(storageKey + panelId);
      if (stored) { loaded[panelId] = stored; prefetching[panelId] = false; return; }
    } catch (e) {}
 
    fetchPage(pageName).then(function (html) {
      loaded[panelId] = html;
      try { localStorage.setItem(storageKey + panelId, html); } catch (e) {}
     }).finally(function () {
      prefetching[panelId] = false;
    });
  }


  function schedulePrefetchOthers() {
    tabs.forEach( function ( tab ) {
    setTimeout(function () {
      tab.addEventListener( 'click', function () {
      switcher.querySelectorAll('.gs-tab-btn').forEach(function (btn) {
        switchGame( this.getAttribute( 'data-game' ), this );
         var panelId = btn.dataset.panel;
      } );
        var pageName = btn.dataset.page;
      tab.addEventListener( 'keydown', function ( e ) {
        if (!loaded[panelId] && !prefetching[panelId] && pageName) {
         if ( e.key === 'Enter' || e.key === ' ' ) {
           prefetch(panelId, pageName);
          e.preventDefault();
           switchGame( this.getAttribute( 'data-game' ), this );
         }
         }
       });
       } );
     }, 500);
     } );
  }


  // ============ API 请求 ============
     window.addEventListener( 'resize', function () {
  function fetchPage(pageName) {
       var active = document.querySelector( '#gf-homepage .gf-tab.active' );
     var url = mw.util.wikiScript('api') +
       if ( active ) { moveIndicator( active ); }
       '?action=parse&page=' + encodeURIComponent(pageName) +
    } );
      '&prop=text&format=json&disablelimitreport=1&origin=*';
    return fetch(url)
      .then(function (r) { return r.json(); })
       .then(function (data) {
        if (data.parse && data.parse.text) return data.parse.text['*'];
        throw new Error('empty');
      });
   }
   }


   // ============ URL hash ============
   if ( document.readyState === 'loading' ) {
  function setHash(panelId) {
     document.addEventListener( 'DOMContentLoaded', init );
     try { history.replaceState(null, '', '#' + panelId); } catch (e) {}
  } else {
    init();
   }
   }


  function restoreHash() {
} )();
    var hash = location.hash.replace('#', '');
</script></includeonly>
    if (hash && hash.indexOf('panel-') === 0) {
      var btn = switcher.querySelector('[data-panel="' + hash + '"]');
      if (btn && !btn.classList.contains('gs-active')) activate(btn);
    }
  }
});
</script>

2026年6月20日 (六) 23:23的最新版本

少女前线系列多游戏首页切换Widget。调用方式:{{#widget:GameSwitcher}}