forked from tilt-dev/tilt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApiButton.tsx
872 lines (781 loc) · 24 KB
/
ApiButton.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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
import {
ButtonClassKey,
ButtonGroup,
ButtonProps,
FormControlLabel,
Icon,
InputLabel,
MenuItem,
Select,
SvgIcon,
} from "@material-ui/core"
import ArrowDropDownIcon from "@material-ui/icons/ArrowDropDown"
import { ClassNameMap } from "@material-ui/styles"
import moment from "moment"
import { useSnackbar } from "notistack"
import React, {
PropsWithChildren,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react"
import { convertFromNode, convertFromString } from "react-from-dom"
import { Link } from "react-router-dom"
import styled from "styled-components"
import { Tags } from "./analytics"
import { annotations } from "./annotations"
import { ReactComponent as CloseSvg } from "./assets/svg/close.svg"
import { usePersistentState } from "./BrowserStorage"
import FloatDialog from "./FloatDialog"
import { useHudErrorContext } from "./HudErrorContext"
import {
InstrumentedButton,
InstrumentedCheckbox,
InstrumentedTextField,
} from "./instrumentedComponents"
import { usePathBuilder } from "./PathBuilder"
import {
AnimDuration,
Color,
Font,
FontSize,
SizeUnit,
ZIndex,
} from "./style-helpers"
import { apiTimeFormat, tiltApiPut } from "./tiltApi"
import { UIButton, UIInputSpec, UIInputStatus } from "./types"
/**
* Note on nomenclature: both `ApiButton` and `UIButton` are used to refer to
* custom action buttons here. On the Tilt backend, these are generally called
* `UIButton`s, but to avoid confusion on the frontend, (where there are many
* UI buttons,) they're generally called `ApiButton`s.
*/
// Types
type ApiButtonProps = ButtonProps & {
className?: string
uiButton: UIButton
}
type ApiIconProps = { iconName?: string; iconSVG?: string }
type ApiButtonInputProps = {
spec: UIInputSpec
status: UIInputStatus | undefined
value: any | undefined
setValue: (name: string, value: any) => void
analyticsTags: Tags
}
type ApiButtonElementProps = ButtonProps & {
text: string
confirming: boolean
disabled: boolean
iconName?: string
iconSVG?: string
analyticsTags: Tags
analyticsName: string
}
// UIButtons for a location, sorted into types
export type ButtonSet = {
default: UIButton[]
toggleDisable?: UIButton
stopBuild?: UIButton
}
function newButtonSet(): ButtonSet {
return { default: [] }
}
export enum ApiButtonType {
Global = "Global",
Resource = "Resource",
}
export enum ApiButtonToggleState {
On = "on",
Off = "off",
}
// Constants
export const UIBUTTON_SPEC_HASH = "uibuttonspec-hash"
export const UIBUTTON_ANNOTATION_TYPE = "tilt.dev/uibutton-type"
export const UIBUTTON_GLOBAL_COMPONENT_ID = "nav"
export const UIBUTTON_TOGGLE_DISABLE_TYPE = "DisableToggle"
export const UIBUTTON_TOGGLE_INPUT_NAME = "action"
export const UIBUTTON_STOP_BUILD_TYPE = "StopBuild"
// Styles
const ApiButtonFormRoot = styled.div`
z-index: ${ZIndex.ApiButton};
`
const ApiButtonFormFooter = styled.div`
text-align: right;
color: ${Color.gray40};
font-size: ${FontSize.smallester};
`
const ApiIconRoot = styled.span``
export const ApiButtonLabel = styled.span``
// MUI makes it tricky to get cursor: not-allowed on disabled buttons
// https://material-ui.com/components/buttons/#cursor-not-allowed
export const ApiButtonRoot = styled(ButtonGroup)<{ disabled?: boolean }>`
${(props) =>
props.disabled &&
`
cursor: not-allowed;
`}
${ApiIconRoot} + ${ApiButtonLabel} {
margin-left: ${SizeUnit(0.25)};
}
`
export const LogLink = styled(Link)`
font-size: ${FontSize.smallest};
padding-left: ${SizeUnit(0.5)};
`
export const confirmingButtonStateMixin = `
&.confirming {
background-color: ${Color.red};
border-color: ${Color.gray30};
color: ${Color.black};
&:hover,
&:active,
&:focus {
background-color: ${Color.red};
border-color: ${Color.redLight};
color: ${Color.black};
}
.fillStd {
fill: ${Color.black} !important; /* TODO (lizz): find this style source! */
}
}
`
/* Manually manage the border that both left and right
* buttons share on the edge between them, so border
* color changes work as expected
*/
export const confirmingButtonGroupBorderMixin = `
&.leftButtonInGroup {
border-right: 0;
&:active + .rightButtonInGroup,
&:focus + .rightButtonInGroup,
&:hover + .rightButtonInGroup {
border-left-color: ${Color.redLight};
}
}
`
const ApiButtonElementRoot = styled(InstrumentedButton)`
${confirmingButtonStateMixin}
${confirmingButtonGroupBorderMixin}
`
const inputLabelMixin = `
font-family: ${Font.monospace};
font-size: ${FontSize.small};
color: ${Color.gray10};
`
const ApiButtonInputLabel = styled(InputLabel)`
${inputLabelMixin}
margin-top: ${SizeUnit(1 / 2)};
margin-bottom: ${SizeUnit(1 / 4)};
`
const ApiButtonInputTextField = styled(InstrumentedTextField)`
margin-bottom: ${SizeUnit(1 / 2)};
.MuiOutlinedInput-root {
background-color: ${Color.offWhite};
}
.MuiOutlinedInput-input {
${inputLabelMixin}
border: 1px solid ${Color.gray70};
border-radius: ${SizeUnit(0.125)};
transition: border-color ${AnimDuration.default} ease;
padding: ${SizeUnit(0.2)} ${SizeUnit(0.4)};
&:hover {
border-color: ${Color.gray40};
}
&:focus,
&:active {
border: 1px solid ${Color.gray20};
}
}
`
const ApiButtonInputFormControlLabel = styled(FormControlLabel)`
${inputLabelMixin}
margin-left: unset;
`
const ApiButtonInputCheckbox = styled(InstrumentedCheckbox)`
&.MuiCheckbox-root,
&.Mui-checked {
color: ${Color.gray40};
}
`
export const ApiButtonInputsToggleButton = styled(InstrumentedButton)`
&&&& {
margin-left: unset; /* Override any margins passed down through "className" props */
padding: 0 0;
}
`
function buttonType(b: UIButton): string {
return annotations(b)[UIBUTTON_ANNOTATION_TYPE]
}
const svgElement = (src: string): React.ReactElement => {
const node = convertFromString(src, {
selector: "svg",
type: "image/svg+xml",
nodeOnly: true,
}) as SVGSVGElement
return convertFromNode(node) as React.ReactElement
}
function ApiButtonInput(props: ApiButtonInputProps) {
if (props.spec.text) {
return (
<>
<ApiButtonInputLabel htmlFor={props.spec.name}>
{props.spec.label ?? props.spec.name}
</ApiButtonInputLabel>
<ApiButtonInputTextField
id={props.spec.name}
placeholder={props.spec.text?.placeholder}
value={props.value ?? props.spec.text?.defaultValue ?? ""}
onChange={(e) => props.setValue(props.spec.name!, e.target.value)}
analyticsName="ui.web.uibutton.inputValue"
analyticsTags={{ inputType: "text", ...props.analyticsTags }}
variant="outlined"
fullWidth
/>
</>
)
} else if (props.spec.bool) {
const isChecked = props.value ?? props.spec.bool.defaultValue ?? false
return (
<ApiButtonInputFormControlLabel
control={
<ApiButtonInputCheckbox
id={props.spec.name}
checked={isChecked}
analyticsName="ui.web.uibutton.inputValue"
analyticsTags={{ inputType: "bool", ...props.analyticsTags }}
/>
}
label={props.spec.label ?? props.spec.name}
onChange={(_, checked) => props.setValue(props.spec.name!, checked)}
/>
)
} else if (props.spec.hidden) {
return null
} else if (props.spec.choice) {
// @ts-ignore
const currentChoice = props.value ?? props.spec.choice.choices?.at(0)
const menuItems = []
// @ts-ignore
for (let choice of props.spec.choice?.choices) {
menuItems.push(<MenuItem value={choice}>{choice}</MenuItem>)
}
return (
<>
<ApiButtonInputFormControlLabel
control={
<Select
id={props.spec.name}
value={currentChoice}
label={props.spec.label ?? props.spec.name}
>
{menuItems}
</Select>
}
label={props.spec.label ?? props.spec.name}
onChange={(e) => {
// @ts-ignore
props.setValue(props.spec.name!, e.target.value as string)
}}
aria-label={props.spec.label ?? props.spec.name}
/>
</>
)
} else {
return (
<div>{`Error: button input ${props.spec.name} had unsupported type`}</div>
)
}
}
type ApiButtonFormProps = {
uiButton: UIButton
analyticsTags: Tags
setInputValue: (name: string, value: any) => void
getInputValue: (name: string) => any | undefined
}
export function ApiButtonForm(props: ApiButtonFormProps) {
return (
<ApiButtonFormRoot>
{props.uiButton.spec?.inputs?.map((spec) => {
const name = spec.name!
const status = props.uiButton.status?.inputs?.find(
(status) => status.name === name
)
const value = props.getInputValue(name)
return (
<ApiButtonInput
key={name}
spec={spec}
status={status}
value={value}
setValue={props.setInputValue}
analyticsTags={props.analyticsTags}
/>
)
})}
<ApiButtonFormFooter>(Changes automatically applied)</ApiButtonFormFooter>
</ApiButtonFormRoot>
)
}
type ApiButtonWithOptionsProps = {
submit: JSX.Element
uiButton: UIButton
analyticsTags: Tags
setInputValue: (name: string, value: any) => void
getInputValue: (name: string) => any | undefined
className?: string
text: string
}
function ApiButtonWithOptions(props: ApiButtonWithOptionsProps & ButtonProps) {
const [open, setOpen] = useState(false)
const anchorRef = useRef(null)
const {
submit,
uiButton,
setInputValue,
getInputValue,
text,
analyticsTags,
...buttonProps
} = props
return (
<>
<ApiButtonRoot
ref={anchorRef}
className={props.className}
disableRipple={true}
disabled={buttonProps.disabled}
>
{props.submit}
<ApiButtonInputsToggleButton
{...buttonProps}
size="small"
onClick={() => {
setOpen((prevOpen) => !prevOpen)
}}
analyticsName="ui.web.uibutton.inputMenu"
analyticsTags={analyticsTags}
aria-label={`Open ${text} options`}
>
<ArrowDropDownIcon />
</ApiButtonInputsToggleButton>
</ApiButtonRoot>
<FloatDialog
open={open}
onClose={() => {
setOpen(false)
}}
anchorEl={anchorRef.current}
title={`Options for ${text}`}
>
<ApiButtonForm {...props} />
</FloatDialog>
</>
)
}
export const ApiIcon = ({ iconName, iconSVG }: ApiIconProps) => {
if (iconSVG) {
// the material SvgIcon handles accessibility/sizing/colors well but can't accept a raw SVG string
// create a ReactElement by parsing the source and then use that as the component, passing through
// the props so that it's correctly styled
const svgEl = svgElement(iconSVG)
const svg = (props: React.PropsWithChildren<any>) => {
// merge the props from material-ui while keeping the children of the actual SVG
return React.cloneElement(svgEl, { ...props }, ...svgEl.props.children)
}
return (
<ApiIconRoot>
<SvgIcon component={svg} />
</ApiIconRoot>
)
}
if (iconName) {
return (
<ApiIconRoot>
<Icon>{iconName}</Icon>
</ApiIconRoot>
)
}
return null
}
// returns metadata + button status w/ the specified input buttons
function buttonStatusWithInputs(
button: UIButton,
inputValues: { [name: string]: any }
): UIButton {
const result = {
metadata: { ...button.metadata },
status: { ...button.status },
} as UIButton
result.status!.lastClickedAt = apiTimeFormat(moment.utc())
result.status!.inputs = []
button.spec!.inputs?.forEach((spec) => {
const value = inputValues[spec.name!]
const defined = value !== undefined
let status: UIInputStatus = { name: spec.name }
// If the value isn't defined, use the default value
// This is unfortunate duplication with the default value checks when initializing the
// MUI managed input components. It might bee cleaner to initialize `inputValues` with
// the default values. However, that breaks a bunch of stuff with persistence (e.g.,
// if you modify one value, you get a cookie and then never get to see any default values
// that get added/changed)
if (spec.text) {
status.text = { value: defined ? value : spec.text?.defaultValue }
} else if (spec.bool) {
status.bool = {
value: (defined ? value : spec.bool.defaultValue) === true,
}
} else if (spec.hidden) {
status.hidden = { value: spec.hidden.value }
} else if (spec.choice) {
status.choice = { value: defined ? value : spec.choice?.choices?.at(0) }
}
result.status!.inputs!.push(status)
})
return result
}
export async function updateButtonStatus(
button: UIButton,
inputValues: { [name: string]: any }
) {
const toUpdate = buttonStatusWithInputs(button, inputValues)
await tiltApiPut("uibuttons", "status", toUpdate)
}
function getButtonTags(button: UIButton): Tags {
const tags: Tags = {}
// The location of the button in the UI
const component = button.spec?.location?.componentType as ApiButtonType
if (component !== undefined) {
tags.component = component
}
const buttonAnnotations = annotations(button)
// A unique hash of the button text to help identify which button was clicked
const specHash = buttonAnnotations[UIBUTTON_SPEC_HASH]
if (specHash !== undefined) {
tags.specHash = specHash
}
// Tilt-specific button annotation, currently only used to differentiate disable toggles
const buttonType = buttonAnnotations[UIBUTTON_ANNOTATION_TYPE]
if (buttonType !== undefined) {
tags.buttonType = buttonType
}
// A toggle button will have a hidden input field with the current value of the toggle
// e.g., when a disable button is clicked, the hidden input will be "on" because that's
// the toggle's value when it's clicked, _not_ the value it's being toggled to.
let toggleInput: UIInputSpec | undefined
if (button.spec?.inputs) {
toggleInput = button.spec.inputs.find(
(input) => input.name === UIBUTTON_TOGGLE_INPUT_NAME
)
}
if (toggleInput !== undefined) {
const toggleValue = toggleInput.hidden?.value
// Only use values defined in `ApiButtonToggleState`, so no user-specific information is saved.
// When toggle buttons are exposed in the button extension, this mini allowlist can be revisited.
if (
toggleValue === ApiButtonToggleState.On ||
toggleValue === ApiButtonToggleState.Off
) {
tags.toggleValue = toggleValue
}
}
return tags
}
export function ApiCancelButton(props: ApiButtonElementProps) {
const {
confirming,
onClick,
analyticsTags,
text,
analyticsName,
...buttonProps
} = props
// Don't display the cancel confirmation button if the button
// group's state isn't confirming
if (!confirming) {
return null
}
// To pass classes to a MUI component, it's necessary to use `classes`, instead of `className`
const classes: Partial<ClassNameMap<ButtonClassKey>> = {
root: "confirming rightButtonInGroup",
}
return (
<ApiButtonElementRoot
analyticsName={analyticsName}
aria-label={`Cancel ${text}`}
analyticsTags={{ confirm: "false", ...analyticsTags }}
classes={classes}
onClick={onClick}
{...buttonProps}
>
<CloseSvg role="presentation" />
</ApiButtonElementRoot>
)
}
// The inner content of an ApiSubmitButton
export function ApiSubmitButtonContent(
props: PropsWithChildren<{
confirming: boolean
displayButtonText: string
iconName?: string
iconSVG?: string
}>
) {
if (props.confirming) {
return <ApiButtonLabel>{props.displayButtonText}</ApiButtonLabel>
}
if (props.children && props.children !== true) {
return <>{props.children}</>
}
return (
<>
<ApiIcon iconName={props.iconName} iconSVG={props.iconSVG} />
<ApiButtonLabel>{props.displayButtonText}</ApiButtonLabel>
</>
)
}
// For a toggle button that requires confirmation to trigger a UIButton's
// action, this component will render both the "submit" and the "confirm submit"
// HTML buttons. For keyboard navigation and accessibility, this component
// intentionally renders both buttons as the same element with different props.
// This makes sure that keyboard focus is moved to (or rather, stays on)
// the "confirm submit" button when the "submit" button is clicked. People
// using assistive tech like screenreaders will know they need to confirm.
// (Screenreaders should announce the "confirm submit" button to users because
// the `aria-label` changes when the "submit" button is clicked.)
export function ApiSubmitButton(
props: PropsWithChildren<ApiButtonElementProps>
) {
const {
analyticsName,
analyticsTags,
confirming,
disabled,
onClick,
iconName,
iconSVG,
text,
...buttonProps
} = props
// Determine display text and accessible button label based on confirmation state
const displayButtonText = confirming ? "Confirm" : text
const ariaLabel = confirming ? `Confirm ${text}` : `Trigger ${text}`
const tags = { ...analyticsTags }
if (confirming) {
tags.confirm = "true"
}
// To pass classes to a MUI component, it's necessary to use `classes`, instead of `className`
const isConfirmingClass = confirming ? "confirming leftButtonInGroup" : ""
const classes: Partial<ClassNameMap<ButtonClassKey>> = {
root: isConfirmingClass,
}
// Note: button text is not included in analytics name since that can be user data
return (
<ApiButtonElementRoot
analyticsName={analyticsName}
analyticsTags={tags}
aria-label={ariaLabel}
classes={classes}
disabled={disabled}
onClick={onClick}
{...buttonProps}
>
<ApiSubmitButtonContent
confirming={confirming}
displayButtonText={displayButtonText}
iconName={iconName}
iconSVG={iconSVG}
>
{props.children}
</ApiSubmitButtonContent>
</ApiButtonElementRoot>
)
}
// Renders a UIButton.
// NB: The `Button` in `ApiButton` refers to a UIButton, not an html <button>.
// This can be confusing because each ApiButton consists of one or two <button>s:
// 1. A submit <button>, which fires the button's action.
// 2. Optionally, an options <button>, which allows the user to configure the
// options used on submit.
export function ApiButton(props: PropsWithChildren<ApiButtonProps>) {
const { className, uiButton, ...buttonProps } = props
const buttonName = uiButton.metadata?.name || ""
const [inputValues, setInputValues] = usePersistentState<{
[name: string]: any
}>(`apibutton-${buttonName}`, {})
const { enqueueSnackbar } = useSnackbar()
const pb = usePathBuilder()
const { setError } = useHudErrorContext()
const [loading, setLoading] = useState(false)
const [confirming, setConfirming] = useState(false)
// Reset the confirmation state when the button's name changes
useLayoutEffect(() => setConfirming(false), [buttonName])
const tags = useMemo(() => getButtonTags(uiButton), [uiButton])
const componentType = uiButton.spec?.location?.componentType as ApiButtonType
const disabled = loading || uiButton.spec?.disabled || false
const buttonText = uiButton.spec?.text || "Button"
const onClick = async (e: React.MouseEvent<HTMLElement>) => {
e.preventDefault()
e.stopPropagation()
if (uiButton.spec?.requiresConfirmation && !confirming) {
setConfirming(true)
return
}
if (confirming) {
setConfirming(false)
}
// TODO(milas): currently the loading state just disables the button for the duration of
// the AJAX request to avoid duplicate clicks - there is no progress tracking at the
// moment, so there's no fancy spinner animation or propagation of result of action(s)
// that occur as a result of click right now
setLoading(true)
try {
await updateButtonStatus(uiButton, inputValues)
} catch (err) {
setError(`Error submitting button click: ${err}`)
return
} finally {
setLoading(false)
}
// skip snackbar notifications for special buttons (e.g., disable, stop build)
if (!buttonType(uiButton)) {
const snackbarLogsLink =
componentType === ApiButtonType.Global ? (
<LogLink to="/r/(all)/overview">Global Logs</LogLink>
) : (
<LogLink
to={pb.encpath`/r/${
uiButton.spec?.location?.componentID || "(all)"
}/overview`}
>
Resource Logs
</LogLink>
)
enqueueSnackbar(
<div>
Triggered button: {uiButton.spec?.text || uiButton.metadata?.name}
{snackbarLogsLink}
</div>
)
}
}
const submitButton = (
<ApiSubmitButton
text={buttonText}
confirming={confirming}
disabled={disabled}
iconName={uiButton.spec?.iconName}
iconSVG={uiButton.spec?.iconSVG}
onClick={onClick}
analyticsName="ui.web.uibutton"
analyticsTags={tags}
{...buttonProps}
>
{props.children}
</ApiSubmitButton>
)
// show the options button if there are any non-hidden inputs
const visibleInputs = uiButton.spec?.inputs?.filter((i) => !i.hidden) || []
if (visibleInputs.length) {
const setInputValue = (name: string, value: any) => {
// Copy to a new object so that the reference changes to force a rerender.
setInputValues({ ...inputValues, [name]: value })
}
const getInputValue = (name: string) => inputValues[name]
return (
<ApiButtonWithOptions
className={className}
submit={submitButton}
uiButton={uiButton}
setInputValue={setInputValue}
getInputValue={getInputValue}
aria-label={buttonText}
analyticsTags={tags}
// use-case-wise, it'd probably be better to leave the options button enabled
// regardless of the submit button's state.
// However, that's currently a low-impact difference, and this is a really
// cheap way to ensure the styling matches.
disabled={disabled}
text={buttonText}
{...buttonProps}
/>
)
} else {
return (
<ApiButtonRoot
className={className}
disableRipple={true}
aria-label={buttonText}
disabled={disabled}
>
{submitButton}
<ApiCancelButton
analyticsName="ui.web.uibutton"
analyticsTags={tags}
text={buttonText}
confirming={confirming}
disabled={disabled}
onClick={() => setConfirming(false)}
{...buttonProps}
/>
</ApiButtonRoot>
)
}
}
function addButtonToSet(bs: ButtonSet, b: UIButton) {
switch (buttonType(b)) {
case UIBUTTON_TOGGLE_DISABLE_TYPE:
bs.toggleDisable = b
break
case UIBUTTON_STOP_BUILD_TYPE:
bs.stopBuild = b
break
default:
bs.default.push(b)
break
}
}
export function buttonsForComponent(
buttons: UIButton[] | undefined,
componentType: ApiButtonType,
componentID: string | undefined
): ButtonSet {
let result = newButtonSet()
if (!buttons) {
return result
}
buttons.forEach((b) => {
const buttonType = b.spec?.location?.componentType || ""
const buttonID = b.spec?.location?.componentID || ""
const buttonTypesMatch =
buttonType.toUpperCase() === componentType.toUpperCase()
const buttonIDsMatch = buttonID === componentID
if (buttonTypesMatch && buttonIDsMatch) {
addButtonToSet(result, b)
}
})
return result
}
export function buttonsByComponent(
buttons: UIButton[] | undefined
): Map<string, ButtonSet> {
const result = new Map<string, ButtonSet>()
if (buttons === undefined) {
return result
}
buttons.forEach((b) => {
const componentID = b.spec?.location?.componentID || ""
// Disregard any buttons that aren't linked to a specific component or resource
if (!componentID.length) {
return
}
let buttonSet = result.get(componentID)
if (!buttonSet) {
buttonSet = newButtonSet()
result.set(componentID, buttonSet)
}
addButtonToSet(buttonSet, b)
})
return result
}