summaryrefslogtreecommitdiff
path: root/plugins/code-modernization/hooks/views/deck.tsx
blob: 53d42cb0a295605037e8bcf1a531509eda481146 (plain)
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
/* @jsxRuntime classic */
/* @jsx h */
/* @jsxFrag Fragment */
import type { RenderChildren, RenderElement } from 'claude-code'

import type { ReviewVerdict } from '../reader/progress'
import { tallyOf } from '../review/deck'
import type { DeckState, SignState } from '../state'
import type { Kit } from './pane'
import { BAD, GOOD, HEAD, WARN } from './palette'

export type DeckActions = {
  decide: (verdict: ReviewVerdict) => void
  undo: () => void
  prev: () => void
  next: () => void
  source: () => void
  close: () => void
}

const SCOPE_WORDS = { flagged: 'high-priority rules a person should check', p0: 'all high-priority rules', all: 'all rules' }
const SCOPE_SHORT = { flagged: 'flagged', p0: 'high-priority', all: 'all' }

const VERDICT_COLORS: Record<ReviewVerdict, string> = {
  confirmed: GOOD,
  wrong: BAD,
  discuss: WARN,
}

/** `text` word-wrapped to `width` cells, at most `maxLines` rows, the last ending in an ellipsis when cut. */
export function wrapLines(text: string, width: number, maxLines: number): string[] {
  const out: string[] = []
  const limit = Math.max(8, width)
  let line = ''

  const push = (value: string) => {
    out.push(value)
  }

  for (const word of text.split(/\s+/).filter(part => part !== '')) {
    let rest = word

    while (rest.length > limit) {
      if (line !== '') {
        push(line)
        line = ''
      }

      push(rest.slice(0, limit))
      rest = rest.slice(limit)
    }

    if (line === '') {
      line = rest
    } else if (line.length + 1 + rest.length <= limit) {
      line = `${line} ${rest}`
    } else {
      push(line)
      line = rest
    }
  }

  if (line !== '') {
    push(line)
  }

  if (out.length <= maxLines) {
    return out
  }

  const kept = out.slice(0, Math.max(1, maxLines))
  const last = kept[kept.length - 1] ?? ''

  kept[kept.length - 1] = `${last.slice(0, Math.max(0, limit - 1))}…`

  return kept
}

/**
 * The review deck's body: one rule card, its verdict, and the keys.
 *
 * It draws in the band above the prompt, where a bare digit presses a Button
 * from an empty composer. A tree taller than the band scrolls and disarms the
 * digits, so the card wraps its own text into counted rows and never exceeds
 * `maxRows`.
 */
