/
NumberInput.tsx
418 lines (367 loc) · 11.5 KB
/
NumberInput.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/**
* @license
* Copyright 2018-2022 Streamlit Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from "react"
import { Plus, Minus } from "@emotion-icons/open-iconic"
import { sprintf } from "sprintf-js"
import { FormClearHelper } from "src/components/widgets/Form"
import { logWarning } from "src/lib/log"
import { NumberInput as NumberInputProto } from "src/autogen/proto"
import { WidgetStateManager, Source } from "src/lib/WidgetStateManager"
import TooltipIcon from "src/components/shared/TooltipIcon"
import { Placement } from "src/components/shared/Tooltip"
import Icon from "src/components/shared/Icon"
import { Input as UIInput } from "baseui/input"
import InputInstructions from "src/components/shared/InputInstructions/InputInstructions"
import {
WidgetLabel,
StyledWidgetLabelHelp,
} from "src/components/widgets/BaseWidget"
import {
StyledInputContainer,
StyledInputControl,
StyledInputControls,
StyledInstructionsContainer,
} from "./styled-components"
export interface Props {
disabled: boolean
element: NumberInputProto
widgetMgr: WidgetStateManager
width: number
}
export interface State {
/**
* True if the user-specified state.value has not yet been synced to the WidgetStateManager.
*/
dirty: boolean
/**
* The value specified by the user via the UI. If the user didn't touch this
* widget's UI, the default value is used.
*/
value: number
/**
* The value with applied format that is going to be shown to the user
*/
formattedValue: string
}
class NumberInput extends React.PureComponent<Props, State> {
private readonly formClearHelper = new FormClearHelper()
private inputRef = React.createRef<HTMLInputElement>()
constructor(props: Props) {
super(props)
this.state = {
dirty: false,
value: this.initialValue,
formattedValue: this.formatValue(this.initialValue),
}
}
get initialValue(): number {
// If WidgetStateManager knew a value for this widget, initialize to that.
// Otherwise, use the default value from the widget protobuf
const storedValue = this.isIntData()
? this.props.widgetMgr.getIntValue(this.props.element)
: this.props.widgetMgr.getDoubleValue(this.props.element)
return storedValue !== undefined ? storedValue : this.props.element.default
}
public componentDidMount(): void {
if (this.props.element.setValue) {
this.updateFromProtobuf()
} else {
this.commitWidgetValue({ fromUi: false })
}
}
public componentDidUpdate(): void {
this.maybeUpdateFromProtobuf()
}
public componentWillUnmount(): void {
this.formClearHelper.disconnect()
}
private maybeUpdateFromProtobuf(): void {
const { setValue } = this.props.element
if (setValue) {
this.updateFromProtobuf()
}
}
private updateFromProtobuf(): void {
const { value } = this.props.element
this.props.element.setValue = false
this.setState({ value, formattedValue: this.formatValue(value) }, () => {
this.commitWidgetValue({ fromUi: false })
})
}
private formatValue = (value: number): string => {
const format = getNonEmptyString(this.props.element.format)
if (format == null) {
return value.toString()
}
try {
return sprintf(format, value)
} catch (e) {
// Don't explode if we have a malformed format string.
logWarning(`Error in sprintf(${format}, ${value}): ${e}`)
return String(value)
}
}
private isIntData = (): boolean => {
return this.props.element.dataType === NumberInputProto.DataType.INT
}
private getMin = (): number => {
return this.props.element.hasMin ? this.props.element.min : -Infinity
}
private getMax = (): number => {
return this.props.element.hasMax ? this.props.element.max : +Infinity
}
private getStep = (): number => {
const { step } = this.props.element
if (step) {
return step
}
if (this.isIntData()) {
return 1
}
return 0.01
}
/** Commit state.value to the WidgetStateManager. */
private commitWidgetValue = (source: Source): void => {
const { value } = this.state
const { element, widgetMgr } = this.props
const data = this.props.element
const min = this.getMin()
const max = this.getMax()
if (min > value || value > max) {
const node = this.inputRef.current
if (node) {
node.reportValidity()
}
} else {
const valueToBeSaved = value || value === 0 ? value : data.default
if (this.isIntData()) {
widgetMgr.setIntValue(element, valueToBeSaved, source)
} else {
widgetMgr.setDoubleValue(element, valueToBeSaved, source)
}
this.setState({
dirty: false,
value: valueToBeSaved,
formattedValue: this.formatValue(valueToBeSaved),
})
}
}
/**
* If we're part of a clear_on_submit form, this will be called when our
* form is submitted. Restore our default value and update the WidgetManager.
*/
private onFormCleared = (): void => {
this.setState({ value: this.props.element.default }, () =>
this.commitWidgetValue({ fromUi: true })
)
}
private onBlur = (): void => {
if (this.state.dirty) {
this.commitWidgetValue({ fromUi: true })
}
}
private onChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
const { value } = e.target
let numValue: number
if (this.isIntData()) {
numValue = parseInt(value, 10)
} else {
numValue = parseFloat(value)
}
this.setState({
dirty: true,
value: numValue,
formattedValue: value,
})
}
private onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>): void => {
const { key } = e
switch (key) {
case "ArrowUp":
e.preventDefault()
this.modifyValueUsingStep("increment")()
break
case "ArrowDown":
e.preventDefault()
this.modifyValueUsingStep("decrement")()
break
default: // Do nothing
}
}
private onKeyPress = (e: React.KeyboardEvent<HTMLInputElement>): void => {
if (e.key === "Enter" && this.state.dirty) {
this.commitWidgetValue({ fromUi: true })
}
}
/** True if the input's current value can be decremented by its step. */
private get canDecrement(): boolean {
return this.state.value - this.getStep() >= this.getMin()
}
/** True if the input's current value can be incremented by its step. */
private get canIncrement(): boolean {
return this.state.value + this.getStep() <= this.getMax()
}
private modifyValueUsingStep = (
modifier: "increment" | "decrement"
): any => (): void => {
const { value } = this.state
const step = this.getStep()
switch (modifier) {
case "increment":
if (this.canIncrement) {
this.setState(
{
dirty: true,
value: value + step,
},
() => {
this.commitWidgetValue({ fromUi: true })
}
)
}
break
case "decrement":
if (this.canDecrement) {
this.setState(
{
dirty: true,
value: value - step,
},
() => {
this.commitWidgetValue({ fromUi: true })
}
)
}
break
default: // Do nothing
}
}
public render(): React.ReactNode {
const { element, width, disabled, widgetMgr } = this.props
const { formattedValue, dirty } = this.state
const style = { width }
const disableDecrement = !this.canDecrement || disabled
const disableIncrement = !this.canIncrement || disabled
// Manage our form-clear event handler.
this.formClearHelper.manageFormClearListener(
widgetMgr,
element.formId,
this.onFormCleared
)
return (
<div className="stNumberInput" style={style}>
<WidgetLabel label={element.label} disabled={disabled}>
{element.help && (
<StyledWidgetLabelHelp>
<TooltipIcon
content={element.help}
placement={Placement.TOP_RIGHT}
/>
</StyledWidgetLabelHelp>
)}
</WidgetLabel>
<StyledInputContainer>
<UIInput
type="number"
inputRef={this.inputRef}
value={formattedValue}
onBlur={this.onBlur}
onChange={this.onChange}
onKeyPress={this.onKeyPress}
onKeyDown={this.onKeyDown}
disabled={disabled}
overrides={{
Input: {
props: {
step: this.getStep(),
min: this.getMin(),
max: this.getMax(),
},
style: {
lineHeight: "1.5",
// Baseweb requires long-hand props, short-hand leads to weird bugs & warnings.
paddingRight: ".5rem",
paddingLeft: ".5rem",
paddingBottom: ".5rem",
paddingTop: ".5rem",
},
},
InputContainer: {
style: () => ({
borderTopRightRadius: 0,
borderBottomRightRadius: 0,
}),
},
Root: {
style: () => ({
borderTopRightRadius: 0,
borderBottomRightRadius: 0,
// Baseweb requires long-hand props, short-hand leads to weird bugs & warnings.
borderLeftWidth: 0,
borderRightWidth: 0,
borderTopWidth: 0,
borderBottomWidth: 0,
}),
},
}}
/>
<StyledInputControls>
<StyledInputControl
className="step-down"
onClick={this.modifyValueUsingStep("decrement")}
disabled={disableDecrement}
>
<Icon
content={Minus}
size="xs"
color={this.canDecrement ? "inherit" : "disabled"}
/>
</StyledInputControl>
<StyledInputControl
className="step-up"
onClick={this.modifyValueUsingStep("increment")}
disabled={disableIncrement}
>
<Icon
content={Plus}
size="xs"
color={this.canIncrement ? "inherit" : "disabled"}
/>
</StyledInputControl>
</StyledInputControls>
</StyledInputContainer>
<StyledInstructionsContainer>
<InputInstructions
dirty={dirty}
value={formattedValue}
className="input-instructions"
/>
</StyledInstructionsContainer>
</div>
)
}
}
/**
* Return a string property from an element. If the string is
* null or empty, return undefined instead.
*/
function getNonEmptyString(
value: string | null | undefined
): string | undefined {
return value == null || value === "" ? undefined : value
}
export default NumberInput