Skip to content

fix: code quality and safety improvements - #3357

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

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

Conversation

@saurabhhhcodes

@saurabhhhcodes saurabhhhcodes commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • Documentation

    • Updated the useMemo example to demonstrate reliable numeric sorting.
  • Bug Fixes

    • Corrected token key ordering so numeric values are sorted in the expected order when compiled.

@github-actions github-actions Bot added area:jsx @termuijs/jsx area:tss @termuijs/tss labels Jul 31, 2026
@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The changes replace default lexicographic sorting with numeric comparators in token compilation and a useMemo documentation example.

Changes

Numeric sorting updates

Layer / File(s) Summary
Token key ordering
packages/tss/src/tokens.ts
compileTokensToJSON sorts merged token keys numerically before resolving and emitting compiled values.
useMemo example sorting
packages/jsx/src/hooks.ts
The useMemo example passes a numeric comparator to items.sort.

Estimated code review effort: 1 (Trivial) | ~5 minutes

Possibly related PRs

Suggested reviewers: karanjot786

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning No pull request description was provided, so the required description, issue, package, change type, checklist, and reviewer notes are missing. Add the required template sections, link the related issue, identify the affected packages, select the change type, and complete the checklist.
Title check ❓ Inconclusive The title mentions general quality improvements but does not identify the numeric sorting changes or documentation update. Use a specific title such as "fix: sort token keys numerically and update useMemo example".
✅ Passed checks (3 passed)
Check name Status Explanation
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 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 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.

@github-actions github-actions Bot added the type:bug +10 pts. Bug fix. label Jul 31, 2026

@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: 1

🧹 Nitpick comments (1)
packages/jsx/src/hooks.ts (1)

482-482: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Copy items before sorting.

items.sort(...) mutates the array. Sort a copied array to avoid changing caller-owned item data.

Proposed fix
- * const sorted = useMemo(() => items.sort((a, b) => a - b), [items]);
+ * const sorted = useMemo(() => [...items].sort((a, b) => a - b), [items]);
🤖 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/jsx/src/hooks.ts` at line 482, Update the useMemo sorting example in
hooks.ts to copy items before calling sort, ensuring the caller-owned array is
not mutated while preserving the existing numeric sort behavior.
🤖 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 `@packages/tss/src/tokens.ts`:
- Line 105: Update the comparator in the Object.keys(merged) sorting loop to
avoid numeric subtraction on string token identifiers. Parse and numerically
compare identifiers when both are numeric-looking, then use lexicographic string
comparison as the fallback for names such as accent, bg, and fg.

---

Nitpick comments:
In `@packages/jsx/src/hooks.ts`:
- Line 482: Update the useMemo sorting example in hooks.ts to copy items before
calling sort, ensuring the caller-owned array is not mutated while preserving
the existing numeric sort behavior.
🪄 Autofix (Beta)

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: 1e24adaf-a9b3-43e0-a04b-cebe9bb0e108

📥 Commits

Reviewing files that changed from the base of the PR and between 48f63a1 and c401def.

📒 Files selected for processing (2)
  • packages/jsx/src/hooks.ts
  • packages/tss/src/tokens.ts


const tokens: Record<string, string> = {};
for (const key of Object.keys(merged).sort()) {
for (const key of Object.keys(merged).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 | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Locate tokens.ts:"
fd 'tokens\.ts$' . | sed -n '1,40p'

echo
echo "Relevant tokens.ts section if present:"
if [ -f packages/tss/src/tokens.ts ]; then
  wc -l packages/tss/src/tokens.ts
  sed -n '1,140p' packages/tss/src/tokens.ts | cat -n
fi

echo
echo "Search normalizeThemeVariables usage:"
rg -n "normalizeThemeVariables|Object\.keys\(merged\)\.sort|for \(const key of Object\.keys\(merged\)\.sort" packages/tss packages -g '*.ts' -g '*.tsx' || true

echo
echo "TypeScript availability/version:"
node - <<'JS'
try {
  const ts = require('typescript');
  console.log('typescript', ts.version);
} catch (e) {
  console.log('typescript not available');
}
JS

echo
echo "Behavioral probe: string keys subtracted/sorted:"
node - <<'JS'
const merged = { accent: '`#f00`', bg: '`#000`', fg: '`#fff`' };
const keys = Object.keys(merged);
const before = [...keys];
const after = keys.sort((a, b) => a - b);
console.log({ before, after, numericSubtraction: { accentFgBefore: Math.acos(), accentFgAfter: Math.acos() } });
const pairs = keys.map(e => [e, Number(e), isNaN(Number(e))]);
console.log({ numericConversionMap: pairs, sortWithNumericFallbackArrayLiteral: [...keys].sort((a, b) => Number(a) - Number(b)).map(k => [k, isNaN(Number(k))]) });
JS

Repository: Karanjot786/TermUI

Length of output: 6723


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Package files:"
fd -a 'package\.json|tsconfig.*\.json' . | sed -n '1,60p'

echo
echo "Root/package.json tsconfig references:"
for f in package.json packages/package.json packages/tss/package.json; do
  if [ -f "$f" ]; then
    echo "--- $f"
    sed -n '1,160p' "$f" | sed -n '/typescript\|compilerOptions\|extends\|references\|scripts/p'
  fi
done

echo
echo "Token-related test files:"
fd -e ts -e js -e tsx . packages tests test __tests__ | rg 'token|TSS|theme|tokens' || true

echo
echo "Behavioral probe with number-like keys:"
node - <<'JS'
const cases = [
  { '10': 'ten', '2': 'two' },
  { 'var-10': 'ten', 'var-2': 'two' },
];
for (const merged of cases) {
  const keys = Object.keys(merged);
  const sortNumeric = [...keys].sort((a, b) => a - b);
  const sortFallback = [...keys].sort((a, b) => {
    const numericA = Number(a);
    const numericB = Number(b);
    if (Number.isFinite(numericA) && Number.isFinite(numericB)) {
      return numericA - numericB;
    }
    return a.localeCompare(b);
  });
  console.log({ input: merged, sortNumeric, sortFallback });
}
JS

Repository: Karanjot786/TermUI

Length of output: 4641


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Relevant token-json tests:"
sed -n '1,220p' packages/tss/src/token-json.test.ts | cat -n

echo
echo "Relevant token tests:"
sed -n '1,240p' packages/tss/src/tokens.test.ts | cat -n

Repository: Karanjot786/TermUI

Length of output: 5310


Use a type-safe comparator with a nonnumeric fallback.

Token identifiers are strings, so a - b is invalid in strict TypeScript and nonnumeric keys sort as NaN at runtime. Sort numeric-looking identifiers as numbers, then fall back to string comparison for names like accent, bg, and fg.

🤖 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/tss/src/tokens.ts` at line 105, Update the comparator in the
Object.keys(merged) sorting loop to avoid numeric subtraction on string token
identifiers. Parse and numerically compare identifiers when both are
numeric-looking, then use lexicographic string comparison as the fallback for
names such as accent, bg, and fg.

Source: Coding guidelines

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

Labels

area:jsx @termuijs/jsx area:tss @termuijs/tss type:bug +10 pts. Bug fix.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant