@aronnaxlin/bgm-cli 1.0.0

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 (46) hide show
  1. package/LICENSE +660 -0
  2. package/README.en.md +122 -0
  3. package/README.md +127 -0
  4. package/README.zh-TW.md +122 -0
  5. package/package.json +41 -0
  6. package/src/cli.js +993 -0
  7. package/src/commands/blog.js +213 -0
  8. package/src/commands/calendar.js +32 -0
  9. package/src/commands/character.js +291 -0
  10. package/src/commands/collection.js +418 -0
  11. package/src/commands/episode.js +379 -0
  12. package/src/commands/group.js +488 -0
  13. package/src/commands/index.js +362 -0
  14. package/src/commands/notify.js +74 -0
  15. package/src/commands/person.js +297 -0
  16. package/src/commands/status.js +74 -0
  17. package/src/commands/subject.js +537 -0
  18. package/src/commands/timeline.js +288 -0
  19. package/src/commands/trending.js +58 -0
  20. package/src/commands/tui.js +1537 -0
  21. package/src/commands/user.js +83 -0
  22. package/src/core/client.js +2065 -0
  23. package/src/core/config.js +450 -0
  24. package/src/core/http.js +144 -0
  25. package/src/core/output.js +3888 -0
  26. package/src/core/proxy.js +47 -0
  27. package/src/core/reactions.js +62 -0
  28. package/src/core/turnstile.js +526 -0
  29. package/src/data/bangumi-emotes.json +311 -0
  30. package/src/utils/args.js +113 -0
  31. package/src/utils/auth-flow.js +373 -0
  32. package/src/utils/auth.js +90 -0
  33. package/src/utils/calendar.js +23 -0
  34. package/src/utils/collection-ops.js +333 -0
  35. package/src/utils/collection.js +240 -0
  36. package/src/utils/formatters.js +157 -0
  37. package/src/utils/helpers.js +283 -0
  38. package/src/utils/hot.js +182 -0
  39. package/src/utils/install.js +40 -0
  40. package/src/utils/prompts.js +87 -0
  41. package/src/utils/relay.js +74 -0
  42. package/src/utils/status.js +68 -0
  43. package/src/utils/tui-interactive.js +197 -0
  44. package/src/utils/tui-render.js +86 -0
  45. package/src/utils/turnstile-flow.js +154 -0
  46. package/src/utils/validators.js +412 -0
