Buttons: Refactor & use new theme (#32767)

* WIP button styles refactoring

* Starting to work

* Tweak form disabled color

* Emotion performance tests

* More benchmarks

* added classnames prop

* Button class names refactor test

* revert to old style generation

* Wrapping up

* Updates

* Updated tests
pull/32568/head
Torkel Ödegaard 4 years ago committed by GitHub
parent 33a4cfde51
commit 2f3ef69b30
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 11
      .eslintrc
  2. 8
      packages/grafana-data/src/themes/createPalette.ts
  3. 3
      packages/grafana-data/src/themes/createSpacing.ts
  4. 2
      packages/grafana-data/src/themes/createTheme.test.ts
  5. 2
      packages/grafana-ui/.storybook/storybookTheme.ts
  6. 8
      packages/grafana-ui/src/components/Button/Button.story.tsx
  7. 202
      packages/grafana-ui/src/components/Button/Button.tsx
  8. 14
      packages/grafana-ui/src/components/Button/ToolbarButton.tsx
  9. 5
      packages/grafana-ui/src/components/DataLinks/DataLinkInput.tsx
  10. 13
      packages/grafana-ui/src/components/FileUpload/FileUpload.tsx
  11. 8
      packages/grafana-ui/src/components/Forms/RadioButtonGroup/RadioButton.tsx
  12. 24
      packages/grafana-ui/src/components/Forms/commonStyles.ts
  13. 3
      packages/grafana-ui/src/components/Forms/getFormStyles.ts
  14. 195
      packages/grafana-ui/src/components/ThemeDemos/EmotionPerfTest.tsx
  15. 5
      packages/grafana-ui/src/components/ThemeDemos/NewThemeDemo.story.tsx
  16. 7
      packages/grafana-ui/src/components/ThemeDemos/NewThemeDemo.tsx
  17. 1
      packages/grafana-ui/src/components/index.ts
  18. 12
      packages/grafana-ui/src/themes/mixins.ts
  19. 12
      public/app/features/sandbox/BenchmarksPage.tsx
  20. 6
      public/app/routes/routes.tsx

@ -5,8 +5,7 @@
"rules": { "rules": {
"no-only-tests/no-only-tests": "error", "no-only-tests/no-only-tests": "error",
"react/prop-types": "off", "react/prop-types": "off",
"@emotion/jsx-import": "error", "@emotion/jsx-import": "error"
"@emotion/pkg-renaming": "error"
}, },
"overrides": [ "overrides": [
{ {
@ -15,6 +14,14 @@
"react-hooks/rules-of-hooks": "off", "react-hooks/rules-of-hooks": "off",
"react-hooks/exhaustive-deps": "off" "react-hooks/exhaustive-deps": "off"
} }
},
{
"files": ["packages/grafana-ui/src/components/ThemeDemos/**/*.{ts,tsx}"],
"rules": {
"@emotion/jsx-import": "off",
"react/jsx-uses-react": "off",
"react/react-in-jsx-scope": "off"
}
} }
] ]
} }

@ -111,7 +111,7 @@ class DarkPalette implements ThemePaletteBase<Partial<ThemePaletteColor>> {
border: this.border1, border: this.border1,
text: this.text.primary, text: this.text.primary,
disabledText: this.text.disabled, disabledText: this.text.disabled,
disabledBackground: colors.gray10, disabledBackground: 'rgba(255, 255, 255, 0.04)',
}; };
contrastThreshold = 3; contrastThreshold = 3;
@ -129,8 +129,8 @@ class LightPalette implements ThemePaletteBase<Partial<ThemePaletteColor>> {
}; };
secondary = { secondary = {
main: 'rgba(0,0,0,0.2)', main: 'rgba(0,0,0,0.18)',
contrastText: 'rgba(0, 0, 0, 0.87)', contrastText: 'rgba(0, 0, 0, 0.75)',
}; };
info = { info = {
@ -170,7 +170,7 @@ class LightPalette implements ThemePaletteBase<Partial<ThemePaletteColor>> {
formComponent = { formComponent = {
background: this.layer1, background: this.layer1,
border: this.border2, border: this.border1,
text: this.text.primary, text: this.text.primary,
disabledBackground: colors.gray95, disabledBackground: colors.gray95,
disabledText: this.text.disabled, disabledText: this.text.disabled,

@ -26,6 +26,7 @@ export interface ThemeSpacing {
bottom: ThemeSpacingArgument, bottom: ThemeSpacingArgument,
left: ThemeSpacingArgument left: ThemeSpacingArgument
): string; ): string;
gridSize: number;
} }
/** @internal */ /** @internal */
@ -64,5 +65,7 @@ export function createSpacing(options: ThemeSpacingOptions = {}): ThemeSpacing {
.join(' '); .join(' ');
}; };
spacing.gridSize = gridSize;
return spacing; return spacing;
} }

