MCPcopy
hub / github.com/darkreader/darkreader / parseGradient

Function parseGradient

src/utils/css-text/parse-gradient.ts:20–85  ·  view source on GitHub ↗
(value: string)

Source from the content-addressed store, hash-verified

18//
19// Specification: https://drafts.csswg.org/css-images-4/#gradients
20export function parseGradient(value: string): ParsedGradient[] {
21 const result: ParsedGradient[] = [];
22
23 // Loop trough the value until we find the first `gradient` keyword.
24 // We will be using the indexOf to find the keyword. From their on
25 // we will check which specific gradient we are dealing with.
26 // Then we will try to parse the rest of the value as a gradient.
27 let index = 0;
28 let startIndex = conicGradient.length;
29 while ((index = value.indexOf('gradient', startIndex)) !== -1) {
30 let typeGradient: string | undefined;
31 // Now we check the type of gradient.
32 // the current index starts at `g` of gradient.
33 // So we have to do a reverse lookup to find the type of gradient.
34 // Because each type of gradient has a different length
35 // will we get the substring of the possible gradient types.
36 [linearGradient, radialGradient, conicGradient].find((possibleType) => {
37 if (index - possibleType.length >= 0) {
38 const possibleGradient = value.substring(index - possibleType.length, index);
39 if (possibleGradient === possibleType) {
40 // Check if the type has a `-` before the `type-gradient` keyword.
41 // If it does, it's a repeating gradient.
42 if (value.slice(index - possibleType.length - 10, index - possibleType.length - 1) === 'repeating') {
43 typeGradient = `repeating-${possibleType}gradient`;
44 return true;
45 }
46 if (value.slice(index - possibleType.length - 8, index - possibleType.length - 1) === '-webkit') {
47 typeGradient = `-webkit-${possibleType}gradient`;
48 return true;
49 }
50 typeGradient = `${possibleType}gradient`;
51 return true;
52 }
53 }
54 });
55
56 if (!typeGradient) {
57 break;
58 }
59
60 // Now we know the type of gradient.
61 // We can go parse the rest of the value as a gradient.
62 const {start, end} = getParenthesesRange(value, index + gradientLength)!;
63
64 const match = value.substring(start + 1, end - 1);
65 startIndex = end + 1 + conicGradientLength;
66
67 result.push({
68 typeGradient,
69 match,
70 // <type>-gradient() is not within match, so in order to still "skip" that section
71 // we add that length as offset.
72 offset: typeGradient.length + 2,
73 index: index - typeGradient.length + gradientLength,
74 hasComma: true,
75 });
76 }
77

Callers 2

getBgImageModifierFunction · 0.90
parsing.tests.tsFile · 0.90

Calls 1

getParenthesesRangeFunction · 0.90

Tested by

no test coverage detected