@@ -0,0 +1,1537 @@
1
+ import process from "node:process";
2
+ import readline from "node:readline/promises";
3
+ import { emitKeypressEvents } from "node:readline";
4
+ import { BangumiClient } from "../core/client.js";
5
+ import { getConfig } from "../core/config.js";
6
+ import { CommandError, formatDisplayResult } from "../core/output.js";
7
+ import { runUserCommand } from "./user.js";
8
+ import { executeSubjectListCommand, executeSubjectSearchCommand } from "./subject.js";
9
+ import {
10
+ executeCollectionCollectCommand,
11
+ executeCollectionCommentCommand,
12
+ executeCollectionGetCommand,
13
+ executeCollectionListCommand,
14
+ executeCollectionRateCommand,
15
+ executeCollectionStatusCommand,
16
+ } from "./collection.js";
17
+ import {
18
+ executeGroupGetCommand,
19
+ executeGroupListCommand,
20
+ executeGroupMembersCommand,
21
+ executeGroupTopicCommand,
22
+ executeGroupTopicsCommand,
23
+ executeHotGroupTopicsCommand,
24
+ executeHotGroupsCommand,
25
+ executeLatestRepliedGroupTopicsCommand,
26
+ executeRecentGroupTopicsCommand,
27
+ } from "./group.js";
28
+ import {
29
+ askMenuChoice,
30
+ askTuiOptional,
31
+ askTuiRequired,
32
+ waitForTuiContinue,
33
+ } from "../utils/tui-interactive.js";
34
+ import {
35
+ clearScreen,
36
+ drawBoxLine,
37
+ drawBoxText,
38
+ drawDivider,
39
+ drawSectionTitle,
40
+ inverse,
41
+ isTuiBackAction,
42
+ renderTuiHeader,
43
+ renderTuiResultScreen,
44
+ } from "../utils/tui-render.js";
45
+ import {
46
+ buildPagedMenu,
47
+ formatCollectionMenuLabel,
48
+ formatCollectionSnapshotSummary,
49
+ formatCollectionStatusLabel,
50
+ formatCriteriaSummary,
51
+ formatGroupMenuLabel,
52
+ formatGroupTopicMenuLabel,
53
+ formatPageSummary,
54
+ formatSubjectMenuLabel,
55
+ formatSubjectTypeLabel,
56
+ } from "../utils/formatters.js";
57
+ import {
58
+ buildCollectionTargetArgs,
59
+ fetchTuiCollectionSnapshot,
60
+ getCollectionStatusKey,
61
+ } from "../utils/collection-ops.js";
62
+
63
+ export async function runTui(context, deps = {}) {
64
+ if (context.json) {
65
+ throw new CommandError("bgm tui does not support --json because it requires interactive prompts.");
66
+ }
67
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
68
+ throw new CommandError("bgm tui requires an interactive TTY terminal.");
69
+ }
70
+
71
+ const rl = readline.createInterface({
72
+ input: process.stdin,
73
+ output: process.stdout,
74
+ });
75
+
76
+ try {
77
+ while (true) {
78
+ const action = await askMenuChoice(
79
+ "Choose an action",
80
+ [
81
+ { key: "1", label: "Subject: search subjects by keyword", value: "subject-search" },
82
+ { key: "2", label: "Subject: fetch one subject by ID", value: "subject-get" },
83
+ { key: "3", label: "Subject: browse subjects by type", value: "subject-list" },
84
+ { key: "4", label: "Collection: list one user's collections", value: "collection-list" },
85
+ { key: "5", label: "Collection: show one collection entry", value: "collection-get" },
86
+ { key: "6", label: "Collection: create or update a collection", value: "collection-collect" },
87
+ { key: "7", label: "Collection: update collection comment", value: "collection-comment" },
88
+ { key: "8", label: "Collection: update collection rating", value: "collection-rate" },
89
+ { key: "9", label: "Collection: update collection status", value: "collection-status" },
90
+ { key: "10", label: "User: show current authenticated user", value: "user-me" },
91
+ { key: "11", label: "User: fetch one public user profile", value: "user-get" },
92
+ { key: "12", label: "Group: browse Bangumi groups", value: "group" },
93
+ { key: "13", label: "System: setup and config", value: "system" },
94
+ { key: "0", label: "Exit", value: "exit" },
95
+ ],
96
+ "subject-search",
97
+ {
98
+ quitValue: "exit",
99
+ quitLabel: "exit",
100
+ },
101
+ );
102
+
103
+ if (action === "exit") {
104
+ clearScreen();
105
+ console.log("");
106
+ console.log("Bye.");
107
+ return;
108
+ }
109
+
110
+ console.log("");
111
+ const actionResult = await runTuiAction(rl, action, context, deps);
112
+ if (actionResult === "exit") {
113
+ clearScreen();
114
+ console.log("");
115
+ console.log("Bye.");
116
+ return;
117
+ }
118
+ if (actionResult === "menu") {
119
+ continue;
120
+ }
121
+
122
+ await waitForTuiContinue();
123
+ }
124
+ } finally {
125
+ rl.close();
126
+ }
127
+ }
128
+
129
+ async function runTuiAction(rl, action, context, deps) {
130
+ switch (action) {
131
+ case "system": {
132
+ const systemAction = await askMenuChoice(
133
+ "System",
134
+ [
135
+ { key: "1", label: "Setup: install bgm into PATH", value: "setup-install-path" },
136
+ { key: "2", label: "Setup: update managed install", value: "setup-update" },
137
+ { key: "3", label: "Config: show current config", value: "config-show" },
138
+ { key: "4", label: "Config: set one config value", value: "config-set" },
139
+ { key: "5", label: "Config: unset one config value", value: "config-unset" },
140
+ { key: "0", label: "Back", value: "back" },
141
+ ],
142
+ "0",
143
+ );
144
+ if (isTuiBackAction(systemAction)) {
145
+ return "menu";
146
+ }
147
+ return runTuiAction(rl, systemAction, context, deps);
148
+ }
149
+ case "group": {
150
+ const groupAction = await askMenuChoice(
151
+ "Groups",
152
+ [
153
+ { key: "1", label: "Joined groups: quick topics", value: "group-joined-topics" },
154
+ { key: "2", label: "List groups", value: "group-list" },
155
+ { key: "3", label: "Open one group", value: "group-get" },
156
+ { key: "4", label: "List one group's topics", value: "group-topics" },
157
+ { key: "5", label: "Open one topic", value: "group-topic" },
158
+ { key: "6", label: "List group members", value: "group-members" },
159
+ { key: "7", label: "Recent group topics", value: "group-recent-topics" },
160
+ { key: "8", label: "Latest replied topics", value: "group-latest-replies" },
161
+ { key: "9", label: "Hot groups", value: "group-hot" },
162
+ { key: "a", label: "Hot topics", value: "group-hot-topics" },
163
+ { key: "0", label: "Back", value: "back" },
164
+ ],
165
+ "1",
166
+ );
167
+ if (isTuiBackAction(groupAction)) {
168
+ return "menu";
169
+ }
170
+ return runTuiAction(rl, groupAction, context, deps);
171
+ }
172
+ case "config-show":
173
+ await deps.runConfigCommand("show", [], context);
174
+ return;
175
+ case "config-set": {
176
+ const key = await askMenuChoice(
177
+ "Config key",
178
+ [
179
+ { key: "1", label: "accessToken", value: "accessToken" },
180
+ { key: "2", label: "refreshToken", value: "refreshToken" },
181
+ { key: "3", label: "clientId", value: "clientId" },
182
+ { key: "4", label: "clientSecret", value: "clientSecret" },
183
+ { key: "5", label: "redirectUri", value: "redirectUri" },
184
+ { key: "6", label: "oauthServerBaseUrl", value: "oauthServerBaseUrl" },
185
+ { key: "7", label: "userAgent", value: "userAgent" },
186
+ { key: "8", label: "timezone", value: "timezone" },
187
+ ],
188
+ "accessToken",
189
+ );
190
+ if (isTuiBackAction(key)) {
191
+ return "menu";
192
+ }
193
+ const value = await askTuiRequired(rl, `Value for ${key}`);
194
+ await deps.runConfigCommand("set", [key, value], context);
195
+ return;
196
+ }
197
+ case "config-unset": {
198
+ const key = await askMenuChoice(
199
+ "Config key",
200
+ [
201
+ { key: "1", label: "accessToken", value: "accessToken" },
202
+ { key: "2", label: "refreshToken", value: "refreshToken" },
203
+ { key: "3", label: "clientId", value: "clientId" },
204
+ { key: "4", label: "clientSecret", value: "clientSecret" },
205
+ { key: "5", label: "redirectUri", value: "redirectUri" },
206
+ { key: "6", label: "oauthServerBaseUrl", value: "oauthServerBaseUrl" },
207
+ { key: "7", label: "userAgent", value: "userAgent" },
208
+ { key: "8", label: "timezone", value: "timezone" },
209
+ ],
210
+ "accessToken",
211
+ );
212
+ if (isTuiBackAction(key)) {
213
+ return "menu";
214
+ }
215
+ await deps.runConfigCommand("unset", [key], context);
216
+ return;
217
+ }
218
+ case "setup-install-path":
219
+ await deps.runSetupCommand("install-path", [], context);
220
+ return;
221
+ case "setup-update":
222
+ await deps.runSetupCommand("update", [], context);
223
+ return;
224
+ case "user-me":
225
+ await runUserCommand("me", [], context);
226
+ return;
227
+ case "user-get": {
228
+ const username = await askTuiRequired(rl, "Username or numeric user ID");
229
+ await runUserCommand("get", [username], context);
230
+ return;
231
+ }
232
+ case "group-list": {
233
+ const mode = await askMenuChoice(
234
+ "List mode",
235
+ [
236
+ { key: "1", label: "all", value: "all" },
237
+ { key: "2", label: "joined", value: "joined" },
238
+ { key: "3", label: "managed", value: "managed" },
239
+ ],
240
+ "all",
241
+ );
242
+ if (isTuiBackAction(mode)) {
243
+ return "menu";
244
+ }
245
+ const sort = await askMenuChoice(
246
+ "Sort",
247
+ [
248
+ { key: "1", label: "created", value: "created" },
249
+ { key: "2", label: "updated", value: "updated" },
250
+ { key: "3", label: "posts", value: "posts" },
251
+ { key: "4", label: "topics", value: "topics" },
252
+ { key: "5", label: "members", value: "members" },
253
+ ],
254
+ "created",
255
+ );
256
+ if (isTuiBackAction(sort)) {
257
+ return "menu";
258
+ }
259
+ const limit = await askMenuChoice(
260
+ "Limit",
261
+ [
262
+ { key: "1", label: "10", value: "10" },
263
+ { key: "2", label: "20", value: "20" },
264
+ { key: "3", label: "50", value: "50" },
265
+ { key: "4", label: "100", value: "100" },
266
+ ],
267
+ "20",
268
+ );
269
+ if (isTuiBackAction(limit)) {
270
+ return "menu";
271
+ }
272
+ const offset = await askTuiOptional(rl, "Offset", "0");
273
+ const args = ["--mode", mode, "--sort", sort, "--limit", limit];
274
+ if (offset) {
275
+ args.push("--offset", offset);
276
+ }
277
+ const result = await executeGroupListCommand(args);
278
+ await browseGroupResults(result, context, { mode, sort, limit, offset: offset || "0" });
279
+ return "menu";
280
+ }
281
+ case "group-joined-topics": {
282
+ const groupsResult = await executeGroupListCommand(["--mode", "joined", "--sort", "updated", "--limit", "100"]);
283
+ const group = await pickGroupResult(groupsResult, {
284
+ mode: "joined",
285
+ sort: "updated",
286
+ limit: "100",
287
+ });
288
+ if (!group?.name) {
289
+ return "menu";
290
+ }
291
+
292
+ const topicsResult = await executeGroupTopicsCommand([String(group.name), "--limit", "20"]);
293
+ await browseGroupTopicResults(topicsResult, context, {
294
+ source: "joined groups",
295
+ group: group.name,
296
+ limit: "20",
297
+ });
298
+ return "menu";
299
+ }
300
+ case "group-get": {
301
+ const groupName = await askTuiRequired(rl, "Group slug");
302
+ const result = await executeGroupGetCommand([groupName]);
303
+ renderTuiResultScreen("Group detail", formatDisplayResult(result, context));
304
+ return;
305
+ }
306
+ case "group-topics": {
307
+ const groupName = await askTuiRequired(rl, "Group slug");
308
+ const limit = await askMenuChoice(
309
+ "Limit",
310
+ [
311
+ { key: "1", label: "10", value: "10" },
312
+ { key: "2", label: "20", value: "20" },
313
+ { key: "3", label: "50", value: "50" },
314
+ { key: "4", label: "100", value: "100" },
315
+ ],
316
+ "20",
317
+ );
318
+ if (isTuiBackAction(limit)) {
319
+ return "menu";
320
+ }
321
+ const offset = await askTuiOptional(rl, "Offset", "0");
322
+ const args = [groupName, "--limit", limit];
323
+ if (offset) {
324
+ args.push("--offset", offset);
325
+ }
326
+ const result = await executeGroupTopicsCommand(args);
327
+ await browseGroupTopicResults(result, context, { group: groupName, limit, offset: offset || "0" });
328
+ return "menu";
329
+ }
330
+ case "group-topic": {
331
+ const topicId = await askTuiRequired(rl, "Topic ID");
332
+ const replyLimit = await askMenuChoice(
333
+ "Reply excerpts",
334
+ [
335
+ { key: "1", label: "10", value: "10" },
336
+ { key: "2", label: "20", value: "20" },
337
+ { key: "3", label: "50", value: "50" },
338
+ { key: "4", label: "100", value: "100" },
339
+ ],
340
+ "20",
341
+ );
342
+ if (isTuiBackAction(replyLimit)) {
343
+ return "menu";
344
+ }
345
+ const result = await executeGroupTopicCommand([topicId, "--reply-limit", replyLimit]);
346
+ renderTuiResultScreen("Group topic", formatDisplayResult(result, context));
347
+ return;
348
+ }
349
+ case "group-members": {
350
+ const groupName = await askTuiRequired(rl, "Group slug");
351
+ const role = await askMenuChoice(
352
+ "Role filter",
353
+ [
354
+ { key: "1", label: "All roles", value: "" },
355
+ { key: "2", label: "visitor", value: "visitor" },
356
+ { key: "3", label: "guest", value: "guest" },
357
+ { key: "4", label: "member", value: "member" },
358
+ { key: "5", label: "creator", value: "creator" },
359
+ { key: "6", label: "moderator", value: "moderator" },
360
+ { key: "7", label: "blocked", value: "blocked" },
361
+ ],
362
+ "",
363
+ );
364
+ if (isTuiBackAction(role)) {
365
+ return "menu";
366
+ }
367
+ const limit = await askMenuChoice(
368
+ "Limit",
369
+ [
370
+ { key: "1", label: "10", value: "10" },
371
+ { key: "2", label: "20", value: "20" },
372
+ { key: "3", label: "50", value: "50" },
373
+ { key: "4", label: "100", value: "100" },
374
+ ],
375
+ "20",
376
+ );
377
+ if (isTuiBackAction(limit)) {
378
+ return "menu";
379
+ }
380
+ const offset = await askTuiOptional(rl, "Offset", "0");
381
+ const args = [groupName, "--limit", limit];
382
+ if (role) {
383
+ args.push("--role", role);
384
+ }
385
+ if (offset) {
386
+ args.push("--offset", offset);
387
+ }
388
+ const result = await executeGroupMembersCommand(args);
389
+ renderTuiResultScreen(
390
+ "Group members",
391
+ formatDisplayResult(result, context),
392
+ formatCriteriaSummary({ group: groupName, role: role || "all", limit, offset: offset || "0" }),
393
+ );
394
+ return;
395
+ }
396
+ case "group-recent-topics": {
397
+ const mode = await askMenuChoice(
398
+ "Topic mode",
399
+ [
400
+ { key: "1", label: "all", value: "all" },
401
+ { key: "2", label: "joined", value: "joined" },
402
+ { key: "3", label: "created", value: "created" },
403
+ { key: "4", label: "replied", value: "replied" },
404
+ ],
405
+ "all",
406
+ );
407
+ if (isTuiBackAction(mode)) {
408
+ return "menu";
409
+ }
410
+ const limit = await askMenuChoice(
411
+ "Limit",
412
+ [
413
+ { key: "1", label: "10", value: "10" },
414
+ { key: "2", label: "20", value: "20" },
415
+ { key: "3", label: "50", value: "50" },
416
+ { key: "4", label: "100", value: "100" },
417
+ ],
418
+ "20",
419
+ );
420
+ if (isTuiBackAction(limit)) {
421
+ return "menu";
422
+ }
423
+ const offset = await askTuiOptional(rl, "Offset", "0");
424
+ const args = ["--mode", mode, "--limit", limit];
425
+ if (offset) {
426
+ args.push("--offset", offset);
427
+ }
428
+ const result = await executeRecentGroupTopicsCommand(args);
429
+ await browseGroupTopicResults(result, context, { mode, limit, offset: offset || "0" });
430
+ return "menu";
431
+ }
432
+ case "group-latest-replies": {
433
+ const mode = await askMenuChoice(
434
+ "Topic mode",
435
+ [
436
+ { key: "1", label: "all", value: "all" },
437
+ { key: "2", label: "joined", value: "joined" },
438
+ { key: "3", label: "created", value: "created" },
439
+ { key: "4", label: "replied", value: "replied" },
440
+ ],
441
+ "all",
442
+ );
443
+ if (isTuiBackAction(mode)) {
444
+ return "menu";
445
+ }
446
+ const limit = await askMenuChoice(
447
+ "Limit",
448
+ [
449
+ { key: "1", label: "10", value: "10" },
450
+ { key: "2", label: "20", value: "20" },
451
+ { key: "3", label: "50", value: "50" },
452
+ ],
453
+ "10",
454
+ );
455
+ if (isTuiBackAction(limit)) {
456
+ return "menu";
457
+ }
458
+ const scan = await askMenuChoice(
459
+ "Scan cap",
460
+ [
461
+ { key: "1", label: "50", value: "50" },
462
+ { key: "2", label: "100", value: "100" },
463
+ { key: "3", label: "200", value: "200" },
464
+ { key: "4", label: "500", value: "500" },
465
+ ],
466
+ "100",
467
+ );
468
+ if (isTuiBackAction(scan)) {
469
+ return "menu";
470
+ }
471
+ const result = await executeLatestRepliedGroupTopicsCommand(["--mode", mode, "--limit", limit, "--scan", scan]);
472
+ await browseGroupTopicResults(result, context, { mode, limit, scan });
473
+ return "menu";
474
+ }
475
+ case "group-hot": {
476
+ const window = await askMenuChoice(
477
+ "Window",
478
+ [
479
+ { key: "1", label: "day", value: "day" },
480
+ { key: "2", label: "week", value: "week" },
481
+ { key: "3", label: "month", value: "month" },
482
+ ],
483
+ "day",
484
+ );
485
+ if (isTuiBackAction(window)) {
486
+ return "menu";
487
+ }
488
+ const mode = await askMenuChoice(
489
+ "Topic mode",
490
+ [
491
+ { key: "1", label: "all", value: "all" },
492
+ { key: "2", label: "joined", value: "joined" },
493
+ { key: "3", label: "created", value: "created" },
494
+ { key: "4", label: "replied", value: "replied" },
495
+ ],
496
+ "all",
497
+ );
498
+ if (isTuiBackAction(mode)) {
499
+ return "menu";
500
+ }
501
+ const limit = await askMenuChoice(
502
+ "Limit",
503
+ [
504
+ { key: "1", label: "10", value: "10" },
505
+ { key: "2", label: "20", value: "20" },
506
+ { key: "3", label: "50", value: "50" },
507
+ ],
508
+ "10",
509
+ );
510
+ if (isTuiBackAction(limit)) {
511
+ return "menu";
512
+ }
513
+ const scan = await askMenuChoice(
514
+ "Scan cap",
515
+ [
516
+ { key: "1", label: "100", value: "100" },
517
+ { key: "2", label: "200", value: "200" },
518
+ { key: "3", label: "500", value: "500" },
519
+ { key: "4", label: "1000", value: "1000" },
520
+ ],
521
+ "200",
522
+ );
523
+ if (isTuiBackAction(scan)) {
524
+ return "menu";
525
+ }
526
+ const result = await executeHotGroupsCommand(["--window", window, "--mode", mode, "--limit", limit, "--scan", scan]);
527
+ await browseGroupResults(result, context, { window, mode, limit, scan });
528
+ return "menu";
529
+ }
530
+ case "group-hot-topics": {
531
+ const window = await askMenuChoice(
532
+ "Window",
533
+ [
534
+ { key: "1", label: "day", value: "day" },
535
+ { key: "2", label: "week", value: "week" },
536
+ { key: "3", label: "month", value: "month" },
537
+ ],
538
+ "day",
539
+ );
540
+ if (isTuiBackAction(window)) {
541
+ return "menu";
542
+ }
543
+ const mode = await askMenuChoice(
544
+ "Topic mode",
545
+ [
546
+ { key: "1", label: "all", value: "all" },
547
+ { key: "2", label: "joined", value: "joined" },
548
+ { key: "3", label: "created", value: "created" },
549
+ { key: "4", label: "replied", value: "replied" },
550
+ ],
551
+ "all",
552
+ );
553
+ if (isTuiBackAction(mode)) {
554
+ return "menu";
555
+ }
556
+ const limit = await askMenuChoice(
557
+ "Limit",
558
+ [
559
+ { key: "1", label: "10", value: "10" },
560
+ { key: "2", label: "20", value: "20" },
561
+ { key: "3", label: "50", value: "50" },
562
+ ],
563
+ "10",
564
+ );
565
+ if (isTuiBackAction(limit)) {
566
+ return "menu";
567
+ }
568
+ const scan = await askMenuChoice(
569
+ "Scan cap",
570
+ [
571
+ { key: "1", label: "100", value: "100" },
572
+ { key: "2", label: "200", value: "200" },
573
+ { key: "3", label: "500", value: "500" },
574
+ { key: "4", label: "1000", value: "1000" },
575
+ ],
576
+ "200",
577
+ );
578
+ if (isTuiBackAction(scan)) {
579
+ return "menu";
580
+ }
581
+ const result = await executeHotGroupTopicsCommand(["--window", window, "--mode", mode, "--limit", limit, "--scan", scan]);
582
+ await browseGroupTopicResults(result, context, { window, mode, limit, scan });
583
+ return "menu";
584
+ }
585
+ case "subject-get": {
586
+ const subjectId = await askTuiRequired(rl, "Subject ID");
587
+ const client = new BangumiClient(getConfig());
588
+ const subject = await client.getSubject(subjectId);
589
+ await browseSubjectDetailActions(client, subject, context);
590
+ return "menu";
591
+ }
592
+ case "subject-list": {
593
+ const type = await askMenuChoice(
594
+ "Subject type",
595
+ [
596
+ { key: "1", label: "book", value: "book" },
597
+ { key: "2", label: "anime", value: "anime" },
598
+ { key: "3", label: "music", value: "music" },
599
+ { key: "4", label: "game", value: "game" },
600
+ { key: "5", label: "real", value: "real" },
601
+ ],
602
+ "anime",
603
+ );
604
+ if (isTuiBackAction(type)) {
605
+ return "menu";
606
+ }
607
+ const sort = await askMenuChoice(
608
+ "Sort",
609
+ [
610
+ { key: "1", label: "rank", value: "rank" },
611
+ { key: "2", label: "date", value: "date" },
612
+ ],
613
+ "rank",
614
+ );
615
+ if (isTuiBackAction(sort)) {
616
+ return "menu";
617
+ }
618
+ const year = await askTuiOptional(rl, "Year filter", "");
619
+ const month = await askTuiOptional(rl, "Month filter", "");
620
+ const limit = await askMenuChoice(
621
+ "Limit",
622
+ [
623
+ { key: "1", label: "10", value: "10" },
624
+ { key: "2", label: "20", value: "20" },
625
+ { key: "3", label: "50", value: "50" },
626
+ { key: "4", label: "100", value: "100" },
627
+ ],
628
+ "10",
629
+ );
630
+ if (isTuiBackAction(limit)) {
631
+ return "menu";
632
+ }
633
+ const args = ["--type", type];
634
+ if (sort) {
635
+ args.push("--sort", sort);
636
+ }
637
+ if (year) {
638
+ args.push("--year", year);
639
+ }
640
+ if (month) {
641
+ args.push("--month", month);
642
+ }
643
+ if (limit) {
644
+ args.push("--limit", limit);
645
+ }
646
+ const result = await executeSubjectListCommand(args);
647
+ await browseSubjectResults(result, context, {
648
+ mode: "list",
649
+ type,
650
+ sort,
651
+ year: year || "any",
652
+ month: month || "any",
653
+ limit,
654
+ });
655
+ return "menu";
656
+ }
657
+ case "subject-search": {
658
+ const keyword = await askTuiRequired(rl, "Keyword");
659
+ const type = await askMenuChoice(
660
+ "Type filter",
661
+ [
662
+ { key: "1", label: "All types", value: "" },
663
+ { key: "2", label: "anime", value: "anime" },
664
+ { key: "3", label: "book", value: "book" },
665
+ { key: "4", label: "music", value: "music" },
666
+ { key: "5", label: "game", value: "game" },
667
+ { key: "6", label: "real", value: "real" },
668
+ ],
669
+ "",
670
+ );
671
+ if (isTuiBackAction(type)) {
672
+ return "menu";
673
+ }
674
+ const sort = await askMenuChoice(
675
+ "Sort",
676
+ [
677
+ { key: "1", label: "match", value: "match" },
678
+ { key: "2", label: "heat", value: "heat" },
679
+ { key: "3", label: "rank", value: "rank" },
680
+ { key: "4", label: "score", value: "score" },
681
+ ],
682
+ "match",
683
+ );
684
+ if (isTuiBackAction(sort)) {
685
+ return "menu";
686
+ }
687
+ const limit = await askMenuChoice(
688
+ "Limit",
689
+ [
690
+ { key: "1", label: "10", value: "10" },
691
+ { key: "2", label: "20", value: "20" },
692
+ { key: "3", label: "50", value: "50" },
693
+ ],
694
+ "10",
695
+ );
696
+ if (isTuiBackAction(limit)) {
697
+ return "menu";
698
+ }
699
+ const args = [keyword];
700
+ if (type) {
701
+ args.push("--type", type);
702
+ }
703
+ if (sort) {
704
+ args.push("--sort", sort);
705
+ }
706
+ if (limit) {
707
+ args.push("--limit", limit);
708
+ }
709
+ const result = await executeSubjectSearchCommand(args);
710
+ await browseSubjectResults(result, context, {
711
+ mode: "search",
712
+ keyword,
713
+ type: type || "all",
714
+ sort,
715
+ limit,
716
+ });
717
+ return "menu";
718
+ }
719
+ case "collection-list": {
720
+ const targetMode = await askMenuChoice(
721
+ "Collection target user",
722
+ [
723
+ { key: "1", label: "Current authenticated user", value: "me" },
724
+ { key: "2", label: "Enter a username manually", value: "manual" },
725
+ ],
726
+ "me",
727
+ );
728
+ if (isTuiBackAction(targetMode)) {
729
+ return "menu";
730
+ }
731
+ const username = targetMode === "manual" ? await askTuiRequired(rl, "Username") : "";
732
+ const type = await askMenuChoice(
733
+ "Type filter",
734
+ [
735
+ { key: "1", label: "All types", value: "" },
736
+ { key: "2", label: "anime", value: "anime" },
737
+ { key: "3", label: "book", value: "book" },
738
+ { key: "4", label: "music", value: "music" },
739
+ { key: "5", label: "game", value: "game" },
740
+ { key: "6", label: "real", value: "real" },
741
+ ],
742
+ "",
743
+ );
744
+ if (isTuiBackAction(type)) {
745
+ return "menu";
746
+ }
747
+ const status = await askMenuChoice(
748
+ "Status filter",
749
+ [
750
+ { key: "1", label: "All statuses", value: "" },
751
+ { key: "2", label: "wish", value: "wish" },
752
+ { key: "3", label: "collect", value: "collect" },
753
+ { key: "4", label: "doing", value: "doing" },
754
+ { key: "5", label: "on_hold", value: "on_hold" },
755
+ { key: "6", label: "dropped", value: "dropped" },
756
+ ],
757
+ "",
758
+ );
759
+ if (isTuiBackAction(status)) {
760
+ return "menu";
761
+ }
762
+ const sort = await askMenuChoice(
763
+ "Sort",
764
+ [
765
+ { key: "1", label: "updated", value: "updated" },
766
+ { key: "2", label: "name", value: "name" },
767
+ { key: "3", label: "rank", value: "rank" },
768
+ { key: "4", label: "community_score", value: "community_score" },
769
+ { key: "5", label: "user_score", value: "user_score" },
770
+ { key: "6", label: "date", value: "date" },
771
+ ],
772
+ "updated",
773
+ );
774
+ if (isTuiBackAction(sort)) {
775
+ return "menu";
776
+ }
777
+ const order = await askMenuChoice(
778
+ "Order",
779
+ [
780
+ { key: "1", label: "desc", value: "desc" },
781
+ { key: "2", label: "asc", value: "asc" },
782
+ ],
783
+ "desc",
784
+ );
785
+ if (isTuiBackAction(order)) {
786
+ return "menu";
787
+ }
788
+ const limit = await askMenuChoice(
789
+ "Limit",
790
+ [
791
+ { key: "1", label: "10", value: "10" },
792
+ { key: "2", label: "20", value: "20" },
793
+ { key: "3", label: "50", value: "50" },
794
+ { key: "4", label: "100", value: "100" },
795
+ ],
796
+ "20",
797
+ );
798
+ if (isTuiBackAction(limit)) {
799
+ return "menu";
800
+ }
801
+ const args = [];
802
+ if (username) {
803
+ args.push("--user", username);
804
+ }
805
+ if (status) {
806
+ args.push("--status", status);
807
+ }
808
+ if (type) {
809
+ args.push("--type", type);
810
+ }
811
+ if (sort) {
812
+ args.push("--sort", sort);
813
+ }
814
+ if (order) {
815
+ args.push("--order", order);
816
+ }
817
+ if (limit) {
818
+ args.push("--limit", limit);
819
+ }
820
+ const result = await executeCollectionListCommand(args);
821
+ await browseCollectionResults(result, context, {
822
+ user: username || "(current user)",
823
+ type: type || "all",
824
+ status: status || "all",
825
+ sort,
826
+ order,
827
+ limit,
828
+ });
829
+ return "menu";
830
+ }
831
+ case "collection-get": {
832
+ const target = await askTuiCollectionTarget(rl);
833
+ if (target === "menu") {
834
+ return "menu";
835
+ }
836
+ const result = await executeCollectionGetCommand(buildCollectionTargetArgs(target));
837
+ renderTuiResultScreen("Collection detail", formatDisplayResult(result, context));
838
+ return;
839
+ }
840
+ case "collection-collect": {
841
+ const target = await askTuiCollectionTarget(rl);
842
+ if (target === "menu") {
843
+ return "menu";
844
+ }
845
+ const snapshot = await fetchTuiCollectionSnapshot(target.subjectId);
846
+ const status = await askMenuChoice(
847
+ "Collection status",
848
+ [
849
+ { key: "1", label: "wish", value: "wish" },
850
+ { key: "2", label: "collect", value: "collect" },
851
+ { key: "3", label: "doing", value: "doing" },
852
+ { key: "4", label: "on_hold", value: "on_hold" },
853
+ { key: "5", label: "dropped", value: "dropped" },
854
+ ],
855
+ getCollectionStatusKey(snapshot?.type) ?? "wish",
856
+ {
857
+ summary: formatCollectionSnapshotSummary(snapshot),
858
+ },
859
+ );
860
+ if (isTuiBackAction(status)) {
861
+ return "menu";
862
+ }
863
+ const result = await executeCollectionCollectCommand([
864
+ ...buildCollectionTargetArgs(target),
865
+ status,
866
+ ]);
867
+ renderTuiResultScreen("Collection update", formatDisplayResult(result, context));
868
+ return;
869
+ }
870
+ case "collection-comment": {
871
+ const target = await askTuiCollectionTarget(rl);
872
+ if (target === "menu") {
873
+ return "menu";
874
+ }
875
+ const snapshot = await fetchTuiCollectionSnapshot(target.subjectId);
876
+ const commentInput = await askTuiOptional(
877
+ rl,
878
+ "Comment",
879
+ snapshot?.comment ?? "",
880
+ `${formatCollectionSnapshotSummary(snapshot)}\nType a single dash (-) to clear the comment.`,
881
+ );
882
+ const comment = commentInput === "-" ? "" : commentInput;
883
+ const result = await executeCollectionCommentCommand([
884
+ ...buildCollectionTargetArgs(target),
885
+ comment,
886
+ ]);
887
+ renderTuiResultScreen("Collection comment", formatDisplayResult(result, context));
888
+ return;
889
+ }
890
+ case "collection-rate": {
891
+ const target = await askTuiCollectionTarget(rl);
892
+ if (target === "menu") {
893
+ return "menu";
894
+ }
895
+ const snapshot = await fetchTuiCollectionSnapshot(target.subjectId);
896
+ const rating = await askMenuChoice(
897
+ "Rating",
898
+ [
899
+ { key: "0", label: "0", value: "0" },
900
+ { key: "1", label: "1", value: "1" },
901
+ { key: "2", label: "2", value: "2" },
902
+ { key: "3", label: "3", value: "3" },
903
+ { key: "4", label: "4", value: "4" },
904
+ { key: "5", label: "5", value: "5" },
905
+ { key: "6", label: "6", value: "6" },
906
+ { key: "7", label: "7", value: "7" },
907
+ { key: "8", label: "8", value: "8" },
908
+ { key: "9", label: "9", value: "9" },
909
+ { key: "10", label: "10", value: "10" },
910
+ ],
911
+ snapshot ? String(snapshot.rate ?? 0) : "7",
912
+ {
913
+ summary: formatCollectionSnapshotSummary(snapshot),
914
+ },
915
+ );
916
+ if (isTuiBackAction(rating)) {
917
+ return "menu";
918
+ }
919
+ const result = await executeCollectionRateCommand([
920
+ ...buildCollectionTargetArgs(target),
921
+ rating,
922
+ ]);
923
+ renderTuiResultScreen("Collection rating", formatDisplayResult(result, context));
924
+ return;
925
+ }
926
+ case "collection-status": {
927
+ const target = await askTuiCollectionTarget(rl);
928
+ if (target === "menu") {
929
+ return "menu";
930
+ }
931
+ const snapshot = await fetchTuiCollectionSnapshot(target.subjectId);
932
+ const status = await askMenuChoice(
933
+ "Collection status",
934
+ [
935
+ { key: "1", label: "wish", value: "wish" },
936
+ { key: "2", label: "collect", value: "collect" },
937
+ { key: "3", label: "doing", value: "doing" },
938
+ { key: "4", label: "on_hold", value: "on_hold" },
939
+ { key: "5", label: "dropped", value: "dropped" },
940
+ ],
941
+ getCollectionStatusKey(snapshot?.type) ?? "collect",
942
+ {
943
+ summary: formatCollectionSnapshotSummary(snapshot),
944
+ },
945
+ );
946
+ if (isTuiBackAction(status)) {
947
+ return "menu";
948
+ }
949
+ const result = await executeCollectionStatusCommand([
950
+ ...buildCollectionTargetArgs(target),
951
+ status,
952
+ ]);
953
+ renderTuiResultScreen("Collection status", formatDisplayResult(result, context));
954
+ return;
955
+ }
956
+ default:
957
+ throw new CommandError(`Unsupported TUI action: ${action}`);
958
+ }
959
+ }
960
+
961
+ async function askTuiCollectionTarget(rl) {
962
+ const targetMode = await askMenuChoice(
963
+ "Collection target",
964
+ [
965
+ { key: "1", label: "Enter subject ID directly", value: "id" },
966
+ { key: "2", label: "Search subjects and choose one", value: "search" },
967
+ ],
968
+ "id",
969
+ );
970
+
971
+ if (isTuiBackAction(targetMode)) {
972
+ return "menu";
973
+ }
974
+
975
+ if (targetMode === "id") {
976
+ const subjectId = await askTuiRequired(rl, "Subject ID");
977
+ return { mode: "id", subjectId };
978
+ }
979
+
980
+ const keyword = await askTuiRequired(rl, "Keyword");
981
+ const type = await askMenuChoice(
982
+ "Type filter",
983
+ [
984
+ { key: "1", label: "All types", value: "" },
985
+ { key: "2", label: "anime", value: "anime" },
986
+ { key: "3", label: "book", value: "book" },
987
+ { key: "4", label: "music", value: "music" },
988
+ { key: "5", label: "game", value: "game" },
989
+ { key: "6", label: "real", value: "real" },
990
+ ],
991
+ "",
992
+ );
993
+ if (isTuiBackAction(type)) {
994
+ return "menu";
995
+ }
996
+
997
+ const sort = await askMenuChoice(
998
+ "Sort",
999
+ [
1000
+ { key: "1", label: "match", value: "match" },
1001
+ { key: "2", label: "heat", value: "heat" },
1002
+ { key: "3", label: "rank", value: "rank" },
1003
+ { key: "4", label: "score", value: "score" },
1004
+ ],
1005
+ "match",
1006
+ );
1007
+ if (isTuiBackAction(sort)) {
1008
+ return "menu";
1009
+ }
1010
+
1011
+ const limit = await askMenuChoice(
1012
+ "Limit",
1013
+ [
1014
+ { key: "1", label: "10", value: "10" },
1015
+ { key: "2", label: "20", value: "20" },
1016
+ { key: "3", label: "50", value: "50" },
1017
+ ],
1018
+ "10",
1019
+ );
1020
+ if (isTuiBackAction(limit)) {
1021
+ return "menu";
1022
+ }
1023
+
1024
+ const args = [keyword];
1025
+ if (type) {
1026
+ args.push("--type", type);
1027
+ }
1028
+ if (sort) {
1029
+ args.push("--sort", sort);
1030
+ }
1031
+ if (limit) {
1032
+ args.push("--limit", limit);
1033
+ }
1034
+
1035
+ const result = await executeSubjectSearchCommand(args);
1036
+ const subjects = Array.isArray(result?.data) ? result.data : [];
1037
+ if (subjects.length === 0) {
1038
+ renderTuiResultScreen("Subject results", formatDisplayResult(result, {}), "No target found.");
1039
+ await waitForTuiContinue();
1040
+ return "menu";
1041
+ }
1042
+
1043
+ const choice = await askMenuChoice(
1044
+ "Choose subject",
1045
+ [
1046
+ ...subjects.map((subject, index) => ({
1047
+ key: String(index + 1),
1048
+ label: formatSubjectMenuLabel(subject),
1049
+ value: String(index),
1050
+ })),
1051
+ { key: "0", label: "Back", value: "back" },
1052
+ ],
1053
+ "0",
1054
+ {
1055
+ summary: formatCriteriaSummary({
1056
+ keyword,
1057
+ type: type || "all",
1058
+ sort,
1059
+ limit,
1060
+ }),
1061
+ },
1062
+ );
1063
+
1064
+ if (isTuiBackAction(choice)) {
1065
+ return "menu";
1066
+ }
1067
+
1068
+ const subject = subjects[Number(choice)];
1069
+ if (!subject?.id) {
1070
+ return "menu";
1071
+ }
1072
+
1073
+ return {
1074
+ mode: "id",
1075
+ subjectId: String(subject.id),
1076
+ };
1077
+ }
1078
+
1079
+ async function browseSubjectResults(result, context, criteria = {}) {
1080
+ const client = new BangumiClient(getConfig());
1081
+ const subjects = Array.isArray(result?.data) ? result.data : [];
1082
+ const summary = formatCriteriaSummary(criteria);
1083
+
1084
+ if (subjects.length === 0) {
1085
+ renderTuiResultScreen("Subject results", formatDisplayResult(result, context), summary);
1086
+ return;
1087
+ }
1088
+
1089
+ let pageIndex = 0;
1090
+ while (true) {
1091
+ const page = buildPagedMenu(subjects, pageIndex, formatSubjectMenuLabel);
1092
+ const choice = await askMenuChoice(
1093
+ "Subject results",
1094
+ [
1095
+ ...page.items.map((subject, index) => ({
1096
+ key: String(index + 1),
1097
+ label: formatSubjectMenuLabel(subject),
1098
+ value: String(page.startIndex + index),
1099
+ })),
1100
+ ...(page.hasPrevious ? [{ key: "8", label: "Previous page", value: "page-prev" }] : []),
1101
+ ...(page.hasNext ? [{ key: "9", label: "Next page", value: "page-next" }] : []),
1102
+ { key: "0", label: "Back", value: "back" },
1103
+ ],
1104
+ "0",
1105
+ {
1106
+ summary: [summary, formatPageSummary(subjects.length, pageIndex, page.pageCount)]
1107
+ .filter(Boolean)
1108
+ .join("\n"),
1109
+ },
1110
+ );
1111
+
1112
+ if (isTuiBackAction(choice)) {
1113
+ return;
1114
+ }
1115
+ if (choice === "page-prev") {
1116
+ pageIndex = Math.max(0, pageIndex - 1);
1117
+ continue;
1118
+ }
1119
+ if (choice === "page-next") {
1120
+ pageIndex = Math.min(page.pageCount - 1, pageIndex + 1);
1121
+ continue;
1122
+ }
1123
+
1124
+ const subject = subjects[Number(choice)];
1125
+ if (!subject) {
1126
+ continue;
1127
+ }
1128
+
1129
+ await browseSubjectDetailActions(client, subject, context);
1130
+ }
1131
+ }
1132
+
1133
+ async function browseCollectionResults(result, context, criteria = {}) {
1134
+ const client = new BangumiClient(getConfig());
1135
+ const items = Array.isArray(result?.data) ? result.data : [];
1136
+ const summary = formatCriteriaSummary(criteria);
1137
+
1138
+ if (items.length === 0) {
1139
+ renderTuiResultScreen("Collection results", formatDisplayResult(result, context), summary);
1140
+ return;
1141
+ }
1142
+
1143
+ let pageIndex = 0;
1144
+ while (true) {
1145
+ const page = buildPagedMenu(items, pageIndex, formatCollectionMenuLabel);
1146
+ const choice = await askMenuChoice(
1147
+ "Collection results",
1148
+ [
1149
+ ...page.items.map((item, index) => ({
1150
+ key: String(index + 1),
1151
+ label: formatCollectionMenuLabel(item),
1152
+ value: String(page.startIndex + index),
1153
+ })),
1154
+ ...(page.hasPrevious ? [{ key: "8", label: "Previous page", value: "page-prev" }] : []),
1155
+ ...(page.hasNext ? [{ key: "9", label: "Next page", value: "page-next" }] : []),
1156
+ { key: "0", label: "Back", value: "back" },
1157
+ ],
1158
+ "0",
1159
+ {
1160
+ summary: [summary, formatPageSummary(items.length, pageIndex, page.pageCount)]
1161
+ .filter(Boolean)
1162
+ .join("\n"),
1163
+ },
1164
+ );
1165
+
1166
+ if (isTuiBackAction(choice)) {
1167
+ return;
1168
+ }
1169
+ if (choice === "page-prev") {
1170
+ pageIndex = Math.max(0, pageIndex - 1);
1171
+ continue;
1172
+ }
1173
+ if (choice === "page-next") {
1174
+ pageIndex = Math.min(page.pageCount - 1, pageIndex + 1);
1175
+ continue;
1176
+ }
1177
+
1178
+ const item = items[Number(choice)];
1179
+ if (!item?.subject_id) {
1180
+ continue;
1181
+ }
1182
+
1183
+ await browseSubjectDetailActions(
1184
+ client,
1185
+ {
1186
+ id: item.subject_id,
1187
+ name_cn: item?.subject?.name_cn,
1188
+ name: item?.subject?.name,
1189
+ },
1190
+ context,
1191
+ );
1192
+ }
1193
+ }
1194
+
1195
+ async function browseGroupResults(result, context, criteria = {}) {
1196
+ const items = Array.isArray(result?.data) ? result.data : [];
1197
+ const summary = formatCriteriaSummary(criteria);
1198
+
1199
+ if (items.length === 0) {
1200
+ renderTuiResultScreen("Group results", formatDisplayResult(result, context), summary);
1201
+ return;
1202
+ }
1203
+
1204
+ let pageIndex = 0;
1205
+ while (true) {
1206
+ const page = buildPagedMenu(items, pageIndex, formatGroupMenuLabel);
1207
+ const choice = await askMenuChoice(
1208
+ "Group results",
1209
+ [
1210
+ ...page.items.map((item, index) => ({
1211
+ key: String(index + 1),
1212
+ label: formatGroupMenuLabel(item),
1213
+ value: String(page.startIndex + index),
1214
+ })),
1215
+ ...(page.hasPrevious ? [{ key: "8", label: "Previous page", value: "page-prev" }] : []),
1216
+ ...(page.hasNext ? [{ key: "9", label: "Next page", value: "page-next" }] : []),
1217
+ { key: "0", label: "Back", value: "back" },
1218
+ ],
1219
+ "0",
1220
+ {
1221
+ summary: [summary, formatPageSummary(items.length, pageIndex, page.pageCount)]
1222
+ .filter(Boolean)
1223
+ .join("\n"),
1224
+ },
1225
+ );
1226
+
1227
+ if (isTuiBackAction(choice)) {
1228
+ return;
1229
+ }
1230
+ if (choice === "page-prev") {
1231
+ pageIndex = Math.max(0, pageIndex - 1);
1232
+ continue;
1233
+ }
1234
+ if (choice === "page-next") {
1235
+ pageIndex = Math.min(page.pageCount - 1, pageIndex + 1);
1236
+ continue;
1237
+ }
1238
+
1239
+ const group = items[Number(choice)];
1240
+ const groupName = group?.name;
1241
+ if (!groupName) {
1242
+ renderTuiResultScreen("Group result", formatDisplayResult(group, context));
1243
+ await waitForTuiContinue();
1244
+ continue;
1245
+ }
1246
+
1247
+ const detail = await executeGroupGetCommand([String(groupName)]);
1248
+ renderTuiResultScreen("Group detail", formatDisplayResult(detail, context));
1249
+ await waitForTuiContinue();
1250
+ }
1251
+ }
1252
+
1253
+ async function pickGroupResult(result, criteria = {}) {
1254
+ const items = Array.isArray(result?.data) ? result.data : [];
1255
+ const summary = formatCriteriaSummary(criteria);
1256
+
1257
+ if (items.length === 0) {
1258
+ renderTuiResultScreen("Choose group", formatDisplayResult(result, {}), summary || "No groups found.");
1259
+ await waitForTuiContinue();
1260
+ return null;
1261
+ }
1262
+
1263
+ let pageIndex = 0;
1264
+ while (true) {
1265
+ const page = buildPagedMenu(items, pageIndex, formatGroupMenuLabel);
1266
+ const choice = await askMenuChoice(
1267
+ "Choose group",
1268
+ [
1269
+ ...page.items.map((item, index) => ({
1270
+ key: String(index + 1),
1271
+ label: formatGroupMenuLabel(item),
1272
+ value: String(page.startIndex + index),
1273
+ })),
1274
+ ...(page.hasPrevious ? [{ key: "8", label: "Previous page", value: "page-prev" }] : []),
1275
+ ...(page.hasNext ? [{ key: "9", label: "Next page", value: "page-next" }] : []),
1276
+ { key: "0", label: "Back", value: "back" },
1277
+ ],
1278
+ "0",
1279
+ {
1280
+ summary: [summary, formatPageSummary(items.length, pageIndex, page.pageCount)]
1281
+ .filter(Boolean)
1282
+ .join("\n"),
1283
+ },
1284
+ );
1285
+
1286
+ if (isTuiBackAction(choice)) {
1287
+ return null;
1288
+ }
1289
+ if (choice === "page-prev") {
1290
+ pageIndex = Math.max(0, pageIndex - 1);
1291
+ continue;
1292
+ }
1293
+ if (choice === "page-next") {
1294
+ pageIndex = Math.min(page.pageCount - 1, pageIndex + 1);
1295
+ continue;
1296
+ }
1297
+
1298
+ const group = items[Number(choice)];
1299
+ if (group) {
1300
+ return group;
1301
+ }
1302
+ }
1303
+ }
1304
+
1305
+ async function browseGroupTopicResults(result, context, criteria = {}) {
1306
+ const items = Array.isArray(result?.data) ? result.data : [];
1307
+ const summary = formatCriteriaSummary(criteria);
1308
+
1309
+ if (items.length === 0) {
1310
+ renderTuiResultScreen("Group topics", formatDisplayResult(result, context), summary);
1311
+ return;
1312
+ }
1313
+
1314
+ let pageIndex = 0;
1315
+ while (true) {
1316
+ const page = buildPagedMenu(items, pageIndex, formatGroupTopicMenuLabel);
1317
+ const choice = await askMenuChoice(
1318
+ "Group topics",
1319
+ [
1320
+ ...page.items.map((item, index) => ({
1321
+ key: String(index + 1),
1322
+ label: formatGroupTopicMenuLabel(item),
1323
+ value: String(page.startIndex + index),
1324
+ })),
1325
+ ...(page.hasPrevious ? [{ key: "8", label: "Previous page", value: "page-prev" }] : []),
1326
+ ...(page.hasNext ? [{ key: "9", label: "Next page", value: "page-next" }] : []),
1327
+ { key: "0", label: "Back", value: "back" },
1328
+ ],
1329
+ "0",
1330
+ {
1331
+ summary: [summary, formatPageSummary(items.length, pageIndex, page.pageCount)]
1332
+ .filter(Boolean)
1333
+ .join("\n"),
1334
+ },
1335
+ );
1336
+
1337
+ if (isTuiBackAction(choice)) {
1338
+ return;
1339
+ }
1340
+ if (choice === "page-prev") {
1341
+ pageIndex = Math.max(0, pageIndex - 1);
1342
+ continue;
1343
+ }
1344
+ if (choice === "page-next") {
1345
+ pageIndex = Math.min(page.pageCount - 1, pageIndex + 1);
1346
+ continue;
1347
+ }
1348
+
1349
+ const topic = items[Number(choice)];
1350
+ if (!topic?.id) {
1351
+ continue;
1352
+ }
1353
+
1354
+ const detail = await executeGroupTopicCommand([String(topic.id), "--reply-limit", "20"]);
1355
+ renderTuiResultScreen("Group topic", formatDisplayResult(detail, context));
1356
+ await waitForTuiContinue();
1357
+ }
1358
+ }
1359
+
1360
+ async function askSubjectDetailAction(detail, subject) {
1361
+ renderTuiHeader();
1362
+ console.log(drawSectionTitle("Subject detail"));
1363
+ console.log(drawDivider());
1364
+ console.log(formatDisplayResult(detail, {}));
1365
+ console.log("");
1366
+ console.log(drawDivider());
1367
+ console.log(`Selected subject: #${subject.id} ${subject.name_cn || subject.name || "-"}`);
1368
+ console.log("Actions");
1369
+ console.log(" [1/c] collect [2/o] open collection [3/m] comment");
1370
+ console.log(" [4/r] rate [5/s] status [0/b/q] back");
1371
+
1372
+ emitKeypressEvents(process.stdin);
1373
+
1374
+ return new Promise((resolve, reject) => {
1375
+ const wasRaw = Boolean(process.stdin.isRaw);
1376
+
1377
+ const cleanup = () => {
1378
+ process.stdin.off("keypress", onKeypress);
1379
+ if (!wasRaw && process.stdin.isTTY) {
1380
+ process.stdin.setRawMode(false);
1381
+ }
1382
+ };
1383
+
1384
+ const mapping = {
1385
+ "1": "collect",
1386
+ c: "collect",
1387
+ "2": "collection-get",
1388
+ o: "collection-get",
1389
+ "3": "comment",
1390
+ m: "comment",
1391
+ "4": "rate",
1392
+ r: "rate",
1393
+ "5": "status",
1394
+ s: "status",
1395
+ "0": "back",
1396
+ b: "back",
1397
+ q: "back",
1398
+ escape: "back",
1399
+ return: "collection-get",
1400
+ enter: "collection-get",
1401
+ };
1402
+
1403
+ const onKeypress = (_str, key = {}) => {
1404
+ if (key.ctrl && key.name === "c") {
1405
+ cleanup();
1406
+ reject(new CommandError("TUI cancelled."));
1407
+ return;
1408
+ }
1409
+
1410
+ const raw = typeof _str === "string" ? _str.toLowerCase() : "";
1411
+ const action = mapping[raw] ?? mapping[key.name];
1412
+ if (!action) {
1413
+ return;
1414
+ }
1415
+
1416
+ cleanup();
1417
+ resolve(action);
1418
+ };
1419
+
1420
+ if (!wasRaw && process.stdin.isTTY) {
1421
+ process.stdin.setRawMode(true);
1422
+ }
1423
+ process.stdin.on("keypress", onKeypress);
1424
+ });
1425
+ }
1426
+
1427
+ async function browseSubjectDetailActions(client, subject, context) {
1428
+ while (true) {
1429
+ const detail = await client.getSubject(subject.id);
1430
+ const action = await askSubjectDetailAction(detail, subject);
1431
+
1432
+ if (isTuiBackAction(action)) {
1433
+ return;
1434
+ }
1435
+
1436
+ const result = await runTuiSubjectCollectionAction(subject.id, action);
1437
+ renderTuiResultScreen("Collection result", formatDisplayResult(result, context));
1438
+ await waitForTuiContinue();
1439
+ }
1440
+ }
1441
+
1442
+ async function runTuiSubjectCollectionAction(subjectId, action) {
1443
+ switch (action) {
1444
+ case "collection-get":
1445
+ return executeCollectionGetCommand([String(subjectId)]);
1446
+ case "collect": {
1447
+ const snapshot = await fetchTuiCollectionSnapshot(subjectId);
1448
+ const status = await askMenuChoice(
1449
+ "Collection status",
1450
+ [
1451
+ { key: "1", label: "wish", value: "wish" },
1452
+ { key: "2", label: "collect", value: "collect" },
1453
+ { key: "3", label: "doing", value: "doing" },
1454
+ { key: "4", label: "on_hold", value: "on_hold" },
1455
+ { key: "5", label: "dropped", value: "dropped" },
1456
+ ],
1457
+ getCollectionStatusKey(snapshot?.type) ?? "wish",
1458
+ {
1459
+ summary: formatCollectionSnapshotSummary(snapshot),
1460
+ },
1461
+ );
1462
+ if (isTuiBackAction(status)) {
1463
+ throw new CommandError("TUI cancelled.");
1464
+ }
1465
+ return executeCollectionCollectCommand([String(subjectId), status]);
1466
+ }
1467
+ case "comment": {
1468
+ const snapshot = await fetchTuiCollectionSnapshot(subjectId);
1469
+ const rl = readline.createInterface({
1470
+ input: process.stdin,
1471
+ output: process.stdout,
1472
+ });
1473
+ try {
1474
+ const commentInput = await askTuiOptional(
1475
+ rl,
1476
+ "Comment",
1477
+ snapshot?.comment ?? "",
1478
+ `${formatCollectionSnapshotSummary(snapshot)}\nType a single dash (-) to clear the comment.`,
1479
+ );
1480
+ const comment = commentInput === "-" ? "" : commentInput;
1481
+ return executeCollectionCommentCommand([String(subjectId), comment]);
1482
+ } finally {
1483
+ rl.close();
1484
+ }
1485
+ }
1486
+ case "rate": {
1487
+ const snapshot = await fetchTuiCollectionSnapshot(subjectId);
1488
+ const rating = await askMenuChoice(
1489
+ "Rating",
1490
+ [
1491
+ { key: "0", label: "0", value: "0" },
1492
+ { key: "1", label: "1", value: "1" },
1493
+ { key: "2", label: "2", value: "2" },
1494
+ { key: "3", label: "3", value: "3" },
1495
+ { key: "4", label: "4", value: "4" },
1496
+ { key: "5", label: "5", value: "5" },
1497
+ { key: "6", label: "6", value: "6" },
1498
+ { key: "7", label: "7", value: "7" },
1499
+ { key: "8", label: "8", value: "8" },
1500
+ { key: "9", label: "9", value: "9" },
1501
+ { key: "10", label: "10", value: "10" },
1502
+ ],
1503
+ snapshot ? String(snapshot.rate ?? 0) : "7",
1504
+ {
1505
+ summary: formatCollectionSnapshotSummary(snapshot),
1506
+ },
1507
+ );
1508
+ if (isTuiBackAction(rating)) {
1509
+ throw new CommandError("TUI cancelled.");
1510
+ }
1511
+ return executeCollectionRateCommand([String(subjectId), rating]);
1512
+ }
1513
+ case "status": {
1514
+ const snapshot = await fetchTuiCollectionSnapshot(subjectId);
1515
+ const status = await askMenuChoice(
1516
+ "Collection status",
1517
+ [
1518
+ { key: "1", label: "wish", value: "wish" },
1519
+ { key: "2", label: "collect", value: "collect" },
1520
+ { key: "3", label: "doing", value: "doing" },
1521
+ { key: "4", label: "on_hold", value: "on_hold" },
1522
+ { key: "5", label: "dropped", value: "dropped" },
1523
+ ],
1524
+ getCollectionStatusKey(snapshot?.type) ?? "collect",
1525
+ {
1526
+ summary: formatCollectionSnapshotSummary(snapshot),
1527
+ },
1528
+ );
1529
+ if (isTuiBackAction(status)) {
1530
+ throw new CommandError("TUI cancelled.");
1531
+ }
1532
+ return executeCollectionStatusCommand([String(subjectId), status]);
1533
+ }
1534
+ default:
1535
+ throw new CommandError(`Unsupported subject collection action: ${action}`);
1536
+ }
1537
+ }