1 line
1.9 KiB
JavaScript
1 line
1.9 KiB
JavaScript
"use strict";var e=require("postcss-selector-parser");const creator=t=>{const r=Object.assign({dir:null,preserve:!1,shadow:!1},t);return{postcssPlugin:"postcss-dir-pseudo-class",prepare(){const t=new WeakSet;return{Rule(o,{result:s}){if(t.has(o))return;let a,n=!1;if(o.selector.toLowerCase().includes(":dir(")){try{a=e((t=>{t.nodes.forEach((t=>{t.walk((t=>{if("pseudo"!==t.type)return;if(":dir"!==t.value.toLowerCase())return;if(!t.nodes||!t.nodes.length)return;const a=t.nodes.toString().toLowerCase();if("rtl"!==a&&"ltr"!==a)return;const l=t.parent;l.nodes.filter((e=>"pseudo"===e.type&&":dir"===e.value.toLowerCase())).length>1&&!n&&(n=!0,o.warn(s,`Hierarchical :dir pseudo class usage can't be transformed correctly to [dir] attributes. This will lead to incorrect selectors for "${o.selector}"`));const c=t.prev(),p=t.next(),i=c&&c.type&&"combinator"!==c.type,u=p&&p.type&&"combinator"!==p.type,d=p&&p.type&&("combinator"!==p.type||"combinator"===p.type&&" "===p.value);i||u||0===l.nodes.indexOf(t)&&d||1===l.nodes.length?t.remove():t.replaceWith(e.universal());const v=l.nodes[0],w=v&&"combinator"===v.type&&" "===v.value,y=v&&"tag"===v.type&&"html"===v.value.toLowerCase(),f=v&&"pseudo"===v.type&&":root"===v.value.toLowerCase();!v||y||f||w||l.prepend(e.combinator({value:" "}));const h=r.dir===a,b=e.attribute({attribute:"dir",operator:"=",quoteMark:'"',value:`"${a}"`,raws:null}),m=e.pseudo({value:":host-context"});m.append(b);const g=e.pseudo({value:(y||f?"":"html")+":not"});g.append(e.attribute({attribute:"dir",operator:"=",quoteMark:'"',value:`"${"ltr"===a?"rtl":"ltr"}"`,raws:null})),h?y?l.insertAfter(v,g):l.prepend(g):y?l.insertAfter(v,b):r.shadow&&!f?l.prepend(m):l.prepend(b)}))}))})).processSync(o.selector)}catch(e){return void o.warn(s,`Failed to parse selector : ${o.selector}`)}void 0!==a&&a!==o.selector&&(t.add(o),o.cloneBefore({selector:a}),r.preserve||o.remove())}}}}}};creator.postcss=!0,module.exports=creator;
|