Repository navigation
Expand file tree
/
Copy pathViewConfigPanel.tsx
More file actions
578 lines (558 loc) · 27.4 KB
/
Copy pathViewConfigPanel.tsx
File metadata and controls
578 lines (558 loc) · 27.4 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
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
/**
* ViewConfigPanel — the runtime ObjectView's right-rail "view editor".
*
* MIGRATED: this panel now hosts the studio's spec-driven
* {@link ViewVariantInspector} instead of the legacy `buildViewConfigSchema`
* engine, so the runtime and the metadata studio share ONE inspector. The
* inspector renders the per-view-type config fields straight from
* `@objectstack/spec` (grid / kanban / calendar / gallery / …) plus the
* shared column / filter / sort / toolbar sections.
*
* The runtime ObjectView keeps the active view as a FLAT NamedListView; the
* inspector authors a canonical ViewItem draft. {@link view-config-adapter}
* bridges the two shapes so the `sys_view` persistence path is untouched:
* edits live as a ViewItem draft while the panel is open, then flatten back
* to the runtime view shape on update / save / create.
*
* Field loading is network-free: `objectDef.fields` is mapped into the
* inspector's `objectFieldsOverride` so neither the inspector nor its
* column editor issue a `client.get('object', …)` request.
*
* objectstack#35054 (route D) — an edit of a stored view edits the view as its
* author STORED it, never the view as it is served. `activeView` comes from the
* served view list, which the server translates for the console's
* Accept-Language (a view's `label`, a form's section titles), and the save
* door stores a view body verbatim, so a Save seeded from it stored the
* translations as the view's source text. With a metadata client the buffer is
* the layered read's authored document (`authoredBuffer`, the reading the
* Studio editors share): the stored pending draft, else the published view.
* The served draft read only says whether a draft is pending; a pending draft
* whose stored copy the layers do not serve opens no editor. ⛔ Never seed from
* the served copy instead. The draft bar no longer resumes its (served,
* translated) draft into the inspector: the host seeds the stored one.
*/
import { useMemo, useEffect, useRef, useCallback, useState } from 'react';
import { Button } from '@object-ui/components';
import { useObjectTranslation } from '@object-ui/i18n';
import { ViewVariantInspector } from './metadata-admin/inspectors/ViewVariantInspector.js';
import { RuntimeDraftBar } from './RuntimeDraftBar.js';
import { isFormFamilyKey } from './metadata-admin/view-variant-model.js';
import { useMetadataLocale, t as tStudio, tFormat } from './metadata-admin/i18n.js';
import { authoredBuffer, formatMetadataError, type AuthoredLayers } from '@object-ui/data-objectstack';
import { unwrapDraftBody } from './runtime-metadata-persistence.js';
import { draftPinOf, useDraftSaveGuard, type DraftPin, type DraftVersionGuard } from './metadata-admin/DraftConflictDialog.js';
import { isSameOptionsValue } from './objectViewOptions.js';
import { declaredFieldOptions, type ObjectFieldInfo } from './metadata-admin/previews/useObjectFields.js';
import {
runtimeViewToInspectorDraft,
inspectorDraftToRuntimeView,
storedViewToRuntimeView,
type InspectorViewDraft,
type RuntimeView,
} from './view-config-adapter.js';
/** Editor panel types that can be opened from clickable rows */
export type EditorPanelType = 'columns' | 'filter' | 'sort';
export interface ViewConfigPanelProps {
/** Whether the panel is open */
open: boolean;
/** Close callback */
onClose: () => void;
/** Panel mode: "edit" for existing views, "create" for new views */
mode?: 'create' | 'edit';
/** The active view definition */
activeView: {
id: string;
label?: string;
type?: string;
columns?: string[];
filter?: any[];
sort?: any[];
description?: string;
[key: string]: any;
};
/** The object definition */
objectDef: {
name: string;
label?: string;
description?: string;
fields?: Record<string, any>;
[key: string]: any;
};
/** Optional record count to display */
recordCount?: number;
/** Called when any view config field changes (local draft update) */
onViewUpdate?: (field: string, value: any) => void;
/**
* Called to persist all draft changes. Any return is accepted, as with the
* `void` this prop was typed with before objectui#11583; the panel awaits
* it and reads ONE refusal signal: `false` (returned, or resolved by a
* promise) or a rejection leaves the panel dirty, with no draft
* announced, so the edit can be saved again. Anything else, nothing
* included, is read as saved: the dirty state clears and the draft
* indicator is raised.
*
* Typed `unknown`, not a union naming the signal: against a union
* TypeScript checks the host's return type, and refuses hosts the `void`
* prop admitted (an `async` host that returns nothing, one resolving to a
* record, a sync non-void return). The contract review of objectui#11583
* measured that; `ViewConfigPanel.onSaveHosts-11583.test.ts` pins it.
*
* objectstack#36137 — `saveDraft` is this panel's draft-version guard,
* holding the pin of the draft the panel loaded (`If-Match`, or
* `If-None-Match: *` over no draft): a host that writes through it gets a
* refused save asked about in the panel (reload the saved version,
* overwrite it, or keep editing) instead of overwriting a draft saved
* since. It resolves `'reloaded'` when the author chose the saved version.
*/
onSave?: (draft: Record<string, any>, saveDraft?: DraftVersionGuard['save']) => unknown;
/** Called when create-mode view is created */
onCreate?: (config: Record<string, any>) => void;
/**
* Studio metadata client — drives saves and the ADR-0034 draft/publish
* chrome ({@link RuntimeDraftBar}).
*/
metadataClient?: any;
/**
* The DataSource whose view caches a publish / discard from this panel
* stales (objectui#4373). Forwarded to {@link RuntimeDraftBar}; the object
* half of the cache keys comes from `objectDef.name`, so nothing here has
* to know what those keys are.
*/
dataSource?: any;
/** Called after a publish / discard so the host can refresh its read. */
onAfterChange?: () => void;
/**
* objectstack#35974 — the view is one the server refuses to save (a view
* a read-only package ships): the panel shows its configuration with
* every control disabled, relays no edit to the host, and offers no Save
* and no draft publish or discard, only Close.
*/
readOnly?: boolean;
}
/**
* objectstack#35054 — the authored view an edit-mode panel edits, read for one
* view id: still being read, read (the runtime shape of the stored body), or
* refused with the sentence the panel shows in place of the inspector.
*/
type AuthoredSeed =
| { for: string; state: 'loading' }
| { for: string; state: 'ready'; view: RuntimeView; pin: DraftPin | null }
| { for: string; state: 'refused'; message: string };
/**
* Map an Object definition's `fields` record into the inspector's flat field
* catalog so it can render field-reference pickers (columns, groupByField, …)
* without a network fetch.
*
* @internal exported for tests
*/
export function mapObjectFields(objectDef: ViewConfigPanelProps['objectDef']): ObjectFieldInfo[] {
const fields = objectDef.fields;
if (!fields || typeof fields !== 'object') return [];
return Object.entries(fields).map(([name, def]) => {
const f = (def ?? {}) as Record<string, any>;
const options = declaredFieldOptions(f);
return {
name,
label: typeof f.label === 'string' && f.label ? f.label : name,
type: typeof f.type === 'string' ? f.type : 'text',
hidden: f.hidden === true,
// The filter builder offers a list-valued column membership and
// the empty checks only (`operatorsForField`).
...(f.multiple === true ? { multiple: true } : {}),
// The filter builder draws a picklist column's value as a picker
// over its declared choices and stores the option's `value`.
...(options ? { options } : {}),
};
});
}
export function ViewConfigPanel({ open, onClose, mode = 'edit', activeView, objectDef, onViewUpdate, onSave, onCreate, metadataClient, dataSource, onAfterChange, readOnly = false }: ViewConfigPanelProps) {
const { t } = useObjectTranslation();
const panelRef = useRef<HTMLDivElement>(null);
const locale = useMetadataLocale();
// Provisional id for a create-mode view. A lazy useState initializer runs
// exactly once, keeping the impure `Date.now()` out of render; the backend
// assigns the real `name` on create, so this only needs to be unique
// within the draft.
const [newViewId] = useState(() => `view_${Date.now()}`);
// Default empty view used to seed create mode.
const defaultNewView = useMemo<RuntimeView>(() => ({
id: newViewId,
label: t('console.objectView.newView'),
type: 'grid',
columns: [],
filter: [],
sort: [],
}), []); // eslint-disable-line react-hooks/exhaustive-deps
// objectstack#35054 — an edit with a metadata client edits the stored
// view (module header). Read on every open, and again after a publish or a
// discard from the draft bar, which change what is stored.
const readsAuthored = mode === 'edit' && !!metadataClient && !!activeView.id;
const [seed, setSeed] = useState<AuthoredSeed | null>(null);
const [authoredReads, setAuthoredReads] = useState(0);
// A publish or a discard from the draft bar changes what is stored, and so
// does a conflict the author resolves by taking the saved version: the
// buffer is read again (objectstack#35054), then the host refreshes.
const handleAfterChange = useCallback(() => {
setAuthoredReads((n) => n + 1);
onAfterChange?.();
}, [onAfterChange]);
// objectstack#37648 — a refused save resolved with "reload" re-reads the
// stored view into the buffer (`handleAfterChange`); the draft that read
// finds is the one the draft bar now shows, so the read hands the bar its
// version (`reloadedDraft`) and the bar's Publish is pinned to it.
const conflictReloadRef = useRef(false);
const [reloadedDraft, setReloadedDraft] = useState<{ signal: number; version?: string; hasDraft: boolean }>({
signal: 0,
hasDraft: false,
});
const handleConflictReload = useCallback(() => {
conflictReloadRef.current = true;
handleAfterChange();
}, [handleAfterChange]);
// objectstack#36137 — the draft-version guard of this panel's buffer
// (`useDraftSaveGuard`): the pin of the draft it was loaded from, then of
// each save it sent, and the conflict dialog a refused save opens.
const {
save: saveDraftVersioned,
recordRead: recordDraftRead,
forget: forgetDraftVersion,
heldDraftVersion,
dialog: draftConflictDialog,
} = useDraftSaveGuard(metadataClient, handleConflictReload);
useEffect(() => {
if (!open || !readsAuthored) return;
const id = activeView.id;
let cancelled = false;
setSeed({ for: id, state: 'loading' });
(async () => {
let next: AuthoredSeed;
let foundDraft = false;
try {
// objectstack#36137 — the served draft read is the envelope, so
// its `version` pins this buffer's saves (`draftPinOf`), at the
// address they write: no package, as the save names none.
const [layers, draftAnswer] = await Promise.all([
metadataClient.layered('view', id),
metadataClient.getDraft('view', id),
]);
const servedDraft = unwrapDraftBody(draftAnswer);
foundDraft = servedDraft !== null;
const authored = authoredBuffer('view', layers as AuthoredLayers, servedDraft);
if (authored.kind === 'unserved') {
next = { for: id, state: 'refused', message: tStudio('engine.studio.refusal.draftUnreadable', locale) };
} else if (Object.keys(authored.body).length === 0) {
next = {
for: id,
state: 'refused',
message: tFormat('engine.edit.loadFailed', locale, {
type: 'view',
name: id,
message: tStudio('engine.form.notFound', locale),
}),
};
} else {
// The stored body is a ViewItem envelope or a flat view;
// its identity is the view the panel was opened on.
next = {
for: id,
state: 'ready',
view: { ...storedViewToRuntimeView(authored.body), id },
pin: draftPinOf(draftAnswer),
};
}
} catch (err) {
next = {
for: id,
state: 'refused',
message: tFormat('engine.edit.loadFailed', locale, { type: 'view', name: id, message: formatMetadataError(err) }),
};
}
if (cancelled) return;
// The buffer is installed from this read: its pin is the one the
// next save sends; a read that installs none leaves nothing held.
if (next.state === 'ready') recordDraftRead('view', id, null, next.pin);
else forgetDraftVersion();
// objectstack#37648 — this read answers a conflict's "reload": the
// draft bar takes the draft it found. A read that could not
// install a buffer hands the bar nothing, so its Publish stays
// pinned to the draft it showed and is refused, never unpinned.
if (conflictReloadRef.current) {
conflictReloadRef.current = false;
if (next.state === 'ready') {
const pin = next.pin;
setReloadedDraft((prev) => ({
signal: prev.signal + 1,
version: pin && 'ifMatch' in pin ? pin.ifMatch : undefined,
hasDraft: foundDraft,
}));
}
}
setSeed(next);
})();
return () => { cancelled = true; };
}, [open, readsAuthored, activeView.id, metadataClient, authoredReads]); // eslint-disable-line react-hooks/exhaustive-deps
const seedFor = readsAuthored && seed?.for === activeView.id ? seed : null;
const authoredView = seedFor?.state === 'ready' ? seedFor.view : null;
// While the stored view is read, or when it cannot be, there is no buffer:
// nothing is shown to edit and nothing can be saved.
const awaitingAuthored = readsAuthored && !authoredView;
// Inspector draft state. Rebuilt only when the source view ID (or create
// mode) changes, or the stored view arrives — not on every parent
// re-render — so in-flight edits are not clobbered (same stabilization the
// legacy panel used with stableKey).
const stableKey = mode === 'create' ? 'create' : activeView.id;
// The view as the host previews it when the panel opened: what Discard
// replays to the host's live list (the host's copy is the served one).
const openingDraft = useMemo<InspectorViewDraft>(
() => runtimeViewToInspectorDraft(
mode === 'create' ? defaultNewView : (activeView as RuntimeView),
objectDef.name,
),
[stableKey, objectDef.name], // eslint-disable-line react-hooks/exhaustive-deps
);
// The buffer the inspector edits and Save sends: the stored view when one
// was read (objectstack#35054), else the opening view (create mode, or a
// host with no metadata client, which saves nothing).
const initialDraft = useMemo<InspectorViewDraft>(
() => (authoredView ? runtimeViewToInspectorDraft(authoredView, objectDef.name) : openingDraft),
[authoredView, openingDraft, objectDef.name],
);
const [draft, setDraft] = useState<InspectorViewDraft>(initialDraft);
const [isDirty, setIsDirty] = useState(false);
// Bumped on each edit-mode save that lands, so the draft/publish chrome
// surfaces the "unpublished changes" indicator immediately (the save
// wrote a draft). Never on a refused one (objectui#11583).
const [savedSignal, setSavedSignal] = useState(0);
// objectstack#36350 — the version the landed save's receipt returned (the
// guard holds it as that save's `If-Match`): the draft bar's Publish after
// this save is pinned to it, so a draft another writer changed since is
// refused instead of published on their behalf.
const [savedDraftVersion, setSavedDraftVersion] = useState<string | undefined>(undefined);
// An edit-mode save is in flight: Save is disabled until it settles.
const [saving, setSaving] = useState(false);
// Mirror the committed draft into a ref so `handlePatch` can compute the
// next draft synchronously without a side-effecting state updater.
const draftRef = useRef(draft);
// Reset the draft when the source view changes — derived from `initialDraft`
// during render (React's "adjust state on prop change" pattern) rather than
// in an effect, so there's no extra render pass.
const lastDraftRef = useRef(initialDraft);
// The fields an edit has relayed to the host's live list (`handlePatch`).
const relayedRef = useRef<Set<string>>(new Set());
if (lastDraftRef.current !== initialDraft) {
lastDraftRef.current = initialDraft;
draftRef.current = initialDraft;
relayedRef.current = new Set();
setDraft(initialDraft);
setIsDirty(false);
}
useEffect(() => { draftRef.current = draft; }, [draft]);
// Focus the panel when it opens for keyboard accessibility.
useEffect(() => {
if (open && panelRef.current) {
panelRef.current.focus();
}
}, [open]);
// Network-free field catalog sourced from the object definition the host
// already holds.
const objectFields = useMemo(() => mapObjectFields(objectDef), [objectDef.fields]); // eslint-disable-line react-hooks/exhaustive-deps
const familyKey = isFormFamilyKey(draft.viewKind) ? 'form' : 'list';
// Shallow-merge an inspector patch into the draft, then mirror the
// flattened runtime view back to the host field-by-field (matching the
// legacy onViewUpdate(field, value) contract ObjectView expects).
//
// objectstack#35054: only the fields the admin changed, compared by content
// with the buffer the panel opened (and any field relayed before, so a
// change back reaches the list too). The buffer is the STORED view while
// the host previews the SERVED one, which carries what the stored view
// does not: the translation, and the columns the host draws into a view
// that declares none (objectui#10694 judges a draft's `columns` against
// those). Relaying an untouched stored field would present it as an edit.
const handlePatch = useCallback((patch: Record<string, unknown>) => {
// A read-only view takes no edit, whichever control would have sent one.
if (readOnly) return;
const next: InspectorViewDraft = { ...draftRef.current, ...(patch as Partial<InspectorViewDraft>) };
draftRef.current = next;
setDraft(next);
setIsDirty(true);
if (onViewUpdate) {
const flat = inspectorDraftToRuntimeView(next);
const opened = inspectorDraftToRuntimeView(lastDraftRef.current) as Record<string, unknown>;
for (const [field, value] of Object.entries(flat)) {
if (field === 'id') continue;
if (!relayedRef.current.has(field) && isSameOptionsValue(value, opened[field])) continue;
relayedRef.current.add(field);
onViewUpdate(field, value);
}
}
}, [onViewUpdate, readOnly]);
const handleSave = useCallback(async () => {
const flat = inspectorDraftToRuntimeView(draft);
if (mode === 'create') {
onCreate?.(flat);
setIsDirty(false);
return;
}
// objectui#11583: the edit is reported as saved only once the host
// says it landed. A refused save keeps the panel dirty, so Save stays
// live and no draft is announced. An edit made while the save is in
// flight is not in it, so it keeps the panel dirty either way.
const savedDraft = draftRef.current;
setSaving(true);
let landed: boolean;
try {
landed = (await onSave?.(flat, saveDraftVersioned)) !== false;
} catch {
landed = false;
} finally {
setSaving(false);
}
if (!landed) return;
setSavedDraftVersion(heldDraftVersion('view', String(flat.id ?? activeView.id)));
setSavedSignal((s) => s + 1);
if (draftRef.current === savedDraft) setIsDirty(false);
}, [draft, onSave, onCreate, mode, saveDraftVersioned, heldDraftVersion, activeView.id]);
// Discard = revert any unsaved edits AND close the panel, in both modes
// (objectui#2320). Create mode has no committed view to preview against, so
// there's nothing to revert on the host — just close (matching prior
// behavior). Edit mode also restores the host's live list preview: edits
// reach the list only through `onViewUpdate` (see `handlePatch`), so we
// replay the panel's opening values — and clear any keys the edits
// introduced — through the same seam, then reset the local draft.
const revertEdits = useCallback(() => {
if (onViewUpdate) {
const original = inspectorDraftToRuntimeView(openingDraft);
const edited = inspectorDraftToRuntimeView(draftRef.current);
const fields = new Set([...Object.keys(edited), ...Object.keys(original)]);
for (const field of fields) {
if (field === 'id') continue;
onViewUpdate(field, original[field]);
}
}
draftRef.current = initialDraft;
relayedRef.current = new Set();
setDraft(initialDraft);
setIsDirty(false);
}, [initialDraft, openingDraft, onViewUpdate]);
const handleDiscard = useCallback(() => {
if (mode === 'edit') revertEdits();
onClose();
}, [mode, onClose, revertEdits]);
// objectstack#35974 — the host's read-only verdict can land after the
// panel opened editable (the package list was still being read) and after
// an edit. A read-only panel offers no Discard, so the edit would be
// stranded on the host's list and shown here in place of the stored view.
// It is discarded instead, the panel staying open.
const wasReadOnlyRef = useRef(readOnly);
useEffect(() => {
const turnedReadOnly = readOnly && !wasReadOnlyRef.current;
wasReadOnlyRef.current = readOnly;
if (turnedReadOnly && mode === 'edit' && (isDirty || relayedRef.current.size > 0)) revertEdits();
}, [readOnly, mode, isDirty, revertEdits]);
const panelTitle = mode === 'create'
? t('console.objectView.createView')
: t('console.objectView.configureView');
if (!open) {
// Keep the slide container (owned by ObjectView) able to collapse to
// zero width without rendering inspector internals while hidden.
//
// objectstack#36137 — the conflict dialog is rendered here too: a
// save still in flight when the panel closes (Discard, another view
// tab) can be refused after it closed, and the guard then waits on
// the author's choice. Without the dialog nothing would answer it,
// and Save would stay disabled. It portals out of this hidden div.
return (
<div ref={panelRef} tabIndex={-1} data-testid="view-config-panel" aria-hidden>
{draftConflictDialog}
</div>
);
}
return (
<div
ref={panelRef}
tabIndex={-1}
role="complementary"
aria-label={panelTitle}
data-testid="view-config-panel"
className="flex h-full flex-col"
>
<div className="min-h-0 flex-1 overflow-auto">
{awaitingAuthored ? (
seedFor?.state === 'refused' ? (
<p role="alert" data-testid="view-config-authored-refused" className="p-4 text-sm text-destructive">
{seedFor.message}
</p>
) : (
<p data-testid="view-config-authored-loading" className="p-4 text-sm text-muted-foreground">
{tStudio('engine.form.loadingEditor', locale)}
</p>
)
) : (
<ViewVariantInspector
type="view"
name={draft.name}
draft={draft as unknown as Record<string, unknown>}
variantKey="config"
familyKey={familyKey}
isHome
readOnly={readOnly}
locale={locale}
objectFieldsOverride={objectFields}
onPatch={handlePatch}
/>
)}
</div>
<div
data-testid="view-config-footer"
className="flex items-center justify-end gap-2 border-t px-4 py-2.5"
>
{mode === 'edit' && !readOnly && (
<RuntimeDraftBar
type="view"
name={activeView.id}
metadataClient={metadataClient}
dataSource={dataSource}
objectName={objectDef.name}
dirty={isDirty}
savedSignal={savedSignal}
savedDraftVersion={savedDraftVersion}
reloadedSignal={reloadedDraft.signal}
reloadedDraftVersion={reloadedDraft.version}
reloadedHasDraft={reloadedDraft.hasDraft}
onAfterChange={handleAfterChange}
/>
)}
{readOnly ? (
<Button
variant="ghost"
size="sm"
onClick={onClose}
data-testid="view-config-close"
>
{t('common.close')}
</Button>
) : (
<>
<Button
variant="ghost"
size="sm"
onClick={handleDiscard}
data-testid="view-config-discard"
>
{t('console.objectView.discard')}
</Button>
<Button
size="sm"
onClick={handleSave}
disabled={saving || awaitingAuthored || (mode === 'edit' && !isDirty)}
data-testid="view-config-save"
>
{t('console.objectView.save')}
</Button>
</>
)}
</div>
{draftConflictDialog}
</div>
);
}