미디어위키:Gadget-CSSVars.js: 두 판 사이의 차이

편집 요약 없음
편집 요약 없음
태그: 수동 되돌리기
 
(같은 사용자의 중간 판 6개는 보이지 않습니다)
1번째 줄: 1번째 줄:
mw.hook('wikipage.content').add(function ($content) {
mw.loader.using(
const el = $content.find('.mw-css-vars').first();
    ['oojs-ui-core', 'oojs-ui.styles.icons-interactions', 'mediawiki.util', 'jquery'],
if (!el.length) return;
    function () {
        // 1. $content가 전역에 없을 경우를 대비해 안전하게 참조 (보통 위키 본문 영역)
        const $contentArea = window.$content || $('#mw-content-text');
        const $el = $contentArea.find('.mw-page-css-vars').first();
       
        if (!$el.length) return;


let vars;
        let vars;
try {
        try {
vars = JSON.parse(el.attr('data-vars'));
            // .attr() 대신 .data()를 사용하면 jQuery가 자동으로 JSON 파싱을 시도할 수 있지만,
} catch (e) {
            // 데이터 속성명에 따라 다르므로 기존 JSON.parse 방식을 유지하되 안전하게 처리합니다.
console.error('PageCSSVars: invalid JSON', e);
            const rawData = $el.attr('data-vars');
return;
            vars = JSON.parse(rawData);
}
        } catch (e) {
            console.error('[PageCSSVars] JSON 파싱 에러:', e);
            return;
        }


const root = document.documentElement;
        const themes = {
const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            common: [],
            light: [],
            dark: []
        };


Object.entries(vars).forEach(([key, value]) => {
        // 2. 루프 내에서 문자열 조작을 미리 처리하여 가독성 및 성능 향상
let targetKey = key;
        Object.entries(vars).forEach(([key, value]) => {
let apply = true;
            if (key.endsWith('-light')) {
                themes.light.push(`--${key.replace(/-light$/, '')}: ${value} !important;`);
            } else if (key.endsWith('-dark')) {
                themes.dark.push(`--${key.replace(/-dark$/, '')}: ${value} !important;`);
            } else {
                themes.common.push(`--${key}: ${value} !important;`);
            }
        });


if (key.endsWith('-light')) {
        // 3. CSS 문자열 조립
targetKey = key.replace(/-light$/, '');
        let cssLines = [];
apply = !isDark;
} else if (key.endsWith('-dark')) {
targetKey = key.replace(/-dark$/, '');
apply = isDark;
}


if (!apply) return;
        if (themes.common.length) {
            cssLines.push(`:root { ${themes.common.join(' ')} }`);
        }


/* 🔥 !important 강제 */
        if (themes.light.length) {
root.style.setProperty(`--${targetKey}`, value, 'important');
            cssLines.push(`@media (prefers-color-scheme: light) { :root { ${themes.light.join(' ')} } }`);
});
        }
});
 
        if (themes.dark.length) {
            cssLines.push(`@media (prefers-color-scheme: dark) { :root { ${themes.dark.join(' ')} } }`);
        }
 
        // 4. 최종 주입
        if (cssLines.length) {
            const finalCss = cssLines.join('\n');
            mw.util.addCSS(finalCss);
        }
    }
);

2026년 2월 12일 (목) 23:59 기준 최신판

mw.loader.using(
    ['oojs-ui-core', 'oojs-ui.styles.icons-interactions', 'mediawiki.util', 'jquery'],
    function () {
        // 1. $content가 전역에 없을 경우를 대비해 안전하게 참조 (보통 위키 본문 영역)
        const $contentArea = window.$content || $('#mw-content-text');
        const $el = $contentArea.find('.mw-page-css-vars').first();
        
        if (!$el.length) return;

        let vars;
        try {
            // .attr() 대신 .data()를 사용하면 jQuery가 자동으로 JSON 파싱을 시도할 수 있지만, 
            // 데이터 속성명에 따라 다르므로 기존 JSON.parse 방식을 유지하되 안전하게 처리합니다.
            const rawData = $el.attr('data-vars');
            vars = JSON.parse(rawData);
        } catch (e) {
            console.error('[PageCSSVars] JSON 파싱 에러:', e);
            return;
        }

        const themes = {
            common: [],
            light: [],
            dark: []
        };

        // 2. 루프 내에서 문자열 조작을 미리 처리하여 가독성 및 성능 향상
        Object.entries(vars).forEach(([key, value]) => {
            if (key.endsWith('-light')) {
                themes.light.push(`--${key.replace(/-light$/, '')}: ${value} !important;`);
            } else if (key.endsWith('-dark')) {
                themes.dark.push(`--${key.replace(/-dark$/, '')}: ${value} !important;`);
            } else {
                themes.common.push(`--${key}: ${value} !important;`);
            }
        });

        // 3. CSS 문자열 조립
        let cssLines = [];

        if (themes.common.length) {
            cssLines.push(`:root { ${themes.common.join(' ')} }`);
        }

        if (themes.light.length) {
            cssLines.push(`@media (prefers-color-scheme: light) { :root { ${themes.light.join(' ')} } }`);
        }

        if (themes.dark.length) {
            cssLines.push(`@media (prefers-color-scheme: dark) { :root { ${themes.dark.join(' ')} } }`);
        }

        // 4. 최종 주입
        if (cssLines.length) {
            const finalCss = cssLines.join('\n');
            mw.util.addCSS(finalCss);
        }
    }
);