| 1 |
import { applyFilters } from '@wordpress/hooks'; |
| 2 |
import { colord, extend } from 'colord'; |
| 3 |
import namesPlugin from 'colord/plugins/names'; |
| 4 |
import defaultThemes from '../defaultThemes.json'; |
| 5 |
import { Attributes, ThemeOption } from '../types'; |
| 6 |
|
| 7 |
extend([namesPlugin]); |
| 8 |
|
| 9 |
export const computeLineHighlightColor = ( |
| 10 |
color: string, |
| 11 |
attributes: Pick<Attributes, 'theme'>, |
| 12 |
) => { |
| 13 |
const themes = applyFilters( |
| 14 |
'blocks.codeBlockPro.themes', |
| 15 |
defaultThemes, |
| 16 |
) as ThemeOption; |
| 17 |
// set in the theme, use that |
| 18 |
if (themes?.[attributes.theme]?.styles?.['line-background']) { |
| 19 |
return themes?.[attributes?.theme]?.styles?.['line-background']; |
| 20 |
} |
| 21 |
// If not set in the theme, but a variable, attempt to compute it |
| 22 |
// but fallback to a known default |
| 23 |
if (color.startsWith('var')) { |
| 24 |
const doc = document.documentElement; |
| 25 |
const maybeColor = getComputedStyle(doc) |
| 26 |
.getPropertyValue( |
| 27 |
// extract from inside var() |
| 28 |
color.replace(/^var\((--[\w-]+)\)$/, '$1'), |
| 29 |
) |
| 30 |
.trim(); |
| 31 |
const computed = |
| 32 |
maybeColor || getComputedStyle(doc).getPropertyValue('--cbp-text'); |
| 33 |
return colord(computed).saturate(0.5).alpha(0.2).toRgbString(); |
| 34 |
} |
| 35 |
|
| 36 |
return colord(color).saturate(0.5).alpha(0.2).toRgbString(); |
| 37 |
}; |
| 38 |
|
| 39 |
export const findLineNumberColor = (attributes: Attributes) => { |
| 40 |
const themes = applyFilters( |
| 41 |
'blocks.codeBlockPro.themes', |
| 42 |
defaultThemes, |
| 43 |
) as ThemeOption; |
| 44 |
// set in the theme, use that |
| 45 |
if (themes?.[attributes.theme]?.styles?.['line-number-color']) { |
| 46 |
return themes?.[attributes?.theme]?.styles?.['line-number-color']; |
| 47 |
} |
| 48 |
return attributes.textColor; |
| 49 |
}; |
| 50 |
|
| 51 |
export const findBackgroundColor = (attributes: Partial<Attributes>) => { |
| 52 |
const themes = applyFilters( |
| 53 |
'blocks.codeBlockPro.themes', |
| 54 |
defaultThemes, |
| 55 |
) as ThemeOption; |
| 56 |
// set in the theme, use that |
| 57 |
if ( |
| 58 |
attributes?.theme && |
| 59 |
themes?.[attributes?.theme]?.styles?.['color-background'] |
| 60 |
) { |
| 61 |
return themes?.[attributes?.theme]?.styles?.['color-background']; |
| 62 |
} |
| 63 |
return attributes.bgColor; |
| 64 |
}; |
| 65 |
|
| 66 |
export const findTextColor = (attributes: Partial<Attributes>) => { |
| 67 |
const themes = applyFilters( |
| 68 |
'blocks.codeBlockPro.themes', |
| 69 |
defaultThemes, |
| 70 |
) as ThemeOption; |
| 71 |
// set in the theme, use that |
| 72 |
if ( |
| 73 |
attributes?.theme && |
| 74 |
themes?.[attributes?.theme]?.styles?.['color-text'] |
| 75 |
) { |
| 76 |
return themes?.[attributes?.theme]?.styles?.['color-text']; |
| 77 |
} |
| 78 |
return attributes.textColor; |
| 79 |
}; |
| 80 |
|