@ -55,7 +55,7 @@ describe('createTheme', () => {
"formComponent": Object { "formComponent": Object {
"background": "#0b0c0e", "background": "#0b0c0e",
"border": "#2c3235", "border": "#2c3235",
"disabledBackground": "#141619", "disabledBackground": "rgba(255, 255, 255, 0.04)",
"disabledText": "rgba(255, 255, 255, 0.3)", "disabledText": "rgba(255, 255, 255, 0.3)",
"text": "rgba(255, 255, 255, 0.75)", "text": "rgba(255, 255, 255, 0.75)",
}, },

@ -9,7 +9,7 @@ const createTheme = (theme: GrafanaTheme) => {
base: theme.name.includes('Light') ? 'light' : 'dark', base: theme.name.includes('Light') ? 'light' : 'dark',
colorPrimary: theme.v2.palette.primary.main, colorPrimary: theme.v2.palette.primary.main,
colorSecondary: theme.v2.palette.secondary.main, colorSecondary: theme.v2.palette.error.main,
// UI // UI
appBg: theme.v2.palette.layer0, appBg: theme.v2.palette.layer0,

@ -1,6 +1,6 @@
import React from 'react'; import React from 'react';
import { Story } from '@storybook/react'; import { Story } from '@storybook/react';
import { Button, ButtonProps, ButtonVariant } from './Button'; import { allButtonVariants, Button, ButtonProps } from './Button';
import { withCenteredStory, withHorizontallyCenteredStory } from '../../utils/storybook/withCenteredStory'; import { withCenteredStory, withHorizontallyCenteredStory } from '../../utils/storybook/withCenteredStory';
import { iconOptions } from '../../utils/storybook/knobs'; import { iconOptions } from '../../utils/storybook/knobs';
import mdx from './Button.mdx'; import mdx from './Button.mdx';
@ -31,18 +31,20 @@ export default {
export const Variants: Story<ButtonProps> = ({ children, ...args }) => { export const Variants: Story<ButtonProps> = ({ children, ...args }) => {
const sizes: ComponentSize[] = ['lg', 'md', 'sm']; const sizes: ComponentSize[] = ['lg', 'md', 'sm'];
const variants: ButtonVariant[] = ['primary', 'secondary', 'destructive', 'link'];
return ( return (
<VerticalGroup> <VerticalGroup>
<HorizontalGroup spacing="lg"> <HorizontalGroup spacing="lg">
{variants.map((variant) => ( {allButtonVariants.map((variant) => (
<VerticalGroup spacing="lg" key={variant}> <VerticalGroup spacing="lg" key={variant}>
{sizes.map((size) => ( {sizes.map((size) => (
<Button variant={variant} size={size} key={size}> <Button variant={variant} size={size} key={size}>
{variant} {size} {variant} {size}
</Button> </Button>
))} ))}
<Button variant={variant} disabled>
{variant} disabled
</Button>
</VerticalGroup> </VerticalGroup>
))} ))}
</HorizontalGroup> </HorizontalGroup>

@ -1,15 +1,15 @@
import React, { AnchorHTMLAttributes, ButtonHTMLAttributes } from 'react'; import React, { AnchorHTMLAttributes, ButtonHTMLAttributes } from 'react';
import { css, cx } from '@emotion/css'; import { css, CSSObject, cx } from '@emotion/css';
import tinycolor from 'tinycolor2';
import { useTheme } from '../../themes'; import { useTheme } from '../../themes';
import { IconName } from '../../types/icon'; import { IconName } from '../../types/icon';
import { getPropertiesForButtonSize } from '../Forms/commonStyles'; import { getPropertiesForButtonSize } from '../Forms/commonStyles';
import { GrafanaTheme } from '@grafana/data'; import { GrafanaTheme, GrafanaThemeV2, ThemePaletteColor } from '@grafana/data';
import { ComponentSize } from '../../types/size'; import { ComponentSize } from '../../types/size';
import { focusCss } from '../../themes/mixins'; import { getFocusStyles } from '../../themes/mixins';
import { Icon } from '../Icon/Icon'; import { Icon } from '../Icon/Icon';
export type ButtonVariant = 'primary' | 'secondary' | 'destructive' | 'link'; export type ButtonVariant = 'primary' | 'secondary' | 'destructive' | 'link';
export const allButtonVariants: ButtonVariant[] = ['primary', 'secondary', 'destructive', 'link'];
type CommonProps = { type CommonProps = {
size?: ComponentSize; size?: ComponentSize;
@ -29,9 +29,8 @@ export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
theme, theme,
size, size,
variant, variant,
icon,
fullWidth, fullWidth,
children, iconOnly: !children,
}); });
return ( return (
@ -55,26 +54,13 @@ export const LinkButton = React.forwardRef<HTMLAnchorElement, ButtonLinkProps>(
fullWidth, fullWidth,
size, size,
variant, variant,
icon, iconOnly: !children,
children,
}); });
const linkButtonStyles = const linkButtonStyles = cx(styles.button, { [styles.disabled]: disabled }, className);
disabled &&
cx(
disabledStyles,
css`
pointer-events: none;
`
);
return ( return (
<a <a className={linkButtonStyles} {...otherProps} ref={ref} tabIndex={disabled ? -1 : 0}>
className={cx(styles.button, linkButtonStyles, className)}
{...otherProps}
ref={ref}
tabIndex={disabled ? -1 : 0}
>
{icon && <Icon name={icon} size={size} className={styles.icon} />} {icon && <Icon name={icon} size={size} className={styles.icon} />}
{children && <span className={styles.content}>{children}</span>} {children && <span className={styles.content}>{children}</span>}
</a> </a>
@ -87,62 +73,63 @@ LinkButton.displayName = 'LinkButton';
export interface StyleProps { export interface StyleProps {
size: ComponentSize; size: ComponentSize;
variant: ButtonVariant; variant: ButtonVariant;
children?: React.ReactNode; iconOnly?: boolean;
icon?: IconName;
theme: GrafanaTheme; theme: GrafanaTheme;
fullWidth?: boolean; fullWidth?: boolean;
narrow?: boolean; narrow?: boolean;
} }
const disabledStyles = css`
cursor: not-allowed;
opacity: 0.65;
box-shadow: none;
`;
export const getButtonStyles = (props: StyleProps) => { export const getButtonStyles = (props: StyleProps) => {
const { theme, variant, size, children, fullWidth } = props; const { theme, variant, size, iconOnly, fullWidth } = props;
const { padding, fontSize, height } = getPropertiesForButtonSize(size, theme); const { height, padding, fontSize } = getPropertiesForButtonSize(size, theme.v2);
const { borderColor, variantStyles } = getPropertiesForVariant(theme, variant); const variantStyles = getPropertiesForVariant(theme.v2, variant);
const iconOnly = !children;
const disabledStyles: CSSObject = {
cursor: 'not-allowed',
opacity: 0.65,
boxShadow: 'none',
background: theme.v2.palette.formComponent.disabledBackground,
border: `1px solid ${theme.v2.palette.formComponent.disabledBackground}`,
color: theme.v2.palette.text.disabled,
pointerEvents: 'none',
'&:hover': {
background: theme.v2.palette.formComponent.disabledBackground,
color: theme.v2.palette.text.disabled,
},
};
return { return {
button: css` button: css({
label: button; label: 'button',
display: inline-flex; display: 'inline-flex',
align-items: center; alignItems: 'center',
font-weight: ${theme.typography.weight.semibold}; fontSize: fontSize,
font-family: ${theme.typography.fontFamily.sansSerif}; fontWeight: theme.v2.typography.fontWeightMedium,
font-size: ${fontSize}; fontFamily: theme.v2.typography.fontFamily,
padding: 0 ${padding}px; padding: theme.v2.spacing(0, padding),
height: ${height}px; height: theme.v2.spacing(height),
// Deduct border from line-height for perfect vertical centering on windows and linux // Deduct border from line-height for perfect vertical centering on windows and linux
line-height: ${height - 2}px; lineHeight: `${theme.v2.spacing.gridSize * height - 2}px`,
vertical-align: middle; verticalAlign: 'middle',
cursor: pointer; cursor: 'pointer',
border: 1px solid ${borderColor}; borderRadius: theme.v2.shape.borderRadius(1),
border-radius: ${theme.border.radius.sm}; ...(fullWidth && {
${fullWidth && flexGrow: 1,
` justifyContent: 'center',
flex-grow: 1; }),
justify-content: center; ...variantStyles,
`} ':disabled': disabledStyles,
${variantStyles} '&[disabled]': disabledStyles,
}),
&[disabled], disabled: css(disabledStyles),
&:disabled {
${disabledStyles};
}
`,
img: css` img: css`
width: 16px; width: 16px;
height: 16px; height: 16px;
margin-right: ${theme.spacing.sm}; margin: ${theme.v2.spacing(0, 1, 0, 0.5)};
margin-left: -${theme.spacing.xs};
`, `,
icon: css` icon: css`
margin-left: -${padding / 2}px; margin: ${theme.v2.spacing(0, (iconOnly ? -padding : padding) / 2, 0, -(padding / 2))};
margin-right: ${(iconOnly ? -padding : padding) / 2}px;
`, `,
content: css` content: css`
display: flex; display: flex;
@ -154,73 +141,50 @@ export const getButtonStyles = (props: StyleProps) => {
}; };
}; };
function getButtonVariantStyles(from: string, to: string, textColor: string, theme: GrafanaTheme) { function getButtonVariantStyles(theme: GrafanaThemeV2, color: ThemePaletteColor): CSSObject {
return css` return {
background: linear-gradient(180deg, ${from} 0%, ${to} 100%); background: color.main,
color: ${textColor}; color: color.contrastText,
&:hover { boxShadow: theme.shadows.z1,
background: ${from}; border: `1px solid transparent`,
color: ${textColor};
} '&:hover': {
background: theme.palette.getHoverColor(color.main),
&:focus { color: color.contrastText,
background: ${from}; },
outline: none;
${focusCss(theme)}; '&:focus': {
} ...getFocusStyles(theme),
`; },
};
} }
export function getPropertiesForVariant(theme: GrafanaTheme, variant: ButtonVariant) { export function getPropertiesForVariant(theme: GrafanaThemeV2, variant: ButtonVariant) {
switch (variant) { switch (variant) {
case 'secondary': case 'secondary':
const from = theme.isLight ? theme.palette.gray7 : theme.palette.gray15; return getButtonVariantStyles(theme, theme.palette.secondary);
const to = theme.isLight ? tinycolor(from).darken(5).toString() : tinycolor(from).lighten(4).toString();
return {
borderColor: theme.isLight ? theme.palette.gray85 : theme.palette.gray25,
variantStyles: getButtonVariantStyles(
from,
to,
theme.isLight ? theme.palette.gray25 : theme.palette.gray4,
theme
),
};
case 'destructive': case 'destructive':
return { return getButtonVariantStyles(theme, theme.palette.error);
borderColor: theme.palette.redShade,
variantStyles: getButtonVariantStyles(
theme.palette.redBase,
theme.palette.redShade,
theme.palette.white,
theme
),
};
case 'link': case 'link':
return { return {
borderColor: 'transparent', background: 'transparent',
variantStyles: css` color: theme.palette.text.link,
background: transparent; border: '1px solid transparent',
color: ${theme.colors.linkExternal}; '&:focus': {
outline: 'none',
&:focus { textDecoration: 'underline',
outline: none; },
text-decoration: underline;
} '&:hover': {
color: theme.palette.getHoverColor(theme.palette.text.link),
&:hover { textDecoration: 'underline',
color: ${theme.colors.linkExternal}; },
text-decoration: underline;
}
`,
}; };
case 'primary': case 'primary':
default: default:
return { return getButtonVariantStyles(theme, theme.palette.primary);
borderColor: theme.colors.bgBlue1,
variantStyles: getButtonVariantStyles(theme.colors.bgBlue1, theme.colors.bgBlue2, theme.palette.white, theme),
};
} }
} }

@ -104,8 +104,8 @@ function renderIcon(icon: IconName | React.ReactNode) {
} }
const getStyles = (theme: GrafanaTheme) => { const getStyles = (theme: GrafanaTheme) => {
const primaryVariant = getPropertiesForVariant(theme, 'primary'); const primaryVariant = getPropertiesForVariant(theme.v2, 'primary');
const destructiveVariant = getPropertiesForVariant(theme, 'destructive'); const destructiveVariant = getPropertiesForVariant(theme.v2, 'destructive');
return { return {
button: css` button: css`
@ -151,14 +151,8 @@ const getStyles = (theme: GrafanaTheme) => {
background: ${styleMixins.hoverColor(theme.colors.bg1, theme)}; background: ${styleMixins.hoverColor(theme.colors.bg1, theme)};
} }
`, `,
primary: css` primary: css(primaryVariant),
border-color: ${primaryVariant.borderColor}; destructive: css(destructiveVariant),
${primaryVariant.variantStyles}
`,
destructive: css`
border-color: ${destructiveVariant.borderColor};
${destructiveVariant.variantStyles}
`,
narrow: css` narrow: css`
padding: 0 ${theme.spacing.xs}; padding: 0 ${theme.spacing.xs};
`, `,

@ -3,7 +3,7 @@ import usePrevious from 'react-use/lib/usePrevious';
import { DataLinkSuggestions } from './DataLinkSuggestions'; import { DataLinkSuggestions } from './DataLinkSuggestions';
import { makeValue, ThemeContext } from '../../index'; import { makeValue, ThemeContext } from '../../index';
import { SelectionReference } from './SelectionReference'; import { SelectionReference } from './SelectionReference';
import { getFormStyles, Portal } from '../index'; import { Portal } from '../index';
// @ts-ignore // @ts-ignore
import Prism, { Grammar, LanguageMap } from 'prismjs'; import Prism, { Grammar, LanguageMap } from 'prismjs';
@ -17,6 +17,7 @@ import { SlatePrism } from '../../slate-plugins';
import { SCHEMA } from '../../utils/slate'; import { SCHEMA } from '../../utils/slate';
import { stylesFactory } from '../../themes'; import { stylesFactory } from '../../themes';
import { DataLinkBuiltInVars, GrafanaTheme, VariableOrigin, VariableSuggestion } from '@grafana/data'; import { DataLinkBuiltInVars, GrafanaTheme, VariableOrigin, VariableSuggestion } from '@grafana/data';
import { getInputStyles } from '../Input/Input';
const modulo = (a: number, n: number) => a - n * Math.floor(a / n); const modulo = (a: number, n: number) => a - n * Math.floor(a / n);
@ -44,7 +45,7 @@ const plugins = [
]; ];
const getStyles = stylesFactory((theme: GrafanaTheme) => ({ const getStyles = stylesFactory((theme: GrafanaTheme) => ({
input: getFormStyles(theme, { variant: 'primary', size: 'md', invalid: false }).input.input, input: getInputStyles({ theme, invalid: false }).input,
editor: css` editor: css`
.token.builtInVariable { .token.builtInVariable {
color: ${theme.palette.queryGreen}; color: ${theme.palette.queryGreen};

@ -1,9 +1,10 @@
import React, { FC, FormEvent, useCallback, useState } from 'react'; import React, { FC, FormEvent, useCallback, useState } from 'react';
import { GrafanaTheme } from '@grafana/data'; import { GrafanaTheme } from '@grafana/data';
import { css, cx } from '@emotion/css'; import { css, cx } from '@emotion/css';
import { getFormStyles, Icon } from '../index'; import { Icon } from '../index';
import { stylesFactory, useTheme } from '../../themes'; import { stylesFactory, useTheme } from '../../themes';
import { ComponentSize } from '../../types/size'; import { ComponentSize } from '../../types/size';
import { getButtonStyles } from '../Button';
export interface Props { export interface Props {
/** Callback function to handle uploaded file */ /** Callback function to handle uploaded file */
@ -75,17 +76,13 @@ export const FileUpload: FC<Props> = ({
}; };
const getStyles = stylesFactory((theme: GrafanaTheme, size: ComponentSize) => { const getStyles = stylesFactory((theme: GrafanaTheme, size: ComponentSize) => {
const buttonFormStyle = getFormStyles(theme, { variant: 'primary', invalid: false, size }).button.button; const buttonStyles = getButtonStyles({ theme, variant: 'primary', size, iconOnly: false });
return { return {
fileUpload: css` fileUpload: css`
display: none; display: none;
`, `,
button: css` button: buttonStyles.button,
${buttonFormStyle} icon: buttonStyles.icon,
`,
icon: css`
margin-right: ${theme.spacing.xs};
`,
fileName: css` fileName: css`
margin-left: ${theme.spacing.xs}; margin-left: ${theme.spacing.xs};
`, `,

@ -19,7 +19,7 @@ export interface RadioButtonProps {
} }
const getRadioButtonStyles = stylesFactory((theme: GrafanaTheme, size: RadioButtonSize, fullWidth?: boolean) => { const getRadioButtonStyles = stylesFactory((theme: GrafanaTheme, size: RadioButtonSize, fullWidth?: boolean) => {
const { fontSize, height, padding } = getPropertiesForButtonSize(size, theme); const { fontSize, height, padding } = getPropertiesForButtonSize(size, theme.v2);
const c = theme.palette; const c = theme.palette;
const textColor = theme.colors.textSemiWeak; const textColor = theme.colors.textSemiWeak;
@ -64,11 +64,11 @@ const getRadioButtonStyles = stylesFactory((theme: GrafanaTheme, size: RadioButt
display: inline-block; display: inline-block;
position: relative; position: relative;
font-size: ${fontSize}; font-size: ${fontSize};
height: ${height}px; height: ${theme.v2.spacing(height)};
// Deduct border from line-height for perfect vertical centering on windows and linux // Deduct border from line-height for perfect vertical centering on windows and linux
line-height: ${height - 2}px; line-height: ${theme.v2.spacing.gridSize * height - 2}px;
color: ${textColor}; color: ${textColor};
padding: 0 ${padding}px; padding: ${theme.v2.spacing(0, padding)};
margin-left: -1px; margin-left: -1px;
border-radius: ${theme.border.radius.sm}; border-radius: ${theme.border.radius.sm};
border: ${border}; border: ${border};

@ -1,5 +1,5 @@
import { css } from '@emotion/css'; import { css } from '@emotion/css';
import { GrafanaTheme } from '@grafana/data'; import { GrafanaTheme, GrafanaThemeV2 } from '@grafana/data';
import { focusCss } from '../../themes/mixins'; import { focusCss } from '../../themes/mixins';
import { ComponentSize } from '../../types/size'; import { ComponentSize } from '../../types/size';
@ -88,29 +88,27 @@ export const inputSizesPixels = (size: string) => {
} }
}; };
export function getPropertiesForButtonSize(size: ComponentSize, theme: GrafanaTheme) { export function getPropertiesForButtonSize(size: ComponentSize, theme: GrafanaThemeV2) {
const { typography, height, spacing } = theme;
switch (size) { switch (size) {
case 'sm': case 'sm':
return { return {
padding: spacing.base, padding: 1,
fontSize: typography.size.sm, fontSize: theme.typography.size.sm,
height: height.sm, height: theme.components.height.sm,
}; };
case 'lg': case 'lg':
return { return {
padding: spacing.base * 3, padding: 3,
fontSize: typography.size.lg, fontSize: theme.typography.size.lg,
height: height.lg, height: theme.components.height.lg,
}; };
case 'md': case 'md':
default: default:
return { return {
padding: spacing.base * 2, padding: 2,
fontSize: typography.size.md, fontSize: theme.typography.size.md,
height: height.md, height: theme.components.height.md,
}; };
} }
} }

@ -8,8 +8,11 @@ import { ComponentSize } from '../../types/size';
import { getInputStyles } from '../Input/Input'; import { getInputStyles } from '../Input/Input';
import { getCheckboxStyles } from './Checkbox'; import { getCheckboxStyles } from './Checkbox';
/** @deprecated */
export const getFormStyles = stylesFactory( export const getFormStyles = stylesFactory(
(theme: GrafanaTheme, options: { variant: ButtonVariant; size: ComponentSize; invalid: boolean }) => { (theme: GrafanaTheme, options: { variant: ButtonVariant; size: ComponentSize; invalid: boolean }) => {
console.warn('getFormStyles is deprecated');
return { return {
label: getLabelStyles(theme), label: getLabelStyles(theme),
legend: getLegendStyles(theme), legend: getLegendStyles(theme),

@ -0,0 +1,195 @@
/** @jsxImportSource @emotion/react */
import { Profiler, ProfilerOnRenderCallback, useState, FC } from 'react';
import { GrafanaTheme } from '@grafana/data';
import { css, cx } from '@emotion/css';
import { useStyles, useTheme } from '../../themes';
import { Button } from '../Button';
import { VerticalGroup } from '../Layout/Layout';
import classnames from 'classnames';
export function EmotionPerfTest() {
console.log('process.env.NODE_ENV', process.env.NODE_ENV);
return (
<VerticalGroup>
<div>Emotion performance tests</div>
<TestScenario name="No styles" Component={NoStyles} />
<TestScenario name="inline emotion/css" Component={InlineEmotionCSS} />
<TestScenario name="useStyles no cx" Component={UseStylesNoCX} />
<TestScenario name="useStyles with conditional cx styles" Component={UseStylesWithConditionalCX} />
<TestScenario name="useStyles with css prop" Component={UseStylesWithCSSProp} />
<TestScenario name="useStyles with conditional css prop" Component={UseStylesWithConditionalCSS} />
<TestScenario name="useStyles with conditional classnames" Component={UseStylesWithConditionalClassNames} />
</VerticalGroup>
);
}
export const TestScenario: FC<{ name: string; Component: FC<TestComponentProps> }> = ({ name, Component }) => {
const [render, setRender] = useState(0);
return (
<div>
<Button onClick={() => setRender(render > 2 ? 0 : render + 1)}>{name}</Button>
{render > 0 && <MeasureRender id={name}>{renderManyComponents(Component)}</MeasureRender>}
</div>
);
};
TestScenario.displayName = 'TestScenario';
function renderManyComponents(Component: FC<TestComponentProps>) {
const elements: React.ReactNode[] = [];
for (let i = 0; i < 5000; i++) {
elements.push(<Component index={i} key={i.toString()} />);
}
return <div style={{ display: 'flex', flexWrap: 'wrap' }}>{elements}</div>;
}
interface TestComponentProps {
index: number;
}
function UseStylesNoCX({ index }: TestComponentProps) {
const styles = useStyles(getStyles);
return (
<div className={styles.main}>
<div className={styles.child}>{index}</div>
</div>
);
}
function UseStylesWithConditionalCX({ index }: TestComponentProps) {
const styles = useStyles(getStyles);
const mainStyles = cx(styles.main, { [styles.large]: index > 10, [styles.disabed]: index % 10 === 0 });
return (
<div className={mainStyles}>
<div className={styles.child}>{index}</div>
</div>
);
}
function UseStylesWithConditionalClassNames({ index }: TestComponentProps) {
const styles = useStyles(getStyles);
const mainStyles = classnames(styles.main, { [styles.large]: index > 10, [styles.disabed]: index % 10 === 0 });
return (
<div className={mainStyles}>
<div className={styles.child}>{index}</div>
</div>
);
}
function UseStylesWithCSSProp({ index }: TestComponentProps) {
const styles = useStyles(getStylesObjects);
return (
<div css={styles.main}>
<div css={styles.child}>{index}</div>
</div>
);
}
function UseStylesWithConditionalCSS({ index }: TestComponentProps) {
const styles = useStyles(getStylesObjects);
const mainStyles = [styles.main, index > 10 && styles.large, index % 10 === 0 && styles.disabed];
return (
<div css={mainStyles}>
<div css={styles.child}>{index}</div>
</div>
);
}
function InlineEmotionCSS({ index }: TestComponentProps) {
const theme = useTheme();
const styles = getStyles(theme);
return (
<div className={styles.main}>
<div className={styles.child}>{index}</div>
</div>
);
}
function NoStyles({ index }: TestComponentProps) {
return (
<div className="no-styles-main">
<div className="no-styles-child">{index}</div>
</div>
);
}
function MeasureRender({ children, id }: { children: React.ReactNode; id: string }) {
const onRender: ProfilerOnRenderCallback = (
id: string,
phase: 'mount' | 'update',
actualDuration: number,
baseDuration: number,
startTime: number,
commitTime: number
) => {
console.log('Profile ' + id, actualDuration);
};
return (
<Profiler id={id} onRender={onRender}>
{children}
</Profiler>
);
}
const getStyles = (theme: GrafanaTheme) => {
return {
main: css(getStylesObjectMain(theme)),
large: css({
fontSize: '20px',
color: 'red',
}),
disabed: css({
fontSize: '10px',
color: 'gray',
}),
child: css(getStylesObjectChild(theme)),
};
};
const getStylesObjects = (theme: GrafanaTheme) => {
return {
main: getStylesObjectMain(theme),
large: {
fontSize: '20px',
color: 'red',
},
disabed: {
fontSize: '10px',
color: 'gray',
},
child: getStylesObjectChild(theme),
};
};
function getStylesObjectMain(theme: GrafanaTheme): any {
return {
background: 'blue',
border: '1px solid red',
color: 'white',
padding: theme.v2.spacing(1),
shadow: theme.v2.shadows.z1,
':hover': {
background: theme.colors.bg1,
},
};
}
function getStylesObjectChild(theme: GrafanaTheme): any {
return {
padding: '2px',
fontSize: '10px',
boxShadow: 'none',
textAlign: 'center',
textDecoration: 'none',
};
}

@ -1,4 +1,5 @@
import React from 'react'; import React from 'react';
import { EmotionPerfTest } from './EmotionPerfTest';
import { NewThemeDemo as NewThemeDemoComponent } from './NewThemeDemo'; import { NewThemeDemo as NewThemeDemoComponent } from './NewThemeDemo';
export default { export default {
@ -16,3 +17,7 @@ export default {
export const NewThemeDemo = () => { export const NewThemeDemo = () => {
return <NewThemeDemoComponent />; return <NewThemeDemoComponent />;
}; };
export const PerfTest = () => {
return <EmotionPerfTest />;
};

@ -9,7 +9,7 @@ import { Field } from '../Forms/Field';
import { Input } from '../Input/Input'; import { Input } from '../Input/Input';
import { RadioButtonGroup } from '../Forms/RadioButtonGroup/RadioButtonGroup'; import { RadioButtonGroup } from '../Forms/RadioButtonGroup/RadioButtonGroup';
import { Switch } from '../Switch/Switch'; import { Switch } from '../Switch/Switch';
import { Button, ButtonVariant } from '../Button'; import { allButtonVariants, Button } from '../Button';
interface DemoBoxProps { interface DemoBoxProps {
bg?: string; bg?: string;
@ -50,7 +50,6 @@ export const NewThemeDemo = () => {
const [boolValue, setBoolValue] = useState(false); const [boolValue, setBoolValue] = useState(false);
const oldTheme = useTheme(); const oldTheme = useTheme();
const t = oldTheme.v2; const t = oldTheme.v2;
const variants: ButtonVariant[] = ['primary', 'secondary', 'destructive', 'link'];
const richColors = [ const richColors = [
t.palette.primary, t.palette.primary,
@ -151,13 +150,13 @@ export const NewThemeDemo = () => {
<CollapsableSection label="Buttons" isOpen={true}> <CollapsableSection label="Buttons" isOpen={true}>
<DemoBox bg={t.palette.layer1}> <DemoBox bg={t.palette.layer1}>
<HorizontalGroup> <HorizontalGroup>
{variants.map((variant) => ( {allButtonVariants.map((variant) => (
<Button variant={variant} key={variant}> <Button variant={variant} key={variant}>
{variant} {variant}
</Button> </Button>
))} ))}
<Button variant="primary" disabled> <Button variant="primary" disabled>
Disabled primary Disabled
</Button> </Button>
</HorizontalGroup> </HorizontalGroup>
</DemoBox> </DemoBox>

@ -227,3 +227,4 @@ export { BarChartOptions, BarStackingMode, BarValueVisibility, BarChartFieldConf
export { TimelineOptions, TimelineFieldConfig } from './Timeline/types'; export { TimelineOptions, TimelineFieldConfig } from './Timeline/types';
export { GraphNGLegendEvent, GraphNGLegendEventMode } from './GraphNG/types'; export { GraphNGLegendEvent, GraphNGLegendEventMode } from './GraphNG/types';
export * from './NodeGraph'; export * from './NodeGraph';
export { EmotionPerfTest } from './ThemeDemos/EmotionPerfTest';

@ -1,4 +1,5 @@
import { GrafanaTheme } from '@grafana/data'; import { CSSObject } from '@emotion/css';
import { GrafanaTheme, GrafanaThemeV2 } from '@grafana/data';
import tinycolor from 'tinycolor2'; import tinycolor from 'tinycolor2';
export function cardChrome(theme: GrafanaTheme): string { export function cardChrome(theme: GrafanaTheme): string {
@ -44,3 +45,12 @@ export const focusCss = (theme: GrafanaTheme) => `
box-shadow: 0 0 0 2px ${theme.colors.bodyBg}, 0 0 0px 4px ${theme.colors.formFocusOutline}; box-shadow: 0 0 0 2px ${theme.colors.bodyBg}, 0 0 0px 4px ${theme.colors.formFocusOutline};
transition: all 0.2s cubic-bezier(0.19, 1, 0.22, 1); transition: all 0.2s cubic-bezier(0.19, 1, 0.22, 1);
`; `;
export function getFocusStyles(theme: GrafanaThemeV2): CSSObject {
return {
outline: '2px dotted transparent',
outlineOffset: '2px',
boxShadow: `0 0 0 2px ${theme.palette.layer0}, 0 0 0px 4px ${theme.palette.primary.border}`,
transition: `all 0.2s cubic-bezier(0.19, 1, 0.22, 1)`,
};
}

@ -0,0 +1,12 @@
import { EmotionPerfTest, VerticalGroup } from '@grafana/ui';
import React, { FC } from 'react';
export const BenchmarksPage: FC = () => {
return (
<VerticalGroup>
<EmotionPerfTest />
</VerticalGroup>
);
};
export default BenchmarksPage;

@ -441,6 +441,12 @@ export function getAppRoutes(): RouteDescriptor[] {
() => import(/* webpackChunkName: "PlaylistEditPage"*/ 'app/features/playlist/PlaylistEditPage') () => import(/* webpackChunkName: "PlaylistEditPage"*/ 'app/features/playlist/PlaylistEditPage')
), ),
}, },
{
path: '/sandbox/benchmarks',
component: SafeDynamicImport(
() => import(/* webpackChunkName: "BenchmarksPage"*/ 'app/features/sandbox/BenchmarksPage')
),
},
...extraRoutes, ...extraRoutes,
{ {
path: '/*', path: '/*',

Loading…
Cancel
Save