MediaWiki:Common.js: differenze tra le versioni

Admin (discussione | contributi)
Auto-language switcher per pagine /ru /en /fr /es /pt
 
Admin (discussione | contributi)
Common.js v7: touch+viewport <=1200 = mobile (cattura Desktop Mode)
 
(6 versioni intermedie di uno stesso utente non sono mostrate)
Riga 1: Riga 1:
/* ============================================================
/* ============================================================
  * Auto-language selection for translated pages
  * Common.js v7 — Wiki Methode Paret
  * ============================================================
  * ============================================================
  * Quando l'utente atterra su una pagina con suffisso linguistico
  * REGOLA UNICA:
  * (es. /ru, /en, /fr, /es, /pt), forza l'UI in quella lingua
  *   URL /Titolo      → UI italiana
  * UNA SOLA VOLTA, salvando un cookie. L'utente può comunque
*  URL /Titolo/ru    → UI russa
  * cambiare lingua manualmente con l'icona globo (ULS), che ha
  *
  * priorità più alta.
  * Mobile detection v7:
*  - Touch capability (funziona anche con "Versione Desktop" del browser)
*  - Viewport width <= 1200 (più tollerante: cattura anche desktop mode 1080)
  *   - Una delle due basta
  * ============================================================ */
  * ============================================================ */
