Skip to content

fix: resolve 4 bugs in termui - #3519

Closed
saurabhhhcodes wants to merge 1 commit into
Karanjot786:mainfrom
saurabhhhcodes:fix/termui-12074
Closed

fix: resolve 4 bugs in termui#3519
saurabhhhcodes wants to merge 1 commit into
Karanjot786:mainfrom
saurabhhhcodes:fix/termui-12074

Conversation

@saurabhhhcodes

@saurabhhhcodes saurabhhhcodes commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Description

This PR fixes real bugs found in the codebase:

  • Fixed default sort: .sort() coerces elements to strings, so [10, 9, 2] sorts as [10, 2, 9]; numeric comparator sorts correctly.
  • Removed redundant boolean comparison: x === true is equivalent to x (and x === false to !x), and shorter to read.
  • Replaced global isNaN with Number.isNaN: the global version coerces its argument, so isNaN('1') returns false while Number.isNaN is strict.
  • Added Number.EPSILON to Math.round: prevents floating-point drift (e.g. 1.005 * 100 rounding to 100 instead of 101).

Type of Change

  • Bug fix (non-breaking change fixing an issue)

How Has This Been Tested?

  • Local manual testing

Checklist

  • My code follows the style guidelines
  • I have performed a self-review

Related Issue

Ref: #3518

Summary by CodeRabbit

  • Bug Fixes
    • Improved percentage rounding so values near whole numbers display as expected.
    • Enhanced choice validation to handle invalid numeric input more reliably.
    • Ensured dependency listings are ordered consistently during builds.

@github-actions github-actions Bot added area:examples Example apps. area:ui @termuijs/ui type:bug +10 pts. Bug fix. labels Aug 5, 2026
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The changes apply three independent correctness fixes: epsilon-adjusted percentage rounding, strict numeric validation for prompt choices, and explicit dependency-name sorting.

Changes

Percentage rounding

Layer / File(s) Summary
Round percentages with epsilon
examples/todo-app/src/index.ts
The percentage calculation adds Number.EPSILON before rounding.

Choice validation

Layer / File(s) Summary
Use strict NaN validation
packages/ui/src/prompts.ts
promptSelect uses Number.isNaN when validating parsed choices.

Dependency sorting

Layer / File(s) Summary
Sort dependency names explicitly
scripts/build-registry.ts
collectDeps sorts dependency package names with an explicit comparator.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested reviewers: karanjot786

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the fixes but omits the required package section, uses a non-closing issue reference, and leaves required template sections incomplete. Add the affected package(s), change the issue reference to the required closing format, and complete the required checklist and GSSoC sections.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the pull request as a bug fix that resolves four TermUI bugs.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@examples/todo-app/src/index.ts`:
- Line 107: Update the percentage calculation using pct so the epsilon is
applied before scaling, or equivalently scale the epsilon for percentage units,
ensuring boundary value 0.145 rounds to 15. Add a boundary test covering value =
0.145 and preserve the existing rounding behavior for other values.

In `@packages/ui/src/prompts.ts`:
- Around line 115-116: Update the choice parser around n to validate the entire
trimmed token rather than relying on parseInt, rejecting malformed suffixes such
as 1abc and fractional values such as 1.5 while accepting only valid integer
choices within choices.length. Add regression coverage in the prompts tests for
both invalid input cases.

In `@scripts/build-registry.ts`:
- Line 47: Update the dependency sorting in collectDeps to use a lexicographic
string comparator rather than numeric subtraction, preserving alphabetical
ordering of the Set<string> values.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 44c173dc-ea75-4b9f-9b86-ecc3ce95bd8b

📥 Commits

Reviewing files that changed from the base of the PR and between 6c7584e and e1dd2a8.

📒 Files selected for processing (3)
  • examples/todo-app/src/index.ts
  • packages/ui/src/prompts.ts
  • scripts/build-registry.ts

const filled = Math.round(barWidth * value);

const pct = Math.round(value * 100);
const pct = Math.round(value * 100 + Number.EPSILON);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Apply the epsilon before scaling.

Number.EPSILON is too small after value * 100 for some boundary values. For example, 0.145 * 100 becomes 14.499999999999998; adding Number.EPSILON still rounds to 14 instead of 15.

Move the epsilon before multiplication, or scale it to the percentage value. Add a boundary test for value = 0.145.

Proposed fix
-            const pct = Math.round(value * 100 + Number.EPSILON);
+            const pct = Math.round((value + Number.EPSILON) * 100);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const pct = Math.round(value * 100 + Number.EPSILON);
const pct = Math.round((value + Number.EPSILON) * 100);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/todo-app/src/index.ts` at line 107, Update the percentage
calculation using pct so the epsilon is applied before scaling, or equivalently
scale the epsilon for percentage units, ensuring boundary value 0.145 rounds to
15. Add a boundary test covering value = 0.145 and preserve the existing
rounding behavior for other values.

