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

편집 요약 없음
편집 요약 없음
태그: 수동 되돌리기
 
(같은 사용자의 중간 판 5개는 보이지 않습니다)
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 light = {};
        const themes = {
const dark = {};
            common: [],
const common = {};
            light: [],
            dark: []
        };


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


const makeVars = (obj) =>
        // 3. CSS 문자열 조립
Object.entries(obj)
        let cssLines = [];
.map(([k, v]) => `--${k}: ${v} !important;`)
.join('');


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


if (Object.keys(common).length) {
        if (themes.light.length) {
css += `:root{${makeVars(common)}}`;
            cssLines.push(`@media (prefers-color-scheme: light) { :root { ${themes.light.join(' ')} } }`);
}
        }


if (Object.keys(light).length) {
        if (themes.dark.length) {
css += `
            cssLines.push(`@media (prefers-color-scheme: dark) { :root { ${themes.dark.join(' ')} } }`);
@media (prefers-color-scheme: light){
        }
:root{${makeVars(light)}}
}`;
}


if (Object.keys(dark).length) {
        // 4. 최종 주입
css += `
        if (cssLines.length) {
@media (prefers-color-scheme: dark){
            const finalCss = cssLines.join('\n');
:root{${makeVars(dark)}}
            mw.util.addCSS(finalCss);
}`;
        }
}
    }
 
);
if (css.trim()) {
mw.util.addCSS(css);
}
});

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);
        }
    }
);