"use strict";var e=require("@csstools/css-tokenizer"),o=require("@csstools/css-parser-algorithms"),a=require("@csstools/css-color-parser");const t=/\bcolor-gamut\b/i;function hasConditionalAncestor(e){let o=e.parent;for(;o;)if("atrule"===o.type){if("media"===o.name.toLowerCase()&&t.test(o.params))return!0;o=o.parent}else o=o.parent;return!1}function sameProperty(e){const o=e.prop.toLowerCase(),a=[],t=e.parent?.nodes??[];for(let e=0;e<t.length;e++){const s=t[e];"decl"===s.type&&s.prop.toLowerCase()===o&&a.push(s)}return a}const s=/\b(?:color|lab|lch|oklab|oklch)\(/i,n=/^(?:color|lab|lch|oklab|oklch)$/i,creator=()=>({postcssPlugin:"postcss-gamut-mapping",prepare(){const t=new WeakMap,r=new WeakSet;return{postcssPlugin:"postcss-gamut-mapping",OnceExit(i,{postcss:l}){i.walkDecls(i=>{if(r.has(i))return;if(!s.test(i.value))return;if(!i.parent||hasConditionalAncestor(i))return;const c=sameProperty(i).map((t,s)=>{r.add(t);let i=!1;const l=t.value,c=o.replaceComponentValues(o.parseCommaSeparatedListOfComponentValues(e.tokenize({css:l})),e=>{if(!o.isFunctionNode(e)||!n.test(e.getName()))return;const t=a.color(e);return!t||t.syntaxFlags.has(a.SyntaxFlag.HasNoneKeywords)||a.colorDataFitsRGB_Gamut(t)?void 0:(i||a.colorDataFitsDisplayP3_Gamut(t)||(i=!0),a.serializeRGB(t,!0))}),p=o.stringify(c);return{isRec2020:i,matchesOriginal:p===l,modifiedValue:p,hasFallback:s>0,item:t}}),p=[];c.reverse();for(const e of c){if(e.matchesOriginal)break;p.push(e)}p.reverse(),p.forEach(({isRec2020:e,modifiedValue:o,hasFallback:a,item:s})=>{const n=s.parent;if(!n)return;const i=t.get(n)||{conditionalRules:[],propNames:new Set,lastConditionParams:{media:void 0},lastConditionalRule:void 0};t.set(n,i);const c=`(color-gamut: ${e?"rec2020":"p3"})`;if(i.lastConditionParams.media!==c&&(i.lastConditionalRule=void 0),!a){const e=s.cloneBefore({value:o});r.add(e)}if(i.lastConditionalRule){const e=s.clone();return i.lastConditionalRule.append(e),r.add(e),void s.remove()}const p=l.atRule({name:"media",params:c,source:n.source,raws:{before:"\n\n",after:"\n"}}),u=n.clone();u.removeAll(),u.raws.before="\n";const d=s.clone();u.append(d),s.remove(),r.add(d),i.lastConditionParams.media=p.params,i.lastConditionalRule=u,p.append(u),i.conditionalRules.push(p)})}),i.walk(e=>{const o=t.get(e);o&&0!==o.conditionalRules.length&&o.conditionalRules.reverse().forEach(o=>{e.after(o)})})}}}});creator.postcss=!0,module.exports=creator;
