|
| 1 | +// Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | + |
| 3 | +/** |
| 4 | + * @file syntaxThemeChoices.ts |
| 5 | + * @input The value of a syntax-theme prop and whether the prop is required |
| 6 | + * @output The preset choices the playground offers, the selected choice, the |
| 7 | + * value a choice sends, and the name of the preset a value is |
| 8 | + * @position Logic of the playground's syntax-theme control |
| 9 | + * (PlaygroundPropsTable) |
| 10 | + */ |
| 11 | + |
| 12 | +import {allSyntaxPresets} from '@astryxdesign/core/theme/syntax'; |
| 13 | + |
| 14 | +/** The choice that leaves an optional syntax-theme prop unset. */ |
| 15 | +export const NO_SYNTAX_THEME = 'None'; |
| 16 | + |
| 17 | +const presets = allSyntaxPresets.map(theme => ({ |
| 18 | + value: theme.name, |
| 19 | + label: theme.name |
| 20 | + .split('-') |
| 21 | + .map(part => part.charAt(0).toUpperCase() + part.slice(1)) |
| 22 | + .join(' '), |
| 23 | + theme, |
| 24 | +})); |
| 25 | + |
| 26 | +/** |
| 27 | + * The presets, with a first choice that leaves the prop unset when the prop |
| 28 | + * is optional. An unset prop keeps the theme-level syntax colors. |
| 29 | + */ |
| 30 | +export function syntaxThemeChoices( |
| 31 | + isRequired: boolean, |
| 32 | +): {value: string; label: string}[] { |
| 33 | + const choices = presets.map(({value, label}) => ({value, label})); |
| 34 | + return isRequired |
| 35 | + ? choices |
| 36 | + : [{value: NO_SYNTAX_THEME, label: NO_SYNTAX_THEME}, ...choices]; |
| 37 | +} |
| 38 | + |
| 39 | +/** The choice that shows `value`. */ |
| 40 | +export function selectedSyntaxTheme( |
| 41 | + value: unknown, |
| 42 | + isRequired: boolean, |
| 43 | +): string { |
| 44 | + const match = presets.find( |
| 45 | + option => |
| 46 | + option.theme === value || |
| 47 | + (value != null && |
| 48 | + typeof value === 'object' && |
| 49 | + 'name' in value && |
| 50 | + option.theme.name === value.name), |
| 51 | + ); |
| 52 | + if (match) { |
| 53 | + return match.value; |
| 54 | + } |
| 55 | + return isRequired ? presets[0].value : NO_SYNTAX_THEME; |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * The name of the preset `value` is, such as "one-dark-pro"; null when |
| 60 | + * `value` is not a preset. |
| 61 | + */ |
| 62 | +export function syntaxPresetName(value: unknown): string | null { |
| 63 | + return presets.find(option => option.theme === value)?.value ?? null; |
| 64 | +} |
| 65 | + |
| 66 | +/** The value a choice sends: a preset, or nothing for the unset choice. */ |
| 67 | +export function syntaxThemeFor(choice: string): unknown { |
| 68 | + return presets.find(option => option.value === choice)?.theme; |
| 69 | +} |
0 commit comments