export function deckView(
  kit: Kit,
  deck: DeckState,
  columns: number,
  maxRows: number,
  actions: DeckActions,
): RenderElement {
  const { Box, Text, Button, Code } = kit
  const width = Math.max(30, columns - 2)
  const rule = deck.queue[deck.index]
  const tally = tallyOf(deck.queue, deck.ledger)

  if (rule === undefined) {
    return (
      <Box flexDirection="column">
        <Text bold color={HEAD}>Rule review</Text>
        <Text dimColor wrap="truncate-end">
          {`Nothing to review among ${SCOPE_WORDS[deck.scope]}${deck.filter !== '' ? ` matching "${deck.filter}"` : ''}. Try /modernize-review-pane all.`}
        </Text>
        <Button key="close" hotkey="0" plain onPress={actions.close}>close</Button>
      </Box>
    )
  }

  const verdict = deck.ledger[rule.id]
  const first = rule.citations[0]
  const shownSource = deck.isSourceShown && deck.source !== null && deck.source.ruleId === rule.id ? deck.source : null

  const meta = [
    rule.domain,
    rule.category !== undefined && rule.category.toLowerCase() === rule.domain?.toLowerCase() ? undefined : rule.category,
    rule.confidence !== undefined ? `confidence ${rule.confidence}` : undefined,
    first !== undefined ? `${first.path.split('/').pop()}:${first.from}${first.to !== first.from ? `-${first.to}` : ''}` : undefined,
  ].filter((part): part is string => part !== undefined && part !== '')

  const keys = (
    <Box columnGap={2}>
      <Button key="confirm" hotkey="1" plain onPress={() => actions.decide('confirmed')}>confirm</Button>
      <Button key="wrong" hotkey="2" plain onPress={() => actions.decide('wrong')}>wrong</Button>
      <Button key="discuss" hotkey="3" plain onPress={() => actions.decide('discuss')}>discuss</Button>
      <Button key="prev" hotkey="4" plain onPress={actions.prev}>back</Button>
      <Button key="skip" hotkey="5" plain onPress={actions.next}>skip</Button>
      <Button key="source" hotkey="6" plain onPress={actions.source}>{deck.isSourceShown ? 'hide source' : 'source'}</Button>
      {verdict !== undefined ? <Button key="undo" hotkey="7" plain onPress={actions.undo}>undo</Button> : null}
      <Button key="close" hotkey="0" plain onPress={actions.close}>close</Button>
    </Box>
  )

  const verdictLine =
    verdict !== undefined ? (
      <Text color={VERDICT_COLORS[verdict.verdict]} bold>{`Your verdict: ${verdict.verdict} (${verdict.at.slice(0, 10)})`}</Text>
    ) : (
      <Text dimColor>Is this rule right? No verdict yet.</Text>
    )

  // The reviewer's own words, when they gave any (the review command records them): one line, cut short.
  const noteLine =
    verdict?.note !== undefined ? (
      <Text wrap="truncate-end">
        <Text dimColor>Note: </Text>
        <Text>{verdict.note}</Text>
      </Text>
    ) : null

  const noteRows = noteLine === null ? 0 : 1

  const headline = (
    <Text wrap="truncate-end">
      <Text bold color={HEAD}>Rule review</Text>
      <Text bold>{` ${deck.index + 1} of ${tally.total}`}</Text>
      <Text dimColor>{' · '}</Text>
      <Text color={GOOD}>{`${tally.confirmed} confirmed`}</Text>
      <Text dimColor>{' · '}</Text>
      <Text color={BAD}>{`${tally.wrong} wrong`}</Text>
      <Text dimColor>{' · '}</Text>
      <Text color={WARN}>{`${tally.discuss} to discuss`}</Text>
      <Text dimColor>{` · ${tally.open} open · ${width < 96 ? SCOPE_SHORT[deck.scope] : SCOPE_WORDS[deck.scope]}${deck.filter !== '' ? ` · "${deck.filter}"` : ''}`}</Text>
    </Text>
  )

  // With the source open the code gets the room: the rule in one line, no blank rows, and as many
  // cited lines as the band holds. Seven rows are spoken for: headline, title, meta, statement,
  // path, verdict, keys.
  if (shownSource !== null && Code !== undefined) {
    const codeRows = Math.max(3, Math.min(24, maxRows - 8 - noteRows))
    const gist = rule.statement !== '' ? rule.statement : (rule.then ?? rule.given ?? '')

    return (
      <Box flexDirection="column" width={width}>
        {headline}
        <Text bold wrap="truncate-end">{`${rule.id.startsWith('R-') ? rule.priority : rule.id} · ${rule.title}`}</Text>
        <Text dimColor wrap="truncate-end">{meta.join(' · ')}</Text>
        <Text wrap="truncate-end">{wrapLines(gist, width, 1)[0] ?? ''}</Text>
        <Text dimColor wrap="truncate-end">{`${shownSource.path}:${shownSource.startLine}`}</Text>
        <Code
          source={shownSource.text.split('\n').slice(0, codeRows).join('\n')}
          path={shownSource.path}
          startLine={shownSource.startLine}
          wrap="truncate-end"
        />
        {verdictLine}
        {noteLine}
        {keys}
      </Box>
    )
  }

  // Rows that are always there: header, blank, title, meta, blank, [body], blank, verdict, keys.
  const fixed = 8
  // One row of slack: a band exactly full still scrolls on some layouts.
  const isTight = maxRows < 16
  const room = Math.max(1, maxRows - (isTight ? fixed - 3 : fixed) - 1 - noteRows)
  const prose = Math.max(1, room)

  // Share the prose rows: flags one row each, the statement up to two, the rest split over Given/When/Then.
  const flagRows = (rule.defect !== undefined ? 1 : 0) + (rule.sme !== undefined ? 1 : 0)
  const statementRows = rule.statement !== '' ? Math.min(2, Math.max(0, prose - flagRows - 3)) : 0
  const parts = [rule.given, rule.when, rule.then].filter(part => part !== undefined).length
  const each = parts > 0 ? Math.max(1, Math.floor((prose - flagRows - statementRows) / parts)) : 0

  type Row = { text: string; color?: string; label?: string }
  const rows: Row[] = []

  for (const line of wrapLines(rule.statement, width, statementRows)) {
    rows.push({ text: line })
  }

  const block = (label: string, text: string | undefined) => {
    if (text === undefined) {
      return
    }

    wrapLines(`${label} ${text}`, width, each).forEach((line, index) => {
      rows.push(index === 0 ? { label, text: line.slice(label.length + 1) } : { text: line })
    })
  }

  block('Given', rule.given)
  block('When', rule.when)
  block('Then', rule.then)

  if (rule.defect !== undefined) {
    rows.push({ text: wrapLines(`! Suspected defect: ${rule.defect}`, width, 1)[0] ?? '', color: WARN })
  }

  if (rule.sme !== undefined) {
    rows.push({ text: wrapLines(`? For an SME: ${rule.sme}`, width, 1)[0] ?? '', color: HEAD })
  }

  return (
    <Box flexDirection="column" width={width}>
      {headline}
      <Box marginTop={isTight ? 0 : 1} flexDirection="column">
        <Text bold wrap="truncate-end">{`${rule.id.startsWith('R-') ? rule.priority : rule.id} · ${rule.title}`}</Text>
        <Text dimColor wrap="truncate-end">{meta.join(' · ')}</Text>
      </Box>
      <Box marginTop={isTight ? 0 : 1} flexDirection="column">
        {rows.slice(0, prose).map(row => (
          <Text wrap="truncate-end" color={row.color}>
            {row.label !== undefined ? <Text bold color={HEAD}>{`${row.label} `}</Text> : null}
            {row.text}
          </Text>
        ))}
      </Box>
      <Box marginTop={isTight ? 0 : 1}>{verdictLine}</Box>
      {noteLine}
      {keys}
    </Box>
  )
}

