@luxass/pi-questions 0.0.0 → 0.1.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 (3) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/dialog.ts +241 -53
package/README.md CHANGED
@@ -41,4 +41,4 @@ Press n outside text editors to add a note. Enter or Escape saves the note. Note
41
41
 
42
42
  Cancelling discards all draft answers. The questionnaire also closes when the agent aborts its request. Unanswered questions remain undecided.
43
43
 
44
- In fullscreen Pi, Page Up, Page Down, and the mouse wheel scroll the conversation while you answer. In regular mode, use your terminal's scrollback controls.
44
+ In fullscreen Pi, click a question header or Review to switch tabs. Clicking another tab saves an open note and keeps custom-answer drafts. Page Up, Page Down, and the mouse wheel scroll the conversation while you answer. In regular mode, use keyboard navigation and your terminal's scrollback controls.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luxass/pi-questions",
3
- "version": "0.0.0",
3
+ "version": "0.1.0",
4
4
  "description": "Ask structured questions in Pi with tabs, choices, notes, and Markdown previews.",
5
5
  "keywords": [
6
6
  "pi",
package/src/dialog.ts CHANGED
@@ -15,6 +15,8 @@ import {
15
15
  type Focusable,
16
16
  type KeybindingsManager,
17
17
  type TUI,
18
+ type TuiMouseEvent,
19
+ type TuiMouseEventResult,
18
20
  } from "@earendil-works/pi-tui";
19
21
 
20
22
  import {
@@ -64,6 +66,8 @@ export class QuestionDialog implements Component, Focusable {
64
66
  private selectedLine = 0;
65
67
  private page = 1;
66
68
  private warning = "";
69
+ private headerTargets: { tab: number; start: number; end: number }[] = [];
70
+ private mouseWidth = 0;
67
71
 
68
72
  constructor(options: DialogOptions) {
69
73
  this.options = options;
@@ -266,6 +270,20 @@ export class QuestionDialog implements Component, Focusable {
266
270
  return component.render(width);
267
271
  }
268
272
 
273
+ private get answeredCount(): number {
274
+ return this.drafts.filter((draft) => draft.selected.size > 0 || draft.custom.trim()).length;
275
+ }
276
+
277
+ /** Keep selection backgrounds inside the content pane, including wrapped lines. */
278
+ private highlight(text: string, width: number, active: boolean): string {
279
+ if (!active) return text;
280
+ const fitted = truncateToWidth(text, width, "");
281
+ return this.options.theme.bg(
282
+ "selectedBg",
283
+ fitted + " ".repeat(Math.max(0, width - visibleWidth(fitted))),
284
+ );
285
+ }
286
+
269
287
  private questionBody(width: number): string[] {
270
288
  const question = this.questions[this.tab]!;
271
289
  const draft = this.drafts[this.tab]!;
@@ -275,28 +293,39 @@ export class QuestionDialog implements Component, Focusable {
275
293
  const lines: string[] = [];
276
294
  const current = this.rows[this.tab]!;
277
295
  const add = (index: number, label: string, description?: string) => {
278
- if (index === current) this.selectedLine = lines.length;
296
+ const active = index === current;
297
+ if (active) this.selectedLine = lines.length;
298
+ const title = this.wrap(
299
+ `${active ? "›" : " "} ${label}`,
300
+ leftWidth,
301
+ active ? "accent" : "text",
302
+ );
279
303
  lines.push(
280
- ...this.wrap(
281
- `${index === current ? ">" : " "} ${label}`,
282
- leftWidth,
283
- index === current ? "accent" : "text",
304
+ ...title.map((line) =>
305
+ this.highlight(active ? this.options.theme.bold(line) : line, leftWidth, active),
284
306
  ),
285
307
  );
286
- if (description) lines.push(...this.wrap(` ${description}`, leftWidth, "muted"));
308
+ if (description) {
309
+ const indent = Math.min(7, Math.max(0, leftWidth - 1));
310
+ lines.push(
311
+ ...this.wrap(description, leftWidth - indent, "muted").map((line) =>
312
+ this.highlight(" ".repeat(indent) + line, leftWidth, active),
313
+ ),
314
+ );
315
+ }
287
316
  lines.push("");
288
317
  };
289
318
  question.options.forEach((option, index) => {
290
319
  const checked = draft.selected.has(index);
291
- const marker = question.multiSelect ? (checked ? "[x]" : "[ ]") : checked ? "(x)" : "( )";
292
- add(index, `${marker} ${index + 1}. ${option.label}`, option.description);
320
+ const marker = question.multiSelect ? (checked ? "■" : "□") : checked ? "●" : "○";
321
+ add(index, `${marker} ${index + 1} ${option.label}`, option.description);
293
322
  });
294
323
  // Uncommitted editor text wins over the committed custom answer.
295
324
  const customText =
296
325
  this.editors.get(`${this.tab}:custom`)?.getExpandedText().trim() || draft.custom;
297
326
  add(
298
327
  question.options.length,
299
- `${question.multiSelect ? (customText ? "[x] " : "[ ] ") : ""}Type something.`,
328
+ `${question.multiSelect ? (customText ? "■ " : "□ ") : "✎ "}Type something.`,
300
329
  this.mode === "custom" ? undefined : customText || "Write your own answer.",
301
330
  );
302
331
  if (this.mode === "custom") lines.push(...this.editor("custom").render(width), "");
@@ -308,13 +337,15 @@ export class QuestionDialog implements Component, Focusable {
308
337
  );
309
338
  else if (question.multiSelect)
310
339
  add(question.options.length + 1, "Next", "Keep these choices and move to the next tab.");
311
- if (draft.notes) lines.push(...this.wrap(`Note: ${draft.notes}`, leftWidth, "muted"));
312
- if (this.warning) lines.push(...this.wrap(this.warning, leftWidth, "warning"));
340
+ if (draft.notes) lines.push(...this.wrap(`✎ Note: ${draft.notes}`, leftWidth, "muted"));
341
+ if (this.warning) lines.push(...this.wrap(`! ${this.warning}`, leftWidth, "warning"));
313
342
  if (!preview) return lines;
314
343
  const previewWidth = sideBySide ? width - leftWidth - 3 : width;
315
344
  const rendered = this.previewLines(preview, previewWidth);
316
345
  const pane = [
317
- this.options.theme.fg("muted", "Preview · p opens full view"),
346
+ this.options.theme.fg("accent", "Preview"),
347
+ ...this.wrap(question.options[current]!.label, previewWidth, "muted"),
348
+ this.options.theme.fg("borderMuted", "─".repeat(previewWidth)),
318
349
  ...rendered.slice(0, 10),
319
350
  ];
320
351
  if (rendered.length > 10) pane.push(this.options.theme.fg("dim", "… press p to read more"));
@@ -332,16 +363,29 @@ export class QuestionDialog implements Component, Focusable {
332
363
 
333
364
  private reviewBody(width: number): string[] {
334
365
  const result = collectAnswers(this.options.params, this.drafts, this.globalNote);
335
- const lines = [...this.wrap("Review your answers", width, "accent"), ""];
366
+ const lines = [
367
+ this.options.theme.bold(this.options.theme.fg("accent", "Review your answers")),
368
+ ...this.wrap(
369
+ "Tab to revisit a question. Unanswered questions stay undecided.",
370
+ width,
371
+ "muted",
372
+ ),
373
+ "",
374
+ ];
336
375
  this.questions.forEach((question, index) => {
337
376
  const answer = result.answers.find((candidate) => candidate.questionIndex === index);
377
+ const answered = !result.unanswered?.includes(index);
338
378
  lines.push(
339
379
  ...this.wrap(
340
- `${index + 1}. ${question.header}: ${answer ? answerText(answer) : "Not answered"}`,
380
+ `${answered ? "✓" : "○"} ${index + 1}. ${question.header}`,
341
381
  width,
382
+ answered ? "accent" : "warning",
342
383
  ),
384
+ ...this.wrap(question.question, width, "muted"),
385
+ ...this.wrap(` ${answer ? answerText(answer) : "Not answered"}`, width),
343
386
  );
344
- if (answer?.notes) lines.push(...this.wrap(` Note: ${answer.notes}`, width, "muted"));
387
+ if (answer?.notes) lines.push(...this.wrap(` ✎ ${answer.notes}`, width, "muted"));
388
+ lines.push("");
345
389
  });
346
390
  if (this.globalNote)
347
391
  lines.push("", ...this.wrap(`Global note: ${this.globalNote}`, width, "muted"));
@@ -356,15 +400,15 @@ export class QuestionDialog implements Component, Focusable {
356
400
  );
357
401
  if (this.warning) lines.push("", ...this.wrap(this.warning, width, "warning"));
358
402
  lines.push("");
359
- this.selectedLine = lines.length + this.reviewRow;
360
- lines.push(
361
- ...["Submit answers", "Cancel questionnaire"].map((label, index) =>
362
- this.options.theme.fg(
363
- index === this.reviewRow ? "accent" : "text",
364
- `${index === this.reviewRow ? ">" : " "} ${label}`,
403
+ ["Submit answers", "Cancel questionnaire"].forEach((label, index) => {
404
+ const active = index === this.reviewRow;
405
+ if (active) this.selectedLine = lines.length;
406
+ lines.push(
407
+ ...this.wrap(`${active ? "›" : " "} ${label}`, width, active ? "accent" : "muted").map(
408
+ (line) => this.highlight(line, width, active),
365
409
  ),
366
- ),
367
- );
410
+ );
411
+ });
368
412
  return lines;
369
413
  }
370
414
 
@@ -380,43 +424,125 @@ export class QuestionDialog implements Component, Focusable {
380
424
  return this.isReview ? this.reviewBody(width) : this.questionBody(width);
381
425
  }
382
426
 
383
- private renderTabs(width: number): string {
427
+ private renderNavigation(width: number): string[] {
384
428
  const { theme } = this.options;
385
- const titles = this.questions.map((question, index) => {
386
- const draft = this.drafts[index]!;
387
- const label = `${index + 1}. ${question.header}${draft.selected.size || draft.custom ? " ✓" : ""}`;
388
- return index === this.tab
389
- ? theme.fg("accent", `[${stripTerminalSequences(label)}]`)
390
- : theme.fg("muted", stripTerminalSequences(label));
429
+ const titles = this.questions.map((question) => stripTerminalSequences(question.header));
430
+ if (titles.length === 1) return [theme.fg("muted", truncateToWidth(titles[0]!, width, ""))];
431
+ titles.push("Review");
432
+ const titleWidths = titles.map(visibleWidth);
433
+ const titleWidth = titleWidths.reduce((sum, size) => sum + size, 0);
434
+ const gap =
435
+ width >= titleWidth + 2 * (titles.length - 1) ? 2 : width >= titles.length * 2 - 1 ? 1 : 0;
436
+ const available = width - gap * (titles.length - 1);
437
+ const padding = titleWidth + titles.length * 2 <= available ? 2 : 0;
438
+ const sizes = titleWidths.map((size) => size + padding);
439
+ let used = sizes.reduce((sum, size) => sum + size, 0);
440
+ // Short tabs keep their space; only the widest titles shrink when necessary.
441
+ while (used > available) {
442
+ const widest = sizes.indexOf(Math.max(...sizes));
443
+ sizes[widest]!--;
444
+ used--;
445
+ }
446
+ const spare = available - used;
447
+ const extra = Math.floor(spare / titles.length);
448
+ const remainder = spare % titles.length;
449
+ // Mouse coordinates include the frame's two-column left inset.
450
+ let column = 2;
451
+ const cells = titles.map((title, index) => {
452
+ const size = sizes[index]! + extra + (index < remainder ? 1 : 0);
453
+ this.headerTargets.push({ tab: index, start: column, end: column + size });
454
+ column += size + gap;
455
+ const compact = index === this.questions.length ? "R" : String(index + 1);
456
+ const label =
457
+ titleWidths[index]! <= size
458
+ ? title
459
+ : size < 4
460
+ ? compact
461
+ : truncateToWidth(title, size, "…");
462
+ const padding = size - visibleWidth(label);
463
+ const centered =
464
+ " ".repeat(Math.floor(padding / 2)) + label + " ".repeat(Math.ceil(padding / 2));
465
+ const active = index === this.tab;
466
+ return {
467
+ title: active ? theme.bold(theme.fg("accent", centered)) : theme.fg("muted", centered),
468
+ rail: theme.fg(active ? "accent" : "borderMuted", (active ? "━" : "─").repeat(size)),
469
+ };
391
470
  });
392
- if (this.drafts.length > 1)
393
- titles.push(this.isReview ? theme.fg("accent", "[Review]") : theme.fg("muted", "Review"));
394
- const tabs = titles.join(" · ");
395
- if (visibleWidth(tabs) <= width) return tabs;
396
- // Too narrow for every title: show the position and the current title only.
397
- return theme.fg(
398
- "accent",
399
- `${this.tab + 1}/${titles.length} · ${stripTerminalSequences(this.questions[this.tab]?.header ?? "Review")}`,
400
- );
471
+ return [
472
+ cells.map((cell) => cell.title).join(" ".repeat(gap)),
473
+ cells.map((cell) => cell.rail).join(theme.fg("borderMuted", "─".repeat(gap))),
474
+ ];
401
475
  }
402
476
 
403
477
  private renderHelp(width: number): string {
478
+ const { theme } = this.options;
479
+ let hints: [string, string][];
404
480
  if (this.mode === "custom" || this.mode === "notes")
405
- return `Enter save · Shift+Enter newline · Ctrl+] collapse · Esc ${this.mode === "notes" ? "save note" : "cancel"}`;
406
- if (this.mode === "preview" || this.mode === "question")
407
- return `↑↓ scroll ${this.mode} · Ctrl+] collapse · Esc back`;
408
- if (width < 70) return "q question · Enter choose · Ctrl+] collapse · Esc cancel";
409
- return `${this.drafts.length > 1 ? "Tab tabs · " : ""}↑↓ move · Enter choose · q question · n note · p preview · Ctrl+] collapse · Esc cancel`;
481
+ hints = [
482
+ ["Enter", "save"],
483
+ ["Esc", this.mode === "notes" ? "save note" : "cancel"],
484
+ ["Shift+Enter", "newline"],
485
+ ["Ctrl+]", "collapse"],
486
+ ];
487
+ else if (this.mode === "preview" || this.mode === "question")
488
+ hints = [
489
+ ["↑↓", "scroll"],
490
+ ["Esc", "back"],
491
+ ["Home/End", "jump"],
492
+ ["Ctrl+]", "collapse"],
493
+ ];
494
+ else {
495
+ const question = this.questions[this.tab];
496
+ const onAction = question && this.rows[this.tab]! > question.options.length;
497
+ let confirm = "choose";
498
+ if (this.isReview) confirm = this.reviewRow === 0 ? "submit" : "cancel";
499
+ else if (onAction) confirm = this.questions.length === 1 ? "submit" : "next";
500
+ else if (question?.multiSelect) confirm = "toggle";
501
+ hints = [
502
+ ["Enter", confirm],
503
+ ["↑↓", "move"],
504
+ ["Esc", "cancel"],
505
+ ];
506
+ if (this.drafts.length > 1) hints.push(["Tab", "next"]);
507
+ if (this.isReview) hints.push(["Home/End", "scroll"]);
508
+ if (this.preview()) hints.push(["p", "preview"]);
509
+ hints.push(["n", "note"], ["Ctrl+]", "collapse"]);
510
+ if (!this.isReview) hints.push(["q", "question"]);
511
+ }
512
+ let help = "";
513
+ for (const [key, label] of hints) {
514
+ const hint = theme.fg("accent", key) + theme.fg("dim", ` ${label}`);
515
+ const candidate = help ? help + theme.fg("borderMuted", " · ") + hint : hint;
516
+ if (visibleWidth(candidate) <= width) help = candidate;
517
+ }
518
+ return help || truncateToWidth(theme.fg("accent", "Esc"), width, "");
519
+ }
520
+
521
+ private border(width: number, left: string, right: string, top: boolean): string {
522
+ const { theme } = this.options;
523
+ const available = width - 4;
524
+ const status = visibleWidth(right) <= Math.floor(available / 2) ? right : "";
525
+ const title = truncateToWidth(left, available - visibleWidth(status), "");
526
+ const gap = width - 2 - visibleWidth(title) - visibleWidth(status);
527
+ return (
528
+ theme.fg("borderAccent", top ? "╭─" : "╰─") +
529
+ title +
530
+ theme.fg("borderMuted", "─".repeat(Math.max(0, gap - 2))) +
531
+ status +
532
+ theme.fg("borderAccent", top ? "─╮" : "─╯")
533
+ );
410
534
  }
411
535
 
412
536
  render(width: number): string[] {
413
537
  const { theme, tui } = this.options;
538
+ this.headerTargets = [];
539
+ this.mouseWidth = width;
414
540
  if (this.collapsed)
415
541
  return [
416
542
  theme.fg(
417
543
  "dim",
418
544
  truncateToWidth(
419
- "Questions collapsed · Ctrl+] expand · Esc cancel",
545
+ `Questions · ${this.answeredCount}/${this.questions.length} answered · Ctrl+] expand · Esc cancel`,
420
546
  Math.max(0, width),
421
547
  "",
422
548
  ),
@@ -429,20 +555,27 @@ export class QuestionDialog implements Component, Focusable {
429
555
  truncateToWidth("Resize to answer · Ctrl+] collapse · Esc cancel", Math.max(0, width), ""),
430
556
  ];
431
557
  const inner = width - 4;
558
+ const navigation = this.renderNavigation(inner);
432
559
  const reading = this.mode === "preview" || this.mode === "question";
433
560
  let heading =
434
561
  !this.isReview && !reading
435
- ? this.wrap(this.questions[this.tab]!.question, inner, "accent")
562
+ ? this.wrap(this.questions[this.tab]!.question, inner, "text").map((line) =>
563
+ theme.bold(line),
564
+ )
436
565
  : [];
437
- const headingLimit = Math.min(3, height - 6);
566
+ const headingLimit = Math.min(3, height - navigation.length - 5);
438
567
  if (heading.length > headingLimit)
439
568
  heading = [
440
569
  ...heading.slice(0, headingLimit - 1),
441
570
  theme.fg("muted", truncateToWidth("… q to read full question", inner, "")),
442
571
  ];
443
- // Borders, tabs, and help take four rows.
444
- this.page = height - 4 - heading.length;
572
+ if (heading.length) heading.push("");
573
+ // Borders and help take three rows. Short content leaves more transcript visible.
445
574
  const lines = this.scroll.render(inner);
575
+ this.page = Math.min(
576
+ height - 3 - navigation.length - heading.length,
577
+ Math.max(1, lines.length),
578
+ );
446
579
  this.scroll.updateLayout(lines.length, this.page, () => tui.requestRender());
447
580
  const editing = this.mode === "custom" || this.mode === "notes";
448
581
  const focusLine = editing
@@ -465,16 +598,71 @@ export class QuestionDialog implements Component, Focusable {
465
598
  theme.fg("borderAccent", " │")
466
599
  );
467
600
  };
601
+ const question = this.questions[this.tab];
602
+ const context =
603
+ this.mode === "notes"
604
+ ? "Note · optional"
605
+ : this.mode === "custom"
606
+ ? "Custom answer"
607
+ : this.mode === "preview"
608
+ ? "Option preview"
609
+ : this.mode === "question"
610
+ ? "Full question"
611
+ : this.isReview
612
+ ? "Review before submitting"
613
+ : question?.multiSelect
614
+ ? "Choose any that apply"
615
+ : "Choose one";
616
+ const start = this.scroll.scrollTop;
617
+ const end = Math.min(lines.length, start + this.page);
618
+ const position =
619
+ lines.length > this.page
620
+ ? ` ${start > 0 ? "↑ " : ""}${start + 1}–${end} / ${lines.length}${end < lines.length ? " ↓" : ""} `
621
+ : "";
468
622
  return [
469
- theme.fg("borderAccent", `┌${"─".repeat(width - 2)}┐`),
470
- row(this.renderTabs(inner)),
623
+ this.border(
624
+ width,
625
+ theme.fg("accent", theme.bold(" Ask questions ")),
626
+ theme.fg("muted", ` ${this.answeredCount}/${this.questions.length} answered `),
627
+ true,
628
+ ),
629
+ ...navigation.map(row),
471
630
  ...heading.map(row),
472
631
  ...visible.map(row),
473
- row(theme.fg("dim", this.renderHelp(width))),
474
- theme.fg("borderAccent", `└${"─".repeat(width - 2)}┘`),
632
+ row(this.renderHelp(inner)),
633
+ this.border(width, theme.fg("dim", ` ${context} `), theme.fg("muted", position), false),
475
634
  ];
476
635
  }
477
636
 
637
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
638
+ if (
639
+ this.closed ||
640
+ this.collapsed ||
641
+ event.width !== this.mouseWidth ||
642
+ event.button !== "left" ||
643
+ event.shift ||
644
+ event.alt ||
645
+ event.ctrl ||
646
+ (event.type !== "press" && event.type !== "click") ||
647
+ (event.y !== 1 && event.y !== 2)
648
+ )
649
+ return undefined;
650
+ const target = this.headerTargets.find(
651
+ (header) => event.x >= header.start && event.x < header.end,
652
+ );
653
+ if (!target) return undefined;
654
+ // Claim the press so Pi delivers a click instead of starting transcript selection.
655
+ if (event.type === "press" || target.tab === this.tab) return { handled: true, focus: true };
656
+ // Notes use the same save-on-leave behavior as Escape in their editor.
657
+ if (this.mode === "notes") {
658
+ const editor = this.editor("notes");
659
+ editor.onSubmit?.(editor.getExpandedText());
660
+ }
661
+ this.switchTab(target.tab);
662
+ this.options.tui.requestRender();
663
+ return { handled: true, focus: true };
664
+ }
665
+
478
666
  handleInput(data: string): void {
479
667
  if (this.closed || isKeyRelease(data)) return;
480
668
  const { keybindings, tui } = this.options;