미디어위키:Common.js

참고: 설정을 저장한 후에 바뀐 점을 확인하기 위해서는 브라우저의 캐시를 새로 고쳐야 합니다.

  • 파이어폭스 / 사파리: Shift 키를 누르면서 새로 고침을 클릭하거나, Ctrl-F5 또는 Ctrl-R을 입력 (Mac에서는 ⌘-R)
  • 구글 크롬: Ctrl-Shift-R키를 입력 (Mac에서는 ⌘-Shift-R)
  • 인터넷 익스플로러 / 엣지: Ctrl 키를 누르면서 새로 고침을 클릭하거나, Ctrl-F5를 입력.
  • 오페라: Ctrl-F5를 입력.
/**
 * 이 스크립트는 위키백과 전체에 적용됩니다. 고칠 때는 주의해주세요.
 * [[위키백과:위키프로젝트 시스템]] 참고
 *
 * 스크립트를 넣을 때는 충분한 설명, 출처를 넣어주세요! 이후 관리가 어려워집니다.
 **/

mw.loader.using( ['mediawiki.util', 'mediawiki.notify', 'jquery.client'], function () {
/* Begin of mw.loader.using callback */

/**
 * Map addPortletLink to mw.util 
 *
 * @deprecated: Use mw.util.addPortletLink instead.
 */
mw.log.deprecate( window, 'addPortletLink', mw.util.addPortletLink,
 'Use mw.util.addPortletLink instead' );
 
/**
 * Extract a URL parameter from the current URL
 *
 * @deprecated: Use mw.util.getParamValue with proper escaping
 */
mw.log.deprecate( window, 'getURLParamValue', mw.util.getParamValue, 'Use mw.util.getParamValue instead' );
 
/** 
 * Test if an element has a certain class
 *
 * @deprecated:  Use $(element).hasClass() instead.
 */
mw.log.deprecate( window, 'hasClass', function ( element, className ) {
    return $( element ).hasClass( className );
}, 'Use jQuery.hasClass() instead' );
 
/**
 * @source www.mediawiki.org/wiki/Snippets/Load_JS_and_CSS_by_URL
 * @rev 5
 */
// CSS
var extraCSS = mw.util.getParamValue( 'withCSS' );
if ( extraCSS ) {
	if ( extraCSS.match( /^MediaWiki:[^&<>=%#]*\.css$/ ) ) {
		importStylesheet( extraCSS );
	} else {
		mw.notify( 'Only pages from the MediaWiki namespace are allowed.', { title: 'Invalid withCSS value' } );
	}
}
 
// JS
var extraJS = mw.util.getParamValue( 'withJS' );
if ( extraJS ) {
	if ( extraJS.match( /^MediaWiki:[^&<>=%#]*\.js$/ ) ) {
		importScript( extraJS );
	} else {
		mw.notify( 'Only pages from the MediaWiki namespace are allowed.', { title: 'Invalid withJS value' } );
	}
}
 

/**
 * Import more specific scripts if necessary
 */

if ( mw.config.get( 'wgNamespaceNumber' ) === 6 ) {
    /* file description page scripts */
    importScript( 'MediaWiki:Common.js/file.js' );
}

/* ([[위키백과:관리자 요청/2007년 5월#스크립트 추가 요청]]) */
/** Collapsible tables *********************************************************
 *
 *  Description: Allows tables to be collapsed, showing only the header. See
 *               [[:en:Wikipedia:NavFrame]].
 *  Maintainers: [[:en:User:R. Koot]]
 */
 
var autoCollapse = 2;
var collapseCaption = '숨기기';
var expandCaption = '보이기';

window.collapseTable = function ( tableIndex ) {
    var Button = document.getElementById( 'collapseButton' + tableIndex );
    var Table = document.getElementById( 'collapsibleTable' + tableIndex );

    if ( !Table || !Button ) {
        return false;
    }

    var Rows = Table.rows;
    var i;

    if ( Button.firstChild.data === collapseCaption ) {
        for ( i = 1; i < Rows.length; i++ ) {
            Rows[i].style.display = 'none';
        }
        Button.firstChild.data = expandCaption;
    } else {
        for ( i = 1; i < Rows.length; i++ ) {
            Rows[i].style.display = Rows[0].style.display;
        }
        Button.firstChild.data = collapseCaption;
    }
};

function createCollapseButtons() {
    var tableIndex = 0;
    var NavigationBoxes = {};
    var Tables = document.getElementsByTagName( 'table' );
    var i;

    function handleButtonLink( index, e ) {
        window.collapseTable( index );
        e.preventDefault();
    }

    for ( i = 0; i < Tables.length; i++ ) {
        if ( $( Tables[i] ).hasClass( 'collapsible' ) ) {

            /* only add button and increment count if there is a header row to work with */
            var HeaderRow = Tables[i].getElementsByTagName( 'tr' )[0];
            if ( !HeaderRow ) continue;
            var Header = HeaderRow.getElementsByTagName( 'th' )[0];
            if ( !Header ) continue;

            NavigationBoxes[ tableIndex ] = Tables[i];
            Tables[i].setAttribute( 'id', 'collapsibleTable' + tableIndex );

            var Button     = document.createElement( 'span' );
            var ButtonLink = document.createElement( 'a' );
            var ButtonText = document.createTextNode( collapseCaption );

            Button.className = 'collapseButton';  /* Styles are declared in Common.css */

            ButtonLink.style.color = Header.style.color;
            ButtonLink.setAttribute( 'id', 'collapseButton' + tableIndex );
            ButtonLink.setAttribute( 'href', '#' );
            $( ButtonLink ).on( 'click', $.proxy( handleButtonLink, ButtonLink, tableIndex ) );
            ButtonLink.appendChild( ButtonText );

            Button.appendChild( document.createTextNode( '[' ) );
            Button.appendChild( ButtonLink );
            Button.appendChild( document.createTextNode( ']' ) );

            Header.insertBefore( Button, Header.firstChild );
            tableIndex++;
        }
    }

    for ( i = 0;  i < tableIndex; i++ ) {
        if ( $( NavigationBoxes[i] ).hasClass( 'collapsed' ) || ( tableIndex >= autoCollapse && $( NavigationBoxes[i] ).hasClass( 'autocollapse' ) ) ) {
            window.collapseTable( i );
        } 
        else if ( $( NavigationBoxes[i] ).hasClass ( 'innercollapse' ) ) {
            var element = NavigationBoxes[i];
            while ((element = element.parentNode)) {
                if ( $( element ).hasClass( 'outercollapse' ) ) {
                    window.collapseTable ( i );
                    break;
                }
            }
        }
    }
}

mw.hook( 'wikipage.content' ).add( createCollapseButtons );

/* ([[위키백과:관리자 요청/2007년 5월#스크립트 추가 요청]]) */
/** Dynamic Navigation Bars (experimental) *************************************
 *
 *  Description: See [[:en:Wikipedia:NavFrame]].
 *  Maintainers: UNMAINTAINED
 */
 
// set up the words in your language
/* set up the words in your language */
var NavigationBarHide = '[' + collapseCaption + ']';
var NavigationBarShow = '[' + expandCaption + ']';

/**
 * Shows and hides content and picture (if available) of navigation bars
 * Parameters:
 *     indexNavigationBar: the index of navigation bar to be toggled
 **/
window.toggleNavigationBar = function ( indexNavigationBar, event ) {
    var NavToggle = document.getElementById( 'NavToggle' + indexNavigationBar );
    var NavFrame = document.getElementById( 'NavFrame' + indexNavigationBar );
    var NavChild;

    if ( !NavFrame || !NavToggle ) {
        return false;
    }

    /* if shown now */
    if ( NavToggle.firstChild.data === NavigationBarHide ) {
        for ( NavChild = NavFrame.firstChild; NavChild !== null; NavChild = NavChild.nextSibling ) {
            if ( $( NavChild ).hasClass( 'NavContent' ) || $( NavChild ).hasClass( 'NavPic' ) ) {
                NavChild.style.display = 'none';
            }
        }
    NavToggle.firstChild.data = NavigationBarShow;

    /* if hidden now */
    } else if ( NavToggle.firstChild.data === NavigationBarShow ) {
        for ( NavChild = NavFrame.firstChild; NavChild !== null; NavChild = NavChild.nextSibling ) {
            if ( $( NavChild ).hasClass( 'NavContent' ) || $( NavChild ).hasClass( 'NavPic' ) ) {
                NavChild.style.display = 'block';
            }
        }
        NavToggle.firstChild.data = NavigationBarHide;
    }

    event.preventDefault();
};

/* adds show/hide-button to navigation bars */
function createNavigationBarToggleButton() {
    var indexNavigationBar = 0;
    var NavFrame;
    var NavChild;
    /* iterate over all < div >-elements */
    var divs = document.getElementsByTagName( 'div' );
    for ( var i = 0; (NavFrame = divs[i]); i++ ) {
        /* if found a navigation bar */
        if ( $( NavFrame ).hasClass( 'NavFrame' ) ) {

            indexNavigationBar++;
            var NavToggle = document.createElement( 'a' );
            NavToggle.className = 'NavToggle';
            NavToggle.setAttribute( 'id', 'NavToggle' + indexNavigationBar );
            NavToggle.setAttribute( 'href', '#' );
            $( NavToggle ).on( 'click', $.proxy( window.toggleNavigationBar, window, indexNavigationBar ) );

            var isCollapsed = $( NavFrame ).hasClass( 'collapsed' );
            /**
             * Check if any children are already hidden.  This loop is here for backwards compatibility:
             * the old way of making NavFrames start out collapsed was to manually add style="display:none"
             * to all the NavPic/NavContent elements.  Since this was bad for accessibility (no way to make
             * the content visible without JavaScript support), the new recommended way is to add the class
             * "collapsed" to the NavFrame itself, just like with collapsible tables.
             */
            for ( NavChild = NavFrame.firstChild; NavChild != null && !isCollapsed; NavChild = NavChild.nextSibling ) {
                if ( $( NavChild ).hasClass( 'NavPic' ) || $( NavChild ).hasClass( 'NavContent' ) ) {
                    if ( NavChild.style.display === 'none' ) {
                        isCollapsed = true;
                    }
                }
            }
            if ( isCollapsed ) {
                for ( NavChild = NavFrame.firstChild; NavChild != null; NavChild = NavChild.nextSibling ) {
                    if ( $( NavChild ).hasClass( 'NavPic' ) || $( NavChild ).hasClass( 'NavContent' ) ) {
                        NavChild.style.display = 'none';
                    }
                }
            }
            var NavToggleText = document.createTextNode( isCollapsed ? NavigationBarShow : NavigationBarHide );
            NavToggle.appendChild( NavToggleText );

            /* Find the NavHead and attach the toggle link (Must be this complicated because Moz's firstChild handling is borked) */
            for( var j = 0; j < NavFrame.childNodes.length; j++ ) {
                if ( $( NavFrame.childNodes[j] ).hasClass( 'NavHead' ) ) {
                    NavToggle.style.color = NavFrame.childNodes[j].style.color;
                    NavFrame.childNodes[j].appendChild( NavToggle );
                }
            }
            NavFrame.setAttribute( 'id', 'NavFrame' + indexNavigationBar );
        }
    }
}

mw.hook( 'wikipage.content' ).add( createNavigationBarToggleButton );

/***** 그림 정보 틀을 자동으로 불러옴 ********
 * Adds a link to subpages of current page
 * from commons.wikimedia.org
 *  Maintainers: [[User:Yonidebest]], [[User:Dschwen]]
 *  [[사용자:Kwj2772]]가 수정
 *  JSconfig items: bool 'loadAutoInformationTemplate'
 *                       (true=enabled (default), false=disabled)
 * JSConfig를 사용하지 않도록 수정함. --[[사용자:Klutzy|klutzy]] ([[사용자토론:Klutzy|토론]]) 2009년 9월 27일 (일) 20:33 (KST)
 ****/
/**
 * 파일 라이선스 체계화 150726 - 리브레위키
 */
if (mw.config.get( 'wgCanonicalSpecialPageName' ) == 'Upload') {
  mw.loader.load( '/index.php?title=MediaWiki:Upload.js&action=raw&ctype=text/javascript');
  mw.loader.load( '/index.php?title=MediaWiki:UploadForm.js&action=raw&ctype=text/javascript');
}

/* 인터랙티브 지도. 영어 위키백과에서 가져옴. -- [[사용자:ChongDae]] 2010년 3월 28일 (일) 02:08 (KST) */
/**
 * WikiMiniAtlas
 *
 * Description: WikiMiniAtlas is a popup click and drag world map.
 *              This script causes all of our coordinate links to display the WikiMiniAtlas popup button.
 *              The script itself is located on meta because it is used by many projects.
 *              See [[Meta:WikiMiniAtlas]] for more information. 
 * Maintainers: [[User:Dschwen]]
 */
( function () {
    var require_wikiminiatlas = false;
    var coord_filter = /geohack/;
    $( function () {
        $( 'a.external.text' ).each( function( key, link ) {
            if ( link.href && coord_filter.exec( link.href ) ) {
                require_wikiminiatlas = true;
                // break from loop
                return false;
            }
        } );
        if ( $( 'div.kmldata' ).length ) {
            require_wikiminiatlas = true;
        }
        if ( require_wikiminiatlas ) {
            mw.loader.load( '//meta.wikimedia.org/w/index.php?title=MediaWiki:Wikiminiatlas.js&action=raw&ctype=text/javascript' );
        }
    } );
} )();

/**
 * Fix for Windows XP Unicode font rendering
 */
if ( navigator.appVersion.search(/windows nt 5/i) !== -1 ) {
    mw.util.addCSS( '.IPA { font-family: "Lucida Sans Unicode", "Arial Unicode MS"; } ' + 
                '.Unicode { font-family: "Arial Unicode MS", "Lucida Sans Unicode"; } ' );
}

/**
 * 편집 안내 ****************************************************
 *
 * 생존 인물에 대한 편집 안내. 영어 위키백과에서 가져옴 - ChongDae
 * Maintainers: [[User:RockMFR]]
 */
function addEditIntro( name ) {
    $( '.mw-editsection, #ca-edit' ).find( 'a' ).each( function ( i, el ) {
        el.href = $( this ).attr( 'href' ) + '&editintro=' + name;
    } );
}

if ( mw.config.get( 'wgNamespaceNumber' ) === 0 ) {
    $( function () {
        var cats = mw.config.get('wgCategories');
        if ( !cats ) {
            return;
        }
        if ( $.inArray( '살아있는 사람', cats ) !== -1 || $.inArray( '생사 불명', cats ) !== -1 ) {
            addEditIntro( '틀:BLP_편집_안내' );
        }
    } );
}

/* End of mw.loader.using callback */
} );
/* DO NOT ADD CODE BELOW THIS LINE */



$(function () {
if (/^(edit|submit)$/.test(mw.config.get('wgAction'))) {
	var eForm = document.getElementById('editform');
	if (!eForm) return;
	var eTools = eForm.getElementsByClassName('mw-editTools')[0]; // DIV
	var eOptions = eForm.getElementsByClassName('editOptions')[0]; // DIV
	if (!eTools || !eOptions) return mw.log(eTools, eForm, eOptions);
	eForm.insertBefore(eTools, eOptions);
}
});

/**
 * Auto-number headings
 *
 * @source https://www.mediawiki.org/wiki/Snippets/Auto-number_headings
 * @author Krinkle
 * @version 2021-10-03
 */
var toc = document.querySelector('#toc');
if (toc) {
  document.querySelectorAll('.mw-parser-output :is(h1,h2,h3,h4,h5,h6) .mw-headline').forEach(function (headline) {
    var num = toc.querySelector('a[href="#' + CSS.escape(headline.id) + '"] .tocnumber');
    if (num) headline.prepend(num.textContent + ' ');
  });
} else {
  document.body.classList.add('tpl-autonum');
}


/* nav bar 속성 */
var last_top = 0;
$(window).scroll(function() {
  var this_top = $(this).scrollTop();
  if( this_top > last_top ) {
    $(".nav-wrapper.navbar-fixed-top").addClass("hide");
  }
  else {
    $(".nav-wrapper.navbar-fixed-top").removeClass("hide");
  }
	last_top = this_top;  
});

/* 케이 펼접 */
document.querySelectorAll(".fold-button").forEach(function(button) {
    var targetId = button.getAttribute("data-target");
    var content = document.getElementById(targetId);

    if (!content) return;

    var opened = false;
    var duration = 350;

    function measureHeight(element) {
        var height = element.style.height;
        var transition = element.style.transition;

        element.style.transition = "none";
        element.style.height = "auto";

        var naturalHeight = element.scrollHeight;

        element.style.height = height;
        element.style.transition = transition;

        return naturalHeight;
    }

    function updateParents() {
        var parent = content.parentElement.closest(".fold-content");

        while (parent) {
            if (parent.style.height !== "0px") {
                parent.style.height = measureHeight(parent) + "px";
            }

            parent = parent.parentElement.closest(".fold-content");
        }
    }

    function animateParents() {
        var start = performance.now();

        function frame(time) {
            updateParents();

            if (time - start < duration) {
                requestAnimationFrame(frame);
            }
        }

        requestAnimationFrame(frame);
    }

    button.addEventListener("click", function() {
        if (!opened) {
            content.style.height = "0px";
            content.style.opacity = "0";

            content.classList.add("open");
            button.classList.add("open");

            var targetHeight = measureHeight(content);

            requestAnimationFrame(function() {
                content.style.height = targetHeight + "px";
                content.style.opacity = "1";

                animateParents();
            });

            opened = true;
        } else {
            var currentHeight = content.scrollHeight;

            content.style.height = currentHeight + "px";

            content.classList.remove("open");
            button.classList.remove("open");

            requestAnimationFrame(function() {
                content.style.height = "0px";
                content.style.opacity = "0";

                animateParents();
            });

            opened = false;
        }
    });
});
/* ===== 대문 슬라이더 ([[틀:대문 슬라이더]]) =====
   탭(칩)이 있으면 탭으로 고른다. 탭을 비우면 그림 띠만 남고 점·화살표가 대신 붙으며,
   들어올 때마다 아무 칸에서나 시작한다. */
( function () {
	function init( root ) {
		var tabs = [].slice.call( root.querySelectorAll( '.wikis-slider-tab' ) );
		var panels = [].slice.call( root.querySelectorAll( '.wikis-slider-panel' ) );
		if ( !panels.length ) {
			return;
		}
		var toggle = root.querySelector( '.wikis-slider-toggle' );
		var delay = parseInt( root.getAttribute( 'data-interval' ), 10 ) || 5000;
		var index = 0;
		var timer = null;
		var playing = false;
		var dots = [];

		// 탭이 없으면 점과 화살표를 만들어 붙인다
		if ( !tabs.length && panels.length > 1 ) {
			var wrap = panels[ 0 ].parentNode;
			var mk = function ( cls, label, d ) {
				var b = document.createElement( 'button' );
				b.type = 'button';
				b.className = 'ws-nav ' + cls;
				b.setAttribute( 'aria-label', label );
				b.addEventListener( 'click', function () {
					show( index + d );
					if ( playing ) {
						start();
					}
				} );
				wrap.appendChild( b );
			};
			mk( 'ws-prev', '이전 띠', -1 );
			mk( 'ws-next', '다음 띠', 1 );
			var dotbox = document.createElement( 'div' );
			dotbox.className = 'ws-dots';
			panels.forEach( function ( p, n ) {
				var d = document.createElement( 'button' );
				d.type = 'button';
				d.className = 'ws-dot';
				d.setAttribute( 'aria-label', ( n + 1 ) + '번째 띠' );
				d.addEventListener( 'click', function () {
					show( n );
					if ( playing ) {
						start();
					}
				} );
				dotbox.appendChild( d );
				dots.push( d );
			} );
			wrap.appendChild( dotbox );
		}

		function show( i ) {
			index = ( i % panels.length + panels.length ) % panels.length;
			tabs.forEach( function ( t, n ) {
				var on = ( n === index );
				t.classList.toggle( 'is-active', on );
				t.setAttribute( 'aria-selected', on ? 'true' : 'false' );
				t.setAttribute( 'tabindex', on ? '0' : '-1' );
			} );
			dots.forEach( function ( d, n ) {
				d.classList.toggle( 'is-active', n === index );
			} );
			panels.forEach( function ( p, n ) {
				p.classList.toggle( 'is-active', n === index );
			} );
		}
		function stop() {
			if ( timer ) {
				clearInterval( timer );
				timer = null;
			}
		}
		function start() {
			stop();
			if ( panels.length > 1 ) {
				timer = setInterval( function () {
					if ( document.hidden ) {
						return;
					}
					show( index + 1 );
				}, delay );
			}
		}
		function setPlaying( on ) {
			playing = on;
			if ( toggle ) {
				toggle.classList.toggle( 'is-paused', !on );
				toggle.setAttribute( 'title', on ? '자동 넘김 멈춤' : '자동 넘김 시작' );
				toggle.setAttribute( 'aria-label', on ? '자동 넘김 멈춤' : '자동 넘김 시작' );
			}
			if ( on ) {
				start();
			} else {
				stop();
			}
		}

		tabs.forEach( function ( t, n ) {
			t.setAttribute( 'role', 'tab' );
			t.setAttribute( 'tabindex', '-1' );
			t.addEventListener( 'click', function () {
				show( n );
				if ( playing ) {
					start();
				}
			} );
			t.addEventListener( 'keydown', function ( e ) {
				if ( e.key === 'Enter' || e.key === ' ' ) {
					e.preventDefault();
					show( n );
					if ( playing ) {
						start();
					}
				} else if ( e.key === 'ArrowRight' || e.key === 'ArrowLeft' ) {
					e.preventDefault();
					show( index + ( e.key === 'ArrowRight' ? 1 : -1 ) );
					tabs[ index ].focus();
					if ( playing ) {
						start();
					}
				}
			} );
		} );

		if ( toggle ) {
			toggle.setAttribute( 'role', 'button' );
			toggle.setAttribute( 'tabindex', '0' );
			toggle.addEventListener( 'click', function () {
				setPlaying( !playing );
			} );
			toggle.addEventListener( 'keydown', function ( e ) {
				if ( e.key === 'Enter' || e.key === ' ' ) {
					e.preventDefault();
					setPlaying( !playing );
				}
			} );
		}

		// 마우스를 올려 두는 동안은 멈춘다 (멈춤 단추를 누른 상태는 그대로)
		root.addEventListener( 'mouseenter', function () {
			if ( playing ) {
				stop();
			}
		} );
		root.addEventListener( 'mouseleave', function () {
			if ( playing ) {
				start();
			}
		} );

		// 손가락으로 쓸어 넘기기
		var x0 = null;
		root.addEventListener( 'touchstart', function ( e ) {
			x0 = e.touches[ 0 ].clientX;
		}, { passive: true } );
		root.addEventListener( 'touchend', function ( e ) {
			if ( x0 === null ) {
				return;
			}
			var dx = e.changedTouches[ 0 ].clientX - x0;
			x0 = null;
			if ( Math.abs( dx ) > 40 ) {
				show( index + ( dx < 0 ? 1 : -1 ) );
				if ( playing ) {
					start();
				}
			}
		}, { passive: true } );

		root.classList.add( 'is-ready' );
		var list = root.querySelector( '.wikis-slider-tablist' );
		if ( list ) {
			list.setAttribute( 'role', 'tablist' );
		}
		// 탭이 없는 띠 슬라이더는 들어올 때마다 아무 칸에서나 시작한다
		show( tabs.length ? 0 : Math.floor( Math.random() * panels.length ) );
		setPlaying( panels.length > 1 );
	}

	function run() {
		[].forEach.call( document.querySelectorAll( '.wikis-slider' ), function ( r ) {
			if ( !r.classList.contains( 'is-ready' ) ) {
				init( r );
			}
		} );
	}

	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', run );
	} else {
		run();
	}
	if ( window.mw && mw.hook ) {
		mw.hook( 'wikipage.content' ).add( run );
	}
}() );
/* ===== 대문에서만: 문서 도구(편집·토론·기록·공유)를 본문 맨 아래로 ===== */
( function () {
	function move() {
		if ( !window.mw || !mw.config ) {
			return;
		}
		if ( mw.config.get( 'wgPageName' ) !== '대문' || mw.config.get( 'wgAction' ) !== 'view' ) {
			return;
		}
		var tools = document.querySelector( '.liberty-content-header > .content-tools' );
		var wrap = document.querySelector( '.liberty-content-main' ) || document.querySelector( '.container-fluid.liberty-content' );
		if ( !tools || !wrap ) {
			return;
		}
		tools.classList.add( 'wikis-tools-bottom' );
		wrap.appendChild( tools );
	}
	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', move );
	} else {
		move();
	}
}() );
/* ===== 추천 국가 슬라이더 ([[틀:추천 국가 슬라이더]]) =====
   가운데 한 장이 서고 양옆이 비스듬히 눕는 겹침 슬라이더.
   칩마다 묶음이 통째로 바뀌고, 그림은 지금 보이는 묶음의 가운데 가까운 것만 받는다. */
( function () {
	var NEAR = 2;		// 가운데에서 이만큼 안쪽 장만 그림을 받는다
	var LOOP_MIN = 6;	// 장이 이보다 적으면 빙 돌리지 않는다 (날아가는 게 보인다)

	function init( root ) {
		var chips = [].slice.call( root.querySelectorAll( '.wc-chip' ) );
		var sets = [].slice.call( root.querySelectorAll( '.wc-set' ) );
		if ( !sets.length ) {
			return;
		}
		var stage = root.querySelector( '.wikis-cover-stage' ) || sets[ 0 ].parentNode;
		var toggle = root.querySelector( '.wikis-slider-toggle' );
		var delay = parseInt( root.getAttribute( 'data-interval' ), 10 ) || 6000;
		var slides = sets.map( function ( s ) {
			return [].slice.call( s.querySelectorAll( '.wc-slide' ) );
		} );

		// 들어올 때마다 차례를 섞는다. 그래야 늘 같은 장이 가운데 서지 않는다.
		sets.forEach( function ( s, k ) {
			var list = slides[ k ];
			for ( var i = list.length - 1; i > 0; i-- ) {
				var j = Math.floor( Math.random() * ( i + 1 ) );
				var t = list[ i ];
				list[ i ] = list[ j ];
				list[ j ] = t;
			}
			list.forEach( function ( sl ) {
				s.appendChild( sl );
			} );
		} );
		// 가운뎃장을 한가운데 세운다 (짝수면 가운데에서 한 장 뒤). 그래야 양옆이 다 차 보인다.
		var at = sets.map( function ( s, k ) {
			return Math.floor( slides[ k ].length / 2 );
		} );
		var cur = 0;
		var timer = null;
		var playing = false;
		var onScreen = true;

		function mkNav( cls, label ) {
			var b = document.createElement( 'button' );
			b.type = 'button';
			b.className = 'wc-nav ' + cls;
			b.setAttribute( 'aria-label', label );
			stage.appendChild( b );
			return b;
		}
		var prev = mkNav( 'wc-prev', '이전 그림' );
		var next = mkNav( 'wc-next', '다음 그림' );
		var cap = document.createElement( 'div' );
		cap.className = 'wc-cap';
		root.appendChild( cap );

		// 그림은 쓸 때가 되어서야 만든다
		function load( sl ) {
			if ( sl.getAttribute( 'data-loaded' ) ) {
				return;
			}
			sl.setAttribute( 'data-loaded', '1' );
			var url = sl.getAttribute( 'data-thumb' ) || sl.getAttribute( 'data-full' );
			if ( !url ) {
				return;
			}
			var img = document.createElement( 'img' );
			img.alt = '';
			img.loading = 'lazy';
			img.decoding = 'async';
			img.onerror = function () {
				var full = sl.getAttribute( 'data-full' );
				if ( full && img.getAttribute( 'src' ) !== full ) {
					img.onerror = null;
					img.src = full;
				}
			};
			img.src = url;
			sl.insertBefore( img, sl.firstChild );
		}

		function layout() {
			var list = slides[ cur ];
			var n = list.length;
			var c = at[ cur ];
			var loop = n >= LOOP_MIN;
			list.forEach( function ( sl, i ) {
				var off = i - c;
				if ( loop ) {
					if ( off > n / 2 ) {
						off -= n;
					} else if ( off < -n / 2 ) {
						off += n;
					}
				}
				var a = Math.abs( off );
				var dir = off < 0 ? -1 : 1;
				sl.classList.toggle( 'is-center', off === 0 );
				sl.style.zIndex = String( 10 - a );
				if ( a > NEAR ) {
					sl.style.opacity = '0';
					sl.style.pointerEvents = 'none';
					sl.style.transform = 'translate(-50%, -50%) translateX(' + ( dir * 150 ) + '%) scale(.6)';
					return;
				}
				load( sl );
				sl.style.pointerEvents = 'auto';
				sl.style.opacity = a === NEAR ? '.92' : '1';
				sl.style.transform = 'translate(-50%, -50%) translateX(' +
					( a === 0 ? 0 : dir * ( a === 1 ? 62 : 108 ) ) + '%) rotateY(' +
					( a === 0 ? 0 : -dir * ( a === 1 ? 20 : 26 ) ) + 'deg) scale(' +
					( a === 0 ? 1 : ( a === 1 ? 0.84 : 0.72 ) ) + ')';
			} );

			while ( cap.firstChild ) {
				cap.removeChild( cap.firstChild );
			}
			var mid = list[ c ];
			if ( mid ) {
				var title = mid.getAttribute( 'data-title' ) || '';
				var sub = mid.getAttribute( 'data-sub' ) || '';
				var src = mid.querySelector( 'a' );
				if ( src ) {
					var a2 = document.createElement( 'a' );
					a2.href = src.href;
					a2.textContent = title || src.textContent;
					a2.className = src.className;
					if ( src.target ) {
						a2.target = src.target;
					}
					if ( src.rel ) {
						a2.rel = src.rel;
					}
					cap.appendChild( a2 );
				} else if ( title ) {
					cap.appendChild( document.createTextNode( title ) );
				}
				if ( sub ) {
					var s = document.createElement( 'span' );
					s.className = 'wc-cap-sub';
					s.textContent = sub;
					cap.appendChild( s );
				}
			}
			var many = ( n > 1 );
			prev.style.display = many ? '' : 'none';
			next.style.display = many ? '' : 'none';
		}

		function go( d ) {
			var n = slides[ cur ].length;
			if ( n < 2 ) {
				return;
			}
			at[ cur ] = ( ( at[ cur ] + d ) % n + n ) % n;
			layout();
		}

		function showSet( k ) {
			cur = ( k % sets.length + sets.length ) % sets.length;
			chips.forEach( function ( ch, n ) {
				var on = ( n === cur );
				ch.classList.toggle( 'is-active', on );
				ch.setAttribute( 'aria-selected', on ? 'true' : 'false' );
				ch.setAttribute( 'tabindex', on ? '0' : '-1' );
			} );
			sets.forEach( function ( s, n ) {
				s.classList.toggle( 'is-active', n === cur );
			} );
			layout();
		}

		function stop() {
			if ( timer ) {
				clearInterval( timer );
				timer = null;
			}
		}
		function start() {
			stop();
			if ( slides[ cur ].length > 1 ) {
				timer = setInterval( function () {
					if ( document.hidden || !onScreen ) {
						return;
					}
					go( 1 );
				}, delay );
			}
		}
		function setPlaying( on ) {
			playing = on;
			if ( toggle ) {
				toggle.classList.toggle( 'is-paused', !on );
				toggle.setAttribute( 'title', on ? '자동 넘김 멈춤' : '자동 넘김 시작' );
				toggle.setAttribute( 'aria-label', on ? '자동 넘김 멈춤' : '자동 넘김 시작' );
			}
			if ( on ) {
				start();
			} else {
				stop();
			}
		}

		chips.forEach( function ( ch, n ) {
			ch.setAttribute( 'role', 'tab' );
			ch.setAttribute( 'tabindex', '-1' );
			ch.addEventListener( 'click', function () {
				showSet( n );
				if ( playing ) {
					start();
				}
			} );
			ch.addEventListener( 'keydown', function ( e ) {
				if ( e.key === 'Enter' || e.key === ' ' ) {
					e.preventDefault();
					showSet( n );
				} else if ( e.key === 'ArrowRight' || e.key === 'ArrowLeft' ) {
					e.preventDefault();
					showSet( cur + ( e.key === 'ArrowRight' ? 1 : -1 ) );
					chips[ cur ].focus();
				} else {
					return;
				}
				if ( playing ) {
					start();
				}
			} );
		} );

		prev.addEventListener( 'click', function () {
			go( -1 );
			if ( playing ) {
				start();
			}
		} );
		next.addEventListener( 'click', function () {
			go( 1 );
			if ( playing ) {
				start();
			}
		} );

		// 옆에 누운 장을 누르면 그 장을 가운데로 (링크는 따라가지 않는다)
		stage.addEventListener( 'click', function ( e ) {
			var sl = e.target.closest ? e.target.closest( '.wc-slide' ) : null;
			if ( !sl || sl.classList.contains( 'is-center' ) ) {
				return;
			}
			var i = slides[ cur ].indexOf( sl );
			if ( i < 0 ) {
				return;
			}
			e.preventDefault();
			at[ cur ] = i;
			layout();
			if ( playing ) {
				start();
			}
		} );

		if ( toggle ) {
			toggle.setAttribute( 'role', 'button' );
			toggle.setAttribute( 'tabindex', '0' );
			toggle.addEventListener( 'click', function () {
				setPlaying( !playing );
			} );
			toggle.addEventListener( 'keydown', function ( e ) {
				if ( e.key === 'Enter' || e.key === ' ' ) {
					e.preventDefault();
					setPlaying( !playing );
				}
			} );
		}

		root.addEventListener( 'mouseenter', function () {
			if ( playing ) {
				stop();
			}
		} );
		root.addEventListener( 'mouseleave', function () {
			if ( playing ) {
				start();
			}
		} );

		var x0 = null;
		stage.addEventListener( 'touchstart', function ( e ) {
			x0 = e.touches[ 0 ].clientX;
		}, { passive: true } );
		stage.addEventListener( 'touchend', function ( e ) {
			if ( x0 === null ) {
				return;
			}
			var dx = e.changedTouches[ 0 ].clientX - x0;
			x0 = null;
			if ( Math.abs( dx ) > 40 ) {
				go( dx < 0 ? 1 : -1 );
				if ( playing ) {
					start();
				}
			}
		}, { passive: true } );

		// 화면 밖으로 밀려나면 넘기지 않는다
		if ( window.IntersectionObserver ) {
			new IntersectionObserver( function ( es ) {
				onScreen = es[ 0 ].isIntersecting;
			}, { threshold: 0 } ).observe( root );
		}

		root.classList.add( 'is-ready' );
		var chiplist = root.querySelector( '.wikis-cover-chiplist' );
		if ( chiplist ) {
			chiplist.setAttribute( 'role', 'tablist' );
		}
		showSet( 0 );
		setPlaying( slides[ 0 ].length > 1 );
	}

	function run() {
		[].forEach.call( document.querySelectorAll( '.wikis-cover' ), function ( r ) {
			if ( !r.classList.contains( 'is-ready' ) ) {
				init( r );
			}
		} );
	}

	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', run );
	} else {
		run();
	}
	if ( window.mw && mw.hook ) {
		mw.hook( 'wikipage.content' ).add( run );
	}
}() );
/* ===== 대문 격자 슬라이더 ([[틀:대문 격자 슬라이더]]) =====
   칩으로 묶음을 고른다. 그림은 고른 묶음 것만 받고, 누르지 않은 묶음은 아예 받지 않는다. */
( function () {
	function init( root ) {
		var chips = [].slice.call( root.querySelectorAll( '.wg-chip' ) );
		var sets = [].slice.call( root.querySelectorAll( '.wg-set' ) );
		if ( !sets.length ) {
			return;
		}
		var cur = 0;

		function loadSet( set ) {
			[].forEach.call( set.querySelectorAll( '.wg-item' ), function ( it ) {
				if ( it.getAttribute( 'data-loaded' ) ) {
					return;
				}
				it.setAttribute( 'data-loaded', '1' );
				var url = it.getAttribute( 'data-thumb' ) || it.getAttribute( 'data-full' );
				var box = it.querySelector( '.wg-img' );
				if ( !box ) {
					return;
				}
				// 그림 자리도 문서로 가는 링크로 감싼다 (글씨만 눌리던 것을 고침)
				var holder = box;
				var cap = it.querySelector( '.wg-cap a' );
				if ( cap && cap.getAttribute( 'href' ) && !box.querySelector( 'a' ) ) {
					var wrap = document.createElement( 'a' );
					wrap.setAttribute( 'href', cap.getAttribute( 'href' ) );
					wrap.className = 'wg-imglink' + ( /�external�/.test( cap.className ) ? ' external' : '' );
					if ( cap.getAttribute( 'title' ) ) {
						wrap.setAttribute( 'title', cap.getAttribute( 'title' ) );
					}
					if ( cap.target ) {
						wrap.target = cap.target;
					}
					if ( cap.rel ) {
						wrap.rel = cap.rel;
					}
					while ( box.firstChild ) {
						wrap.appendChild( box.firstChild );
					}
					box.appendChild( wrap );
					holder = wrap;
				}
				if ( !url ) {
					return;
				}
				var img = document.createElement( 'img' );
				img.alt = '';
				img.loading = 'lazy';
				img.decoding = 'async';
				img.onerror = function () {
					var full = it.getAttribute( 'data-full' );
					if ( full && img.getAttribute( 'src' ) !== full ) {
						img.onerror = null;
						img.src = full;
						return;
					}
					// 그림을 못 받으면 이름이 적힌 자리를 되살린다
					img.parentNode && img.parentNode.removeChild( img );
					box.classList.remove( 'has-img' );
				};
				img.onload = function () {
					var n = box.querySelector( '.wg-noimg' );
					if ( n ) {
						n.style.display = 'none';
					}
				};
				img.src = url;
				holder.appendChild( img );
				box.classList.add( 'has-img' );
			} );
		}

		function show( k ) {
			cur = ( k % sets.length + sets.length ) % sets.length;
			chips.forEach( function ( ch, n ) {
				var on = ( n === cur );
				ch.classList.toggle( 'is-active', on );
				ch.setAttribute( 'aria-selected', on ? 'true' : 'false' );
				ch.setAttribute( 'tabindex', on ? '0' : '-1' );
			} );
			sets.forEach( function ( s, n ) {
				s.classList.toggle( 'is-active', n === cur );
			} );
			loadSet( sets[ cur ] );
		}

		chips.forEach( function ( ch, n ) {
			ch.setAttribute( 'role', 'tab' );
			ch.setAttribute( 'tabindex', '-1' );
			ch.addEventListener( 'click', function () {
				show( n );
			} );
			ch.addEventListener( 'keydown', function ( e ) {
				if ( e.key === 'Enter' || e.key === ' ' ) {
					e.preventDefault();
					show( n );
				} else if ( e.key === 'ArrowRight' || e.key === 'ArrowLeft' ) {
					e.preventDefault();
					show( cur + ( e.key === 'ArrowRight' ? 1 : -1 ) );
					chips[ cur ].focus();
				}
			} );
		} );

		root.classList.add( 'is-ready' );
		var list = root.querySelector( '.wikis-grid-chiplist' );
		if ( list ) {
			list.setAttribute( 'role', 'tablist' );
		}
		show( 0 );
	}

	function run() {
		[].forEach.call( document.querySelectorAll( '.wikis-grid' ), function ( r ) {
			if ( !r.classList.contains( 'is-ready' ) ) {
				init( r );
			}
		} );
	}

	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', run );
	} else {
		run();
	}
	if ( window.mw && mw.hook ) {
		mw.hook( 'wikipage.content' ).add( run );
	}
}() );

