File size: 12,631 Bytes
fb62a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdfb5de
 
 
 
fb62a97
 
 
 
 
 
 
 
cdfb5de
 
fb62a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Alert, Anchor, Button, Code, CopyButton, Group, Pagination, Popover, Text, Tooltip } from '@mantine/core';
import { IconCheck, IconCopy, IconHelp, IconPlus, IconRobot, IconShieldLock } from '@/components/icons';
import type { ReactNode } from 'react';
import { Link } from 'react-router-dom';
import { explainError, supportDetails } from '../api/errors';
import { useAuth } from '../auth/AuthContext';
import { decisionWords, GLOSSARY, RUN_STATUS_WORDS } from '../domain/glossary';
import { TextBlurReveal } from './wensity/text-blur-reveal';

export const MOCK_TEXT = 'Mock app, not Oracle Fusion';

export function MockBanner({ fusion = false }: { fusion?: boolean }) {
  return (
    <div role="note" aria-label="target system" data-testid="mock-banner" className="fpt-mock"
      title={fusion ? 'Runs target either the practice app or a connected Oracle Fusion test pod; every run says which.'
        : 'Every test run targets the local mock app. Results say nothing about a real Oracle Fusion pod.'}>
      <IconShieldLock size={13} aria-hidden />
      <span>{fusion ? 'Test environments: the practice app and Oracle Fusion pods' : `Practice environment: ${MOCK_TEXT}`}</span>
    </div>
  );
}

export type Tone = 'neutral' | 'mint' | 'lav' | 'amber' | 'red' | 'green' | 'ink';

/** Small rounded tag (date, tier, status), the design's basic unit. Tones are AA-contrast pairs from styles.css. */
export function Pill({ tone = 'neutral', icon, children, testId, title, outline }: { tone?: Tone | string; icon?: ReactNode; children: ReactNode; testId?: string; title?: string; outline?: boolean }) {
  return <span className="fpt-pill" data-tone={tone} data-outline={outline || undefined} data-testid={testId} title={title}>{icon}{children}</span>;
}

/** "Written by the AI model" as dim text with a robot icon (not a coloured pill). */
export function AiText({ children = 'Written by the AI model' }: { children?: ReactNode }) {
  return <span className="fpt-aitext"><IconRobot size={14} aria-hidden />{children}</span>;
}

/** A priority word ("Critical") as plain 600-weight text: priority is not a state to act on. */
export function Prio({ words }: { words: string }) {
  return <span className="fpt-prio">{words}</span>;
}

/** Page header: the page's large heading, a back link on detail pages, its one-line description (`extra`) and actions
 * (`children`). The top navigation is on every screen size, so a page draws no toolbar of its own; `bar` (a short title
 * for one) is kept for callers. */
export function PageHeader({ crumbs, title, children, extra, eyebrow }: { crumbs: { label: string; to?: string }[]; title: ReactNode; children?: ReactNode; extra?: ReactNode; bar?: string; eyebrow?: ReactNode }) {
  const trail = crumbs.filter((c) => c.to);
  // detail pages (three or more crumbs) get a back link to their parent; top-level pages have none
  const last = trail[trail.length - 1];
  const back = crumbs.length >= 3 && last ? (last.label === 'Home' ? { label: 'Settings', to: '/admin' } : { label: last.label, to: last.to! }) : undefined;
  return (
    <>
      <div className="trio-head">
        <div className="trio-head-text">
          {back && <Link to={back.to} className="trio-eyebrow" aria-label={`Back to ${back.label}`}>← {back.label}</Link>}
          {!back && eyebrow && <span className="trio-eyebrow">{eyebrow}</span>}
          {/* the title blurs in word by word (Wensity UI); the full title stays its accessible name */}
          {typeof title === 'string' ? <TextBlurReveal as="h1" text={title} startOnView={false} delay={70} className="trio-h1" /> : <h1>{title}</h1>}
          {extra && <div className="trio-lede">{extra}</div>}
        </div>
        {children && <div className="trio-head-actions">{children}</div>}
      </div>
    </>
  );
}

const STATUS_TONE: Record<string, Tone> = {
  queued: 'neutral', running: 'ink', waiting_approval: 'amber', waiting_sign_in: 'amber', waiting_review: 'amber', completed: 'green', failed: 'red',
  killed: 'red', cancelled: 'neutral', interrupted: 'amber', pending: 'neutral', approved: 'green', rejected: 'red', staged: 'ink',
  promoted: 'green', discarded: 'neutral', no_snapshot: 'neutral', no_candidate: 'neutral', open: 'red',
};
const STATUS_LABEL: Record<string, string> = RUN_STATUS_WORDS;


