Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Colorpicker] Add hex/alpha text fields #8294

Closed
wants to merge 16 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/slow-bears-guess.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@shopify/polaris': minor
---

Add text editor to the `ColorPicker`
4 changes: 4 additions & 0 deletions polaris-react/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@
"spinnerAccessibilityLabel": "Loading",
"connectedDisclosureAccessibilityLabel": "Related actions"
},
"ColorPicker": {
"textPickerAccessibilityLabel": "HEX color",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Localization quality issue found

The following issues may affect the quality of localized translations if they are not addressed:

  • The value HEX color for key Polaris.ColorPicker.textPickerAccessibilityLabel is very short. Short strings are more likely to be misunderstood by translators without context. Please provide additional context for the translators if possible.

Please look out for other instances of this issue in your PR and fix them as well if possible.

Questions about these messages? Hop in the #help-localization Slack channel.

"alphaFieldAccessibilityLabel": "Alpha"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Localization quality issue found

The following issues may affect the quality of localized translations if they are not addressed:

  • The value Alpha for key Polaris.ColorPicker.alphaFieldAccessibilityLabel is very short. Short strings are more likely to be misunderstood by translators without context. Please provide additional context for the translators if possible.

Please look out for other instances of this issue in your PR and fix them as well if possible.

Questions about these messages? Hop in the #help-localization Slack channel.

},
"Common": {
"checkbox": "checkbox",
"undo": "Undo",
Expand Down
47 changes: 47 additions & 0 deletions polaris-react/src/components/ColorPicker/ColorPicker.scss
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@
// stylelint-disable-next-line -- generated by polaris-migrator DO NOT COPY
width: var(--pc-color-picker-size);

// stylelint-disable-next-line selector-max-class
.AlphaAllowed.TextAllowed & {
width: 224px;
}

.fullWidth & {
// stylelint-disable-next-line -- generated by polaris-migrator DO NOT COPY
width: auto;
Expand Down Expand Up @@ -214,3 +219,45 @@ $vertical-picker-border-radius: calc(var(--pc-color-picker-size) * 0.5);
width: 100%;
cursor: pointer;
}

.TextFields {
display: flex;
}

.TextPicker {
width: 192px;
margin-top: var(--p-space-2);

&.AlphaAllowed {
width: 180px;
}

.fullWidth & {
width: auto;
flex-grow: 1;
}
}

.TextFieldSwatch {
width: var(--p-space-5);
height: var(--p-space-5);
margin-left: -(var(--p-space-1));
border-radius: 50%;
box-shadow: var(--p-shadow-deep);

&.AlphaAllowed {
@include checkers;
}
}

.SwatchBackground {
width: 100%;
height: 100%;
border-radius: inherit;
box-shadow: inherit;
}

.AlphaField {
flex: 0 0 100px;
margin: var(--p-space-2) 0 0 var(--p-space-2);
}
79 changes: 30 additions & 49 deletions polaris-react/src/components/ColorPicker/ColorPicker.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,63 +44,44 @@ export function WithTransparentValueFullWidth() {
return <ColorPicker fullWidth onChange={setColor} color={color} allowAlpha />;
}

export function WithHexTextField() {
export function WithTextFields() {
const [color, setColor] = useState({
hue: 300,
saturation: 0.7,
hue: 120,
brightness: 1,
saturation: 1,
});

const [hex, setHex] = useState(hsbToHex(color));

const handleBlur = useCallback(() => {
setColor(rgbToHsb(hexToRgb(hex)));
}, [hex]);

useEffect(() => {
setHex(hsbToHex(color));
}, [color]);
return <ColorPicker onChange={setColor} color={color} textEditor />;
}

const styles = {
Wrapper: {
display: 'grid',
gap: 'var(--p-space-2)',
gridTemplateColumns: 'auto 1fr',
maxWidth: 'fit-content',
},
Picker: {
gridColumn: '1 / 3',
},
Tile: {
minHeight: 'calc(100% - 0.125rem)',
aspectRatio: '1 / 1',
borderRadius: 'var(--p-border-radius-1)',
border: 'var(--p-border-divider)',
backgroundColor: hsbToHex(color),
},
TextField: {
maxWidth: 'fit-content',
},
};
export function WithTransparentValueAndTextFields() {
const [color, setColor] = useState({
hue: 300,
brightness: 1,
saturation: 0.7,
alpha: 0.7,
});

return (
<div style={styles.Wrapper}>
<div style={styles.Picker}>
<ColorPicker onChange={setColor} color={color} />
</div>
<ColorPicker onChange={setColor} color={color} allowAlpha textEditor />
);
}

<div style={styles.Tile} />
export function WithTransparentValueAndTextFieldsFullWidth() {
const [color, setColor] = useState({
hue: 300,
brightness: 1,
saturation: 0.7,
alpha: 0.7,
});

<div style={styles.TextField}>
<TextField
label=""
prefix="#"
value={hex.replace('#', '')}
onChange={setHex}
onBlur={handleBlur}
autoComplete="off"
/>
</div>
</div>
return (
<ColorPicker
onChange={setColor}
color={color}
allowAlpha
fullWidth
textEditor
/>
);
}
86 changes: 68 additions & 18 deletions polaris-react/src/components/ColorPicker/ColorPicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,19 @@ import React, {PureComponent} from 'react';
import {debounce} from '../../utilities/debounce';
import {clamp} from '../../utilities/clamp';
import {classNames} from '../../utilities/css';
import {hsbToRgb} from '../../utilities/color-transformers';
import {hsbToRgb, hexToHsb} from '../../utilities/color-transformers';
import type {HSBColor, HSBAColor} from '../../utilities/color-types';
// eslint-disable-next-line import/no-deprecated
import {EventListener} from '../EventListener';

import {AlphaPicker, HuePicker, Slidable, SlidableProps} from './components';
import {
AlphaField,
AlphaPicker,
HuePicker,
Slidable,
SlidableProps,
TextPicker,
} from './components';
import styles from './ColorPicker.scss';

interface State {
Expand All @@ -32,6 +39,8 @@ export interface ColorPickerProps {
allowAlpha?: boolean;
/** Allow HuePicker to take the full width */
fullWidth?: boolean;
/** Show text fields for entering color and alpha values */
textEditor?: boolean;
/** Callback when color is selected */
onChange(color: HSBAColor): void;
}
Expand Down Expand Up @@ -92,7 +101,7 @@ export class ColorPicker extends PureComponent<ColorPickerProps, State> {
}

render() {
const {id, color, allowAlpha, fullWidth} = this.props;
const {id, color, allowAlpha, fullWidth, textEditor} = this.props;
const {hue, saturation, brightness, alpha: providedAlpha} = color;
const {pickerSize} = this.state;

Expand All @@ -114,26 +123,58 @@ export class ColorPicker extends PureComponent<ColorPickerProps, State> {
/>
) : null;

const className = classNames(
styles.ColorPicker,
const hexPickerMarkup = (
<TextPicker
color={color}
allowAlpha={allowAlpha}
onChange={this.handleHexChange}
/>
);

const alphaFieldMarkup = allowAlpha ? (
<AlphaField alpha={alpha} onChange={this.handleAlphaChange} />
) : null;

const textFieldsMarkup = textEditor ? (
<div className={styles.TextFields}>
{hexPickerMarkup}
{alphaFieldMarkup}
</div>
) : null;

const wrapperClassName = classNames(
allowAlpha && styles.AlphaAllowed,
fullWidth && styles.fullWidth,
textEditor && styles.TextAllowed,
);

const colorNodeClassName = classNames(
styles.MainColor,
allowAlpha && styles.AlphaAllowed,
);

return (
<div className={className} id={id} onMouseDown={this.handlePickerDrag}>
<div ref={this.setColorNode} className={styles.MainColor}>
<div
className={styles.ColorLayer}
style={{backgroundColor: colorString}}
/>
<Slidable
onChange={this.handleDraggerMove}
draggerX={draggerX}
draggerY={draggerY}
/>
<div className={wrapperClassName}>
<div
className={styles.ColorPicker}
id={id}
onMouseDown={this.handlePickerDrag}
>
<div ref={this.setColorNode} className={colorNodeClassName}>
<div
className={styles.ColorLayer}
style={{backgroundColor: colorString}}
/>
<Slidable
onChange={this.handleDraggerMove}
draggerX={draggerX}
draggerY={draggerY}
/>
</div>
<HuePicker hue={hue} onChange={this.handleHueChange} />
{alphaSliderMarkup}
</div>
<HuePicker hue={hue} onChange={this.handleHueChange} />
{alphaSliderMarkup}
{textFieldsMarkup}
<EventListener event="resize" handler={this.handleResize} />
</div>
);
Expand All @@ -159,6 +200,15 @@ export class ColorPicker extends PureComponent<ColorPickerProps, State> {
onChange({hue, brightness, saturation, alpha});
};

private handleHexChange = (hex: string) => {
const {
color: {alpha = 1},
onChange,
} = this.props;
const newColor = hexToHsb(hex);
onChange({...newColor, alpha});
};

private handleDraggerMove: SlidableProps['onChange'] = ({x, y}) => {
const {pickerSize} = this.state;
const {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import React, {useCallback, useEffect, useState} from 'react';

import {clamp} from '../../../../utilities/clamp';
import {useI18n} from '../../../../utilities/i18n';
import {TextField} from '../../../TextField';
import styles from '../../ColorPicker.scss';

export interface AlphaFieldProps {
alpha: number;
onChange(alpha: number): void;
}

export function AlphaField({alpha, onChange}: AlphaFieldProps) {
const i18n = useI18n();

const [percentage, setPercentage] = useState(
clamp(Math.round(alpha * 100) || 0, 0, 100),
);

const label = i18n.translate(
'Polaris.ColorPicker.alphaFieldAccessibilityLabel',
);

useEffect(() => {
setPercentage(Math.round(alpha * 100));
}, [alpha]);

const handleKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLElement>) => {
const {key, shiftKey} = event;
const step = shiftKey ? 0.05 : 0.01;
if (key === 'ArrowUp') {
event.preventDefault();
onChange(clamp(alpha + step, 0, 1));
} else if (key === 'ArrowDown') {
event.preventDefault();
onChange(clamp(alpha - step, 0, 1));
}
},
[alpha, onChange],
);

const handleTextChange = useCallback(
(value: string) => {
const updatedPercentage = parseInt(value, 10);

const activeElementRole = document?.activeElement?.getAttribute('role');

if (activeElementRole === 'button') {
onChange(updatedPercentage / 100);
} else {
setPercentage(updatedPercentage);
}
},
[onChange],
);

const handleBlur = useCallback(() => {
const normalizedPercentage = clamp(percentage, 0, 100);

if (normalizedPercentage !== null) {
setPercentage(normalizedPercentage);

const alphaHasChanged = normalizedPercentage !== alpha * 100;

if (alphaHasChanged) {
onChange(normalizedPercentage / 100);
}
}
}, [alpha, onChange, percentage]);

return (
<div
id="AlphaFieldWrapper"
onKeyDown={handleKeyDown}
className={styles.AlphaField}
>
<TextField
suffix="%"
value={percentage.toString()}
label={label}
labelHidden
type="number"
autoComplete="off"
max={100}
min={0}
onChange={handleTextChange}
onBlur={handleBlur}
/>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './AlphaField';
Loading