export type SignActions = {
  name: (value: string) => void
  covers: (value: 'phase-1' | 'full') => void
  sign: () => void
  cancel: () => void
}

/** The sign-off dialog: a person's name, what the approval covers, and the button that writes it. */
export function signView(
  kit: Kit,
  sign: SignState,
  system: string,
  openQuestions: number,
  columns: number,
  actions: SignActions,
): RenderElement {
  const { Box, Text, Button, Input } = kit
  const width = Math.max(30, columns)

  return (
    <Box flexDirection="column" width={width}>
      <Text bold color={HEAD}>Sign the brief</Text>
      <Text dimColor wrap="wrap">
        {`Records who approved the plan in analysis/${system}/MODERNIZATION_BRIEF.md, and how much of it. Nothing is built until it is signed.`}
      </Text>
      {openQuestions > 0 ? (
        <Text color={WARN} wrap="wrap">{`${openQuestions} open question${openQuestions === 1 ? '' : 's'} in the brief ${openQuestions === 1 ? 'is' : 'are'} still unticked.`}</Text>
      ) : null}
      <Box marginTop={1} flexDirection="column">
        {Input !== undefined ? (
          <Input
            key="signer"
            label="Approved by"
            placeholder="name, role"
            value={sign.name}
            submitLabel="sign"
            autoFocus
            onInput={actions.name}
            onSubmit={value => {
              actions.name(value)
              actions.sign()
            }}
          />
        ) : (
          <Text>{`Approved by: ${sign.name}`}</Text>
        )}
      </Box>
      <Box marginTop={1} columnGap={2}>
        <Text dimColor>Covers:</Text>
        <Button key="phase1" plain onPress={() => actions.covers('phase-1')}>
          {`${sign.covers === 'phase-1' ? '◉' : '○'} Phase 1 only`}
        </Button>
        <Button key="full" plain onPress={() => actions.covers('full')}>
          {`${sign.covers === 'full' ? '◉' : '○'} Full plan`}
        </Button>
      </Box>
      {sign.error !== null ? <Text color={BAD} wrap="wrap">{sign.error}</Text> : null}
      <Box marginTop={1} columnGap={2}>
        <Button key="do-sign" onPress={actions.sign}>sign</Button>
        <Button key="cancel" dimColor onPress={actions.cancel}>cancel</Button>
      </Box>
      <Box>
        <Text dimColor>enter signs · tab moves · esc cancels</Text>
      </Box>
    </Box>
  )
}