export function StatusBadge({ status }: { status?: string | null }) {
  if (!status) return <Pill>-</Pill>;
  return <Pill tone={STATUS_TONE[status] ?? 'neutral'} testId={`status-${status}`}>{STATUS_LABEL[status] ?? status.replace(/_/g, ' ')}</Pill>;
}

/** Decision in consultant words ("Ready" / "Not ready" / "On hold"); the exact rule result stays on the element
 * (data-rule) and in the tooltip, and RuleResult shows it in reports for audit. */
export function DecisionBadge({ decision, size = 'md' }: { decision?: string | null; size?: 'sm' | 'md' | 'lg' | 'xl' }) {
  if (!decision) return <span className="fpt-dchip" data-tone="neutral" data-size={size}>Not decided yet</span>;
  const tone = decision === 'GO' ? 'green' : decision === 'HELD' ? 'amber' : 'red';
  // the text content is exactly the verdict words: the dot carries no text
  return (
    <Tooltip label="Decided by the QA rule from this test run's results. The exact rule result is under Audit details in the report.">
      <span className="fpt-dchip" data-tone={tone} data-size={size} data-testid="decision-badge" data-rule={decision}><span className="fpt-dchip-dot" aria-hidden />{decisionWords(decision)}</span>
    </Tooltip>
  );
}

/** The exact go/no-go rule result, for audit. */
export function RuleResult({ decision }: { decision?: string | null }) {
  return <span className="fpt-ruleresult" data-testid="rule-result" title="exact result of the QA rule (C1-C6)">Rule result: {decision ?? 'none'}</span>;
}

/** A consultant word with its meaning (and the technical term) on hover/focus. */
export function Term({ children, k, plain }: { children: ReactNode; k?: string; plain?: boolean }) {
  const g = GLOSSARY.find((x) => x.term.toLowerCase() === String(k ?? children).toLowerCase());
  if (!g) return <>{children}</>;
  return (
    <Tooltip label={`${g.means} (technical name: ${g.technical})`} multiline w={300} withArrow>
      <span tabIndex={0} style={plain ? { cursor: 'help' } : { borderBottom: '1px dotted currentColor', cursor: 'help' }}>{children}</span>
    </Tooltip>
  );
}

