docrev 0.11.1 → 0.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/.gitattributes +1 -1
  2. package/CHANGELOG.md +207 -197
  3. package/PLAN-tables-and-postprocess.md +850 -850
  4. package/README.md +433 -433
  5. package/bin/rev.js +11 -11
  6. package/bin/rev.ts +145 -145
  7. package/completions/rev.bash +127 -127
  8. package/completions/rev.ps1 +210 -210
  9. package/completions/rev.zsh +207 -207
  10. package/dist/lib/annotations.d.ts.map +1 -1
  11. package/dist/lib/annotations.js +28 -0
  12. package/dist/lib/annotations.js.map +1 -1
  13. package/dist/lib/build.d.ts +28 -0
  14. package/dist/lib/build.d.ts.map +1 -1
  15. package/dist/lib/build.js +81 -4
  16. package/dist/lib/build.js.map +1 -1
  17. package/dist/lib/commands/comments.d.ts.map +1 -1
  18. package/dist/lib/commands/comments.js +58 -28
  19. package/dist/lib/commands/comments.js.map +1 -1
  20. package/dist/lib/commands/context.d.ts +1 -0
  21. package/dist/lib/commands/context.d.ts.map +1 -1
  22. package/dist/lib/commands/context.js +1 -0
  23. package/dist/lib/commands/context.js.map +1 -1
  24. package/dist/lib/commands/core.d.ts.map +1 -1
  25. package/dist/lib/commands/core.js +25 -8
  26. package/dist/lib/commands/core.js.map +1 -1
  27. package/dist/lib/commands/response.js +1 -1
  28. package/dist/lib/commands/response.js.map +1 -1
  29. package/dist/lib/commands/utilities.js +164 -164
  30. package/dist/lib/commands/word-tools.js +8 -8
  31. package/dist/lib/grammar.js +3 -3
  32. package/dist/lib/import.d.ts +14 -0
  33. package/dist/lib/import.d.ts.map +1 -1
  34. package/dist/lib/import.js +23 -0
  35. package/dist/lib/import.js.map +1 -1
  36. package/dist/lib/input.d.ts +67 -0
  37. package/dist/lib/input.d.ts.map +1 -0
  38. package/dist/lib/input.js +164 -0
  39. package/dist/lib/input.js.map +1 -0
  40. package/dist/lib/macro-filter.lua +201 -201
  41. package/dist/lib/pdf-comments.js +44 -44
  42. package/dist/lib/plugins.js +57 -57
  43. package/dist/lib/pptx-color-filter.lua +37 -37
  44. package/dist/lib/pptx-themes.js +115 -115
  45. package/dist/lib/response.d.ts +1 -1
  46. package/dist/lib/response.d.ts.map +1 -1
  47. package/dist/lib/response.js +5 -2
  48. package/dist/lib/response.js.map +1 -1
  49. package/dist/lib/schema.d.ts.map +1 -1
  50. package/dist/lib/schema.js +8 -2
  51. package/dist/lib/schema.js.map +1 -1
  52. package/dist/lib/spelling.js +2 -2
  53. package/dist/lib/templates.js +387 -387
  54. package/dist/lib/themes.js +51 -51
  55. package/eslint.config.js +27 -27
  56. package/lib/anchor-match.ts +307 -307
  57. package/lib/annotations.ts +695 -664
  58. package/lib/build.ts +2047 -1956
  59. package/lib/citations.ts +160 -160
  60. package/lib/commands/build.ts +885 -885
  61. package/lib/commands/citations.ts +515 -515
  62. package/lib/commands/comments.ts +1077 -1050
  63. package/lib/commands/context.ts +185 -176
  64. package/lib/commands/core.ts +328 -309
  65. package/lib/commands/doi.ts +451 -451
  66. package/lib/commands/file-ops.ts +372 -372
  67. package/lib/commands/history.ts +320 -320
  68. package/lib/commands/index.ts +87 -87
  69. package/lib/commands/init.ts +259 -259
  70. package/lib/commands/merge-resolve.ts +378 -378
  71. package/lib/commands/preview.ts +178 -178
  72. package/lib/commands/project-info.ts +244 -244
  73. package/lib/commands/quality.ts +517 -517
  74. package/lib/commands/response.ts +454 -454
  75. package/lib/commands/section-boundaries.ts +82 -82
  76. package/lib/commands/sections.ts +451 -451
  77. package/lib/commands/sync.ts +689 -689
  78. package/lib/commands/text-ops.ts +449 -449
  79. package/lib/commands/utilities.ts +448 -448
  80. package/lib/commands/verify-anchors.ts +272 -272
  81. package/lib/commands/word-tools.ts +340 -340
  82. package/lib/comment-realign.ts +99 -99
  83. package/lib/config.ts +84 -84
  84. package/lib/crossref.ts +781 -781
  85. package/lib/csl.ts +191 -191
  86. package/lib/dependencies.ts +132 -132
  87. package/lib/diff-engine.ts +465 -465
  88. package/lib/doi-cache.ts +115 -115
  89. package/lib/doi.ts +879 -879
  90. package/lib/equations.ts +506 -506
  91. package/lib/errors.ts +350 -350
  92. package/lib/format.ts +541 -541
  93. package/lib/git.ts +326 -326
  94. package/lib/grammar.ts +303 -303
  95. package/lib/image-registry.ts +180 -180
  96. package/lib/import.ts +932 -906
  97. package/lib/input.ts +174 -0
  98. package/lib/journals.ts +543 -543
  99. package/lib/macro-filter.lua +201 -201
  100. package/lib/macros.ts +273 -273
  101. package/lib/merge.ts +633 -633
  102. package/lib/ooxml.ts +768 -768
  103. package/lib/orcid.ts +144 -144
  104. package/lib/pdf-comments.ts +263 -263
  105. package/lib/pdf-import.ts +524 -524
  106. package/lib/plugins.ts +362 -362
  107. package/lib/postprocess.ts +188 -188
  108. package/lib/pptx-color-filter.lua +37 -37
  109. package/lib/pptx-template.ts +469 -469
  110. package/lib/pptx-themes.ts +483 -483
  111. package/lib/protect-restore.ts +520 -520
  112. package/lib/rate-limiter.ts +127 -127
  113. package/lib/response.ts +200 -197
  114. package/lib/restore-references.ts +240 -240
  115. package/lib/review.ts +327 -327
  116. package/lib/schema.ts +494 -488
  117. package/lib/scientific-words.ts +73 -73
  118. package/lib/sections.ts +428 -428
  119. package/lib/slides.ts +756 -756
  120. package/lib/spelling.ts +334 -334
  121. package/lib/templates.ts +526 -526
  122. package/lib/themes.ts +742 -742
  123. package/lib/trackchanges.ts +166 -166
  124. package/lib/tui.ts +450 -450
  125. package/lib/types.ts +546 -546
  126. package/lib/undo.ts +250 -250
  127. package/lib/utils.ts +69 -69
  128. package/lib/variables.ts +179 -179
  129. package/lib/word-extraction.ts +525 -525
  130. package/lib/word.ts +526 -526
  131. package/lib/wordcomments.ts +789 -789
  132. package/package.json +1 -1
  133. package/scripts/postbuild.js +47 -47
  134. package/skill/REFERENCE.md +550 -550
  135. package/skill/SKILL.md +302 -302
  136. package/tsconfig.json +26 -26
  137. package/types/index.d.ts +531 -531
  138. package/issues.md +0 -180
  139. package/site/assets/extra.css +0 -208
  140. package/site/commands.html +0 -926
  141. package/site/configuration.html +0 -469
  142. package/site/index.html +0 -288
  143. package/site/troubleshooting.html +0 -461
  144. package/site/workflow.html +0 -518
