@@ -34,21 +34,49 @@ export function perceivedBackgroundBrightness(background: string): number | null
3434 const solidBrightness = parseSolidBrightness ( value )
3535 if ( solidBrightness !== null ) return solidBrightness
3636
37- if ( ! / ^ (?: r e p e a t i n g - ) ? (?: l i n e a r | r a d i a l | c o n i c ) - g r a d i e n t \( / . test ( value ) ) return null
37+ const gradient = value . match ( / ^ (?: r e p e a t i n g - ) ? ( l i n e a r | r a d i a l | c o n i c ) - g r a d i e n t \( ( .* ) \) $ / )
38+ if ( ! gradient ) return null
3839
39- const colorStops = value . match ( / # [ 0 - 9 a - f ] { 6 } \b | # [ 0 - 9 a - f ] { 3 } \b | \b (?: w h i t e | b l a c k ) \b / g)
40- if ( ! colorStops || colorStops . length < 2 ) return null
40+ const [ , gradientType , contents ] = gradient
41+ const parts = contents . split ( ',' ) . map ( ( part ) => part . trim ( ) )
42+ const firstStop = parseSupportedColorStop ( parts [ 0 ] )
43+ const colorStops = firstStop === null ? parts . slice ( 1 ) : parts
44+ if (
45+ colorStops . length < 2 ||
46+ ( firstStop === null && ! isSupportedGradientPreamble ( gradientType , parts [ 0 ] ) )
47+ ) {
48+ return null
49+ }
4150
4251 let totalBrightness = 0
4352 for ( const colorStop of colorStops ) {
44- const brightness = parseSolidBrightness ( colorStop )
53+ const brightness = parseSupportedColorStop ( colorStop )
4554 if ( brightness === null ) return null
4655 totalBrightness += brightness
4756 }
4857
4958 return totalBrightness / colorStops . length
5059}
5160
61+ function parseSupportedColorStop ( value : string ) : number | null {
62+ const match = value . match ( / ^ ( # [ 0 - 9 a - f ] { 6 } \b | # [ 0 - 9 a - f ] { 3 } \b | (?: w h i t e | b l a c k ) \b ) (?: \s | $ ) / )
63+ return match ? parseSolidBrightness ( match [ 1 ] ) : null
64+ }
65+
66+ function isSupportedGradientPreamble ( type : string , value : string ) : boolean {
67+ if ( type === 'linear' ) {
68+ return / ^ (?: - ? (?: \d + (?: \. \d + ) ? | \. \d + ) (?: d e g | g r a d | r a d | t u r n ) | t o \s + (?: t o p | r i g h t | b o t t o m | l e f t ) (?: \s + (?: t o p | r i g h t | b o t t o m | l e f t ) ) ? ) $ / . test (
69+ value
70+ )
71+ }
72+ if ( type === 'radial' ) {
73+ return / ^ (?: (?: c i r c l e | e l l i p s e | c l o s e s t - s i d e | c l o s e s t - c o r n e r | f a r t h e s t - s i d e | f a r t h e s t - c o r n e r | a t ) \b | - ? (?: \d | \. \d ) ) / . test (
74+ value
75+ )
76+ }
77+ return / ^ (?: f r o m | a t ) \b / . test ( value )
78+ }
79+
5280function parseSolidBrightness ( value : string ) : number | null {
5381 if ( value === 'white' ) return 1
5482 if ( value === 'black' ) return 0
0 commit comments