/** The words of the app with their meaning and technical name, plus the keyboard keys. */
export function GlossaryList() {
  return (
    <>
      <dl style={{ margin: 0, display: 'grid', gridTemplateColumns: 'auto 1fr', gap: '6px 10px', fontSize: 12 }}>
        {GLOSSARY.map((g) => (
          <div key={g.term} style={{ display: 'contents' }}>
            <dt style={{ fontWeight: 600 }}>{g.term}</dt>
            <dd style={{ margin: 0 }}>{g.means} <span style={{ color: 'var(--fpt-dim)' }}>({g.technical})</span></dd>
          </div>
        ))}
      </dl>
      <Text size="xs" c="dimmed" mt={10} style={{ borderTop: '1px solid var(--fpt-border)', paddingTop: 8 }}>
        Keys: <kbd className="fpt-kbd">N</kbd> new test run · <kbd className="fpt-kbd">Ctrl K</kbd> search, go to a page or ask · <kbd className="fpt-kbd">[</kbd> hide the sidebar ·{' '}
        <kbd className="fpt-kbd">?</kbd> all shortcuts · on a test run <kbd className="fpt-kbd">Alt 1</kbd> the steps, <kbd className="fpt-kbd">Alt 3</kbd> the details panel,{' '}
        <kbd className="fpt-kbd">Ctrl \</kbd> show or hide the details panel.
      </Text>
    </>
  );
}

export function GlossaryButton() {
  return (
    <Popover width={420} position="bottom-end" withArrow shadow="md">
      <Popover.Target>
        <button type="button" className="fpt-iconbtn" aria-label="Glossary: what do these words mean?"><IconHelp size={14} /></button>
      </Popover.Target>
      <Popover.Dropdown>
        <Text fw={600} size="sm" mb={6}>Words used in this app</Text>
        <GlossaryList />
      </Popover.Dropdown>
    </Popover>
  );
}

/** An error in plain words: what happened, the fields to fix, what to do (or a link that helps), and a small
 * "Copy details for support" control that holds the code and request id. */
export function ErrorAlert({ error, title = 'That did not work', hint, onRetry }: { error: unknown; title?: string; hint?: string; onRetry?: () => void }) {
  if (!error) return null;
  const i = explainError(error);
  return (
    <Alert color="red" title={title} role="alert" data-testid="error-alert" data-code={i.code}>
      <Text size="sm">{i.message}</Text>
      {i.fields && i.fields.length > 0 && (
        <ul className="fpt-errfields" data-testid="error-fields">{i.fields.map((f, n) => <li key={n}><b>{f.field}:</b> {f.message}</li>)}</ul>
      )}
      {(hint ?? i.hint) && <Text size="sm" mt={4}>{hint ?? i.hint}</Text>}
      <Group gap={12} mt={6} wrap="wrap">
        {onRetry && <Button size="compact-sm" variant="default" onClick={onRetry} data-testid="error-retry">Try again</Button>}
        {i.action &&<Anchor component={Link} to={i.action.to} size="sm" fw={600}>{i.action.label}</Anchor>}
        <CopyButton value={supportDetails(i)} timeout={2000}>
          {({ copied, copy }) => (
            <button type="button" className="fpt-linkbtn fpt-errcopy" onClick={copy} title={i.requestId ? `Request id ${i.requestId}` : undefined}>
              {copied ? <IconCheck size={12} aria-hidden /> : <IconCopy size={12} aria-hidden />}{copied ? 'Copied' : 'Copy details for support'}
            </button>
          )}
        </CopyButton>
      </Group>
    </Alert>
  );
}

export function Pre({ children, maxHeight = 360 }: { children: ReactNode; maxHeight?: number }) {
  return <Code block style={{ maxHeight, overflow: 'auto', whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>{children}</Code>;
}

export function Diff({ text }: { text: string }) {
  return (
    <pre aria-label="diff" style={{ maxHeight: 360, overflow: 'auto', fontSize: 12, margin: 0, padding: 8, background: 'var(--mantine-color-default-hover)', borderRadius: 4 }}>
      {text.split('\n').map((l, i) => (
        <div key={i} style={{ color: l.startsWith('+') && !l.startsWith('+++') ? 'var(--mantine-color-teal-7)' : l.startsWith('-') && !l.startsWith('---') ? 'var(--mantine-color-red-7)' : undefined }}>{l || ' '}</div>
      ))}
    </pre>
  );
}

const PAGER_WORDS = { first: 'First page', previous: 'Previous page', next: 'Next page', last: 'Last page' } as const;

export function Pager({ total, limit, offset, onChange }: { total: number; limit: number; offset: number; onChange: (offset: number) => void }) {
  const pages = Math.max(1, Math.ceil(total / limit));
  return (
    <Group justify="space-between" mt="sm">
      <Text size="sm" c="dimmed">{total} item(s)</Text>
      {pages > 1 && (
        <nav aria-label="Pagination">
          <Pagination total={pages} value={Math.floor(offset / limit) + 1} onChange={(p) => onChange((p - 1) * limit)} size="sm"
            getItemProps={(page) => ({ 'aria-label': `Page ${page} of ${pages}` })}
            getControlProps={(control) => ({ 'aria-label': PAGER_WORDS[control] })} />
        </nav>
      )}
    </Group>
  );
}

/** Why a viewer cannot start a test run, in one sentence (self-registered accounts start as viewers). */
export const VIEWER_START_WORDS = 'Your account can view results. Ask an administrator for consultant access to start test runs.';

/** "New test run" for people who may start one; for viewers the same button, switched off, with the reason on hover and focus. */
export function StartRunGate({ children, label = 'New test run' }: { children: ReactNode; label?: string }) {
  const { can, user } = useAuth();
  if (!user || can('run.start')) return <>{children}</>;
  return (
    <Tooltip label={VIEWER_START_WORDS} multiline w={280} withArrow>
      <span tabIndex={0} data-testid="start-run-locked" aria-label={`${label} is not available. ${VIEWER_START_WORDS}`}><Button variant="filled" disabled leftSection={<IconPlus size={14} />} style={{ pointerEvents: 'none' }}>{label}</Button></span>
    </Tooltip>
  );
}

/** Renders children only for users holding `perm` (the API enforces the same rule; this only hides controls). */
export function Can({ perm, children, fallback = null }: { perm: string; children: ReactNode; fallback?: ReactNode }) {
  const { can } = useAuth();
  return <>{can(perm) ? children : fallback}</>;
}

export const pct = (v: number | null | undefined) => (v === null || v === undefined ? '-' : `${(v * 100).toFixed(1)}%`);
export const fmtTs = (s?: string | null) => (s ? new Date(s).toLocaleString() : '-');