( function ( mw ) {
( function ( mw ) {
     'use strict';
     'use strict';


     var SUPPORTED_SUFFIXES = [ 'ru', 'en', 'fr', 'es', 'pt' ];
     var SUPPORTED_LANGS = [ 'ru', 'en', 'fr', 'es', 'pt' ];
    var COOKIE_NAME = 'autolang_set';


    // Legge cookie semplice
     function getCookie( name ) {
     function getCookie( name ) {
         var match = document.cookie.match( new RegExp( '(?:^|;\\s*)' + name + '=([^;]*)' ) );
         var m = document.cookie.match( new RegExp( '(?:^|;\\s*)' + name + '=([^;]*)' ) );
         return match ? decodeURIComponent( match[ 1 ] ) : null;
         return m ? decodeURIComponent( m[ 1 ] ) : null;
    }
    function deleteCookie( name ) {
        var hostname = window.location.hostname;
        var parts = hostname.split( '.' );
        var domains = [ hostname, '' ];
        if ( parts.length > 2 ) {
            domains.push( '.' + parts.slice( -2 ).join( '.' ) );
        }
        domains.forEach( function ( d ) {
            var suffix = d ? '; domain=' + d : '';
            document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/' + suffix;
        } );
     }
     }


     function setCookie( name, value, days ) {
     // ─── DETECTION MOBILE ROBUSTA ──────────────────────────
        var d = new Date();
    var ua = navigator.userAgent || '';
        d.setTime( d.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
    var isMobileUA = /iPhone|iPad|iPod|Android|Mobile|webOS|BlackBerry|Opera Mini|IEMobile|Silk/i.test( ua );
        document.cookie = name + '=' + encodeURIComponent( value ) +
    var viewportWidth = window.innerWidth || document.documentElement.clientWidth || 1024;
            '; expires=' + d.toUTCString() + '; path=/; SameSite=Lax';
    var isSmallViewport = viewportWidth <= 1200;
    }
    var hasTouch = ( 'ontouchstart' in window ) ||
                  ( navigator.maxTouchPoints > 0 ) ||
                  ( navigator.msMaxTouchPoints > 0 );


     function getPageLangFromTitle() {
     // Mobile se: UA mobile OPPURE (touch + viewport piccolino)
        // Usa il titolo MediaWiki ufficiale (no URL encoding)
    // Il caso "Versione Desktop attivata" ha touch=true e viewport ~1080 → cattura
        var title = mw.config.get( 'wgPageName' ) || '';
    var isMobile = isMobileUA || ( hasTouch && isSmallViewport );
        // Cerca suffisso /XX in fondo al titolo
        var m = title.match( /\/([a-z]{2})$/ );
        if ( m && SUPPORTED_SUFFIXES.indexOf( m[ 1 ] ) !== -1 ) {
            return m[ 1 ];
        }
        return null;
    }


     function userHasExplicitChoice() {
     if ( isMobile ) {
         // L'utente ha scelto manualmente una lingua se:
         [ 'stopMobileRedirect', 'mf_useformat' ].forEach( function ( n ) {
        // 1. ULS ha salvato preferenza (cookie 'uls-preferences' o simili)
             if ( getCookie( n ) !== null ) deleteCookie( n );
        // 2. Abbiamo già forzato la lingua una volta in questa sessione
         } );
        if ( getCookie( COOKIE_NAME ) ) {
             return true;
        }
        // Per utenti loggati: mw.user.options ha 'language' impostato
        var userLang = mw.user.options.get( 'language' );
        if ( userLang && userLang !== mw.config.get( 'wgContentLanguage' ) ) {
            return true;
         }
        return false;
     }
     }


     function init() {
     [ 'autolang_set', 'no_auto_lang_redirect' ].forEach( function ( n ) {
         var targetLang = getPageLangFromTitle();
         if ( getCookie( n ) !== null ) deleteCookie( n );
        if ( !targetLang ) {
    } );
            return; // pagina non multilingue
        }


        // Se l'URL ha già ?uselang=, l'utente sta già usando una lingua scelta
    // ─── Force ?useformat=mobile se mobile + su Vector ─────
    if ( isMobile &&
        document.body &&
        /skin-vector/.test( document.body.className ) ) {
         var url = new URL( window.location.href );
         var url = new URL( window.location.href );
         if ( url.searchParams.get( 'uselang' ) ) {
         if ( url.searchParams.get( 'useformat' ) !== 'mobile' ) {
             // Salva il cookie per ricordare la scelta
             url.searchParams.set( 'useformat', 'mobile' );
            setCookie( COOKIE_NAME, url.searchParams.get( 'uselang' ), 365 );
            window.location.replace( url.toString() );
             return;
             return;
         }
         }
    }


         // Se l'utente ha già fatto una scelta esplicita, non interferire
    // ─── URL decide UI lingua ─────────────────────────────
         if ( userHasExplicitChoice() ) {
    function syncUILangFromURL() {
             return;
        if ( typeof mw === 'undefined' || !mw.config ) return;
 
        var pageName = mw.config.get( 'wgPageName' ) || '';
        var currentUI = mw.config.get( 'wgUserLanguage' );
        var contentLang = mw.config.get( 'wgContentLanguage' ) || 'it';
 
         var match = pageName.match( /\/([a-z]{2})$/ );
        var desiredLang;
         if ( match && SUPPORTED_LANGS.indexOf( match[ 1 ] ) !== -1 ) {
             desiredLang = match[ 1 ];
        } else {
            desiredLang = contentLang;
         }
         }


         // Aggiungi uselang=XX all'URL e ricarica (UNA volta)
         if ( currentUI === desiredLang ) return;
         setCookie( COOKIE_NAME, targetLang, 365 );
 
         url.searchParams.set( 'uselang', targetLang );
        var action = mw.config.get( 'wgAction' );
        if ( action && action !== 'view' ) return;
 
        var ns = mw.config.get( 'wgNamespaceNumber' );
        if ( ns < 0 ) return;
 
        var url = new URL( window.location.href );
         if ( url.searchParams.get( 'uselang' ) ) return;
 
         url.searchParams.set( 'uselang', desiredLang );
         window.location.replace( url.toString() );
         window.location.replace( url.toString() );
     }
     }


    // Esegui non appena mw è pronto
     if ( typeof mw !== 'undefined' && mw.config ) {
     if ( typeof mw !== 'undefined' && mw.config ) {
         mw.loader.using( [ 'mediawiki.util', 'user.options' ] ).then( init );
         mw.loader.using( [ 'mediawiki.util' ] ).then( syncUILangFromURL );
     }
     }


}( window.mediaWiki || window.mw ) );
}( window.mediaWiki || window.mw ) );
/* ============================================================
* Fine auto-language
* ============================================================ */