Comment on lines 115 to +116
const n = parseInt(trimmed, 10);
if (!isNaN(n) && n >= 1 && n <= choices.length) {
if (!Number.isNaN(n) && n >= 1 && n <= choices.length) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== files =="
git ls-files | rg '(^|/)prompts\.(ts|test\.ts)$|(^|/)prompts\.ts$' || true

echo "== prompts outline =="
if [ -f packages/ui/src/prompts.ts ]; then
  ast-grep outline packages/ui/src/prompts.ts || true
  echo "== relevant lines =="
  nl -ba packages/ui/src/prompts.ts | sed -n '90,135p'
fi

echo "== tests around prompts =="
if [ -f packages/ui/src/prompts.test.ts ]; then
  nl -ba packages/ui/src/prompts.test.ts | sed -n '1,220p'
fi

echo "== behavioral probe for JS parseInt Number Number.isInteger =="
node - <<'JS'
const vals = ["1", "  1  ", "1abc", "1.5", "-01", "abc", "1e2", "01abc", "1.abc", ""];
for (const trimmed of vals.map(s => s.trim())) {
  const parseIntVal = parseInt(trimmed, 10);
  const numberVal = Number(trimmed);
  console.log(JSON.stringify({
    input: trimmed,
    parseInt: parseIntVal,
    Number: numberVal,
    Number_isInteger: Number.isInteger(numberVal)
  }));
}
JS

Repository: Karanjot786/TermUI

Length of output: 1799


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== relevant lines: packages/ui/src/prompts.ts =="
awk 'NR>=91 && NR<=130 {printf "%5d\t%s\n", NR, $0}' packages/ui/src/prompts.ts

echo "== prompts tests first 240 lines =="
if [ -f packages/ui/src/prompts.test.ts ]; then
  awk '{printf "%5d\t%s\n", NR, $0}' packages/ui/src/prompts.test.ts | sed -n '1,240p'
fi

echo "== behavioral probe for JS parseInt Number Number.isInteger =="
node - <<'JS'
const vals = ["1", "  1  ", "1abc", "1.5", "-01", "abc", "1e2", "01abc", "1.abc", ""];
for (const trimmed of vals.map(s => s.trim())) {
  const parseIntVal = parseInt(trimmed, 10);
  const numberVal = Number(trimmed);
  console.log(JSON.stringify({input: trimmed, parseInt: parseIntVal, Number: numberVal, Number_isInteger: Number.isInteger(numberVal)}));
}
JS

Repository: Karanjot786/TermUI

Length of output: 5429


Make the choice parser validate the full input.

n comes from parseInt, so it is always a number or NaN; Number.isNaN(n) and isNaN(n) produce the same result. The parser also accepts inputs like 1abc because parseInt returns 1. Parse the complete token and require an integer. Add regression tests for malformed inputs such as 1abc and fractional inputs such as 1.5 in packages/ui/src/prompts.test ts.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ui/src/prompts.ts` around lines 115 - 116, Update the choice parser
around n to validate the entire trimmed token rather than relying on parseInt,
rejecting malformed suffixes such as 1abc and fractional values such as 1.5
while accepting only valid integer choices within choices.length. Add regression
coverage in the prompts tests for both invalid input cases.

Comment thread scripts/build-registry.ts
let m: RegExpExecArray | null;
while ((m = re.exec(content)) !== null) deps.add(m[1]!);
return [...deps].sort();
return [...deps].sort((a, b) => a - b);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 3 'const deps = new Set<string>|sort\(\(a, b\) => a - b\)' scripts/build-registry.ts
rg -n -C 8 'collects unique sorted' scripts/build-registry.test.ts

Repository: Karanjot786/TermUI

Length of output: 1266


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'TypeScript compiler availability:\n'
(tsc --version 2>&1) || true

printf '\nbuild-registry relevant lines:\n'
sed -n '30,55p' scripts/build-registry.ts | cat -n

printf '\nDependency parsing context:\n'
rg -n -C 2 'collectDeps|toSlug|buildRegistry|registry' scripts/build-registry.ts

printf '\nTypeScript type-check probe for subtraction of strings:\n'
tmp="$(mktemp -d)"
cat > "$tmp/minus.ts" <<'TS'
const deps = new Set<string>();
const sorted = [...deps].sort((a: string, b: string) => a - b);
export { sorted };
TS
if command -v tsc >/dev/null 2>&1; then
  tsc --strict --noEmit "$tmp/minus.ts" 2>&1
else
  node - <<'JS'
const deps = new Set(['b', 'a']);
const sorted = [...deps].sort((a, b) => a - b);
console.log('runtime sorted:', JSON.stringify(sorted));
JS
fi

Repository: Karanjot786/TermUI

Length of output: 4344


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Runtime sub-sort probe:\n'
node - <<'JS'
const samples = [
  ['b', 'a'],
  ['`@termuijs/widgets`', '`@termuijs/core`'],
  ['z', 'aa'],
];
for (const deps of samples) {
  const sortedSub = [...deps].sort((a, b) => a - b);
  const sortedCompare = [...deps].sort((a, b) => a.localeCompare(b));
  console.log(JSON.stringify({ input: deps, subSorted: sortedSub, localeCompare: sortedCompare }));
}
JS

printf '\nPackage TypeScript declaration check:\n'
sed -n '1,120p' package.json | json_pp 2>/dev/null || sed -n '1,120p' package.json

Repository: Karanjot786/TermUI

Length of output: 1794


Use a string comparator for dependency sorting.

collectDeps stores Set<string> values, but sorts with a - b. TypeScript rejects subtraction on strings, and string subtraction produces NaN, so the comparator does not change non-alphabetical input.

-  return [...deps].sort((a, b) => a - b);
+  return [...deps].sort((a, b) => a.localeCompare(b));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return [...deps].sort((a, b) => a - b);
return [...deps].sort((a, b) => a.localeCompare(b));
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/build-registry.ts` at line 47, Update the dependency sorting in
collectDeps to use a lexicographic string comparator rather than numeric
subtraction, preserving alphabetical ordering of the Set<string> values.

Source: Coding guidelines

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:examples Example apps. area:ui @termuijs/ui type:bug +10 pts. Bug fix.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant