-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathaction-button.tsx
More file actions
216 lines (199 loc) · 8.43 KB
/
Copy pathaction-button.tsx
File metadata and controls
216 lines (199 loc) · 8.43 KB
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
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* action:button — Smart action button driven by ActionSchema.
*
* Renders a Shadcn Button wired to the ActionRunner. Supports:
* - All 5 spec action types (script, url, modal, flow, api)
* - Conditional visibility & enabled state
* - Loading indicator during async execution
* - Icon rendering via Lucide
* - Variant / size / className overrides from schema
*/
import React, { forwardRef, useCallback, useEffect, useRef, useState } from 'react';
import { ComponentRegistry } from '@object-ui/core';
import type { ActionSchema } from '@object-ui/types';
import { useAction } from '@object-ui/react';
import { useCondition, toPredicateInput } from '@object-ui/react';
import { Button } from '../../ui';
import { cn } from '../../lib/utils';
import { Loader2 } from 'lucide-react';
import { resolveIcon } from './resolve-icon';
export interface ActionButtonProps {
schema: ActionSchema & { type: string; className?: string; actionType?: string };
className?: string;
/** Override context for this specific action */
context?: Record<string, any>;
[key: string]: any;
}
const ActionButtonRenderer = forwardRef<HTMLButtonElement, ActionButtonProps>(
({ schema, className, context: localContext, ...props }, ref) => {
const {
'data-obj-id': dataObjId,
'data-obj-type': dataObjType,
style,
data,
...rest
} = props;
const { execute } = useAction();
const [loading, setLoading] = useState(false);
// Record data may be passed from SchemaRenderer (e.g. DetailView passes record data)
const recordData = data != null && typeof data === 'object' ? data as Record<string, any> : {};
// Evaluate visibility and disabled conditions with record data context.
// `visible` fails CLOSED on a throwing predicate (mirrors ActionEngine's
// getActionsForLocation) — a precondition that can't be evaluated should
// hide the action, not silently show one whose guard is broken.
const isVisible = useCondition(toPredicateInput(schema.visible), recordData, {
throwOnError: true,
label: `action "${schema.name ?? schema.label ?? 'action:button'}" (visible)`,
});
// Spec field is `disabled` (boolean | CEL predicate — disabled when TRUE).
// It previously had zero consumers (the renderer only read a non-spec
// `enabled`), so a spec-authored `disabled` guard did nothing (#1885,
// ADR-0049). We now consume `disabled` as the primary control and keep the
// legacy non-spec `enabled` as a deprecated fallback so existing metadata
// keeps working.
const isDisabled = useCondition(toPredicateInput((schema as any).disabled), recordData);
const isEnabled = useCondition(toPredicateInput(schema.enabled), recordData);
// Resolve icon
const Icon = resolveIcon(schema.icon);
// Map schema variant to Shadcn button variant
const variant = schema.variant === 'primary' ? 'default' : (schema.variant || 'default');
const size = schema.size === 'md' ? 'default' : (schema.size || 'default');
const handleClick = useCallback(async () => {
if (loading) return;
setLoading(true);
try {
// Route params correctly:
// - Array of objects with name+type → ActionParamDef[] → pass as actionParams for collection
// - Otherwise → pass as actual param values
const paramsPayload = Array.isArray(schema.params)
? { actionParams: schema.params as any }
: { params: schema.params as Record<string, any> | undefined };
await execute({
type: schema.actionType || schema.type,
name: schema.name,
// Forward the human label/description so a param-collection dialog
// can title itself as the action ("Create Environment") instead of a
// generic "Action parameters" prompt.
label: schema.label,
description: (schema as any).description,
target: schema.target,
// Static "open in new tab" switch for url actions — forward so the
// runner's executeUrl honors it (dropped, the toggle is silently lost).
openIn: (schema as any).openIn,
endpoint: schema.endpoint,
method: schema.method,
...paramsPayload,
confirmText: schema.confirmText,
successMessage: schema.successMessage,
errorMessage: schema.errorMessage,
refreshAfter: schema.refreshAfter,
// Forward `undoable` (and the row id field) so update actions can
// offer an Undo affordance — without this the flag is dropped and the
// handler never builds the undo operation.
undoable: (schema as any).undoable,
recordIdField: (schema as any).recordIdField,
// Forward the placement declaration — the console runtime uses it to
// tell record-scoped actions (also mounted on rows) from pure
// object-level toolbar actions when no row is selected (#2210).
locations: (schema as any).locations,
toast: schema.toast,
// One-shot reveal dialog for actions whose response is shown
// exactly once (2FA setup, OAuth client_secret, regenerated
// backup codes). Without this forward the ActionRunner falls
// back to the success toast and the user loses the value.
resultDialog: (schema as any).resultDialog,
...localContext,
});
} finally {
setLoading(false);
}
}, [schema, execute, loading, localContext]);
// Client-side auto-trigger (#844): a caller (e.g. a welcome-page CTA that
// deep-links into "create") can mark an action `autoTrigger: true` to run
// it once as soon as the button mounts — the exact same execute path as a
// click, so param dialogs / confirms / entitlement gates all still apply.
// NOT persisted metadata: the flag only exists on client-composed schemas.
// The ref guards re-fires across re-renders; the flag flipping true later
// (state-dependent toolbars) still triggers exactly once.
const autoTriggered = useRef(false);
const autoTrigger = (schema as any).autoTrigger === true;
useEffect(() => {
if (!autoTrigger || autoTriggered.current) return;
autoTriggered.current = true;
void handleClick();
// handleClick identity changes with schema/context churn; the ref makes
// this once-only regardless, so it's safe to depend on it.
}, [autoTrigger, handleClick]);
if (schema.visible && !isVisible) return null;
return (
<Button
ref={ref}
type="button"
variant={variant as any}
size={size as any}
className={cn(schema.className, className)}
disabled={(
(schema as any).disabled != null
? isDisabled
: schema.enabled != null
? !isEnabled
: false
) || loading}
onClick={handleClick}
{...rest}
{...{ 'data-obj-id': dataObjId, 'data-obj-type': dataObjType, style }}
>
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{!loading && Icon && <Icon className={cn('h-4 w-4', schema.label && 'mr-2')} />}
{schema.label}
</Button>
);
},
);
ActionButtonRenderer.displayName = 'ActionButtonRenderer';
ComponentRegistry.register('button', ActionButtonRenderer, {
namespace: 'action',
skipFallback: true,
label: 'Action Button',
inputs: [
{ name: 'name', type: 'string', label: 'Action Name' },
{ name: 'label', type: 'string', label: 'Label', defaultValue: 'Action' },
{ name: 'icon', type: 'string', label: 'Icon' },
{
name: 'type',
type: 'enum',
label: 'Action Type',
enum: ['script', 'url', 'modal', 'flow', 'api'],
defaultValue: 'script',
},
{ name: 'target', type: 'string', label: 'Target' },
{
name: 'variant',
type: 'enum',
label: 'Variant',
enum: ['default', 'primary', 'secondary', 'destructive', 'outline', 'ghost'],
defaultValue: 'default',
},
{
name: 'size',
type: 'enum',
label: 'Size',
enum: ['sm', 'md', 'lg'],
defaultValue: 'md',
},
{ name: 'className', type: 'string', label: 'CSS Class', advanced: true },
],
defaultProps: {
label: 'Action',
type: 'script',
variant: 'default',
size: 'md',
},
});