코드스피츠 css rendering 3회차 part3 (step 41) - sheet 클래스 생성
sheet 클래스
const Sheet = class{
constructor(sheet){
this._sheet = sheet;
this._rules = new Map();
}
add(selector){
const index = this._sheet.cssRules.length;
this._sheet.insertRule(`${selector}{}`,index);
const cssRule = this._sheet.cssRules[index];
const rule = new Rule(cssRule);
this._rules.set(selector,rule);
return rule;
}
remove(selector){
if(!this._rules.contains(selector)) return;
const rule = this._rules.get(selector)._rule;
Array.from(this._sheet.cssRules).some((cssRule,index)=>{
if(cssRule === rule._rule){
this._sheet.deleteRule(index);
return true;
}
})
}
get(selector){return this._rules.get(selector);}
}
전체코드
<html>
<head lang="en">
<meta charset="UTF-8">
<style>
</style>
<body>
<div class="test">a</div>
</body>
<script>
const Style = ((_) => {
const prop = new Map, prefix = 'webkt,moz,ms,chrome,o,khtml'.split(',');
const NONE = Symbol();
const BASE = document.body.style;
const getKey = (key) => {
if(prop.has(key)) return prop.get(key);
if(key in BASE) prop.set(key, key);
else if(!prefix.some(v =>{
// prefix를 붙인 속성은 존재하는가?를 알아볼 차례
// 메소드 some의 인수인 callback 함수 부분이다.
// webkitBackground 이런식으로 속성명 첫글자가 대문자이므로 표준 key인 background의 앞에 vendor prefix를 붙이고 대문자로 바꾸고 나머지 뒤인 'ackground'를 붙여주는 작업이 필요하다.
const newKey = v + key[0].toUpperCase() + key.substr(1);
if(newKey in BASE){ // prefix붙인 속성이 body에 있다면,
prop.set(key, newKey); // border-radius 부르면 prefix를 붙인 진짜 이름을 캐시에 저장
key = newKey; // 리턴할 key는 더이상 원래 키가 아니라 newKey
return true; // 진짜 이름을 찾았으니 여기서 끊어 라는것. some을 더 돌지 않아도 된다고 끊어버리는 것이다.
} else return false;
})){
// some의 결과가 false일 경우에만 여기에 들어온다.
prop.set(key, NONE);
key = NONE;
}
return key; // 그냥 key가 리턴되든지, newKey가 리턴되든지, NONE이 리턴될 것임
}; // end of getKey()
return class {
constructor(style) {
this._style = style;
} // 생성자에 style객체를 준다. 이 클래스는 style 객체를 안고 태어난다.
// 키를 얻기(스타일 시트에 있는 background라는 값을 얻고싶다면?)
get(key) {
key = getKey(key); // 반드시 getKey에 보내서 진짜 이름을 얻어야 한다.
if (key === NONE) return null; // 브라우저가 지원하지 않는 경우 부드럽게 null을 리턴하기 // Unsupported Property 문제 해결!
return this._style[key]; // 이름이 있다면 진짜 이름으로 style객체에 해당 속성값을 가져오자
}
set(key, val) {
key = getKey(key);
// key가 NONE이 아니면
if (key !== NONE) this._style[key] = val; // 값을 설정
// NONE이면 스타일을 아예 건들지 않는다(Graceful Fail)
return this; // set을 계속 호출하는 경우가 많아서 set을 쓸 수 있게 this를 리턴
}
};
})();
const Rule = class{
constructor(rule){
this._rule = rule;
this._style = new Style(rule.style);
}
get(key){
return this._style.get(key);
}
set(key,val){
this._style.set(key,val);
return this;
}
}
const Sheet = class{
constructor(sheet){
this._sheet = sheet;
this._rules = new Map();
}
add(selector){
const index = this._sheet.cssRules.length;
this._sheet.insertRule(`${selector}{}`,index);
const cssRule = this._sheet.cssRules[index];
const rule = new Rule(cssRule);
this._rules.set(selector,rule);
return rule;
}
remove(selector){
if(!this._rules.contains(selector)) return;
const rule = this._rules.get(selector)._rule;
Array.from(this._sheet.cssRules).some((cssRule,index)=>{
if(cssRule === rule._rule){
this._sheet.deleteRule(index);
return true;
}
})
}
get(selector){return this._rules.get(selector);}
}
const sheet = new Sheet(document.styleSheets[0]);
sheet.add('body').set('background', '#f00');
sheet.add('.test').set(
'cssText',
`
width:200px;
border:1px solid #fff;
color: #000;
background: #fff
`
);
</script>
</html>
Author And Source
이 문제에 관하여(코드스피츠 css rendering 3회차 part3 (step 41) - sheet 클래스 생성), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@khw970421/코드스피츠-css-rendering-3회차-part3-step-42-sheet-클래스-생성저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)