-
Notifications
You must be signed in to change notification settings - Fork 0
Enable strictNullChecks in TS package #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
WalkthroughThis update introduces comprehensive null and undefined safety across the codebase. It adjusts type annotations, adds defensive programming patterns, and ensures default values are provided where necessary. Several utility and core classes now handle missing data more gracefully. TypeScript configuration is tightened with Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Component
participant DOM
participant Utility
participant Global
User->>Component: Render or update component
Component->>Utility: Request data, config, or color
Utility->>Global: Access global config (with nullish coalescing)
Utility-->>Component: Return value (with safe defaults)
Component->>DOM: Manipulate DOM nodes (with null checks)
DOM-->>Component: DOM node or null
Component-->>User: Rendered output or safe fallback
Poem
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ESLint
npm error code ERESOLVE 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
⏰ Context from checks skipped due to timeout of 90000ms (1)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
♻️ Duplicate comments (2)
packages/ts/src/core/xy-component/index.ts (2)
81-81: Duplicate type assertion concern - verify getExtent safety.Same concern as line 75 - the type assertion assumes
getExtentwill never returnundefinedvalues. Consider adding proper null handling instead of type assertions.
89-89: Duplicate type assertion concern - verify getExtent safety.Same concern as lines 75 and 81 - the type assertion may not be safe if
getExtentcan actually returnundefinedvalues.
🧹 Nitpick comments (2)
packages/ts/src/core/container/index.ts (1)
132-135: Consider using optional chaining for cleaner code.The null check is correct, but you could use optional chaining for more concise code:
- while (this.element && this.element.firstChild) { - this.element.removeChild(this.element.firstChild) - } + while (this.element?.firstChild) { + this.element.removeChild(this.element.firstChild) + }packages/ts/src/utils/data.ts (1)
321-321: Non-null assertions may be risky - consider safer alternatives.The non-null assertion operators (
!) assume thatvalues[index - 1]andvalues[index]are never undefined. While this is likely true given the logic, it could cause runtime errors if the assumptions are incorrect.Consider a safer approach:
- return value - values[index - 1]! > values[index]! - value ? data[index] : data[index - 1] + const prevValue = values[index - 1] ?? 0 + const nextValue = values[index] ?? 0 + return value - prevValue > nextValue - value ? data[index] : data[index - 1]
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (21)
packages/ts/src/components/annotations/index.ts(4 hunks)packages/ts/src/containers/xy-container/index.ts(4 hunks)packages/ts/src/core/component/index.ts(2 hunks)packages/ts/src/core/container/index.ts(6 hunks)packages/ts/src/core/xy-component/index.ts(1 hunks)packages/ts/src/data-models/core.ts(1 hunks)packages/ts/src/data-models/graph.ts(3 hunks)packages/ts/src/data-models/map-graph.ts(2 hunks)packages/ts/src/data-models/map.ts(1 hunks)packages/ts/src/styles/colors.ts(1 hunks)packages/ts/src/styles/index.ts(1 hunks)packages/ts/src/types/d3-interpolate-path.d.ts(1 hunks)packages/ts/src/types/globals.d.ts(1 hunks)packages/ts/src/utils/color.ts(2 hunks)packages/ts/src/utils/data.ts(7 hunks)packages/ts/src/utils/html.ts(1 hunks)packages/ts/src/utils/map.ts(1 hunks)packages/ts/src/utils/misc.ts(2 hunks)packages/ts/src/utils/path.ts(1 hunks)packages/ts/src/utils/text.ts(13 hunks)packages/ts/tsconfig.json(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (7)
packages/ts/src/core/xy-component/index.ts (3)
packages/ts/src/utils/data.ts (3)
getExtent(309-311)filterDataByRange(324-331)isArray(13-13)packages/ts/src/types/accessor.ts (1)
NumericAccessor(1-1)packages/ts/src/data-models/core.ts (2)
data(4-6)data(8-10)
packages/ts/src/styles/index.ts (1)
packages/ts/src/types/text.ts (1)
UnovisText(24-43)
packages/ts/src/data-models/map.ts (1)
packages/ts/src/utils/map.ts (1)
getDataLatLngBounds(9-29)
packages/ts/src/components/annotations/index.ts (4)
packages/ts/src/components/annotations/style.ts (1)
annotation(28-30)packages/ts/src/styles/index.ts (1)
UNOVIS_TEXT_DEFAULT(11-18)packages/ts/src/utils/misc.ts (1)
parseUnit(60-66)packages/ts/src/utils/text.ts (1)
renderTextIntoFrame(556-597)
packages/ts/src/types/globals.d.ts (1)
packages/ts/src/styles/index.ts (3)
UNOVIS_TEXT_SEPARATOR_DEFAULT(9-9)UNOVIS_TEXT_HYPHEN_CHARACTER_DEFAULT(10-10)UNOVIS_TEXT_DEFAULT(11-18)
packages/ts/src/utils/misc.ts (1)
packages/ts/src/types/accessor.ts (1)
StringAccessor(2-2)
packages/ts/src/utils/color.ts (3)
packages/ts/src/utils/data.ts (2)
isNumber(8-8)getString(184-186)packages/ts/src/types/accessor.ts (1)
StringAccessor(2-2)packages/ts/src/styles/colors.ts (1)
getCSSColorVariable(9-11)
🪛 Biome (1.9.4)
packages/ts/src/core/container/index.ts
[error] 132-132: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: build
🔇 Additional comments (55)
packages/ts/tsconfig.json (3)
19-19: LGTM! Enabling strictNullChecks aligns with PR objectives.This change enables strict null checking which is the primary goal of this PR.
24-24: Good addition of skipLibCheck option.This option helps avoid type-checking issues with third-party libraries while maintaining strict checks for the project code.
26-29: Appropriate scope narrowing for type checking.Limiting the include scope to
utilsandtypesdirectories makes the strict null checking more manageable and aligns with the PR's strategy of gradually enabling strict checks.packages/ts/src/utils/path.ts (1)
127-127: Excellent null safety improvement.The nullish coalescing operator ensures the function always returns a string as declared, preventing potential runtime errors when
path(data)returnsnullorundefined.packages/ts/src/types/d3-interpolate-path.d.ts (1)
1-3: Well-structured type declaration.The type declaration correctly defines the
interpolatePathfunction signature with appropriate parameter types and return type for SVG path interpolation functionality.packages/ts/src/types/globals.d.ts (3)
1-1: Appropriate ESLint disable for global declarations.The
no-varrule disable is necessary since global variable declarations require thevarkeyword in TypeScript.
2-2: Good module export pattern.The empty export ensures this file is treated as a module rather than a script, which is the correct approach for global type declarations.
4-12: Excellent null-safe global variable declarations.All global variables are properly typed with
| undefinedunions, which aligns perfectly with the strictNullChecks requirement. The consistentUNOVIS_*naming convention and comprehensive coverage of theme-related globals is well-structured.packages/ts/src/core/xy-component/index.ts (1)
75-75: ```shell
#!/bin/bash
set -eLocate and display the implementation of getExtent, getMin, and getMax
rg -n "export function getExtent" -C5
rg -n "export function getMin" -C5
rg -n "export function getMax" -C5</details> <details> <summary>packages/ts/src/data-models/map.ts (1)</summary> `16-16`: **LGTM: Proper null safety implementation.** The nullish coalescing operator ensures `getDataLatLngBounds` always receives a defined array, preventing potential runtime errors when `this.data` is null or undefined. This aligns perfectly with the `strictNullChecks` objectives. </details> <details> <summary>packages/ts/src/core/component/index.ts (2)</summary> `25-25`: **LGTM: Explicit undefined type annotation.** Adding `| undefined` to the element property type makes the potential undefined state explicit, which is essential for strict null checking. This aligns with the pattern used throughout the codebase for better type safety. --- `116-116`: **LGTM: Proper guard clause for null safety.** The early return when `attributeMap` is falsy prevents attempting to iterate over `undefined` or `null` values, which would cause runtime errors. This defensive programming pattern is exactly what's needed for `strictNullChecks`. </details> <details> <summary>packages/ts/src/data-models/map-graph.ts (2)</summary> `27-27`: **LGTM: Safe fallback for undefined data.** The nullish coalescing operator ensures the getter always returns a defined object, preventing undefined values from propagating through the system. This is essential for `strictNullChecks` compliance. --- `37-44`: **LGTM: Improved type safety in link processing.** The explicit typing of the accumulator and the conditional check for valid source/target points prevent invalid links from being added to the array. The object spreading preserves original link properties while safely adding resolved points, which is exactly the right approach for strict null checking. </details> <details> <summary>packages/ts/src/utils/map.ts (1)</summary> `16-17`: **LGTM: Safe numeric fallbacks for coordinate calculations.** Adding `?? 0` to the `max` and `min` results ensures numeric values are always returned, even when the data array is empty or contains no valid numbers. This prevents `undefined` values from propagating into the bounding box calculations, which is essential for `strictNullChecks` compliance. Also applies to: 21-22 </details> <details> <summary>packages/ts/src/data-models/core.ts (2)</summary> `4-4`: **LGTM: Explicit undefined handling in core data model.** Making `undefined` explicit in both getter and setter signatures establishes the foundation for proper null safety throughout the data model hierarchy. This is essential for `strictNullChecks` and ensures all extending classes handle undefined data appropriately. Also applies to: 8-8 --- `13-13`: **LGTM: Direct assignment in constructor.** Assigning data directly to `_data` instead of using the setter prevents potential complications with setter logic during initialization. This is a safer approach when establishing the base data model behavior. </details> <details> <summary>packages/ts/src/utils/html.ts (1)</summary> `17-24`: **Excellent control flow improvement for strictNullChecks.** The refactored control flow with explicit `else if` structure and final fallback return ensures all code paths are handled correctly. This eliminates potential undefined returns and aligns well with strict null checking requirements. </details> <details> <summary>packages/ts/src/styles/index.ts (1)</summary> `7-18`: **Proper use of nullish coalescing for strictNullChecks compliance.** The change from `globalThis?.PROP || default` to `globalThis.PROP ?? default` is more precise for strict null checking, as nullish coalescing only triggers for `null`/`undefined` values rather than all falsy values. Note: The removal of optional chaining on `globalThis` assumes it's always available, which is safe in modern JavaScript environments. </details> <details> <summary>packages/ts/src/styles/colors.ts (1)</summary> `5-6`: **Good strictNullChecks improvements with explicit typing.** The combination of nullish coalescing and explicit `string[]` type annotations properly handles the global color variables while ensuring type safety under strict null checking. </details> <details> <summary>packages/ts/src/data-models/graph.ts (3)</summary> `32-34`: **Correct return type for strictNullChecks.** The updated return type `OutNode | undefined` accurately reflects that the node may not be found, improving type safety. --- `36-38`: **Good defensive programming pattern.** Returning a default object with empty nodes array prevents undefined access issues under strict null checking. --- `55-56`: **Safer accessor handling for strictNullChecks.** Using inline functions with nullish coalescing (`?? ''`) is safer than passing method references directly, as it handles potential undefined returns from the accessor functions. </details> <details> <summary>packages/ts/src/containers/xy-container/index.ts (3)</summary> `379-381`: **Proper generic typing for nullable array filtering.** The explicit generic type annotations help TypeScript understand that the input array may contain `null` or `undefined` elements while the output is strongly typed. This is essential for strictNullChecks compliance. --- `393-395`: **Consistent nullable array handling.** Good use of explicit generics for filtering potentially nullable component arrays, maintaining type safety throughout the container logic. --- `412-415`: **Safe margin calculations with nullish coalescing.** Using nullish coalescing (`?? 0`) prevents potential NaN results from undefined margin values, ensuring robust layout calculations under strict null checking. Also applies to: 425-428 </details> <details> <summary>packages/ts/src/utils/misc.ts (2)</summary> `29-29`: **LGTM: Correct return type update for null safety.** The return type change to `number | null` accurately reflects that `toPx()` can return `null`, improving type safety under `strictNullChecks`. --- `55-58`: **LGTM: Accurate return type and null handling.** The function correctly returns `null` when no valid identifier is found, and the return type `string | null` properly reflects this behavior. </details> <details> <summary>packages/ts/src/utils/color.ts (3)</summary> `20-27`: **LGTM: Improved null safety and explicit return handling.** The changes enhance type safety by: - Using `isNumber()` instead of `isFinite()` for more precise type checking - Adding explicit null returns with clear conditional logic - Properly handling the fallback to CSS variables --- `49-49`: **LGTM: Safe fallback using nullish coalescing.** The nullish coalescing operator (`??`) provides a safe fallback to an empty string when color parsing fails, preventing potential runtime errors. --- `52-56`: **LGTM: Enhanced return type and null handling.** The function now: - Explicitly includes `undefined` in the return type - Safely handles nullish RGB values - Returns early for fully opaque colors or invalid inputs - Uses nullish coalescing for robust background color parsing </details> <details> <summary>packages/ts/src/components/annotations/index.ts (5)</summary> `44-44`: **LGTM: Safe data binding with null coalescing.** Using `config.items ?? []` ensures the data binding always has a valid array, preventing runtime errors when items is undefined. --- `61-61`: **LGTM: Explicit null handling for cursor attribute.** Using `d.cursor ?? null` ensures the cursor attribute is explicitly set to null when undefined, which is important for proper DOM attribute management. --- `65-75`: **LGTM: Comprehensive null safety for positioning and DOM operations.** The changes add robust null safety by: - Using nullish coalescing for position/dimension properties with appropriate defaults - Checking for DOM node existence before calling `renderTextIntoFrame` This prevents runtime errors when annotation properties are undefined or when DOM nodes are not available. --- `99-121`: **LGTM: Thorough null safety for subject rendering.** Excellent defensive programming with: - Early return when subject is undefined - Null coalescing for all subject properties with appropriate defaults - Safe handling of function vs. direct value properties for x/y coordinates --- `122-167`: **LGTM: Safe DOM operations with explicit null attribute handling.** The changes ensure robust rendering by: - Checking for content node existence before accessing `getBBox()` - Explicitly handling null values for SVG style attributes - Using conditional style setting to properly clear or set attributes This prevents runtime errors and ensures proper SVG attribute management. </details> <details> <summary>packages/ts/src/core/container/index.ts (5)</summary> `15-21`: **LGTM: Appropriate type updates for null safety.** The type changes to allow `null` values for `element` and `_renderAnimationFrameId` properly reflect the actual runtime behavior and support `strictNullChecks`. --- `62-79`: **LGTM: Comprehensive null handling for configuration.** The changes properly handle potentially null/undefined values: - Safe SVG defs content management - Conditional aria-label attribute setting with explicit null handling --- `102-102`: **LGTM: Defensive animation frame management.** Adding null checks before `cancelAnimationFrame` calls prevents potential runtime errors and ensures safe cleanup. Also applies to: 169-169 --- `111-111`: **LGTM: Safe element dimension access.** The null checks ensure safe access to `clientWidth` and `clientHeight`, returning 0 when the element is null instead of throwing runtime errors. Also applies to: 117-117 --- `122-128`: **LGTM: Robust margin handling with null coalescing.** Using nullish coalescing operators ensures safe access to potentially undefined margin properties, preventing runtime errors during width/height calculations. </details> <details> <summary>packages/ts/src/utils/text.ts (7)</summary> `40-42`: **LGTM: Safe regex match handling.** Using nullish coalescing (`|| []`) ensures the function continues safely even when the regex match returns null, preventing runtime errors in the subsequent `filter` and `map` operations. --- `160-161`: **LGTM: Defensive DOM node access.** Adding null checks before calling DOM methods like `getComputedTextLength()` prevents runtime errors when SVG nodes don't exist, providing safe fallbacks (0 for dimensions). Also applies to: 196-197, 274-275 --- `190-190`: **LGTM: Safe attribute and style handling.** The changes ensure robust handling of: - Font size extraction with safe fallback to 0 - Font family attribute setting with empty string fallback Also applies to: 237-237 --- `390-391`: **LGTM: Comprehensive null safety for text properties.** Using nullish coalescing throughout ensures safe access to optional text properties like `lineHeight`, `marginTop`, `marginBottom`, preventing undefined access errors during text layout calculations. Also applies to: 399-405, 454-456 --- `510-518`: **LGTM: Safe attribute retrieval and text alignment.** The changes provide robust attribute handling: - Safe retrieval of x/y coordinates with numeric fallbacks - Explicit text alignment setting with proper defaults --- `540-542`: **LGTM: Safe DOM manipulation.** Adding existence checks before `appendChild` operations prevents runtime errors when parsed SVG content is null, ensuring robust text rendering. Also applies to: 594-596 --- `563-578`: **LGTM: Comprehensive frame options null safety.** Using nullish coalescing for frame dimensions and alignment options ensures safe text positioning calculations and proper SVG attribute generation, preventing undefined value errors. Also applies to: 583-583 </details> <details> <summary>packages/ts/src/utils/data.ts (7)</summary> `8-20`: **Excellent type safety improvements in type guard functions.** The conversion from generic conditional types to explicit type guards with `unknown` inputs is well-executed. The `isAClassInstance` function's rewrite with optional chaining and type assertions provides safer constructor checking. All type guards now follow consistent patterns and provide better type narrowing for strict null checks. --- `178-178`: **Good addition of explicit null/undefined to return type.** The `getValue` function now correctly reflects that accessors can return `null` or `undefined`, which aligns with the strict null checking requirements. This makes the nullable nature of the return value explicit to consumers. --- `228-242`: **Excellent simplification of getStackedExtent function.** The rewrite with explicit variable initialization and nullish coalescing (`|| 0`) provides much cleaner and more readable code. The logic correctly handles null/undefined values from `getNumber` by defaulting to 0, which is appropriate for stacking calculations. --- `270-272`: **Good use of nullish coalescing for safer null handling.** The use of `?? 0` and `?? false` provides appropriate defaults when dealing with potentially undefined values from `mean()` and array access. This handles the strict null checking requirements well. --- `275-275`: **Type casting for array initialization is appropriate.** The cast `[] as unknown as StackValuesRecord` is necessary due to the complex type structure and the map operation creating arrays that will be populated later. This is a reasonable workaround for TypeScript's type system limitations. --- `316-316`: **Appropriate null handling in getNearest function.** Using nullish coalescing (`?? 0`) to replace null/undefined values with 0 before sorting is a good approach for numerical operations. This ensures the sort operation works correctly with the bisector. --- `327-327`: **Excellent explicit null check before range comparison.** The addition of `value != null` provides proper null safety before performing range comparisons. This prevents potential runtime errors and aligns well with strict null checking requirements. </details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
| link.source = this.findNode(nodes, link.source)! | ||
| link.target = this.findNode(nodes, link.target)! |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Risky non-null assertions could cause runtime errors.
The non-null assertion operators (!) assume that findNode will always return a value, but findNode can return undefined (as seen in its implementation). This could lead to runtime errors if nodes are not found.
Consider adding explicit checks instead:
- link.source = this.findNode(nodes, link.source)!
- link.target = this.findNode(nodes, link.target)!
+ const source = this.findNode(nodes, link.source)
+ const target = this.findNode(nodes, link.target)
+ if (!source || !target) {
+ console.warn(`Unovis | Graph Data Model: Skipping link ${i} due to missing source or target node`)
+ return
+ }
+ link.source = source
+ link.target = targetCommittable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In packages/ts/src/data-models/graph.ts around lines 72 to 73, the use of
non-null assertions on the results of findNode is risky because findNode can
return undefined, potentially causing runtime errors. Replace the non-null
assertions with explicit checks to verify that the returned nodes are not
undefined before assigning them to link.source and link.target. Handle the case
where a node is not found, for example by throwing an error or skipping the
assignment, to ensure safe and predictable behavior.
Summary
Testing
npx tsc --noEmit -p packages/ts/tsconfig.jsonhttps://chatgpt.com/codex/tasks/task_e_685c68a4001483268dda8e048ed7848f
Summary by CodeRabbit
New Features
Bug Fixes
Refactor
Chores