-
Notifications
You must be signed in to change notification settings - Fork 2
/
WeightPickerButton.tsx
259 lines (236 loc) · 8 KB
/
WeightPickerButton.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module LineWeight
*/
import "./WeightPickerButton.scss";
import classnames from "classnames";
import * as React from "react";
import { Key } from "ts-key-enum";
import type { ColorDef } from "@itwin/core-common";
import { RelativePosition } from "@itwin/appui-abstract";
import type { CommonProps } from "@itwin/core-react";
import { ElementResizeObserver, Popup } from "@itwin/core-react";
import { LineWeightSwatch } from "./Swatch";
// cSpell:ignore weightpicker lineweight
/** Properties for the [[WeightPickerButton]] React component
* @public
*/
export interface WeightPickerProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
CommonProps {
/** active weight */
activeWeight: number;
/** available weights */
weights: number[];
/** color specification */
colorDef?: ColorDef;
/** function to run when user selects weight swatch */
onLineWeightPick?: ((weight: number) => void) | undefined;
/** Disabled or not */
disabled?: boolean;
/** Readonly or not */
readonly?: boolean;
/** hide the weight label */
hideLabel?: boolean;
/** Title to show at top of DropDown */
dropDownTitle?: string;
}
/** @internal */
interface WeightPickerState {
showPopup: boolean;
targetElement: HTMLDivElement | null;
}
/** WeightPickerButton component
* @public
*/
export class WeightPickerButton extends React.PureComponent<
WeightPickerProps,
WeightPickerState
> {
private _target = React.createRef<HTMLDivElement>();
private _weightsContainer: HTMLDivElement | null = null;
private _focusTarget = React.createRef<HTMLButtonElement>(); // weight button that should receive focus after popup is open
/** @internal */
constructor(props: WeightPickerProps) {
super(props);
this.state = { showPopup: false, targetElement: null };
}
public setFocus(): void {
// istanbul ignore next
this._focusTarget.current && this._focusTarget.current.focus();
}
public static defaultProps = {
weights: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
};
private _togglePopup = () => {
if (this.props.readonly) return;
this.setState((prevState) => ({ showPopup: !prevState.showPopup }));
};
private _onPopupOpened = () => {};
private _closePopup = () => {
this.setState((_prevState) => ({ showPopup: false }));
};
private _handleWeightPicked = (weight: number) => {
this._closePopup();
this.props.onLineWeightPick && this.props.onLineWeightPick(weight);
};
public override componentDidMount() {
this.setState({ targetElement: this._target.current });
}
private buildIdForWeight(weight: number): string {
return `ui-core-lineweight-${weight}`;
}
private moveFocusInPopup(moveUp: boolean, event: React.KeyboardEvent<any>) {
const activeElement = document.activeElement;
// istanbul ignore else
if (
this._weightsContainer &&
activeElement &&
activeElement.tagName === "BUTTON"
) {
const values = activeElement.id.split("-");
// istanbul ignore else
if (values.length === 4 && values[2] === "lineweight") {
const weight = parseInt(values[3], 10);
const foundIndex = this.props.weights.findIndex(
(val) => val === weight
);
// istanbul ignore next
if (foundIndex < 0) return;
const nextWeight = moveUp
? foundIndex <= 0
? this.props.weights[this.props.weights.length - 1]
: this.props.weights[foundIndex - 1]
: foundIndex < this.props.weights.length - 1
? this.props.weights[foundIndex + 1]
: this.props.weights[0];
const focusLocation = this._weightsContainer.querySelector(
`#${this.buildIdForWeight(nextWeight)}`
) as HTMLButtonElement;
// istanbul ignore else
if (focusLocation) {
focusLocation.focus();
event.preventDefault();
event.stopPropagation();
}
}
}
}
private _handleKeyDown = (event: React.KeyboardEvent<any>) => {
if (event.key === Key.Enter.valueOf()) {
event.preventDefault();
event.stopPropagation();
const weightButton = document.activeElement as HTMLElement;
// istanbul ignore else
if (weightButton.tagName === "BUTTON") {
try {
const values = weightButton.id.split("-");
// istanbul ignore else
if (values.length) {
const weight = parseInt(values[values.length - 1], 10);
// istanbul ignore else
if (!isNaN(weight)) {
// istanbul ignore else
if (this.props.onLineWeightPick)
this.props.onLineWeightPick(weight);
}
}
} catch {}
}
this._closePopup();
} else {
switch (event.key) {
case Key.ArrowDown.valueOf():
this.moveFocusInPopup(false, event);
break;
case Key.ArrowUp.valueOf():
this.moveFocusInPopup(true, event);
break;
}
}
};
private _setWeightContainer = (el: any) => {
this._weightsContainer = el;
};
private renderPopup(title: string | undefined) {
return (
<div className="components-weightpicker-popup-container">
{title && <h4>{title}</h4>}
{/* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions */}
<ul
data-testid="components-weightpicker-popup-lines"
className="components-weightpicker-popup-lines"
onKeyDown={this._handleKeyDown}
ref={this._setWeightContainer}
>
{this.props.weights.map((weight, index) => {
const classNames = classnames(
"components-weightpicker-swatch",
weight === this.props.activeWeight && "active"
);
return (
<LineWeightSwatch
className={classNames}
key={index}
colorDef={this.props.colorDef}
id={this.buildIdForWeight(weight)}
hideLabel={this.props.hideLabel}
onClick={this._handleWeightPicked.bind(this, weight)}
weight={weight}
/>
);
})}
</ul>
</div>
);
}
/** @internal */
public override render() {
const buttonClassNames = classnames(
"components-weightpicker-button",
this.props.className
);
return (
<>
<div ref={this._target} style={this.props.style}>
<LineWeightSwatch
data-testid="components-weightpicker-button"
className={buttonClassNames}
weight={this.props.activeWeight}
colorDef={this.props.colorDef}
readonly={this.props.readonly}
disabled={this.props.disabled}
hideLabel={this.props.hideLabel}
aria-haspopup="listbox"
aria-expanded={this.state.showPopup}
onClick={this._togglePopup}
/>
</div>
<ElementResizeObserver
watchedElement={this.state.targetElement}
render={({ width }) => (
<Popup
className="components-weightpicker-popup"
style={{ width: `${width}px` }}
isOpen={this.state.showPopup}
position={RelativePosition.Bottom}
offset={0}
showShadow={false}
onClose={this._closePopup}
onOpen={this._onPopupOpened}
focusTarget={`#${this.buildIdForWeight(this.props.activeWeight)}`}
moveFocus={true}
target={this.state.targetElement}
closeOnNestedPopupOutsideClick
>
{this.renderPopup(this.props.dropDownTitle)}
</Popup>
)}
/>
</>
);
}
}