미디어위키:ManifestoIntro.js

Nxdsxn (토론 | 기여)님의 2026년 7월 13일 (월) 06:40 판 (Install package: clbiwiki-mainpage-manifesto-divider-true-growth-20260713 / js/ManifestoIntro.js)

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

  • 파이어폭스 / 사파리: Shift 키를 누르면서 새로 고침을 클릭하거나, Ctrl-F5 또는 Ctrl-R을 입력 (Mac에서는 ⌘-R)
  • 구글 크롬: Ctrl-Shift-R키를 입력 (Mac에서는 ⌘-Shift-R)
  • 인터넷 익스플로러 / 엣지: Ctrl 키를 누르면서 새로 고침을 클릭하거나, Ctrl-F5를 입력.
  • 오페라: Ctrl-F5를 입력.
/* =========================================
ManifestoIntro
대문 선언문 절차적 진입 애니메이션
========================================= */

/*
새 기능과 공개 이름에는 프로젝트 접두사를 사용하지 않는다.
실제 HTML 텍스트를 유지한 채 제목, 구분선, 본문 행을 순서대로 연다.
이미지, canvas, 글자 래스터화는 사용하지 않는다.
*/

(function (window, document, mw) {
    'use strict';

    var PORTAL_SELECTOR = '.main-portal';
    var TITLE_SELECTOR = '.main-manifesto-title';
    var COPY_SELECTOR = '.main-manifesto-copy';
    var FONT_QUERY = '18px "NanumMyeongjoBold Pixel 18"';
    var TITLE_DELAY = 50;
    var TITLE_DURATION = 420;
    var DIVIDER_DELAY = 190;
    var DIVIDER_DURATION = 500;
    var BODY_DELAY = DIVIDER_DELAY + DIVIDER_DURATION + 30;
    var LINE_STAGGER = 64;
    var LINE_DURATION = 230;
    var LINE_HEIGHT = 26;
    var portalStates = typeof WeakMap === 'function' ? new WeakMap() : null;
    var observer = null;

    function findPortal(root) {
        var scope = root && root.querySelector ? root : document;

        if (scope.matches && scope.matches(PORTAL_SELECTOR)) {
            return scope;
        }

        return scope.querySelector(PORTAL_SELECTOR) || document.querySelector(PORTAL_SELECTOR);
    }

    function prefersReducedMotion() {
        return !!(
            window.matchMedia &&
            window.matchMedia('(prefers-reduced-motion: reduce)').matches
        );
    }

    function getState(portal) {
        if (portalStates) return portalStates.get(portal) || '';
        return portal.getAttribute('data-manifesto-intro-state') || '';
    }

    function setState(portal, state) {
        if (portalStates) portalStates.set(portal, state);
        portal.setAttribute('data-manifesto-intro-state', state);
    }

    function disarmPending() {
        document.documentElement.classList.remove('manifesto-intro-pending');
        document.documentElement.classList.remove('manifesto-intro-active');
    }

    function waitForFont() {
        if (!document.fonts || typeof document.fonts.load !== 'function') {
            return Promise.resolve();
        }

        var timeout = new Promise(function (resolve) {
            window.setTimeout(resolve, 1400);
        });

        var load = document.fonts.load(FONT_QUERY).then(function () {
            return document.fonts.ready;
        }).catch(function () {
            return null;
        });

        return Promise.race([load, timeout]);
    }

    function tokenizeParagraph(paragraph) {
        var text = String(paragraph.textContent || '').replace(/\s+/g, ' ').trim();
        var words = text ? text.split(' ') : [];

        paragraph.textContent = '';
        paragraph.setAttribute('data-manifesto-original-text', text);

        words.forEach(function (word, index) {
            var token = document.createElement('span');
            token.className = 'manifesto-measure-token';
            token.textContent = word;
            paragraph.appendChild(token);

            if (index < words.length - 1) {
                paragraph.appendChild(document.createTextNode(' '));
            }
        });

        return Array.prototype.slice.call(
            paragraph.querySelectorAll('.manifesto-measure-token')
        );
    }

    function groupTokensIntoRows(tokens) {
        var rows = [];
        var current = null;

        tokens.forEach(function (token) {
            var top = Math.round(token.getBoundingClientRect().top);

            if (!current || Math.abs(current.top - top) > 1) {
                current = { top: top, words: [] };
                rows.push(current);
            }

            current.words.push(token.textContent);
        });

        return rows.map(function (row) {
            return row.words.join(' ');
        });
    }

    function createLine(text, index) {
        var line = document.createElement('span');
        var inner = document.createElement('span');

        line.className = 'manifesto-line';
        line.setAttribute('data-manifesto-line-index', String(index));

        inner.className = 'manifesto-line-inner';
        inner.textContent = text;

        line.appendChild(inner);
        return line;
    }

    function buildRenderedLines(copy) {
        var paragraphs = Array.prototype.slice.call(copy.querySelectorAll('p'));
        var lines = [];
        var lineIndex = 0;

        if (!paragraphs.length) return lines;

        copy.classList.add('manifesto-line-measuring');

        paragraphs.forEach(function (paragraph) {
            var tokens = tokenizeParagraph(paragraph);
            var rows = groupTokensIntoRows(tokens);

            paragraph.textContent = '';

            rows.forEach(function (text) {
                var line = createLine(text, lineIndex);
                paragraph.appendChild(line);
                lines.push(line);
                lineIndex += 1;
            });
        });

        copy.classList.remove('manifesto-line-measuring');
        return lines;
    }

    function restoreOriginalText(copy) {
        Array.prototype.forEach.call(copy.querySelectorAll('p'), function (paragraph) {
            var original = paragraph.getAttribute('data-manifesto-original-text');
            if (original !== null) {
                paragraph.textContent = original;
                paragraph.removeAttribute('data-manifesto-original-text');
            }
        });
    }

    function ensureDivider(title) {
        var divider = title.querySelector('.manifesto-divider');

        if (!divider) {
            divider = document.createElement('span');
            divider.className = 'manifesto-divider';
            divider.setAttribute('aria-hidden', 'true');
            title.appendChild(divider);
        }

        return divider;
    }

    function applyInitialFrame(portal, title, copy, divider, lines) {
        portal.classList.remove('manifesto-intro-complete');
        portal.classList.add('manifesto-intro-prepared');
        document.documentElement.classList.add('manifesto-intro-active');

        title.style.opacity = '0';
        divider.style.left = '50%';
        divider.style.width = '0px';
        divider.style.transform = 'none';

        lines.forEach(function (line) {
            var inner = line.querySelector('.manifesto-line-inner');

            line.style.height = '0px';
            line.style.maxHeight = '0px';
            line.style.opacity = '0';
            line.style.overflow = 'hidden';
            line.style.clipPath = 'inset(0 0 100% 0)';

            if (inner) {
                inner.style.opacity = '0.18';
                inner.style.transform = 'translateY(-10px)';
            }
        });

        copy.style.visibility = 'visible';

        /* 초기 프레임을 실제 렌더 트리에 확정한 뒤 pending을 해제한다. */
        portal.getBoundingClientRect();
        lines.forEach(function (line) { line.getBoundingClientRect(); });
        document.documentElement.classList.remove('manifesto-intro-pending');
    }

    function finishAnimation(animation, element, finalStyles) {
        if (!animation || !animation.finished) return Promise.resolve();

        return animation.finished.catch(function () {
            return null;
        }).then(function () {
            Object.keys(finalStyles).forEach(function (property) {
                element.style[property] = finalStyles[property];
            });
            animation.cancel();
        });
    }

    function animateTitle(title) {
        var animation = title.animate([
            { opacity: 0 },
            { opacity: 1 }
        ], {
            duration: TITLE_DURATION,
            delay: TITLE_DELAY,
            easing: 'cubic-bezier(.18,.72,.24,1)',
            fill: 'both'
        });

        return finishAnimation(animation, title, { opacity: '1' });
    }

    function animateDivider(divider) {
        /*
        완성된 선을 미리 깔고 scale로 채우지 않는다.
        실제 선 요소의 좌표와 폭 자체를 중앙 0px에서 좌우 끝까지 늘린다.
        */
        var animation = divider.animate([
            { left: '50%', width: '0px' },
            { left: '0%', width: '100%' }
        ], {
            duration: DIVIDER_DURATION,
            delay: DIVIDER_DELAY,
            easing: 'cubic-bezier(.2,.78,.22,1)',
            fill: 'both'
        });

        return finishAnimation(animation, divider, {
            left: '0%',
            width: '100%',
            transform: 'none'
        });
    }

    function animateLine(line, index) {
        var delay = BODY_DELAY + (index * LINE_STAGGER);
        var inner = line.querySelector('.manifesto-line-inner');
        var outerAnimation = line.animate([
            {
                height: '0px',
                maxHeight: '0px',
                opacity: 0,
                clipPath: 'inset(0 0 100% 0)'
            },
            {
                offset: 0.42,
                height: '11px',
                maxHeight: '11px',
                opacity: 0.56,
                clipPath: 'inset(0 0 58% 0)'
            },
            {
                height: LINE_HEIGHT + 'px',
                maxHeight: LINE_HEIGHT + 'px',
                opacity: 1,
                clipPath: 'inset(0 0 0 0)'
            }
        ], {
            duration: LINE_DURATION,
            delay: delay,
            easing: 'cubic-bezier(.16,.76,.22,1)',
            fill: 'both'
        });
        var promises = [finishAnimation(outerAnimation, line, {
            height: LINE_HEIGHT + 'px',
            maxHeight: LINE_HEIGHT + 'px',
            opacity: '1',
            overflow: 'visible',
            clipPath: 'inset(0 0 0 0)'
        })];

        if (inner) {
            var innerAnimation = inner.animate([
                { transform: 'translateY(-10px)', opacity: 0.18 },
                { offset: 0.5, transform: 'translateY(-3px)', opacity: 0.72 },
                { transform: 'translateY(0)', opacity: 1 }
            ], {
                duration: LINE_DURATION,
                delay: delay,
                easing: 'cubic-bezier(.16,.76,.22,1)',
                fill: 'both'
            });

            promises.push(finishAnimation(innerAnimation, inner, {
                transform: 'translateY(0)',
                opacity: '1'
            }));
        }

        return Promise.all(promises);
    }

    function showImmediately(portal) {
        var title = portal && portal.querySelector(TITLE_SELECTOR);
        var copy = portal && portal.querySelector(COPY_SELECTOR);

        if (title) {
            title.style.opacity = '1';
            title.style.borderBottomColor = '';
        }
        if (copy) copy.style.visibility = 'visible';

        if (portal) {
            portal.classList.remove('manifesto-intro-prepared');
            portal.classList.add('manifesto-intro-complete');
            setState(portal, 'complete');
            portal.setAttribute('data-manifesto-intro-played', '1');
        }

        disarmPending();
    }

    function prepare(portal) {
        var title = portal.querySelector(TITLE_SELECTOR);
        var copy = portal.querySelector(COPY_SELECTOR);
        var lines;
        var divider;

        if (!title || !copy) return null;

        try {
            lines = buildRenderedLines(copy);
            divider = ensureDivider(title);
        } catch (error) {
            restoreOriginalText(copy);
            return null;
        }

        if (!lines.length || !divider) {
            restoreOriginalText(copy);
            return null;
        }

        applyInitialFrame(portal, title, copy, divider, lines);

        return {
            title: title,
            copy: copy,
            divider: divider,
            lines: lines
        };
    }

    function play(portal, prepared) {
        var animations = [];

        setState(portal, 'running');
        portal.setAttribute('data-manifesto-intro-played', '1');

        animations.push(animateTitle(prepared.title));
        animations.push(animateDivider(prepared.divider));

        prepared.lines.forEach(function (line, index) {
            animations.push(animateLine(line, index));
        });

        return Promise.all(animations).then(function () {
            portal.classList.add('manifesto-intro-complete');
            portal.classList.remove('manifesto-intro-running');
            setState(portal, 'complete');
            document.documentElement.classList.remove('manifesto-intro-active');
            return true;
        });
    }

    function begin(portal) {
        if (!portal || !portal.isConnected) return Promise.resolve(false);

        var state = getState(portal);
        if (state === 'preparing' || state === 'running' || state === 'complete') {
            return Promise.resolve(false);
        }

        if (prefersReducedMotion() || typeof Element.prototype.animate !== 'function') {
            showImmediately(portal);
            return Promise.resolve(false);
        }

        setState(portal, 'preparing');

        return waitForFont().then(function () {
            if (!portal.isConnected) return false;

            var prepared = prepare(portal);
            if (!prepared) {
                showImmediately(portal);
                return false;
            }

            portal.classList.add('manifesto-intro-running');

            return new Promise(function (resolve) {
                window.requestAnimationFrame(function () {
                    window.requestAnimationFrame(function () {
                        play(portal, prepared).then(resolve).catch(function () {
                            showImmediately(portal);
                            resolve(false);
                        });
                    });
                });
            });
        }).catch(function () {
            showImmediately(portal);
            return false;
        });
    }

    function init(root) {
        var portal = findPortal(root);

        if (!portal) {
            return Promise.resolve(false);
        }

        return begin(portal);
    }

    function observeForPortal() {
        if (observer || !window.MutationObserver || !document.documentElement) return;

        observer = new MutationObserver(function () {
            var portal = document.querySelector(PORTAL_SELECTOR);
            if (!portal) return;
            init(portal);
        });

        observer.observe(document.documentElement, {
            childList: true,
            subtree: true
        });
    }

    function boot(root) {
        init(root || document);
        observeForPortal();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () {
            boot(document);
        }, { once: true });
    } else {
        boot(document);
    }

    window.addEventListener('load', function () {
        boot(document);
    }, { once: true });

    window.addEventListener('pageshow', function () {
        boot(document);
    });

    if (mw && mw.hook) {
        mw.hook('wikipage.content').add(function ($content) {
            boot($content && $content[0] ? $content[0] : document);
        });
    }

    window.ManifestoIntro = {
        version: '20260713-procedural-002',
        init: init,
        status: function () {
            var portal = document.querySelector(PORTAL_SELECTOR);
            return {
                loaded: true,
                portal: !!portal,
                state: portal ? getState(portal) : '',
                prepared: !!(portal && portal.classList.contains('manifesto-intro-prepared')),
                running: !!(portal && portal.classList.contains('manifesto-intro-running')),
                complete: !!(portal && portal.classList.contains('manifesto-intro-complete')),
                lineCount: portal ? portal.querySelectorAll('.manifesto-line').length : 0
            };
        }
    };
}(window, document, window.mw));