package/lib/tui.ts CHANGED
@@ -1,450 +1,450 @@
1
- /**
2
- * TUI (Text User Interface) components for enhanced visual display
3
- * Uses box-drawing characters and colors for a richer terminal experience
4
- */
5
-
6
- import chalk from 'chalk';
7
- import * as readline from 'readline';
8
- import type { Annotation } from './types.js';
9
- import type { DocumentSession } from './undo.js';
10
-
11
- // =============================================================================
12
- // Interfaces
13
- // =============================================================================
14
-
15
- interface BoxOptions {
16
- title?: string;
17
- content?: string[];
18
- width?: number;
19
- borderColor?: string;
20
- }
21
-
22
- interface TuiReviewOptions {
23
- author?: string;
24
- addReply?: (text: string, comment: Annotation, author: string, reply: string) => string;
25
- setStatus?: (text: string, comment: Annotation, resolved: boolean) => string;
26
- }
27
-
28
- interface TuiReviewResult {
29
- text: string;
30
- resolved: number;
31
- replied: number;
32
- skipped: number;
33
- }
34
-
35
- // =============================================================================
36
- // Utility Functions
37
- // =============================================================================
38
-
39
- /**
40
- * Strip ANSI codes for length calculation
41
- */
42
- export function stripAnsi(str: string): string {
43
- return str.replace(/\x1b\[[0-9;]*m/g, '');
44
- }
45
-
46
- /**
47
- * Word wrap text to fit within width
48
- */
49
- function wordWrap(text: string, width: number): string[] {
50
- const words = text.split(/\s+/);
51
- const lines: string[] = [];
52
- let currentLine = '';
53
-
54
- for (const word of words) {
55
- if (currentLine.length + word.length + 1 <= width) {
56
- currentLine += (currentLine ? ' ' : '') + word;
57
- } else {
58
- if (currentLine) lines.push(currentLine);
59
- currentLine = word;
60
- }
61
- }
62
-
63
- if (currentLine) lines.push(currentLine);
64
- return lines;
65
- }
66
-
67
- // =============================================================================
68
- // Screen Functions
69
- // =============================================================================
70
-
71
- /**
72
- * Clear the terminal screen
73
- */
74
- export function clearScreen(): void {
75
- process.stdout.write('\x1B[2J\x1B[H');
76
- }
77
-
78
- /**
79
- * Move cursor to position
80
- */
81
- export function moveCursor(row: number, col: number): void {
82
- process.stdout.write(`\x1B[${row};${col}H`);
83
- }
84
-
85
- /**
86
- * Get terminal dimensions
87
- */
88
- export function getTerminalSize(): { rows: number; cols: number } {
89
- return {
90
- rows: process.stdout.rows || 24,
91
- cols: process.stdout.columns || 80,
92
- };
93
- }
94
-
95
- // =============================================================================
96
- // Drawing Functions
97
- // =============================================================================
98
-
99
- /**
100
- * Draw a box with content
101
- */
102
- export function drawBox({ title = '', content = [], width = 60, borderColor = 'dim' }: BoxOptions = {}): string[] {
103
- const border = {
104
- tl: '\u256D', tr: '\u256E', bl: '\u2570', br: '\u256F',
105
- h: '\u2500', v: '\u2502',
106
- };
107
-
108
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
109
- const colorFn = ((chalk as any)[borderColor] as ((str: string) => string)) || chalk.dim;
110
- const lines: string[] = [];
111
-
112
- // Top border with title
113
- if (title) {
114
- const titleDisplay = ` ${title} `;
115
- const remaining = width - titleDisplay.length - 2;
116
- lines.push(
117
- colorFn(border.tl + border.h) +
118
- chalk.bold(titleDisplay) +
119
- colorFn(border.h.repeat(Math.max(0, remaining)) + border.tr)
120
- );
121
- } else {
122
- lines.push(colorFn(border.tl + border.h.repeat(width - 2) + border.tr));
123
- }
124
-
125
- // Content lines
126
- for (const line of content) {
127
- const plainLen = stripAnsi(line).length;
128
- const padding = Math.max(0, width - 4 - plainLen);
129
- lines.push(
130
- colorFn(border.v) + ' ' + line + ' '.repeat(padding) + ' ' + colorFn(border.v)
131
- );
132
- }
133
-
134
- // Bottom border
135
- lines.push(colorFn(border.bl + border.h.repeat(width - 2) + border.br));
136
-
137
- return lines;
138
- }
139
-
140
- /**
141
- * Draw a status bar at the bottom of the screen
142
- */
143
- export function statusBar(left: string, right: string = ''): string {
144
- const { cols } = getTerminalSize();
145
- const leftLen = stripAnsi(left).length;
146
- const rightLen = stripAnsi(right).length;
147
- const padding = Math.max(0, cols - leftLen - rightLen);
148
-
149
- return chalk.inverse(left + ' '.repeat(padding) + right);
150
- }
151
-
152
- /**
153
- * Draw a progress indicator
154
- */
155
- export function progressIndicator(current: number, total: number, width: number = 20): string {
156
- const ratio = current / total;
157
- const filled = Math.round(ratio * width);
158
- const empty = width - filled;
159
-
160
- const bar = chalk.cyan('\u2588'.repeat(filled)) + chalk.dim('\u2591'.repeat(empty));
161
- return `${bar} ${current}/${total}`;
162
- }
163
-
164
- /**
165
- * Format a comment for TUI display
166
- */
167
- export function formatCommentCard(comment: Annotation, index: number, total: number, width: number = 70): string[] {
168
- const statusIcon = comment.resolved ? chalk.green('\u2713') : chalk.yellow('\u25CB');
169
- const author = comment.author || 'Anonymous';
170
-
171
- const content: string[] = [];
172
-
173
- // Author and status line
174
- content.push(chalk.blue(author) + ' ' + statusIcon);
175
- content.push('');
176
-
177
- // Comment text (word-wrap)
178
- const wrappedText = wordWrap(comment.content, width - 6);
179
- for (const line of wrappedText) {
180
- content.push(line);
181
- }
182
-
183
- // Context
184
- if (comment.before) {
185
- content.push('');
186
- const context = comment.before.trim().slice(-50);
187
- content.push(chalk.dim(`Context: "...${context}"`));
188
- }
189
-
190
- // Line number
191
- content.push('');
192
- content.push(chalk.dim(`Line ${comment.line}`));
193
-
194
- return drawBox({
195
- title: `Comment ${index + 1}/${total}`,
196
- content,
197
- width,
198
- borderColor: comment.resolved ? 'green' : 'cyan',
199
- });
200
- }
201
-
202
- /**
203
- * Draw the action menu
204
- */
205
- export function actionMenu(options: [string, string][]): string {
206
- return options
207
- .map(([key, desc]) => chalk.bold(`[${key}]`) + chalk.dim(desc))
208
- .join(' ');
209
- }
210
-
211
- // =============================================================================
212
- // Interactive TUI Review
213
- // =============================================================================
214
-
215
- /**
216
- * Prompt for a single keypress
217
- */
218
- function promptKey(validKeys: string[]): Promise<string> {
219
- return new Promise((resolve) => {
220
- const rl = readline.createInterface({
221
- input: process.stdin,
222
- output: process.stdout,
223
- });
224
-
225
- if (process.stdin.isTTY) {
226
- process.stdin.setRawMode(true);
227
- }
228
- process.stdin.resume();
229
-
230
- process.stdin.once('data', (key: Buffer) => {
231
- const char = key.toString();
232
-
233
- if (process.stdin.isTTY) {
234
- process.stdin.setRawMode(false);
235
- }
236
- rl.close();
237
-
238
- if (char === '\u0003') {
239
- // Ctrl+C
240
- clearScreen();
241
- process.exit(0);
242
- }
243
-
244
- if (validKeys.includes(char.toLowerCase()) || validKeys.includes(char)) {
245
- resolve(char);
246
- } else {
247
- resolve(promptKey(validKeys));
248
- }
249
- });
250
- });
251
- }
252
-
253
- /**
254
- * Prompt for text input
255
- */
256
- function promptText(prompt: string): Promise<string> {
257
- return new Promise((resolve) => {
258
- const rl = readline.createInterface({
259
- input: process.stdin,
260
- output: process.stdout,
261
- });
262
- rl.question(prompt, (answer: string) => {
263
- rl.close();
264
- resolve(answer);
265
- });
266
- });
267
- }
268
-
269
- /**
270
- * Run TUI comment review session
271
- */
272
- export async function tuiCommentReview(text: string, options: TuiReviewOptions = {}): Promise<TuiReviewResult> {
273
- const { getComments } = await import('./annotations.js');
274
- const { createDocumentSession } = await import('./undo.js');
275
- const { author = 'Author', addReply, setStatus } = options;
276
-
277
- const comments = getComments(text, { pendingOnly: true });
278
-
279
- if (comments.length === 0) {
280
- console.log(chalk.green('No pending comments found.'));
281
- return { text, resolved: 0, replied: 0, skipped: 0 };
282
- }
283
-
284
- // Create session with undo support
285
- const session: DocumentSession = createDocumentSession(text);
286
-
287
- let currentIndex = 0;
288
- let resolved = 0;
289
- let replied = 0;
290
- let skipped = 0;
291
- let message = '';
292
-
293
- const render = (): void => {
294
- clearScreen();
295
-
296
- const { cols } = getTerminalSize();
297
- const cardWidth = Math.min(cols - 4, 80);
298
-
299
- // Header
300
- console.log(chalk.cyan.bold(` Reviewing ${comments.length} comment(s) as ${author}`));
301
- const undoInfo = session.info();
302
- const undoStatus = session.canUndo()
303
- ? chalk.dim(` | ${undoInfo.undoSteps} undo`)
304
- : '';
305
- console.log(chalk.dim(` ${progressIndicator(currentIndex + 1, comments.length)}${undoStatus}`));
306
- console.log();
307
-
308
- // Current comment card
309
- const comment = comments[currentIndex];
310
- const card = formatCommentCard(comment, currentIndex, comments.length, cardWidth);
311
- for (const line of card) {
312
- console.log(' ' + line);
313
- }
314
-
315
- console.log();
316
-
317
- // Status message
318
- if (message) {
319
- console.log(' ' + message);
320
- console.log();
321
- message = '';
322
- }
323
-
324
- // Action menu with undo
325
- const menuItems: [string, string][] = [
326
- ['r', 'eply'],
327
- ['m', 'ark resolved'],
328
- ['s', 'kip'],
329
- ['n', 'ext'],
330
- ['p', 'rev'],
331
- ];
332
-
333
- if (session.canUndo()) {
334
- menuItems.push(['u', 'ndo']);
335
- }
336
-
337
- menuItems.push(['A', 'll resolve'], ['q', 'uit']);
338
-
339
- console.log(' ' + actionMenu(menuItems));
340
- console.log();
341
- };
342
-
343
- // Main loop
344
- while (currentIndex < comments.length) {
345
- render();
346
-
347
- const validKeys = session.canUndo()
348
- ? ['r', 'm', 's', 'n', 'p', 'u', 'A', 'q']
349
- : ['r', 'm', 's', 'n', 'p', 'A', 'q'];
350
-
351
- const choice = await promptKey(validKeys);
352
- const comment = comments[currentIndex];
353
-
354
- switch (choice) {
355
- case 'q':
356
- clearScreen();
357
- console.log(chalk.yellow('Aborted.'));
358
- return { text: session.getText(), resolved, replied, skipped: comments.length - currentIndex };
359
-
360
- case 'u':
361
- if (session.canUndo()) {
362
- const undone = session.undo();
363
- if (undone) {
364
- message = chalk.yellow(`Undone: ${undone.description}`);
365
- if (undone.description.includes('Resolved')) resolved = Math.max(0, resolved - 1);
366
- if (undone.description.includes('Reply')) replied = Math.max(0, replied - 1);
367
- if (currentIndex > 0) currentIndex--;
368
- }
369
- }
370
- break;
371
-
372
- case 'A': {
373
- let newText = session.getText();
374
- for (let j = currentIndex; j < comments.length; j++) {
375
- if (setStatus) {
376
- newText = setStatus(newText, comments[j], true);
377
- }
378
- }
379
- session.applyChange(newText, `Resolved ${comments.length - currentIndex} comments`);
380
- resolved += comments.length - currentIndex;
381
- currentIndex = comments.length;
382
- break;
383
- }
384
-
385
- case 'm':
386
- if (setStatus) {
387
- const newText = setStatus(session.getText(), comment, true);
388
- session.applyChange(newText, `Resolved comment #${currentIndex + 1}`);
389
- }
390
- resolved++;
391
- currentIndex++;
392
- break;
393
-
394
- case 'r': {
395
- console.log();
396
- const replyText = await promptText(chalk.cyan(' Reply: '));
397
- if (replyText.trim() && addReply) {
398
- const newText = addReply(session.getText(), comment, author, replyText.trim());
399
- session.applyChange(newText, `Reply to comment #${currentIndex + 1}`);
400
- replied++;
401
- }
402
- currentIndex++;
403
- break;
404
- }
405
-
406
- case 's':
407
- skipped++;
408
- currentIndex++;
409
- break;
410
-
411
- case 'n':
412
- if (currentIndex < comments.length - 1) {
413
- currentIndex++;
414
- }
415
- break;
416
-
417
- case 'p':
418
- if (currentIndex > 0) {
419
- currentIndex--;
420
- }
421
- break;
422
- }
423
- }
424
-
425
- // Summary
426
- clearScreen();
427
- console.log(chalk.cyan.bold(' Review Complete'));
428
- console.log();
429
-
430
- const undoInfo = session.info();
431
- const summaryBox = drawBox({
432
- title: 'Summary',
433
- content: [
434
- chalk.green(`Resolved: ${resolved}`),
435
- chalk.blue(`Replied: ${replied}`),
436
- chalk.yellow(`Skipped: ${skipped}`),
437
- undoInfo.undoSteps > 1 ? chalk.dim(`Changes: ${undoInfo.undoSteps}`) : '',
438
- ].filter(Boolean),
439
- width: 30,
440
- borderColor: 'cyan',
441
- });
442
-
443
- for (const line of summaryBox) {
444
- console.log(' ' + line);
445
- }
446
-
447
- console.log();
448
-
449
- return { text: session.getText(), resolved, replied, skipped };
450
- }
1
+ /**
2
+ * TUI (Text User Interface) components for enhanced visual display
3
+ * Uses box-drawing characters and colors for a richer terminal experience
4
+ */
5
+
6
+ import chalk from 'chalk';
7
+ import * as readline from 'readline';
8
+ import type { Annotation } from './types.js';
9
+ import type { DocumentSession } from './undo.js';
10
+
11
+ // =============================================================================
12
+ // Interfaces
13
+ // =============================================================================
14
+
15
+ interface BoxOptions {
16
+ title?: string;
17
+ content?: string[];
18
+ width?: number;
19
+ borderColor?: string;
20
+ }
21
+
22
+ interface TuiReviewOptions {
23
+ author?: string;
24
+ addReply?: (text: string, comment: Annotation, author: string, reply: string) => string;
25
+ setStatus?: (text: string, comment: Annotation, resolved: boolean) => string;
26
+ }
27
+
28
+ interface TuiReviewResult {
29
+ text: string;
30
+ resolved: number;
31
+ replied: number;
32
+ skipped: number;
33
+ }
34
+
35
+ // =============================================================================
36
+ // Utility Functions
37
+ // =============================================================================
38
+
39
+ /**
40
+ * Strip ANSI codes for length calculation
41
+ */
42
+ export function stripAnsi(str: string): string {
43
+ return str.replace(/\x1b\[[0-9;]*m/g, '');
44
+ }
45
+
46
+ /**
47
+ * Word wrap text to fit within width
48
+ */
49
+ function wordWrap(text: string, width: number): string[] {
50
+ const words = text.split(/\s+/);
51
+ const lines: string[] = [];
52
+ let currentLine = '';
53
+
54
+ for (const word of words) {
55
+ if (currentLine.length + word.length + 1 <= width) {
56
+ currentLine += (currentLine ? ' ' : '') + word;
57
+ } else {
58
+ if (currentLine) lines.push(currentLine);
59
+ currentLine = word;
60
+ }
61
+ }
62
+
63
+ if (currentLine) lines.push(currentLine);
64
+ return lines;
65
+ }
66
+
67
+ // =============================================================================
68
+ // Screen Functions
69
+ // =============================================================================
70
+
71
+ /**
72
+ * Clear the terminal screen
73
+ */
74
+ export function clearScreen(): void {
75
+ process.stdout.write('\x1B[2J\x1B[H');
76
+ }
77
+
78
+ /**
79
+ * Move cursor to position
80
+ */
81
+ export function moveCursor(row: number, col: number): void {
82
+ process.stdout.write(`\x1B[${row};${col}H`);
83
+ }
84
+
85
+ /**
86
+ * Get terminal dimensions
87
+ */
88
+ export function getTerminalSize(): { rows: number; cols: number } {
89
+ return {
90
+ rows: process.stdout.rows || 24,
91
+ cols: process.stdout.columns || 80,
92
+ };
93
+ }
94
+
95
+ // =============================================================================
96
+ // Drawing Functions
97
+ // =============================================================================
98
+
99
+ /**
100
+ * Draw a box with content
101
+ */
102
+ export function drawBox({ title = '', content = [], width = 60, borderColor = 'dim' }: BoxOptions = {}): string[] {
103
+ const border = {
104
+ tl: '\u256D', tr: '\u256E', bl: '\u2570', br: '\u256F',
105
+ h: '\u2500', v: '\u2502',
106
+ };
107
+
108
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
109
+ const colorFn = ((chalk as any)[borderColor] as ((str: string) => string)) || chalk.dim;
110
+ const lines: string[] = [];
111
+
112
+ // Top border with title
113
+ if (title) {
114
+ const titleDisplay = ` ${title} `;
115
+ const remaining = width - titleDisplay.length - 2;
116
+ lines.push(
117
+ colorFn(border.tl + border.h) +
118
+ chalk.bold(titleDisplay) +
119
+ colorFn(border.h.repeat(Math.max(0, remaining)) + border.tr)
120
+ );
121
+ } else {
122
+ lines.push(colorFn(border.tl + border.h.repeat(width - 2) + border.tr));
123
+ }
124
+
125
+ // Content lines
126
+ for (const line of content) {
127
+ const plainLen = stripAnsi(line).length;
128
+ const padding = Math.max(0, width - 4 - plainLen);
129
+ lines.push(
130
+ colorFn(border.v) + ' ' + line + ' '.repeat(padding) + ' ' + colorFn(border.v)
131
+ );
132
+ }
133
+
134
+ // Bottom border
135
+ lines.push(colorFn(border.bl + border.h.repeat(width - 2) + border.br));
136
+
137
+ return lines;
138
+ }
139
+
140
+ /**
141
+ * Draw a status bar at the bottom of the screen
142
+ */
143
+ export function statusBar(left: string, right: string = ''): string {
144
+ const { cols } = getTerminalSize();
145
+ const leftLen = stripAnsi(left).length;
146
+ const rightLen = stripAnsi(right).length;
147
+ const padding = Math.max(0, cols - leftLen - rightLen);
148
+
149
+ return chalk.inverse(left + ' '.repeat(padding) + right);
150
+ }
151
+
152
+ /**
153
+ * Draw a progress indicator
154
+ */
155
+ export function progressIndicator(current: number, total: number, width: number = 20): string {
156
+ const ratio = current / total;
157
+ const filled = Math.round(ratio * width);
158
+ const empty = width - filled;
159
+
160
+ const bar = chalk.cyan('\u2588'.repeat(filled)) + chalk.dim('\u2591'.repeat(empty));
161
+ return `${bar} ${current}/${total}`;
162
+ }
163
+
164
+ /**
165
+ * Format a comment for TUI display
166
+ */
167
+ export function formatCommentCard(comment: Annotation, index: number, total: number, width: number = 70): string[] {
168
+ const statusIcon = comment.resolved ? chalk.green('\u2713') : chalk.yellow('\u25CB');
169
+ const author = comment.author || 'Anonymous';
170
+
171
+ const content: string[] = [];
172
+
173
+ // Author and status line
174
+ content.push(chalk.blue(author) + ' ' + statusIcon);
175
+ content.push('');
176
+
177
+ // Comment text (word-wrap)
178
+ const wrappedText = wordWrap(comment.content, width - 6);
179
+ for (const line of wrappedText) {
180
+ content.push(line);
181
+ }
182
+
183
+ // Context
184
+ if (comment.before) {
185
+ content.push('');
186
+ const context = comment.before.trim().slice(-50);
187
+ content.push(chalk.dim(`Context: "...${context}"`));
188
+ }
189
+
190
+ // Line number
191
+ content.push('');
192
+ content.push(chalk.dim(`Line ${comment.line}`));
193
+
194
+ return drawBox({
195
+ title: `Comment ${index + 1}/${total}`,
196
+ content,
197
+ width,
198
+ borderColor: comment.resolved ? 'green' : 'cyan',
199
+ });
200
+ }
201
+
202
+ /**
203
+ * Draw the action menu
204
+ */
205
+ export function actionMenu(options: [string, string][]): string {
206
+ return options
207
+ .map(([key, desc]) => chalk.bold(`[${key}]`) + chalk.dim(desc))
208
+ .join(' ');
209
+ }
210
+
211
+ // =============================================================================
212
+ // Interactive TUI Review
213
+ // =============================================================================
214
+
215
+ /**
216
+ * Prompt for a single keypress
217
+ */
218
+ function promptKey(validKeys: string[]): Promise<string> {
219
+ return new Promise((resolve) => {
220
+ const rl = readline.createInterface({
221
+ input: process.stdin,
222
+ output: process.stdout,
223
+ });
224
+
225
+ if (process.stdin.isTTY) {
226
+ process.stdin.setRawMode(true);
227
+ }
228
+ process.stdin.resume();
229
+
230
+ process.stdin.once('data', (key: Buffer) => {
231
+ const char = key.toString();
232
+
233
+ if (process.stdin.isTTY) {
234
+ process.stdin.setRawMode(false);
235
+ }
236
+ rl.close();
237
+
238
+ if (char === '\u0003') {
239
+ // Ctrl+C
240
+ clearScreen();
241
+ process.exit(0);
242
+ }
243
+
244
+ if (validKeys.includes(char.toLowerCase()) || validKeys.includes(char)) {
245
+ resolve(char);
246
+ } else {
247
+ resolve(promptKey(validKeys));
248
+ }
249
+ });
250
+ });
251
+ }
252
+
253
+ /**
254
+ * Prompt for text input
255
+ */
256
+ function promptText(prompt: string): Promise<string> {
257
+ return new Promise((resolve) => {
258
+ const rl = readline.createInterface({
259
+ input: process.stdin,
260
+ output: process.stdout,
261
+ });
262
+ rl.question(prompt, (answer: string) => {
263
+ rl.close();
264
+ resolve(answer);
265
+ });
266
+ });
267
+ }
268
+
269
+ /**
270
+ * Run TUI comment review session
271
+ */
272
+ export async function tuiCommentReview(text: string, options: TuiReviewOptions = {}): Promise<TuiReviewResult> {
273
+ const { getComments } = await import('./annotations.js');
274
+ const { createDocumentSession } = await import('./undo.js');
275
+ const { author = 'Author', addReply, setStatus } = options;
276
+
277
+ const comments = getComments(text, { pendingOnly: true });
278
+
279
+ if (comments.length === 0) {
280
+ console.log(chalk.green('No pending comments found.'));
281
+ return { text, resolved: 0, replied: 0, skipped: 0 };
282
+ }
283
+
284
+ // Create session with undo support
285
+ const session: DocumentSession = createDocumentSession(text);
286
+
287
+ let currentIndex = 0;
288
+ let resolved = 0;
289
+ let replied = 0;
290
+ let skipped = 0;
291
+ let message = '';
292
+
293
+ const render = (): void => {
294
+ clearScreen();
295
+
296
+ const { cols } = getTerminalSize();
297
+ const cardWidth = Math.min(cols - 4, 80);
298
+
299
+ // Header
300
+ console.log(chalk.cyan.bold(` Reviewing ${comments.length} comment(s) as ${author}`));
301
+ const undoInfo = session.info();
302
+ const undoStatus = session.canUndo()
303
+ ? chalk.dim(` | ${undoInfo.undoSteps} undo`)
304
+ : '';
305
+ console.log(chalk.dim(` ${progressIndicator(currentIndex + 1, comments.length)}${undoStatus}`));
306
+ console.log();
307
+
308
+ // Current comment card
309
+ const comment = comments[currentIndex];
310
+ const card = formatCommentCard(comment, currentIndex, comments.length, cardWidth);
311
+ for (const line of card) {
312
+ console.log(' ' + line);
313
+ }
314
+
315
+ console.log();
316
+
317
+ // Status message
318
+ if (message) {
319
+ console.log(' ' + message);
320
+ console.log();
321
+ message = '';
322
+ }
323
+
324
+ // Action menu with undo
325
+ const menuItems: [string, string][] = [
326
+ ['r', 'eply'],
327
+ ['m', 'ark resolved'],
328
+ ['s', 'kip'],
329
+ ['n', 'ext'],
330
+ ['p', 'rev'],
331
+ ];
332
+
333
+ if (session.canUndo()) {
334
+ menuItems.push(['u', 'ndo']);
335
+ }
336
+
337
+ menuItems.push(['A', 'll resolve'], ['q', 'uit']);
338
+
339
+ console.log(' ' + actionMenu(menuItems));
340
+ console.log();
341
+ };
342
+
343
+ // Main loop
344
+ while (currentIndex < comments.length) {
345
+ render();
346
+
347
+ const validKeys = session.canUndo()
348
+ ? ['r', 'm', 's', 'n', 'p', 'u', 'A', 'q']
349
+ : ['r', 'm', 's', 'n', 'p', 'A', 'q'];
350
+
351
+ const choice = await promptKey(validKeys);
352
+ const comment = comments[currentIndex];
353
+
354
+ switch (choice) {
355
+ case 'q':
356
+ clearScreen();
357
+ console.log(chalk.yellow('Aborted.'));
358
+ return { text: session.getText(), resolved, replied, skipped: comments.length - currentIndex };
359
+
360
+ case 'u':
361
+ if (session.canUndo()) {
362
+ const undone = session.undo();
363
+ if (undone) {
364
+ message = chalk.yellow(`Undone: ${undone.description}`);
365
+ if (undone.description.includes('Resolved')) resolved = Math.max(0, resolved - 1);
366
+ if (undone.description.includes('Reply')) replied = Math.max(0, replied - 1);
367
+ if (currentIndex > 0) currentIndex--;
368
+ }
369
+ }
370
+ break;
371
+
372
+ case 'A': {
373
+ let newText = session.getText();
374
+ for (let j = currentIndex; j < comments.length; j++) {
375
+ if (setStatus) {
376
+ newText = setStatus(newText, comments[j], true);
377
+ }
378
+ }
379
+ session.applyChange(newText, `Resolved ${comments.length - currentIndex} comments`);
380
+ resolved += comments.length - currentIndex;
381
+ currentIndex = comments.length;
382
+ break;
383
+ }
384
+
385
+ case 'm':
386
+ if (setStatus) {
387
+ const newText = setStatus(session.getText(), comment, true);
388
+ session.applyChange(newText, `Resolved comment #${currentIndex + 1}`);
389
+ }
390
+ resolved++;
391
+ currentIndex++;
392
+ break;
393
+
394
+ case 'r': {
395
+ console.log();
396
+ const replyText = await promptText(chalk.cyan(' Reply: '));
397
+ if (replyText.trim() && addReply) {
398
+ const newText = addReply(session.getText(), comment, author, replyText.trim());
399
+ session.applyChange(newText, `Reply to comment #${currentIndex + 1}`);
400
+ replied++;
401
+ }
402
+ currentIndex++;
403
+ break;
404
+ }
405
+
406
+ case 's':
407
+ skipped++;
408
+ currentIndex++;
409
+ break;
410
+
411
+ case 'n':
412
+ if (currentIndex < comments.length - 1) {
413
+ currentIndex++;
414
+ }
415
+ break;
416
+
417
+ case 'p':
418
+ if (currentIndex > 0) {
419
+ currentIndex--;
420
+ }
421
+ break;
422
+ }
423
+ }
424
+
425
+ // Summary
426
+ clearScreen();
427
+ console.log(chalk.cyan.bold(' Review Complete'));
428
+ console.log();
429
+
430
+ const undoInfo = session.info();
431
+ const summaryBox = drawBox({
432
+ title: 'Summary',
433
+ content: [
434
+ chalk.green(`Resolved: ${resolved}`),
435
+ chalk.blue(`Replied: ${replied}`),
436
+ chalk.yellow(`Skipped: ${skipped}`),
437
+ undoInfo.undoSteps > 1 ? chalk.dim(`Changes: ${undoInfo.undoSteps}`) : '',
438
+ ].filter(Boolean),
439
+ width: 30,
440
+ borderColor: 'cyan',
441
+ });
442
+
443
+ for (const line of summaryBox) {
444
+ console.log(' ' + line);
445
+ }
446
+
447
+ console.log();
448
+
449
+ return { text: session.getText(), resolved, replied, skipped };
450
+ }