/* ===== Live2D 로더 (MediaWiki:Common.js 맨 아래에 추가) =====
 * .live2d-model 요소가 있는 문서에서만 동작한다. 없는 문서에서는 아무 것도 불러오지 않는다.
 * 지원: Cubism 2.x 모델 (pixi-live2d-display + live2d.min.js)
 *
 * div 속성
 *   data-model   model.json 주소 (필수)
 *   data-width   캔버스 너비 px   (기본 400)
 *   data-height  캔버스 높이 px   (기본 500)
 *   data-zoom    확대 배율        (기본 1)
 *   data-offset-x / data-offset-y  위치 보정 px (기본 0)
 *   data-interact  "1"이면 마우스 시선 추적/클릭 반응 (기본 끔)
 *   data-expression  model.json의 expressions 이름 (예: smile01). 표정 고정
 *   data-click   클릭 시 재생할 모션 이름 목록 "smile01,sad01,idle" (클릭할 때마다 순서대로, 끝나면 마지막 자세로 고정)
 */
( function () {
	'use strict';

	// 외부 라이브러리. 버전 고정. 가능하면 본인 호스팅으로 바꾸는 것을 권장.
	var LIBS = [
		// Cubism 2 코어 (Live2D 공식 CDN은 Cubism 2용을 제공하지 않아 서드파티 미러 사용)
		'https://cdn.jsdelivr.net/gh/dylanNew/live2d@master/webgl/Live2D/lib/live2d.min.js',
		'https://cdn.jsdelivr.net/npm/[email protected]/dist/browser/pixi.min.js',
		'https://cdn.jsdelivr.net/npm/[email protected]/dist/cubism2.min.js'
	];

	var libsPromise = null;

	function loadLibs() {
		if ( libsPromise ) {
			return libsPromise;
		}
		libsPromise = LIBS.reduce( function ( p, src ) {
			return p.then( function () {
				return mw.loader.getScript( src );
			} );
		}, $.Deferred().resolve().promise() );
		return libsPromise;
	}

	function fail( el, msg ) {
		el.classList.add( 'live2d-error' );
		el.textContent = msg;
	}

	function render( el ) {
		var url = el.getAttribute( 'data-model' );
		var w = parseInt( el.getAttribute( 'data-width' ), 10 ) || 400;
		var h = parseInt( el.getAttribute( 'data-height' ), 10 ) || 500;
		var zoom = parseFloat( el.getAttribute( 'data-zoom' ) ) || 1;
		var ox = parseFloat( el.getAttribute( 'data-offset-x' ) ) || 0;
		var oy = parseFloat( el.getAttribute( 'data-offset-y' ) ) || 0;
		var interact = el.getAttribute( 'data-interact' ) === '1';
		var expression = el.getAttribute( 'data-expression' );

		if ( !url ) {
			fail( el, 'Live2D: data-model 이 없습니다.' );
			return;
		}

		el.style.width = w + 'px';
		el.style.height = h + 'px';
		el.classList.add( 'live2d-loading' );

		loadLibs().then( function () {
			var app = new PIXI.Application( {
				width: w,
				height: h,
				backgroundAlpha: 0,
				antialias: true,
				autoDensity: true,
				resolution: window.devicePixelRatio || 1
			} );
			el.textContent = '';
			el.appendChild( app.view );

			// 모바일 터치 대응: Pixi 의 상호작용 모듈은 터치에 preventDefault 를 걸어 click 을 막고,
			// 캔버스 위 세로 스크롤도 막는다. 여기서는 Pixi 상호작용을 쓰지 않으므로 끈다.
			try {
				var im = app.renderer.plugins && app.renderer.plugins.interaction;
				if ( im ) {
					im.autoPreventDefault = false;
					if ( im.removeEvents ) {
						im.removeEvents();
					}
				}
			} catch ( e ) {}
			app.view.style.touchAction = 'pan-y'; // 세로 스크롤은 허용, 탭은 그대로 받는다
			app.view.style.webkitTapHighlightColor = 'transparent';

			return PIXI.live2d.Live2DModel.from( url, { autoInteract: interact } ).then( function ( model ) {
				var s = Math.min( w / model.width, h / model.height ) * zoom;
				model.anchor.set( 0.5, 0.5 );
				model.scale.set( s );
				model.x = w / 2 + ox;
				model.y = h / 2 + oy;
				app.stage.addChild( model );
				el.classList.remove( 'live2d-loading' );

				// 진단용: F12 Console 에서 확인할 수 있다
				el.l2dModel = model;
				if ( window.console ) {
					console.info( '[Live2D] 모션 그룹:', Object.keys( model.internalModel.motionManager.definitions || {} ),
						'/ click =', el.getAttribute( 'data-click' ) );
				}

				// 클릭하면 모션을 재생하고, 끝난 뒤에는 그 모션의 마지막 자세로 고정되어 흔들린다.
				// model.json 에 <이름> 그룹과 hold_<이름> 그룹이 있어야 한다. "idle" 은 기본 모션으로 복귀.
				var clicks = ( el.getAttribute( 'data-click' ) || '' ).split( ',' )
					.map( function ( s ) { return s.trim(); } ).filter( Boolean );
				if ( clicks.length ) {
					var mm = model.internalModel.motionManager;
					var FORCE = ( PIXI.live2d.MotionPriority && PIXI.live2d.MotionPriority.FORCE ) || 3;
					var next = 0;
					app.view.style.cursor = 'pointer';

					// 탭 판정: 마우스/터치/펜 모두 pointer 이벤트로 받고, 거의 안 움직이고 짧게 눌렀을 때만 탭으로 본다.
					// (스크롤하려고 움직인 경우는 pointercancel/이동량으로 걸러진다)
					var downAt = null;
					var onTap = function () {
						var name = clicks[ next++ % clicks.length ];
						try {
							if ( name === 'idle' ) {
								mm.groups.idle = 'idle';
								model.motion( 'idle', undefined, FORCE );
								return;
							}
							var holdGroup = 'hold_' + name;
							var defs = mm.definitions || {};
							if ( defs[ holdGroup ] ) {
								mm.groups.idle = holdGroup;
							}
							model.motion( name, undefined, FORCE );
						} catch ( e ) {
							if ( window.console ) {
								console.error( '[Live2D]', e );
							}
						}
					};

					if ( window.PointerEvent ) {
						app.view.addEventListener( 'pointerdown', function ( e ) {
							downAt = { x: e.clientX, y: e.clientY, t: Date.now() };
						} );
						app.view.addEventListener( 'pointerup', function ( e ) {
							if ( !downAt ) {
								return;
							}
							var moved = Math.hypot( e.clientX - downAt.x, e.clientY - downAt.y );
							var held = Date.now() - downAt.t;
							downAt = null;
							if ( moved < 12 && held < 700 ) {
								onTap();
							}
						} );
						app.view.addEventListener( 'pointercancel', function () {
							downAt = null;
						} );
					} else {
						app.view.addEventListener( 'click', onTap ); // 구형 브라우저
					}
				}

				// 표정 고정 (model.json의 expressions 이름과 같아야 함)
				if ( expression ) {
					try {
						var r = model.expression( expression );
						if ( r && r.catch ) {
							r.catch( function () {} );
						}
					} catch ( e ) {}
				}
			} );
		} ).fail( function () {
			fail( el, 'Live2D 라이브러리를 불러오지 못했습니다.' );
		} ).catch( function ( e ) {
			if ( window.console ) {
				console.error( '[Live2D]', e );
			}
			fail( el, 'Live2D 모델을 불러오지 못했습니다.' );
		} );
	}

	mw.hook( 'wikipage.content' ).add( function ( $content ) {
		var nodes = $content.find( '.live2d-model' ).filter( function () {
			return !this.getAttribute( 'data-l2d-init' );
		} ).get();
		if ( !nodes.length ) {
			return;
		}

		// 화면에 보일 때만 초기화 (한 문서에 여러 개 있어도 가볍게)
		var io = 'IntersectionObserver' in window ? new IntersectionObserver( function ( entries ) {
			entries.forEach( function ( en ) {
				if ( en.isIntersecting ) {
					io.unobserve( en.target );
					render( en.target );
				}
			} );
		}, { rootMargin: '200px' } ) : null;

		nodes.forEach( function ( el ) {
			el.setAttribute( 'data-l2d-init', '1' );
			if ( io ) {
				io.observe( el );
			} else {
				render( el );
			}
		} );
	} );
}() );